@esposter/shared-node 4.3.3 → 4.4.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/README.md CHANGED
@@ -5,12 +5,14 @@
5
5
  [![NPM downloads][badge-npm-downloads]][url-npm]
6
6
  [![NPM Unpacked Size (with version)][badge-npm-unpacked-size]][url-npm]
7
7
 
8
- Node-only shared tooling for Esposter — the machine-wide download cache, hidden-window child processes and benchmark reporting reused across packages. Server/build environment only; never import in browser code.
8
+ Node-only shared tooling for Esposter — the machine-wide download cache, hidden-window child processes and benchmark reporting reused across packages.
9
+
10
+ Design notes live in [the specs](https://github.com/Esposter/Esposter/tree/main/openspec/specs).
9
11
 
10
12
  ## Table of Contents
11
13
 
12
14
  - 🚀 [Getting Started](#getting-started)
13
- - 📖 [Documentation](#documentation)
15
+ - 🧩 [Key Exports](#key-exports)
14
16
  - ⚖️ [License](#license)
15
17
 
16
18
  ---
@@ -27,59 +29,17 @@ import { spawnSync } from "@esposter/shared-node/child-process";
27
29
  spawnSync("pnpm", ["install"], { stdio: "inherit" });
28
30
  ```
29
31
 
30
- ## <a name="documentation">📖 Documentation</a>
31
-
32
- We highly recommend you take a look at the [documentation](https://github.com/Esposter/Esposter/tree/main/openspec/specs) to level up.
33
-
34
- ### What's Included
35
-
36
- The machine-wide download cache, the hidden-window child process wrappers, and the benchmark reporting toolkit consumed by the repo's `vitest bench` runs (see the `bench` skill).
37
-
38
- `@esposter/shared-node/child-process` exports `spawn`, `spawnSync`, `execFile`, `execFileSync` and `execSync` with node's own names and types. Each forces `windowsHide: true` last, so a console child never opens its own terminal window on Windows, including from a windowless parent such as a Claude Code hook. Import these instead of `node:child_process`; the repo's lint rule enforces it.
39
-
40
- ```ts
41
- import { spawnSync } from "@esposter/shared-node/child-process";
42
-
43
- spawnSync("pnpm", ["install"], { stdio: "inherit" });
44
- ```
45
-
46
- `@esposter/shared-node/cache` exports `CACHE_ROOT` (`~/Esposter/cache`), the one folder every checkout, worktree and ephemeral run on a machine shares for what it downloads, and `readContentAddressedObject`, a read-through cache for objects named by the hex SHA-256 of their bytes. A hit is read from `CONTENT_CACHE_DIRECTORY`; a miss is downloaded once and kept only if its bytes hash to its name, so a hit never goes stale and any source of the same content shares one copy.
47
-
48
- ```ts
49
- import { readContentAddressedObject } from "@esposter/shared-node/cache";
50
-
51
- const bytes = await readContentAddressedObject(
52
- hash,
53
- async () => new Uint8Array(await (await fetch(url)).arrayBuffer()),
54
- );
55
- ```
56
-
57
- | Export | Description |
58
- | ------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------- |
59
- | `BenchmarkMarkdownReporter` | Vitest reporter — writes `Foo.bench.md` + `Foo.bench.json` beside `Foo.bench.ts` |
60
- | `BENCHMARK_RUN_OPTIONS` | Run options every `bench.compare` passes, fixing the iteration count |
61
- | `buildBenchmarkFileReport` | Projects a module's reported tests into a structured `BenchmarkReport` |
62
- | `formatBenchmarkMarkdown` | Renders a `BenchmarkReport` to Markdown tables |
63
- | `writeBenchmarkReport` | Persists the JSON + Markdown report artifacts |
64
- | `readBenchmarkEnvironment` | Captures CPU/OS/runtime metadata for reproducible results |
65
- | `BenchmarkFile` · `BenchmarkGroup` · `BenchmarkReport` · `BenchmarkResult` · `BenchmarkTestCase` | Report data models |
32
+ - Server/build environment only; never import in browser code.
66
33
 
67
- ### Architecture Notes
34
+ ## <a name="key-exports">🧩 Key Exports</a>
68
35
 
69
- - **Node-only**: depends on Node built-ins (`fs`, `os`) — must not be bundled into the browser app.
70
- - Depends on `@esposter/shared` for shared types and utilities.
71
- - Wired into `vitest bench` via `BenchmarkMarkdownReporter`; the emitted artifacts are committed and diffed offline as the speed gate.
72
-
73
- ### Commands
74
-
75
- Run from `packages/shared-node/`:
76
-
77
- ```bash
78
- pnpm build # compile to dist/
79
- pnpm test # vitest watch mode (coverage is run from the repo root)
80
- pnpm lint:fix # auto-fix lint
81
- pnpm typecheck # type check
82
- ```
36
+ | Export | Description |
37
+ | ------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
38
+ | `BENCHMARK_RUN_OPTIONS` (`/bench`) | Run options every `bench.compare` passes, fixing the iteration count |
39
+ | `BenchmarkMarkdownReporter` (default export, `/reporter`) | Vitest reporter — writes `Foo.bench.md` + `Foo.bench.json` beside `Foo.bench.ts` |
40
+ | `spawn`, `spawnSync`, `execFile`, `execFileSync`, `execSync` (`/child-process`) | Node's own child-process functions, each forcing `windowsHide: true` so a console child never opens a window of its own |
41
+ | `execFileAsync` (`/child-process`) | The promisified `execFile`, with the same window flag, resolving `{ stdout, stderr }` |
42
+ | `CACHE_ROOT`, `readContentAddressedObject` (`/cache`) | The download cache folder every checkout shares, and a read-through cache for objects named by the hex SHA-256 of their bytes |
83
43
 
84
44
  ## <a name="license">⚖️ License</a>
85
45
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@esposter/shared-node",
3
- "version": "4.3.3",
3
+ "version": "4.4.0",
4
4
  "description": "Node-only shared tooling: the machine-wide download cache, hidden-window child processes, and benchmark reporting reused across packages.",
5
5
  "keywords": [
6
6
  "benchmark",
@@ -47,15 +47,15 @@
47
47
  "lint": "eslint .",
48
48
  "lint:fix": "eslint --fix .",
49
49
  "test": "vitest",
50
- "typecheck": "tsc"
50
+ "typecheck": "tsrs --fast"
51
51
  },
52
52
  "dependencies": {
53
- "@esposter/shared": "4.3.3"
53
+ "@esposter/shared": "4.4.0"
54
54
  },
55
55
  "devDependencies": {
56
- "@esposter/configuration": "4.3.3",
57
- "@types/node": "^26.6.5",
58
- "tsdown": "^0.23.1"
56
+ "@esposter/configuration": "4.4.0",
57
+ "@types/node": "^26.6.6",
58
+ "tsdown": "0.23.2"
59
59
  },
60
60
  "peerDependencies": {
61
61
  "vitest": "^5.0.5"
@@ -65,5 +65,5 @@
65
65
  "optional": true
66
66
  }
67
67
  },
68
- "gitHead": "955bbc130ad9b28877fd4ae8efc73a045141ce01"
68
+ "gitHead": "e1a416c4b91da69cc2aa259b50a4d656f204d272"
69
69
  }
package/dist/bench.d.ts DELETED
@@ -1,3 +0,0 @@
1
- import { BenchCompareOptions } from "vitest";
2
- export declare const BASELINE_TASK_NAME = "native";
3
- export declare const BENCHMARK_RUN_OPTIONS: BenchCompareOptions;
package/dist/bench.js DELETED
@@ -1,9 +0,0 @@
1
- // src/services/constants.ts
2
- const BASELINE_TASK_NAME = "native";
3
- const BENCHMARK_RUN_OPTIONS = {
4
- iterations: 10,
5
- time: 0,
6
- warmupIterations: 5,
7
- warmupTime: 0
8
- };
9
- export { BASELINE_TASK_NAME, BENCHMARK_RUN_OPTIONS };
package/dist/cache.d.ts DELETED
@@ -1,3 +0,0 @@
1
- export declare const CACHE_ROOT: string;
2
- export declare const CONTENT_CACHE_DIRECTORY: string;
3
- export declare const readContentAddressedObject: (hash: string, download: () => Promise<Uint8Array>, directory?: string) => Promise<Buffer>;
package/dist/cache.js DELETED
@@ -1,27 +0,0 @@
1
- import { InvalidOperationError, Operation, SITE_NAME, getResultAsync, noop } from "@esposter/shared";
2
- import { homedir } from "node:os";
3
- import { join } from "node:path";
4
- import { createHash } from "node:crypto";
5
- import { existsSync } from "node:fs";
6
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
7
- // src/services/cache/constants.ts
8
- const CACHE_ROOT = join(homedir(), SITE_NAME, "cache");
9
- const CONTENT_CACHE_DIRECTORY = join(CACHE_ROOT, "content");
10
- // src/services/cache/readContentAddressedObject.ts
11
- const SHA_256_HEX_REGEX = /^[0-9a-f]{64}$/u;
12
- const readContentAddressedObject = async (hash, download, directory = CONTENT_CACHE_DIRECTORY) => {
13
- if (!SHA_256_HEX_REGEX.test(hash)) throw new InvalidOperationError(Operation.Read, hash, "is not a SHA-256 hex digest");
14
- const path = join(directory, hash);
15
- if (existsSync(path)) return readFile(path);
16
- const bytes = Buffer.from(await download());
17
- if (createHash("sha256").update(bytes).digest("hex") !== hash) throw new InvalidOperationError(Operation.Read, hash, "does not hash to its name");
18
- await mkdir(directory, { recursive: true });
19
- const temporaryPath = `${path}.${crypto.randomUUID()}.part`;
20
- await writeFile(temporaryPath, bytes);
21
- await getResultAsync(() => rename(temporaryPath, path)).match(noop, async (error) => {
22
- await rm(temporaryPath, { force: true });
23
- if (!existsSync(path)) throw error;
24
- });
25
- return bytes;
26
- };
27
- export { CACHE_ROOT, CONTENT_CACHE_DIRECTORY, readContentAddressedObject };
@@ -1,6 +0,0 @@
1
- import { execFile as execFile$1, execFileSync as execFileSync$1, execSync as execSync$1, spawn as spawn$1, spawnSync as spawnSync$1 } from "node:child_process";
2
- export declare const execFile: typeof execFile$1;
3
- export declare const execFileSync: typeof execFileSync$1;
4
- export declare const execSync: typeof execSync$1;
5
- export declare const spawn: typeof spawn$1;
6
- export declare const spawnSync: typeof spawnSync$1;
@@ -1,13 +0,0 @@
1
- import { n as withHiddenWindow, t as execSync } from "./execSync-DCcbOCo8.js";
2
- import { execFile as execFile$1, execFileSync as execFileSync$1, spawn as spawn$1, spawnSync as spawnSync$1 } from "node:child_process";
3
- import { promisify } from "node:util";
4
- // src/services/childProcess/execFile.ts
5
- const execFile = ((file, ...parameters) => execFile$1(file, ...withHiddenWindow(parameters)));
6
- Object.defineProperty(execFile, promisify.custom, { value: (file, ...parameters) => promisify(execFile$1)(file, ...withHiddenWindow(parameters)) });
7
- // src/services/childProcess/execFileSync.ts
8
- const execFileSync = ((file, ...parameters) => execFileSync$1(file, ...withHiddenWindow(parameters)));
9
- // src/services/childProcess/spawn.ts
10
- const spawn = ((file, ...parameters) => spawn$1(file, ...withHiddenWindow(parameters)));
11
- // src/services/childProcess/spawnSync.ts
12
- const spawnSync = ((file, ...parameters) => spawnSync$1(file, ...withHiddenWindow(parameters)));
13
- export { execFile, execFileSync, execSync, spawn, spawnSync };
@@ -1,15 +0,0 @@
1
- import { execSync } from "node:child_process";
2
- // src/services/childProcess/withHiddenWindow.ts
3
- const withHiddenWindow = (parameters) => {
4
- const optionsIndex = Array.isArray(parameters[0]) || parameters[0] === void 0 && parameters.length > 1 ? 1 : 0;
5
- const options = parameters[optionsIndex];
6
- if (typeof options === "object" && options !== null) return parameters.toSpliced(optionsIndex, 1, {
7
- ...options,
8
- windowsHide: true
9
- });
10
- const isPlaceholder = options === void 0 && optionsIndex < parameters.length;
11
- return parameters.toSpliced(optionsIndex, Number(isPlaceholder), { windowsHide: true });
12
- };
13
- // src/services/childProcess/execSync.ts
14
- const execSync$1 = ((command, ...parameters) => execSync(command, ...withHiddenWindow(parameters)));
15
- export { withHiddenWindow as n, execSync$1 as t };
@@ -1,4 +0,0 @@
1
- import { Reporter, TestModule } from "vitest/node";
2
- export default class BenchmarkMarkdownReporter implements Reporter {
3
- onTestRunEnd(testModules: readonly TestModule[]): Promise<void>;
4
- }
package/dist/reporter.js DELETED
@@ -1,128 +0,0 @@
1
- import "./bench.js";
2
- import { t as execSync } from "./execSync-DCcbOCo8.js";
3
- import { GIBIBYTE, InvalidOperationError, Operation, getResult, getResultAsync, noop, normalizeString, takeOne } from "@esposter/shared";
4
- import { arch, cpus, platform, release, totalmem } from "node:os";
5
- import { writeFile } from "node:fs/promises";
6
- // src/services/readBenchmarkEnvironment.ts
7
- const readCommit = () => getResult(() => execSync("git rev-parse --short HEAD", {
8
- encoding: "utf8",
9
- stdio: "pipe"
10
- })).match((stdout) => normalizeString(stdout), () => "unknown");
11
- const readBenchmarkEnvironment = () => {
12
- const cpu = cpus();
13
- return [
14
- `- Date: ${(/* @__PURE__ */ new Date()).toISOString()}`,
15
- `- Commit: ${readCommit()}`,
16
- `- Node: ${process.version}`,
17
- `- OS: ${platform()} ${release()} (${arch()})`,
18
- `- CPU: ${normalizeString(cpu[0]?.model) || "unknown"} × ${cpu.length}`,
19
- `- RAM: ${(totalmem() / GIBIBYTE).toFixed(1)} GiB`
20
- ].join("\n");
21
- };
22
- // src/services/buildBenchmarkFileReport.ts
23
- const getGroupName = (testCase, benchmarkName, benchmarkCount) => benchmarkCount > 1 ? `${testCase.fullName} > ${benchmarkName}` : testCase.fullName;
24
- const buildBenchmarkFileReport = (filepath, testCases) => {
25
- const groups = [];
26
- for (const testCase of testCases) {
27
- const testCaseBenchmarks = testCase.benchmarks();
28
- for (const { name, tasks } of testCaseBenchmarks) {
29
- const benchmarks = [];
30
- for (const task of tasks.toSorted((firstTask, secondTask) => firstTask.rank - secondTask.rank)) {
31
- if (!Number.isFinite(task.latency.mean)) throw new InvalidOperationError(Operation.Read, testCase.fullName, `benchmark "${task.name}" produced no samples — it likely threw on every iteration`);
32
- benchmarks.push({
33
- mean: task.latency.mean,
34
- name: task.name,
35
- p99: task.latency.p99,
36
- rme: task.latency.rme,
37
- sampleCount: task.latency.samplesCount
38
- });
39
- }
40
- if (benchmarks.length > 0) groups.push({
41
- benchmarks,
42
- fullName: getGroupName(testCase, name, testCaseBenchmarks.length)
43
- });
44
- }
45
- }
46
- return { files: [{
47
- filepath,
48
- groups
49
- }] };
50
- };
51
- // src/services/formatBenchmarkMarkdown.ts
52
- const getBaseline = (benchmarks) => benchmarks.find(({ name }) => name === "native") ?? benchmarks[0];
53
- const formatRelative = (baselineMean, mean) => {
54
- const ratio = baselineMean / mean;
55
- return `${ratio >= 1 ? ratio.toFixed(2) : Number(ratio.toPrecision(2))}×`;
56
- };
57
- const HEADER = [
58
- "task",
59
- "vs base",
60
- "mean (ms)",
61
- "±rme",
62
- "p99 (ms)",
63
- "samples"
64
- ];
65
- const formatTable = (rows) => {
66
- const widths = rows.reduce((accumulator, row) => accumulator.map((width, index) => Math.max(width, takeOne(row, index).length)), HEADER.map((header) => header.length));
67
- const formatRow = (cells) => `| ${cells.map((cell, index) => cell.padEnd(takeOne(widths, index))).join(" | ")} |`;
68
- return [
69
- formatRow(HEADER),
70
- `| ${widths.map((width) => "-".repeat(width)).join(" | ")} |`,
71
- ...rows.map((row) => formatRow(row))
72
- ];
73
- };
74
- const formatBenchmarkMarkdown = (report, environment) => {
75
- return [
76
- "# Benchmark results",
77
- "",
78
- "Auto-generated by the BenchmarkMarkdownReporter on `pnpm bench`, colocated beside the bench file (a",
79
- "`.bench.json` sits next to it). Diff over time to catch regressions. Tasks are listed fastest first.",
80
- "`vs base` is a throughput multiplier against each group's baseline (the `native` task, else the",
81
- "fastest): `1.00×` is the baseline, higher is faster, lower is slower — a fast task drifting back",
82
- "toward `1.00×` is a regression. `±rme` is the relative margin of error.",
83
- "Numbers are machine- and commit-dependent (see Environment); only compare runs from the same host.",
84
- "",
85
- "## Environment",
86
- "",
87
- environment,
88
- "",
89
- ...report.files.flatMap((file) => file.groups.map((group) => {
90
- const baselineMean = getBaseline(group.benchmarks)?.mean ?? NaN;
91
- const rows = group.benchmarks.map(({ mean, name, p99, rme, sampleCount }) => [
92
- name.replaceAll("|", String.raw`\|`),
93
- formatRelative(baselineMean, mean),
94
- mean.toFixed(4),
95
- `±${rme.toFixed(2)}%`,
96
- p99.toFixed(4),
97
- `${sampleCount}`
98
- ]);
99
- return [
100
- `## ${group.fullName}`,
101
- "",
102
- ...formatTable(rows),
103
- ""
104
- ].join("\n");
105
- }))
106
- ].join("\n");
107
- };
108
- // src/services/writeBenchmarkReport.ts
109
- const TS_EXTENSION_REGEX = /\.ts$/u;
110
- const writeFileOrThrow = (path, contents) => getResultAsync(() => writeFile(path, contents)).match(noop, (error) => {
111
- throw new InvalidOperationError(Operation.Create, path, error.message);
112
- });
113
- const writeBenchmarkReport = async (moduleId, relativeModuleId, testCases, environment) => {
114
- const report = buildBenchmarkFileReport(relativeModuleId, testCases);
115
- const [benchmarkFile] = report.files;
116
- if (benchmarkFile === void 0 || benchmarkFile.groups.length === 0) return;
117
- const basePath = moduleId.replace(TS_EXTENSION_REGEX, "");
118
- const reportPath = basePath.endsWith(".platform.bench") ? `${basePath}.${process.platform}` : basePath;
119
- await Promise.all([writeFileOrThrow(`${reportPath}.json`, `${JSON.stringify(report, null, 2)}\n`), writeFileOrThrow(`${reportPath}.md`, formatBenchmarkMarkdown(report, environment))]);
120
- };
121
- // src/services/BenchmarkMarkdownReporter.ts
122
- var BenchmarkMarkdownReporter = class {
123
- async onTestRunEnd(testModules) {
124
- const environment = readBenchmarkEnvironment();
125
- await Promise.all(testModules.map((testModule) => writeBenchmarkReport(testModule.moduleId, testModule.relativeModuleId, testModule.children.allTests(), environment)));
126
- }
127
- };
128
- export { BenchmarkMarkdownReporter as default };