@emesoft/tokenhub 0.8.14 → 0.9.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.
@@ -0,0 +1,227 @@
1
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { run as defaultRun } from "./run.js";
4
+
5
+ /** First and last line of the block `connect` adds to a shell profile on macOS; `disconnect` removes exactly what is between them. */
6
+ export const PROFILE_BEGIN = "# >>> tokenhub remote (written by `tokenhub connect`, removed by `tokenhub disconnect`) >>>";
7
+ export const PROFILE_END = "# <<< tokenhub remote <<<";
8
+ /** The PowerShell that reads and writes the user's `Path` value in the registry (see `windowsUserPath`). */
9
+ const REGISTRY_SCRIPT = `
10
+ $ErrorActionPreference = 'Stop'
11
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false
12
+ $sub = $env:TOKENHUB_PS_KEY
13
+ $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($sub)
14
+ $name = 'Path'
15
+ switch ($env:TOKENHUB_PS_MODE) {
16
+ 'get' {
17
+ $raw = $key.GetValue($name, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
18
+ if ($null -eq $raw) { Write-Output '{"value":null,"kind":"ExpandString"}' }
19
+ else { Write-Output (ConvertTo-Json -Compress @{ value = [string]$raw; kind = $key.GetValueKind($name).ToString() }) }
20
+ }
21
+ 'set' { $key.SetValue($name, $env:TOKENHUB_PS_VALUE, [Microsoft.Win32.RegistryValueKind]$env:TOKENHUB_PS_KIND) }
22
+ 'delete' { $key.DeleteValue($name, $false) }
23
+ }
24
+ $key.Close()
25
+ if ($env:TOKENHUB_PS_MODE -ne 'get' -and $sub -eq 'Environment') {
26
+ Add-Type -Namespace TokenHub -Name Native -MemberDefinition '[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint flags, uint timeout, out UIntPtr result);'
27
+ $result = [UIntPtr]::Zero
28
+ [void][TokenHub.Native]::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$result)
29
+ }
30
+ `;
31
+ /** @param {string} dir A folder. @param {string} platform Node platform name. @returns {string} It in the form PATH entries are compared in. */
32
+ function key(dir, platform) {
33
+ const trimmed = dir.trim().replace(/^"(.*)"$/, "$1").replace(/[\\/]+$/, "");
34
+ return platform === "win32" ? trimmed.toLowerCase().replace(/\//g, "\\") : trimmed;
35
+ }
36
+ /**
37
+ * @param {string | null} value A PATH value.
38
+ * @param {string} platform Node platform name.
39
+ * @returns {string[]} Its non-empty entries in comparison form.
40
+ */
41
+ function pathEntries(value, platform) {
42
+ return String(value ?? "")
43
+ .split(platform === "win32" ? ";" : ":")
44
+ .filter((entry) => entry.trim() !== "")
45
+ .map((entry) => key(entry, platform));
46
+ }
47
+ /**
48
+ * Whether a PATH value has `dir` among its entries.
49
+ * @param {string | null} value A PATH value.
50
+ * @param {string} dir The folder.
51
+ * @param {string} [platform] Node platform name.
52
+ * @returns {boolean} True when it does.
53
+ */
54
+ export function hasPathEntry(value, dir, platform = process.platform) {
55
+ return pathEntries(value, platform).includes(key(dir, platform));
56
+ }
57
+ /**
58
+ * A PATH value with `dir` in front (and removed from wherever it was before). Entries are kept as they are; empty ones go.
59
+ * @param {string | null} value The current value (null when there is none).
60
+ * @param {string} dir The folder to put first.
61
+ * @param {string} [platform] Node platform name; Windows compares case-insensitively and separates with `;`.
62
+ * @returns {string} The new value.
63
+ */
64
+ export function addPathEntry(value, dir, platform = process.platform) {
65
+ const sep = platform === "win32" ? ";" : ":";
66
+ if (pathEntries(value, platform)[0] === key(dir, platform)) return String(value);
67
+ const rest = removePathEntry(value, dir, platform);
68
+ return rest ? [dir, rest].join(sep) : dir;
69
+ }
70
+ /**
71
+ * A PATH value without `dir`.
72
+ * @param {string | null} value The current value.
73
+ * @param {string} dir The folder to take out.
74
+ * @param {string} [platform] Node platform name.
75
+ * @returns {string} The new value; entries other than `dir` are kept as they are (empty ones go).
76
+ */
77
+ export function removePathEntry(value, dir, platform = process.platform) {
78
+ const sep = platform === "win32" ? ";" : ":";
79
+ const target = key(dir, platform);
80
+ return String(value ?? "")
81
+ .split(sep)
82
+ .filter((entry) => entry.trim() !== "" && key(entry, platform) !== target)
83
+ .join(sep);
84
+ }
85
+ /**
86
+ * The marked block for a shell profile.
87
+ * @param {string} dir The folder to put first on PATH.
88
+ * @returns {string} The lines, without a final newline.
89
+ */
90
+ export function profileBlock(dir) {
91
+ return [PROFILE_BEGIN, `export PATH='${dir.replace(/'/g, `'\\''`)}':"$PATH"`, PROFILE_END].join("\n");
92
+ }
93
+ /**
94
+ * A profile's text with the block at the end (an earlier block of ours is replaced, so running twice adds nothing).
95
+ * @param {string} text The profile's current text ("" when it does not exist).
96
+ * @param {string} dir The folder to put first on PATH.
97
+ * @returns {string} The new text.
98
+ */
99
+ export function addProfileBlock(text, dir) {
100
+ const clean = removeProfileBlock(text).text;
101
+ if (clean === "") return `${profileBlock(dir)}\n`;
102
+ return `${clean.endsWith("\n") ? clean : `${clean}\n`}\n${profileBlock(dir)}\n`;
103
+ }
104
+ /**
105
+ * A profile's text without our block (the blank line added before it goes too). Lines outside the block are untouched.
106
+ * @param {string} text The profile's text.
107
+ * @returns {{ text: string, removed: boolean }} The new text and whether a block was there.
108
+ */
109
+ export function removeProfileBlock(text) {
110
+ const start = text.indexOf(PROFILE_BEGIN);
111
+ if (start === -1) return { text, removed: false };
112
+ const endAt = text.indexOf(PROFILE_END, start);
113
+ if (endAt === -1) return { text, removed: false };
114
+ let end = endAt + PROFILE_END.length;
115
+ if (text[end] === "\n") end += 1;
116
+ let from = start;
117
+ if (text.slice(from - 2, from) === "\n\n") from -= 1;
118
+ return { text: text.slice(0, from) + text.slice(end), removed: true };
119
+ }
120
+ /**
121
+ * The profiles `connect` edits on macOS: `~/.zprofile` (created when missing, it is the default shell's) and `~/.bash_profile` (only
122
+ * when it exists).
123
+ * @param {string} home Home directory.
124
+ * @returns {Array<{ file: string, create: boolean }>} The files.
125
+ */
126
+ export function profileFiles(home) {
127
+ return [
128
+ { file: join(home, ".zprofile"), create: true },
129
+ { file: join(home, ".bash_profile"), create: false },
130
+ ];
131
+ }
132
+ /**
133
+ * Access to the user's `Path` in the registry (`HKCU\Environment`), through Windows PowerShell and .NET so the raw, unexpanded value
134
+ * and its type (`ExpandString` keeps `%USERPROFILE%` entries working) survive and non-ASCII folder names are not mangled; a write
135
+ * tells every open window the environment changed.
136
+ *
137
+ * @param {object} [options]
138
+ * @param {import("./run.js").Runner} [options.run] Runs a program (tests replace it).
139
+ * @param {string} [options.subKey] Key under HKCU; only a test uses another one (a scratch key, which is also not broadcast).
140
+ * @returns {{ get: () => Promise<{ value: string | null, kind: string }>, set: (value: string | null, kind: string) => Promise<void> }} Reader and writer; `set(null)` deletes the value.
141
+ */
142
+ export function windowsUserPath({ run = defaultRun, subKey = "Environment" } = {}) {
143
+ const encoded = Buffer.from(REGISTRY_SCRIPT, "utf16le").toString("base64");
144
+ const call = async (mode, extra = {}) => {
145
+ const env = { ...process.env, TOKENHUB_PS_KEY: subKey, TOKENHUB_PS_MODE: mode, ...extra };
146
+ const result = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], { env, timeoutMs: 60_000 });
147
+ if (result.code !== 0) throw new Error(`Could not ${mode} the user PATH (${result.stderr.trim().split("\n")[0] || `exit ${result.code}`}).`);
148
+ return result.stdout.replace(/^/, "").trim();
149
+ };
150
+ return {
151
+ async get() {
152
+ const parsed = JSON.parse(await call("get"));
153
+ return { value: parsed.value ?? null, kind: parsed.kind === "String" ? "String" : "ExpandString" };
154
+ },
155
+ async set(value, kind) {
156
+ if (value === null) await call("delete");
157
+ else await call("set", { TOKENHUB_PS_VALUE: value, TOKENHUB_PS_KIND: kind });
158
+ },
159
+ };
160
+ }
161
+ /**
162
+ * Put `dir` first on the user's PATH: the registry value on Windows, a marked block in the shell profiles on macOS.
163
+ *
164
+ * @param {object} options
165
+ * @param {string} options.dir The folder (`~/.tokenhub/bin`).
166
+ * @param {string} options.platform `win32` or `darwin`.
167
+ * @param {string} options.home Home directory (where the profiles are).
168
+ * @param {ReturnType<typeof windowsUserPath>} [options.userPath] The registry access; only used on Windows.
169
+ * @returns {Promise<{ changed: boolean, targets: Array<{ kind: "registry" } | { kind: "profile", file: string }> }>} Whether anything was written, and what holds the entry now (kept for `disconnect`).
170
+ * @throws {Error} When the registry or a profile cannot be written; nothing else is touched then.
171
+ * @sideEffect A profile that exists is copied to `<file>.tokenhub.bak` first, once (an existing backup is kept: it is the original).
172
+ */
173
+ export async function addBinToPath({ dir, platform, home, userPath = windowsUserPath() }) {
174
+ if (platform === "win32") {
175
+ const { value, kind } = await userPath.get();
176
+ const next = addPathEntry(value, dir, "win32");
177
+ if (next === value) return { changed: false, targets: [{ kind: "registry" }] };
178
+ await userPath.set(next, kind);
179
+ return { changed: true, targets: [{ kind: "registry" }] };
180
+ }
181
+ let changed = false;
182
+ const targets = [];
183
+ for (const { file, create } of profileFiles(home)) {
184
+ const exists = existsSync(file);
185
+ if (!exists && !create) continue;
186
+ const before = exists ? readFileSync(file, "utf8") : "";
187
+ const after = addProfileBlock(before, dir);
188
+ targets.push({ kind: "profile", file });
189
+ if (after === before) continue;
190
+ mkdirSync(dirname(file), { recursive: true });
191
+ if (exists && !existsSync(`${file}.tokenhub.bak`)) copyFileSync(file, `${file}.tokenhub.bak`);
192
+ writeFileSync(file, after);
193
+ changed = true;
194
+ }
195
+ return { changed, targets };
196
+ }
197
+ /**
198
+ * Undo `addBinToPath`: take `dir` out of the user's PATH (Windows) or our block out of the profiles (macOS). Only that entry or block
199
+ * is touched; a profile left empty is deleted, since only our block was in it.
200
+ *
201
+ * @param {object} options
202
+ * @param {string} options.dir The folder.
203
+ * @param {string} options.platform `win32` or `darwin`.
204
+ * @param {string} options.home Home directory.
205
+ * @param {ReturnType<typeof windowsUserPath>} [options.userPath] The registry access; only used on Windows.
206
+ * @returns {Promise<{ changed: boolean }>} Whether anything was written.
207
+ */
208
+ export async function removeBinFromPath({ dir, platform, home, userPath = windowsUserPath() }) {
209
+ if (platform === "win32") {
210
+ const { value, kind } = await userPath.get();
211
+ if (value === null || !hasPathEntry(value, dir, "win32")) return { changed: false };
212
+ const next = removePathEntry(value, dir, "win32");
213
+ await userPath.set(next === "" ? null : next, kind);
214
+ return { changed: true };
215
+ }
216
+ let changed = false;
217
+ for (const { file } of profileFiles(home)) {
218
+ if (!existsSync(file)) continue;
219
+ const before = readFileSync(file, "utf8");
220
+ const { text, removed } = removeProfileBlock(before);
221
+ if (!removed) continue;
222
+ if (text.trim() === "") rmSync(file);
223
+ else writeFileSync(file, text);
224
+ changed = true;
225
+ }
226
+ return { changed };
227
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@emesoft/tokenhub",
3
- "version": "0.8.14",
3
+ "version": "0.9.0",
4
4
  "description": "Connect Claude Code to a TokenHub pool in one command, and track your spend from the terminal",
5
5
  "keywords": [
6
6
  "claude",