carotid 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sarthak Kamon
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,250 @@
1
- # Temporary Holding Version
1
+ # carotid
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **A zero-config dev proxy that makes `localhost` behave like the real world:** open your app on your phone by scanning a QR code, then make the network slow, flaky or dead while you watch every request go by.
4
+
5
+ ```
6
+ npx carotid 3000
7
+ ```
8
+
9
+ ```
10
+ carotid v0.1.0
11
+
12
+ Local http://localhost:2345
13
+ Network http://192.168.1.20:2345 <- open this on your phone
14
+ Target http://localhost:3000
15
+ Chaos profile 3g (300ms ±100, 200 KB/s, 1% fail), 0 rules
16
+ Config none (create carotid.yaml here to add rules, it loads live)
17
+ Stats http://localhost:2345/__carotid/stats
18
+
19
+ █▀▀▀▀▀█ ▄▀ ▄▀ █▀▀▀▀▀█
20
+ █ ███ █ ▀█▄▀▄ █ ███ █ (a real, scannable QR code)
21
+ █ ▀▀▀ █ █ ▄ ▀ █ ▀▀▀ █
22
+ ▀▀▀▀▀▀▀ ▀ █ ▀ ▀▀▀▀▀▀▀
23
+
24
+ Requests appear below. Press Ctrl+C to stop.
25
+
26
+ 14:02:11 GET / 200 412ms delay 371ms, throttle 200KB/s
27
+ 14:02:11 GET /assets/index.js 200 1904ms delay 284ms, throttle 200KB/s
28
+ 14:02:12 WS /?token=abc 101 303ms delay 301ms
29
+ 14:02:14 POST /api/cart 503 344ms delay 339ms, fail 503
30
+ 14:02:14 GET /favicon.ico 200 3ms favicon fallback
31
+ ```
32
+
33
+ ## The demo
34
+
35
+ 1. Your app is running on `localhost:3000`, the way it always is.
36
+ 2. Run `npx carotid 3000 --profile 3g`.
37
+ 3. Point your phone's camera at the QR code in the terminal. Your app opens on the phone, hot reload included.
38
+ 4. Tap around. On the phone the app now feels like it is on a 3G connection; in the terminal you see each request with its status, how long it took, and what carotid did to it.
39
+ 5. Create a `carotid.yaml`, write `profile: offline`, hit save. No restart: the next tap on the phone fails, and you find out what your app does when the network goes away.
40
+
41
+ ## Install
42
+
43
+ Nothing to install; `npx` runs it on demand:
44
+
45
+ ```
46
+ npx carotid 3000
47
+ ```
48
+
49
+ Or add it to a project:
50
+
51
+ ```
52
+ npm install --save-dev carotid
53
+ ```
54
+
55
+ Requires Node.js 18.3 or newer. Works on Windows, macOS and Linux.
56
+
57
+ ## Usage
58
+
59
+ ```
60
+ carotid <port> [options] proxy localhost:<port>, print a LAN URL + QR code
61
+ carotid export [options] save the traffic captured by a running carotid
62
+ ```
63
+
64
+ | Option | Meaning |
65
+ | --- | --- |
66
+ | `-p, --profile <name>` | Apply a network profile (table below) |
67
+ | `-l, --listen <port>` | Port carotid listens on. Default `2345`; if that is busy carotid takes the next free one |
68
+ | `--no-qr` | Do not print the QR code |
69
+ | `-h, --help` | Help |
70
+ | `-v, --version` | Version |
71
+
72
+ ```
73
+ carotid 3000 # just LAN access, QR code and the request log
74
+ carotid 5173 --profile slow-3g # Vite app on a bad connection
75
+ carotid 8080 --listen 9000 # choose carotid's own port
76
+ ```
77
+
78
+ What you get without any configuration:
79
+
80
+ - **LAN access.** carotid listens on all interfaces, finds your machine's LAN address, and prints the URL plus a QR code.
81
+ - **A transparent proxy.** HTTP, streaming responses (SSE) and WebSocket upgrades pass straight through, so hot reload in Vite, Next.js and webpack keeps working. Headers are preserved, including `Host`.
82
+ - **A live request log.** One line per request: time, method, path, status, duration, and the chaos that was applied.
83
+ - **A favicon.** If your app has no `/favicon.ico`, carotid serves a small generated icon whose colour depends on the port, so three localhost tabs are easy to tell apart and your log has no favicon 404s. If your app serves its own favicon, carotid never touches it.
84
+ - **A waiting page.** Started carotid before your dev server? The page says so and loads by itself once the server is up.
85
+
86
+ ## Profiles
87
+
88
+ | Profile | Latency | Bandwidth | Failures | Feels like |
89
+ | --- | --- | --- | --- | --- |
90
+ | `3g` | 300 ms ± 100 | 200 KB/s (~1.6 Mbit/s) | 1% get a 503 | An average phone on 3G |
91
+ | `slow-3g` | 2000 ms ± 500 | 50 KB/s (~400 kbit/s) | 2% get a 503 | One bar of signal |
92
+ | `flaky-wifi` | 150 ms ± 150 | 1000 KB/s | 5% get 502/503/504, 5% dropped, 3% cut mid-response | Coffee-shop wifi |
93
+ | `airplane-mode` | hangs 2 to 6 s | n/a | 100% dropped after the hang | The signal just vanished and nothing has noticed yet |
94
+ | `offline` | none | n/a | 100% dropped immediately | No network at all |
95
+
96
+ `airplane-mode` and `offline` also block page loads, so load the page first and then switch profile in `carotid.yaml`.
97
+
98
+ Profiles live in one file, [`src/profiles/index.js`](src/profiles/index.js). The numbers are easy to change.
99
+
100
+ ## Config: `carotid.yaml`
101
+
102
+ Optional. Put it in the folder you run carotid from; it is detected automatically and **reloaded on every save**, with a one-line notice in the terminal:
103
+
104
+ ```
105
+ [config] carotid.yaml reloaded: profile 3g (300ms ±100, 200 KB/s, 1% fail), 2 rules
106
+ ```
107
+
108
+ ```yaml
109
+ profile: 3g
110
+
111
+ rules:
112
+ # A slow endpoint
113
+ - path: /api/search
114
+ delay: 1200 # ms
115
+ jitter: 400 # random +/- ms
116
+
117
+ # 1 in 4 writes fails
118
+ - path: /api/**
119
+ method: [POST, PUT]
120
+ fail: 25 # percent
121
+ status: 503 # or a list: [500, 502, 503]
122
+
123
+ # Thin pipe that sometimes dies halfway
124
+ - path: /downloads/**
125
+ throttle: 30 # KB/s
126
+ cut: 10 # percent of responses cut mid-body
127
+
128
+ # Exempt something from the profile
129
+ - path: /health
130
+ delay: 0
131
+ jitter: 0
132
+ fail: 0
133
+ throttle: 0 # 0 = unlimited
134
+ ```
135
+
136
+ | Field | Meaning |
137
+ | --- | --- |
138
+ | `path` | Path pattern. `/api/users` exact, `/api/*` one segment, `/api/**` everything below (and `/api`), `**/*.png` by extension. Omit to match every path |
139
+ | `method` | One method or a list. Omit to match all |
140
+ | `delay` | Fixed latency in ms |
141
+ | `jitter` | Random ± ms on top of `delay` |
142
+ | `fail` | Percent of requests answered with an injected status instead of reaching your app |
143
+ | `status` | Status code for injected failures, or a list to pick from. Default 503 |
144
+ | `throttle` | Response bandwidth in KB/s. `0` means unlimited |
145
+ | `drop` | Percent of requests whose connection is closed without any response |
146
+ | `cut` | Percent of responses cut off partway through the body |
147
+
148
+ How rules combine: the profile is the baseline; every rule that matches a request overrides the fields it sets; rules apply top to bottom, so later ones win.
149
+
150
+ `--profile` on the command line overrides `profile:` in the file.
151
+
152
+ If the file has a mistake, carotid tells you what and where, and keeps running with the previous rules:
153
+
154
+ ```
155
+ carotid.yaml has 2 problems:
156
+ - unknown profile "4g"; available: 3g, slow-3g, flaky-wifi, airplane-mode, offline
157
+ - rules[0].delay must be a number of milliseconds (0 or more), got "fast"
158
+ Keeping the previous rules until the file is fixed.
159
+ ```
160
+
161
+ A commented example is in [`examples/carotid.yaml`](examples/carotid.yaml).
162
+
163
+ ## Stats and export
164
+
165
+ While carotid runs, `http://localhost:2345/__carotid/stats` returns JSON:
166
+
167
+ ```json
168
+ {
169
+ "target": "http://localhost:3000",
170
+ "profile": "3g",
171
+ "requests": { "total": 128, "buffered": 128, "capacity": 1000 },
172
+ "status": { "2xx": 119, "3xx": 4, "4xx": 2, "5xx": 3, "none": 0, "codes": { "200": 119, "304": 4, "404": 2, "503": 3 } },
173
+ "latency": { "avg": 412, "p50": 371, "p95": 1204, "max": 2210, "sample": 128 },
174
+ "chaos": { "delay": 128, "throttle": 125, "fail": 3 },
175
+ "recent": [ { "time": "…", "method": "GET", "url": "/", "status": 200, "duration": 412, "chaos": ["delay 371ms"] } ]
176
+ }
177
+ ```
178
+
179
+ The last 1000 requests are kept in memory. To save them, run this in a second terminal while carotid is running:
180
+
181
+ ```
182
+ carotid export # HAR, opens in browser devtools (Network tab > Import)
183
+ carotid export --format json # carotid's own JSON
184
+ carotid export --out traffic.har --listen 2345
185
+ ```
186
+
187
+ Exports contain request headers, including cookies and tokens. Look before you share one.
188
+
189
+ ## Phone can't connect?
190
+
191
+ - The phone has to be on the **same Wi-Fi** as your computer. Guest networks and some office networks block devices from talking to each other.
192
+ - **Windows:** the first time, Windows Security asks whether Node.js may accept connections: click **Allow**. If you dismissed it, open *Allow an app through Windows Firewall*, find *Node.js JavaScript Runtime* and tick **Private**. Also check that your Wi-Fi is set to *Private network* (Settings > Network & Internet > Wi-Fi > your network).
193
+ - **macOS:** click **Allow** when asked whether `node` may accept incoming connections.
194
+ - **Linux:** open the port if you run a firewall, e.g. `sudo ufw allow 2345/tcp`.
195
+ - VPNs often take over routing. If carotid prints the wrong address, the banner also lists the other addresses it found.
196
+ - Vite 6+ and some other dev servers only accept requests for known host names. IP addresses are allowed by default, so the LAN URL works as is.
197
+
198
+ ## Limitations
199
+
200
+ carotid is honest about what it is: an HTTP-level simulator.
201
+
202
+ - **It is not packet-level.** There is no real packet loss, reordering, TCP congestion or DNS delay. `drop` closes a socket; it does not lose packets. For that, use OS tools (`tc netem` on Linux, Network Link Conditioner on macOS, clumsy on Windows).
203
+ - **Throttling is on responses only**, per request, measured at the proxy. Upload speed is not limited, and ten parallel requests each get the full rate rather than sharing one pipe.
204
+ - **Latency is added once per request**, before it is forwarded. It does not model per-round-trip latency or slow connection setup.
205
+ - **WebSockets:** `delay`, `drop` and `fail` apply to the handshake. Messages on an open socket are not delayed, throttled or cut.
206
+ - **Bodies are not captured.** The request log and exports contain headers, sizes and timings, not content.
207
+ - **HTTP only.** No HTTPS, so browser features that need a secure context (service workers, camera, geolocation, clipboard) will not work on the phone over the LAN URL.
208
+ - **The favicon fallback is an SVG.** Chrome, Firefox and Edge render it; Safari support for SVG favicons is patchy, so you may still see a blank icon there.
209
+ - **It opens your dev server to your local network.** That is the point, but anyone on the same network can reach it, and `/__carotid/stats` too, while carotid runs. Use it on networks you trust.
210
+ - Stats and latency percentiles cover the last 1000 requests and are lost when carotid stops.
211
+
212
+ ## Roadmap
213
+
214
+ Not in v1, but the code is laid out so they can be added:
215
+
216
+ - Web dashboard
217
+ - HTTPS with locally trusted certificates (mkcert)
218
+ - Public tunnel sharing
219
+ - mDNS (`carotid.local`)
220
+ - Request breakpoints and editing
221
+ - Mocking
222
+
223
+ ## Development
224
+
225
+ ```
226
+ git clone <this repo> && cd carotid
227
+ npm install
228
+ npm test # node:test, no extra tooling
229
+ node bin/carotid.js 3000
230
+ ```
231
+
232
+ ```
233
+ bin/carotid.js entry point
234
+ src/cli.js argument parsing
235
+ src/start.js wires everything together for `carotid <port>`
236
+ src/proxy/ server, HTTP forwarding + chaos, WebSocket tunnel, throttle, favicon, /__carotid endpoints
237
+ src/rules/ path matching, the per-request chaos plan, config validation
238
+ src/profiles/ built-in network profiles
239
+ src/config/ carotid.yaml loading and hot reload
240
+ src/net/ LAN address detection, port picking
241
+ src/store/ ring buffer of recent requests + stats
242
+ src/ui/ banner, QR code, request log, colour
243
+ src/export/ HAR and JSON export
244
+ ```
245
+
246
+ Dependencies: [`yaml`](https://www.npmjs.com/package/yaml) and [`qrcode-terminal`](https://www.npmjs.com/package/qrcode-terminal). The proxy itself is plain `node:http` and `node:net`.
247
+
248
+ ## License
249
+
250
+ MIT
package/bin/carotid.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.js';
3
+
4
+ main(process.argv.slice(2));
@@ -0,0 +1,49 @@
1
+ # carotid.yaml
2
+ #
3
+ # Copy this file next to your project (the folder you run `carotid` from).
4
+ # carotid picks it up automatically and reloads it every time you save.
5
+ #
6
+ # How it fits together:
7
+ # 1. `profile` sets the baseline for every request.
8
+ # 2. Each rule that matches a request overrides the fields it sets.
9
+ # Rules are applied top to bottom, so later rules win.
10
+
11
+ # One of: 3g, slow-3g, flaky-wifi, airplane-mode, offline. Remove for no baseline.
12
+ profile: 3g
13
+
14
+ rules:
15
+ # A slow endpoint: fixed delay plus random jitter (both in ms).
16
+ - path: /api/search
17
+ delay: 1200
18
+ jitter: 400
19
+
20
+ # A flaky write path: 1 in 4 POST/PUT requests under /api gets a 503.
21
+ - path: /api/**
22
+ method: [POST, PUT]
23
+ fail: 25 # percent of requests
24
+ status: 503 # or a list, e.g. [500, 502, 503]
25
+
26
+ # Big downloads on a thin pipe, and sometimes the connection dies halfway.
27
+ - path: /downloads/**
28
+ throttle: 30 # KB/s
29
+ cut: 10 # percent of responses cut mid-body
30
+
31
+ # Requests that never get an answer: the socket is simply closed.
32
+ - path: /api/analytics
33
+ drop: 50 # percent
34
+
35
+ # Opt something out of the profile entirely.
36
+ - path: /health
37
+ delay: 0
38
+ jitter: 0
39
+ fail: 0
40
+ throttle: 0 # 0 = unlimited
41
+
42
+ # Path patterns (matched against the path, without the query string):
43
+ # /api/users exactly that path
44
+ # /api/* one segment: /api/users, but not /api/users/1
45
+ # /api/** everything under /api, and /api itself
46
+ # **/*.png any .png at any depth
47
+ #
48
+ # `method` is optional: one method or a list. Without it the rule matches all methods.
49
+ # A rule without `path` matches every request.
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "carotid",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Zero-config dev proxy that makes localhost behave like the real world: LAN URL + QR code, latency, failures, throttling, live request log.",
5
+ "type": "module",
6
+ "bin": {
7
+ "carotid": "bin/carotid.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src",
12
+ "examples",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "scripts": {
17
+ "start": "node bin/carotid.js",
18
+ "test": "node --test"
19
+ },
20
+ "engines": {
21
+ "node": ">=18"
22
+ },
23
+ "keywords": [
24
+ "proxy",
25
+ "dev",
26
+ "localhost",
27
+ "chaos",
28
+ "latency",
29
+ "throttle",
30
+ "network",
31
+ "qr",
32
+ "lan",
33
+ "mobile"
34
+ ],
35
+ "license": "MIT",
36
+ "dependencies": {
37
+ "qrcode-terminal": "^0.12.0",
38
+ "yaml": "^2.4.0"
39
+ },
40
+ "author": "Sarthak Kamon <kamonsarthak@hotmail.com>",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/kamonsarthak/carotid.git"
44
+ },
45
+ "homepage": "https://github.com/kamonsarthak/carotid#readme",
46
+ "bugs": {
47
+ "url": "https://github.com/kamonsarthak/carotid/issues"
48
+ }
49
+ }
package/src/cli.js ADDED
@@ -0,0 +1,124 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { VERSION } from './version.js';
3
+ import { profiles, profileNames, describeEffects } from './profiles/index.js';
4
+ import { createColors } from './ui/color.js';
5
+ import { start, DEFAULT_LISTEN_PORT } from './start.js';
6
+ import { runExport, EXPORT_FORMATS } from './export/index.js';
7
+
8
+ function helpText() {
9
+ const width = Math.max(...profileNames.map((name) => name.length));
10
+ const profileLines = profileNames.map((name) => ` ${name.padEnd(width)} ${describeEffects(profiles[name])}`);
11
+ return `carotid ${VERSION}: make localhost behave like the real world
12
+
13
+ Usage
14
+ carotid <port> [options] proxy localhost:<port>, print a LAN URL + QR code
15
+ carotid export [options] save the traffic captured by a running carotid
16
+
17
+ Options
18
+ -p, --profile <name> apply a network profile (see below)
19
+ -l, --listen <port> port carotid listens on (default ${DEFAULT_LISTEN_PORT}, next free one if busy)
20
+ --no-qr do not print the QR code
21
+ -h, --help show this help
22
+ -v, --version show the version
23
+
24
+ Export options
25
+ -f, --format <fmt> har (default) or json
26
+ -o, --out <file> output file (default carotid-export-<time>.<fmt>)
27
+ -l, --listen <port> port of the running carotid (default: found automatically)
28
+
29
+ Profiles
30
+ ${profileLines.join('\n')}
31
+
32
+ Config
33
+ Put a carotid.yaml in the folder you run carotid from. It is picked up
34
+ automatically and reloaded on every save. Example:
35
+
36
+ profile: 3g
37
+ rules:
38
+ - path: /api/**
39
+ method: POST
40
+ fail: 20 # percent
41
+ status: 503
42
+
43
+ Examples
44
+ carotid 3000
45
+ carotid 5173 --profile slow-3g
46
+ carotid export --format har
47
+ `;
48
+ }
49
+
50
+ function parsePort(value, what) {
51
+ const port = Number(value);
52
+ if (!/^\d+$/.test(String(value)) || port < 1 || port > 65535) {
53
+ throw new UsageError(`${what} must be a port number between 1 and 65535, got "${value}".`);
54
+ }
55
+ return port;
56
+ }
57
+
58
+ class UsageError extends Error {}
59
+
60
+ async function run(argv) {
61
+ let parsed;
62
+ try {
63
+ parsed = parseArgs({
64
+ args: argv,
65
+ allowPositionals: true,
66
+ options: {
67
+ profile: { type: 'string', short: 'p' },
68
+ listen: { type: 'string', short: 'l' },
69
+ format: { type: 'string', short: 'f' },
70
+ out: { type: 'string', short: 'o' },
71
+ 'no-qr': { type: 'boolean' },
72
+ help: { type: 'boolean', short: 'h' },
73
+ version: { type: 'boolean', short: 'v' },
74
+ },
75
+ });
76
+ } catch (err) {
77
+ throw new UsageError(err.message.split('. ')[0] + '.');
78
+ }
79
+ const { values, positionals } = parsed;
80
+
81
+ if (values.help) return console.log(helpText());
82
+ if (values.version) return console.log(VERSION);
83
+
84
+ const [command, ...rest] = positionals;
85
+ if (command === undefined) {
86
+ throw new UsageError('Which port is your app on? Try: carotid 3000');
87
+ }
88
+ const listenPort = values.listen !== undefined ? parsePort(values.listen, '--listen') : null;
89
+
90
+ if (command === 'export') {
91
+ const format = values.format ?? 'har';
92
+ if (!EXPORT_FORMATS.includes(format)) {
93
+ throw new UsageError(`--format must be one of: ${EXPORT_FORMATS.join(', ')}. Got "${format}".`);
94
+ }
95
+ return runExport({ format, out: values.out ?? null, listenPort });
96
+ }
97
+
98
+ if (rest.length) throw new UsageError(`Unexpected extra argument "${rest[0]}".`);
99
+ const targetPort = parsePort(command, 'The port');
100
+ if (listenPort === targetPort) {
101
+ throw new UsageError(`--listen ${listenPort} is the port of your app. carotid needs a different port for itself.`);
102
+ }
103
+ if (values.profile !== undefined && !profileNames.includes(values.profile)) {
104
+ throw new UsageError(`Unknown profile "${values.profile}". Available: ${profileNames.join(', ')}.`);
105
+ }
106
+
107
+ await start({ targetPort, listenPort, profile: values.profile ?? null, qr: !values['no-qr'] });
108
+ }
109
+
110
+ export async function main(argv) {
111
+ try {
112
+ await run(argv);
113
+ } catch (err) {
114
+ const c = createColors();
115
+ if (err.friendly) {
116
+ console.error(`\n ${c.red(err.message)}\n`);
117
+ } else if (err instanceof UsageError) {
118
+ console.error(`\n ${c.red(err.message)}\n ${c.dim('Run "carotid --help" for usage.')}\n`);
119
+ } else {
120
+ console.error(`\n ${c.red(`carotid failed: ${err.message}`)}\n`);
121
+ }
122
+ process.exitCode = 1;
123
+ }
124
+ }
@@ -0,0 +1,40 @@
1
+ import { readFileSync, existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { validateConfig } from '../rules/validate.js';
4
+ import { profileNames } from '../profiles/index.js';
5
+
6
+ export const CONFIG_FILES = ['carotid.yaml', 'carotid.yml'];
7
+
8
+ const EMPTY = Object.freeze({ profile: null, rules: [] });
9
+
10
+ /**
11
+ * Look for carotid.yaml in `dir`, parse and validate it. Never throws: problems come
12
+ * back as human-readable strings in `errors` (and `config` is then null).
13
+ *
14
+ * @returns {Promise<{ name: string | null, text: string | null, config: { profile: string | null, rules: object[] } | null, errors: string[] }>}
15
+ */
16
+ export async function readConfig(dir) {
17
+ const name = CONFIG_FILES.find((file) => existsSync(path.join(dir, file))) ?? null;
18
+ if (!name) return { name: null, text: null, config: { ...EMPTY }, errors: [] };
19
+
20
+ let text;
21
+ try {
22
+ text = readFileSync(path.join(dir, name), 'utf8');
23
+ } catch (err) {
24
+ return { name, text: null, config: null, errors: [`cannot read the file: ${err.message}`] };
25
+ }
26
+
27
+ let raw;
28
+ try {
29
+ // Loaded on demand: the zero-config path never pays for the YAML parser.
30
+ const { parse } = await import('yaml');
31
+ raw = parse(text);
32
+ } catch (err) {
33
+ // yaml's messages already include line, column and a code frame
34
+ const message = err.message.split('\n').filter((line) => line.trim()).join('\n');
35
+ return { name, text, config: null, errors: [`invalid YAML: ${message}`] };
36
+ }
37
+
38
+ const { config, errors } = validateConfig(raw, profileNames);
39
+ return { name, text, config, errors };
40
+ }
@@ -0,0 +1,40 @@
1
+ import { watch, watchFile, unwatchFile } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { CONFIG_FILES } from './load.js';
4
+
5
+ /**
6
+ * Call `onChange` (debounced) whenever carotid.yaml is created, saved or deleted.
7
+ *
8
+ * We watch the directory rather than the file: editors often save by writing a temp
9
+ * file and renaming it, which silently breaks a watch on the file itself, and watching
10
+ * the directory also notices a config file that did not exist at startup.
11
+ *
12
+ * @returns {() => void} stop watching
13
+ */
14
+ export function watchConfig(dir, onChange, debounceMs = 100) {
15
+ let timer = null;
16
+ const trigger = () => {
17
+ clearTimeout(timer);
18
+ timer = setTimeout(onChange, debounceMs);
19
+ };
20
+
21
+ try {
22
+ const watcher = watch(dir, { persistent: false }, (_event, filename) => {
23
+ // filename can be null on some platforms: then we cannot tell, so check anyway
24
+ if (!filename || CONFIG_FILES.includes(path.basename(filename.toString()))) trigger();
25
+ });
26
+ watcher.on('error', () => {});
27
+ return () => {
28
+ clearTimeout(timer);
29
+ watcher.close();
30
+ };
31
+ } catch {
32
+ // fs.watch is unavailable on a few filesystems (some network shares): poll instead
33
+ const files = CONFIG_FILES.map((file) => path.join(dir, file));
34
+ for (const file of files) watchFile(file, { interval: 500, persistent: false }, trigger);
35
+ return () => {
36
+ clearTimeout(timer);
37
+ for (const file of files) unwatchFile(file, trigger);
38
+ };
39
+ }
40
+ }
@@ -0,0 +1,60 @@
1
+ import { VERSION } from '../version.js';
2
+
3
+ const headerList = (headers = {}) =>
4
+ Object.entries(headers).flatMap(([name, value]) => [].concat(value).map((v) => ({ name, value: String(v) })));
5
+
6
+ function queryList(url) {
7
+ const q = url.indexOf('?');
8
+ if (q === -1) return [];
9
+ return [...new URLSearchParams(url.slice(q + 1))].map(([name, value]) => ({ name, value }));
10
+ }
11
+
12
+ /**
13
+ * Convert captured entries to HAR 1.2 (loadable in browser devtools and HAR viewers).
14
+ * carotid does not capture bodies, so sizes are real but content is absent.
15
+ *
16
+ * @param {import('../store/ring.js').Entry[]} entries
17
+ */
18
+ export function toHar(entries) {
19
+ return {
20
+ log: {
21
+ version: '1.2',
22
+ creator: { name: 'carotid', version: VERSION },
23
+ entries: entries.map((entry) => {
24
+ const httpVersion = `HTTP/${entry.httpVersion ?? '1.1'}`;
25
+ const resHeaders = entry.resHeaders ?? {};
26
+ const wait = entry.ttfb ?? entry.duration;
27
+ return {
28
+ startedDateTime: new Date(entry.startedAt).toISOString(),
29
+ time: entry.duration,
30
+ request: {
31
+ method: entry.method,
32
+ url: `${entry.kind === 'ws' ? 'ws' : 'http'}://${entry.reqHeaders?.host ?? 'localhost'}${entry.url}`,
33
+ httpVersion,
34
+ cookies: [],
35
+ headers: headerList(entry.reqHeaders),
36
+ queryString: queryList(entry.url),
37
+ headersSize: -1,
38
+ bodySize: entry.reqBytes ?? 0,
39
+ },
40
+ response: {
41
+ status: entry.status,
42
+ statusText: entry.statusText ?? '',
43
+ httpVersion,
44
+ cookies: [],
45
+ headers: headerList(resHeaders),
46
+ content: { size: entry.resBytes ?? 0, mimeType: String(resHeaders['content-type'] ?? '') },
47
+ redirectURL: String(resHeaders.location ?? ''),
48
+ headersSize: -1,
49
+ bodySize: entry.resBytes ?? 0,
50
+ },
51
+ cache: {},
52
+ timings: { send: 0, wait, receive: Math.max(0, entry.duration - wait) },
53
+ serverIPAddress: '127.0.0.1',
54
+ // Custom fields (HAR allows "_" prefixed extensions)
55
+ _carotid: { chaos: entry.chaos, note: entry.note ?? null, error: entry.error ?? null, client: entry.client ?? null },
56
+ };
57
+ }),
58
+ },
59
+ };
60
+ }