@narumitw/pi-starship 0.59.1 → 0.60.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 +29 -3
- package/dist/chunks/{chunk-MTFSZ63Q.ts → chunk-KZZKGGFW.ts} +327 -42
- package/dist/chunks/chunk-KZZKGGFW.ts.map +7 -0
- package/dist/chunks/{commands-M6GHLJIR.ts → commands-C2VJ6ZBN.ts} +1281 -111
- package/dist/chunks/commands-C2VJ6ZBN.ts.map +7 -0
- package/dist/index.ts +25 -9
- package/dist/index.ts.map +2 -2
- package/package.json +4 -4
- package/skills/configure-pi-starship/SKILL.md +5 -1
- package/skills/configure-pi-starship/references/configuration.md +122 -11
- package/skills/configure-pi-starship/scripts/apply.mjs +87 -33
- package/skills/configure-pi-starship/scripts/backup.mjs +17 -0
- package/src/command-commit.ts +169 -0
- package/src/command-configuration.ts +80 -34
- package/src/command-gist.ts +11 -3
- package/src/command-preset-picker.ts +6 -2
- package/src/command-profiles.ts +664 -0
- package/src/commands.ts +223 -77
- package/src/config.ts +112 -14
- package/src/format/formatter.ts +8 -4
- package/src/format/style.ts +54 -15
- package/src/format/terminal-safety.ts +80 -0
- package/src/format/theme-colors.ts +69 -0
- package/src/modules/model.ts +1 -1
- package/src/modules/render.ts +75 -5
- package/src/pi-starship.ts +22 -6
- package/src/profile-store.ts +526 -0
- package/dist/chunks/chunk-MTFSZ63Q.ts.map +0 -7
- package/dist/chunks/commands-M6GHLJIR.ts.map +0 -7
package/src/pi-starship.ts
CHANGED
|
@@ -90,6 +90,7 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
|
|
|
90
90
|
};
|
|
91
91
|
let sessionGeneration = 0;
|
|
92
92
|
let menuController = new AbortController();
|
|
93
|
+
let commandInFlight: object | undefined;
|
|
93
94
|
let sessionOwner: ExtensionContext["sessionManager"] | undefined;
|
|
94
95
|
let activeTarget: RefreshTarget | undefined;
|
|
95
96
|
let eventDebounceTimer: ReturnType<typeof setTimeout> | undefined;
|
|
@@ -241,6 +242,7 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
|
|
|
241
242
|
|
|
242
243
|
const installFooter = (ctx: ExtensionContext) => {
|
|
243
244
|
const generation = ++sessionGeneration;
|
|
245
|
+
commandInFlight = undefined;
|
|
244
246
|
sessionOwner = ctx.sessionManager;
|
|
245
247
|
previewLoaded = undefined;
|
|
246
248
|
menuController.abort(new DOMException("Starship session context replaced", "AbortError"));
|
|
@@ -263,12 +265,12 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
|
|
|
263
265
|
workspaceController.start(generation);
|
|
264
266
|
startGithubPr(target);
|
|
265
267
|
|
|
266
|
-
ctx.ui.setFooter((tui,
|
|
268
|
+
ctx.ui.setFooter((tui, theme, footerData) => {
|
|
267
269
|
runtime.requestRender = () => tui.requestRender();
|
|
268
270
|
runtime.renderPreview = (preview, width) => {
|
|
269
271
|
const snapshot = runtimeSnapshot(ctx, footerData, runtime);
|
|
270
272
|
return wrapFormattedStatusline(
|
|
271
|
-
renderStatusline(preview.config, snapshot, width, getCapabilities().trueColor).ansi,
|
|
273
|
+
renderStatusline(preview.config, snapshot, width, getCapabilities().trueColor, theme.colors).ansi,
|
|
272
274
|
width,
|
|
273
275
|
);
|
|
274
276
|
};
|
|
@@ -308,6 +310,7 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
|
|
|
308
310
|
{ ...lastRender.snapshot, now },
|
|
309
311
|
lastRender.width,
|
|
310
312
|
getCapabilities().trueColor,
|
|
313
|
+
theme.colors,
|
|
311
314
|
).ansi,
|
|
312
315
|
lastRender.width,
|
|
313
316
|
);
|
|
@@ -344,7 +347,7 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
|
|
|
344
347
|
if (!current) return [];
|
|
345
348
|
const snapshot = runtimeSnapshot(ctx, footerData, runtime);
|
|
346
349
|
const lines = wrapFormattedStatusline(
|
|
347
|
-
renderStatusline(current.config, snapshot, width, getCapabilities().trueColor).ansi,
|
|
350
|
+
renderStatusline(current.config, snapshot, width, getCapabilities().trueColor, theme.colors).ansi,
|
|
348
351
|
width,
|
|
349
352
|
);
|
|
350
353
|
lastRender = { snapshot, lines, config: current.config, width };
|
|
@@ -401,9 +404,21 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
|
|
|
401
404
|
description: "Customize or inspect the native Starship-style footer",
|
|
402
405
|
getArgumentCompletions: completeStarshipArguments,
|
|
403
406
|
handler: async (args, ctx) => {
|
|
404
|
-
const
|
|
405
|
-
if (
|
|
406
|
-
|
|
407
|
+
const interactive = ctx.mode === "tui" && (!args.trim() || args.trim().toLowerCase() === "settings");
|
|
408
|
+
if (interactive && commandInFlight) {
|
|
409
|
+
ctx.ui.notify("A pi-starship configuration workflow is already open.", "info");
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
const token = interactive ? {} : undefined;
|
|
413
|
+
if (token) commandInFlight = token;
|
|
414
|
+
const generation = sessionGeneration;
|
|
415
|
+
try {
|
|
416
|
+
const commands = await loadStarshipCommands();
|
|
417
|
+
if (sessionOwner !== ctx.sessionManager || generation !== sessionGeneration) return;
|
|
418
|
+
await commands.handleStarshipCommand(args, ctx, commandOptions);
|
|
419
|
+
} finally {
|
|
420
|
+
if (token && commandInFlight === token) commandInFlight = undefined;
|
|
421
|
+
}
|
|
407
422
|
},
|
|
408
423
|
});
|
|
409
424
|
|
|
@@ -429,6 +444,7 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
|
|
|
429
444
|
pi.on("session_shutdown", (_event, ctx) => {
|
|
430
445
|
if (sessionOwner !== ctx.sessionManager) return;
|
|
431
446
|
sessionOwner = undefined;
|
|
447
|
+
commandInFlight = undefined;
|
|
432
448
|
previewLoaded = undefined;
|
|
433
449
|
sessionGeneration += 1;
|
|
434
450
|
menuController.abort(new DOMException("Starship session shut down", "AbortError"));
|
|
@@ -0,0 +1,526 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
type BigIntStats,
|
|
4
|
+
closeSync,
|
|
5
|
+
constants,
|
|
6
|
+
fstatSync,
|
|
7
|
+
fsyncSync,
|
|
8
|
+
lstatSync,
|
|
9
|
+
mkdirSync,
|
|
10
|
+
openSync,
|
|
11
|
+
readdirSync,
|
|
12
|
+
readFileSync,
|
|
13
|
+
realpathSync,
|
|
14
|
+
renameSync,
|
|
15
|
+
rmdirSync,
|
|
16
|
+
unlinkSync,
|
|
17
|
+
writeFileSync,
|
|
18
|
+
} from "node:fs";
|
|
19
|
+
import { basename, dirname, join, parse, resolve, sep } from "node:path";
|
|
20
|
+
|
|
21
|
+
export interface DocumentIdentity {
|
|
22
|
+
readonly dev: bigint;
|
|
23
|
+
readonly ino: bigint;
|
|
24
|
+
readonly size: bigint;
|
|
25
|
+
readonly mtimeNs: bigint;
|
|
26
|
+
readonly ctimeNs: bigint;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface ProfileDocument {
|
|
30
|
+
readonly kind: "profile";
|
|
31
|
+
readonly name: string;
|
|
32
|
+
readonly path: string;
|
|
33
|
+
readonly rawDocument: string | undefined;
|
|
34
|
+
readonly rawBytes: Buffer;
|
|
35
|
+
readonly readError?: string;
|
|
36
|
+
readonly identity: DocumentIdentity;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface TextProfileDocument extends ProfileDocument {
|
|
40
|
+
readonly rawDocument: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface ArchiveReference {
|
|
44
|
+
readonly name: string;
|
|
45
|
+
readonly path: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface HistoryDocument {
|
|
49
|
+
readonly kind: "history";
|
|
50
|
+
/** Filename, including .toml; not an arbitrary path. */
|
|
51
|
+
readonly name: string;
|
|
52
|
+
readonly path: string;
|
|
53
|
+
/** Undefined when rawBytes are not valid UTF-8; never apply a decoded fallback. */
|
|
54
|
+
readonly rawDocument: string | undefined;
|
|
55
|
+
readonly rawBytes: Buffer;
|
|
56
|
+
readonly readError?: string;
|
|
57
|
+
readonly identity: DocumentIdentity;
|
|
58
|
+
readonly legacy: boolean;
|
|
59
|
+
/** ISO recovery time for new entries; local timestamp for legacy backups. */
|
|
60
|
+
readonly createdAt: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
type Document = ProfileDocument | HistoryDocument;
|
|
64
|
+
const HISTORY_NAME =
|
|
65
|
+
/^(\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}\.\d{3}Z)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.toml$/u;
|
|
66
|
+
const LEGACY_NAME = /^pi-starship-(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})\.toml$/u;
|
|
67
|
+
const RESERVED_NAME = /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]|conin\$|conout\$|clock\$)(?:\.|$)/iu;
|
|
68
|
+
|
|
69
|
+
/** Normalize new names, but never trim, truncate, or replace forbidden characters. */
|
|
70
|
+
export function normalizeProfileName(value: string): string {
|
|
71
|
+
const name = value.normalize("NFC");
|
|
72
|
+
if (
|
|
73
|
+
[...name].length < 1 ||
|
|
74
|
+
[...name].length > 80 ||
|
|
75
|
+
name !== name.trim() ||
|
|
76
|
+
name.startsWith(".") ||
|
|
77
|
+
name.endsWith(".") ||
|
|
78
|
+
/[\p{Cc}\p{Cf}\p{Cs}<>:"/\\|?*]/u.test(name) ||
|
|
79
|
+
RESERVED_NAME.test(name) ||
|
|
80
|
+
Buffer.byteLength(`${name}.toml`, "utf8") > 255
|
|
81
|
+
) {
|
|
82
|
+
throw new Error("Invalid profile name: use 1–80 characters without controls, path characters, or reserved names");
|
|
83
|
+
}
|
|
84
|
+
return name;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The caller supplies a trusted settings directory; its home/system symlink ancestors are valid. */
|
|
88
|
+
function trustedDirectory(path: string): string {
|
|
89
|
+
try {
|
|
90
|
+
return realpathSync(path);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (!isMissing(error)) throw error;
|
|
93
|
+
const parent = dirname(path);
|
|
94
|
+
if (parent === path) throw error;
|
|
95
|
+
return join(trustedDirectory(parent), basename(path));
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function rootPath(settingsPath: string): string {
|
|
100
|
+
return join(trustedDirectory(dirname(resolve(settingsPath))), "pi-starship");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function profileDirectory(settingsPath: string): string {
|
|
104
|
+
return join(rootPath(settingsPath), "profiles");
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function historyDirectory(settingsPath: string): string {
|
|
108
|
+
return join(rootPath(settingsPath), "history");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function isMissing(error: unknown): boolean {
|
|
112
|
+
return (error as NodeJS.ErrnoException).code === "ENOENT";
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function statIfPresent(path: string): BigIntStats | undefined {
|
|
116
|
+
try {
|
|
117
|
+
return lstatSync(path, { bigint: true });
|
|
118
|
+
} catch (error) {
|
|
119
|
+
if (isMissing(error)) return undefined;
|
|
120
|
+
throw error;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Paths already have a canonical trusted parent; reject symlinks in every storage-owned component. */
|
|
125
|
+
function checkedDirectory(path: string, create = false): boolean {
|
|
126
|
+
const absolute = resolve(path);
|
|
127
|
+
const root = parse(absolute).root;
|
|
128
|
+
let current = root;
|
|
129
|
+
for (const part of absolute.slice(root.length).split(sep).filter(Boolean)) {
|
|
130
|
+
current = join(current, part);
|
|
131
|
+
let stat = statIfPresent(current);
|
|
132
|
+
let created = false;
|
|
133
|
+
if (!stat && create) {
|
|
134
|
+
try {
|
|
135
|
+
mkdirSync(current, { mode: 0o700 });
|
|
136
|
+
} catch (error) {
|
|
137
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
138
|
+
}
|
|
139
|
+
stat = statIfPresent(current);
|
|
140
|
+
created = true;
|
|
141
|
+
}
|
|
142
|
+
if (!stat) return false;
|
|
143
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`Not a safe directory: ${current}`);
|
|
144
|
+
// Persist each new ancestor's directory entry, including a previously absent agent directory.
|
|
145
|
+
if (created) flushDirectory(dirname(current));
|
|
146
|
+
}
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function identity(stat: BigIntStats): DocumentIdentity {
|
|
151
|
+
return Object.freeze({ dev: stat.dev, ino: stat.ino, size: stat.size, mtimeNs: stat.mtimeNs, ctimeNs: stat.ctimeNs });
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function sameIdentity(left: DocumentIdentity, right: DocumentIdentity): boolean {
|
|
155
|
+
return (
|
|
156
|
+
left.dev === right.dev &&
|
|
157
|
+
left.ino === right.ino &&
|
|
158
|
+
left.size === right.size &&
|
|
159
|
+
left.mtimeNs === right.mtimeNs &&
|
|
160
|
+
left.ctimeNs === right.ctimeNs
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function sameFile(left: DocumentIdentity, right: BigIntStats): boolean {
|
|
165
|
+
return left.dev === right.dev && left.ino === right.ino;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function encodeDocument(rawDocument: string): Buffer {
|
|
169
|
+
const bytes = Buffer.from(rawDocument, "utf8");
|
|
170
|
+
if (bytes.toString("utf8") !== rawDocument) throw new Error("Document is not lossless UTF-8 text");
|
|
171
|
+
return bytes;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function readBytes(path: string): { rawBytes: Buffer; identity: DocumentIdentity } {
|
|
175
|
+
if (!checkedDirectory(dirname(path))) throw new Error(`Document directory is missing: ${dirname(path)}`);
|
|
176
|
+
const before = statIfPresent(path);
|
|
177
|
+
if (!before?.isFile() || before.isSymbolicLink()) throw new Error(`Not a regular document: ${path}`);
|
|
178
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
179
|
+
try {
|
|
180
|
+
const opened = fstatSync(fd, { bigint: true });
|
|
181
|
+
if (!opened.isFile() || !sameIdentity(identity(before), identity(opened))) {
|
|
182
|
+
throw new Error(`Document changed while opening: ${path}`);
|
|
183
|
+
}
|
|
184
|
+
const bytes = readFileSync(fd);
|
|
185
|
+
const after = fstatSync(fd, { bigint: true });
|
|
186
|
+
const published = statIfPresent(path);
|
|
187
|
+
if (
|
|
188
|
+
!sameIdentity(identity(opened), identity(after)) ||
|
|
189
|
+
!published ||
|
|
190
|
+
!sameIdentity(identity(after), identity(published))
|
|
191
|
+
) {
|
|
192
|
+
throw new Error(`Document changed while reading: ${path}`);
|
|
193
|
+
}
|
|
194
|
+
return { rawBytes: bytes, identity: identity(after) };
|
|
195
|
+
} finally {
|
|
196
|
+
closeSync(fd);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export function readProfile(settingsPath: string, name: string): ProfileDocument {
|
|
201
|
+
const normalized = normalizeProfileName(name);
|
|
202
|
+
const path = join(profileDirectory(settingsPath), `${normalized}.toml`);
|
|
203
|
+
const document = readBytes(path);
|
|
204
|
+
const decoded = document.rawBytes.toString("utf8");
|
|
205
|
+
const valid = Buffer.from(decoded, "utf8").equals(document.rawBytes);
|
|
206
|
+
return Object.freeze({
|
|
207
|
+
kind: "profile",
|
|
208
|
+
name: normalized,
|
|
209
|
+
path,
|
|
210
|
+
...document,
|
|
211
|
+
rawDocument: valid ? decoded : undefined,
|
|
212
|
+
...(valid ? {} : { readError: "Profile document is not valid UTF-8; raw bytes are preserved" }),
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function listProfiles(settingsPath: string): ProfileDocument[] {
|
|
217
|
+
const directory = profileDirectory(settingsPath);
|
|
218
|
+
if (!checkedDirectory(directory)) return [];
|
|
219
|
+
const profiles: ProfileDocument[] = [];
|
|
220
|
+
for (const filename of readdirSync(directory).sort()) {
|
|
221
|
+
if (!filename.endsWith(".toml")) continue;
|
|
222
|
+
const name = filename.slice(0, -5);
|
|
223
|
+
try {
|
|
224
|
+
if (normalizeProfileName(name) !== name) continue;
|
|
225
|
+
} catch {
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
const stat = statIfPresent(join(directory, filename));
|
|
229
|
+
if (!stat?.isFile() || stat.isSymbolicLink()) continue;
|
|
230
|
+
profiles.push(readProfile(settingsPath, name));
|
|
231
|
+
}
|
|
232
|
+
return profiles;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Sync mutations cannot interleave in one JS thread. This directory lock also coordinates
|
|
237
|
+
* cooperating store callers in other processes. Contention fails instead of blocking the event
|
|
238
|
+
* loop. A crashed owner's lock requires explicit manual recovery; never guess that a lock is stale.
|
|
239
|
+
* Node has no portable rename-no-replace operation. Collision checks + rename under this lock
|
|
240
|
+
* prevent cooperative clobbering, NOT races with external editors or directory replacement.
|
|
241
|
+
* There is no portable openat/renameat API here; external directory TOCTOU remains as well.
|
|
242
|
+
*/
|
|
243
|
+
function mutate<T>(settingsPath: string, operation: () => T): T {
|
|
244
|
+
const root = rootPath(settingsPath);
|
|
245
|
+
checkedDirectory(root, true);
|
|
246
|
+
const lock = join(root, ".mutation-lock");
|
|
247
|
+
try {
|
|
248
|
+
mkdirSync(lock, { mode: 0o700 });
|
|
249
|
+
} catch (error) {
|
|
250
|
+
if ((error as NodeJS.ErrnoException).code === "EEXIST") {
|
|
251
|
+
throw new Error(`Profile/history storage is locked; inspect the owner before manually removing ${lock}`);
|
|
252
|
+
}
|
|
253
|
+
throw error;
|
|
254
|
+
}
|
|
255
|
+
const owned = lstatSync(lock, { bigint: true });
|
|
256
|
+
let result!: T;
|
|
257
|
+
let operationError: unknown;
|
|
258
|
+
let failed = false;
|
|
259
|
+
try {
|
|
260
|
+
result = operation();
|
|
261
|
+
} catch (error) {
|
|
262
|
+
failed = true;
|
|
263
|
+
operationError = error;
|
|
264
|
+
}
|
|
265
|
+
try {
|
|
266
|
+
const current = statIfPresent(lock);
|
|
267
|
+
if (current?.isDirectory() && sameFile(identity(owned), current)) rmdirSync(lock);
|
|
268
|
+
} catch (error) {
|
|
269
|
+
if (failed) throw new AggregateError([operationError, error], `Mutation and lock cleanup failed at ${lock}`);
|
|
270
|
+
throw new Error(`Mutation completed but lock cleanup failed at ${lock}`, { cause: error });
|
|
271
|
+
}
|
|
272
|
+
if (failed) throw operationError;
|
|
273
|
+
return result;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Conservative Unicode caseless key, including expansions such as ß -> ss and final sigma. */
|
|
277
|
+
function collisionKey(name: string): string {
|
|
278
|
+
// A second pass includes uppercase sharp S (ẞ -> ß -> ss).
|
|
279
|
+
return name.normalize("NFC").toUpperCase().toLowerCase().toUpperCase().toLowerCase().normalize("NFC");
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function assertAvailable(directory: string, filename: string): void {
|
|
283
|
+
const key = collisionKey(filename);
|
|
284
|
+
if (readdirSync(directory).some((entry) => collisionKey(entry) === key)) {
|
|
285
|
+
throw new Error(`Document name already exists: ${filename}`);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function assertExpected<T extends Document>(current: T, expected: T): void {
|
|
290
|
+
if (
|
|
291
|
+
current.kind !== expected.kind ||
|
|
292
|
+
current.path !== expected.path ||
|
|
293
|
+
current.name !== expected.name ||
|
|
294
|
+
current.rawDocument !== expected.rawDocument ||
|
|
295
|
+
!current.rawBytes.equals(expected.rawBytes) ||
|
|
296
|
+
!sameIdentity(current.identity, expected.identity)
|
|
297
|
+
) {
|
|
298
|
+
throw new Error(`Document changed since review: ${current.path}`);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function flushDirectory(path: string): void {
|
|
303
|
+
// Windows does not support opening/fsyncing directories through this API.
|
|
304
|
+
// File flushing still applies; directory-entry crash durability is POSIX-only.
|
|
305
|
+
if (process.platform === "win32") return;
|
|
306
|
+
checkedDirectory(path);
|
|
307
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_DIRECTORY);
|
|
308
|
+
try {
|
|
309
|
+
fsyncSync(fd);
|
|
310
|
+
} finally {
|
|
311
|
+
closeSync(fd);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function flushMutation(directory: string, path: string): void {
|
|
316
|
+
try {
|
|
317
|
+
flushDirectory(directory);
|
|
318
|
+
} catch (error) {
|
|
319
|
+
throw new Error(`Mutation completed at ${path}, but directory flush failed: ${String(error)}`, { cause: error });
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Published files are never removed on a subsequent flush/read failure. */
|
|
324
|
+
function publish(directory: string, filename: string, bytes: Buffer, beforeRename: () => void): void {
|
|
325
|
+
const temporary = join(directory, `.tmp-${randomUUID()}`);
|
|
326
|
+
const fd = openSync(
|
|
327
|
+
temporary,
|
|
328
|
+
constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,
|
|
329
|
+
0o600,
|
|
330
|
+
);
|
|
331
|
+
const owned = fstatSync(fd, { bigint: true });
|
|
332
|
+
let open = true;
|
|
333
|
+
try {
|
|
334
|
+
writeFileSync(fd, bytes);
|
|
335
|
+
fsyncSync(fd);
|
|
336
|
+
closeSync(fd);
|
|
337
|
+
open = false;
|
|
338
|
+
checkedDirectory(directory);
|
|
339
|
+
beforeRename();
|
|
340
|
+
const destination = join(directory, filename);
|
|
341
|
+
renameSync(temporary, destination);
|
|
342
|
+
flushMutation(directory, destination);
|
|
343
|
+
} finally {
|
|
344
|
+
try {
|
|
345
|
+
if (open) closeSync(fd);
|
|
346
|
+
} finally {
|
|
347
|
+
const current = statIfPresent(temporary);
|
|
348
|
+
if (current && sameFile(identity(owned), current)) unlinkSync(temporary);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function readTextProfile(settingsPath: string, name: string): TextProfileDocument {
|
|
354
|
+
const document = readProfile(settingsPath, name);
|
|
355
|
+
if (document.rawDocument === undefined) throw new Error(document.readError);
|
|
356
|
+
return { ...document, rawDocument: document.rawDocument };
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
export function createProfile(settingsPath: string, name: string, rawDocument: string): TextProfileDocument {
|
|
360
|
+
const normalized = normalizeProfileName(name);
|
|
361
|
+
const bytes = encodeDocument(rawDocument);
|
|
362
|
+
return mutate(settingsPath, () => {
|
|
363
|
+
const directory = profileDirectory(settingsPath);
|
|
364
|
+
checkedDirectory(directory, true);
|
|
365
|
+
const filename = `${normalized}.toml`;
|
|
366
|
+
assertAvailable(directory, filename);
|
|
367
|
+
publish(directory, filename, bytes, () => assertAvailable(directory, filename));
|
|
368
|
+
return readTextProfile(settingsPath, normalized);
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
export function duplicateProfile(
|
|
373
|
+
settingsPath: string,
|
|
374
|
+
name: string,
|
|
375
|
+
newName: string,
|
|
376
|
+
expected: ProfileDocument,
|
|
377
|
+
): ProfileDocument {
|
|
378
|
+
const normalized = normalizeProfileName(newName);
|
|
379
|
+
return mutate(settingsPath, () => {
|
|
380
|
+
const current = readProfile(settingsPath, name);
|
|
381
|
+
assertExpected(current, expected);
|
|
382
|
+
const directory = profileDirectory(settingsPath);
|
|
383
|
+
const filename = `${normalized}.toml`;
|
|
384
|
+
assertAvailable(directory, filename);
|
|
385
|
+
publish(directory, filename, current.rawBytes, () => {
|
|
386
|
+
assertExpected(readProfile(settingsPath, name), expected);
|
|
387
|
+
assertAvailable(directory, filename);
|
|
388
|
+
});
|
|
389
|
+
return readProfile(settingsPath, normalized);
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
export function saveProfile(
|
|
394
|
+
settingsPath: string,
|
|
395
|
+
name: string,
|
|
396
|
+
rawDocument: string,
|
|
397
|
+
expected: ProfileDocument,
|
|
398
|
+
): TextProfileDocument {
|
|
399
|
+
const normalized = normalizeProfileName(name);
|
|
400
|
+
const bytes = encodeDocument(rawDocument);
|
|
401
|
+
return mutate(settingsPath, () => {
|
|
402
|
+
const current = readProfile(settingsPath, normalized);
|
|
403
|
+
assertExpected(current, expected);
|
|
404
|
+
if (current.rawDocument === rawDocument) return { ...current, rawDocument };
|
|
405
|
+
publish(profileDirectory(settingsPath), `${normalized}.toml`, bytes, () => {
|
|
406
|
+
assertExpected(readProfile(settingsPath, normalized), expected);
|
|
407
|
+
});
|
|
408
|
+
return readTextProfile(settingsPath, normalized);
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
export function renameProfile(
|
|
413
|
+
settingsPath: string,
|
|
414
|
+
name: string,
|
|
415
|
+
newName: string,
|
|
416
|
+
expected: ProfileDocument,
|
|
417
|
+
): ProfileDocument {
|
|
418
|
+
const normalized = normalizeProfileName(newName);
|
|
419
|
+
return mutate(settingsPath, () => {
|
|
420
|
+
const current = readProfile(settingsPath, name);
|
|
421
|
+
assertExpected(current, expected);
|
|
422
|
+
if (current.name === normalized) return current;
|
|
423
|
+
// Explicitly reject case-only renames rather than depending on filesystem case behavior.
|
|
424
|
+
if (collisionKey(current.name) === collisionKey(normalized))
|
|
425
|
+
throw new Error("Case-only profile rename is not supported");
|
|
426
|
+
const directory = profileDirectory(settingsPath);
|
|
427
|
+
assertAvailable(directory, `${normalized}.toml`);
|
|
428
|
+
assertExpected(readProfile(settingsPath, name), expected);
|
|
429
|
+
const destination = join(directory, `${normalized}.toml`);
|
|
430
|
+
renameSync(current.path, destination);
|
|
431
|
+
flushMutation(directory, destination);
|
|
432
|
+
return readProfile(settingsPath, normalized);
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
export function deleteProfile(settingsPath: string, name: string, expected: ProfileDocument): void {
|
|
437
|
+
mutate(settingsPath, () => {
|
|
438
|
+
const current = readProfile(settingsPath, name);
|
|
439
|
+
assertExpected(current, expected);
|
|
440
|
+
unlinkSync(current.path);
|
|
441
|
+
flushMutation(dirname(current.path), current.path);
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function assertTimestamp(value: string): void {
|
|
446
|
+
const time = Date.parse(value);
|
|
447
|
+
if (!Number.isFinite(time) || new Date(time).toISOString() !== value) throw new Error("Invalid history timestamp");
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function historyLocation(settingsPath: string, name: string): { path: string; legacy: boolean; createdAt: string } {
|
|
451
|
+
const modern = HISTORY_NAME.exec(name);
|
|
452
|
+
if (modern) {
|
|
453
|
+
const createdAt = modern[1].replace(/T(\d{2})-(\d{2})-(\d{2})/u, "T$1:$2:$3");
|
|
454
|
+
assertTimestamp(createdAt);
|
|
455
|
+
return { path: join(historyDirectory(settingsPath), name), legacy: false, createdAt };
|
|
456
|
+
}
|
|
457
|
+
const legacy = LEGACY_NAME.exec(name);
|
|
458
|
+
if (legacy) {
|
|
459
|
+
const createdAt = `${legacy[1]}-${legacy[2]}-${legacy[3]}T${legacy[4]}:${legacy[5]}`;
|
|
460
|
+
assertTimestamp(`${createdAt}:00.000Z`);
|
|
461
|
+
return { path: join(rootPath(settingsPath), name), legacy: true, createdAt };
|
|
462
|
+
}
|
|
463
|
+
throw new Error("Invalid history filename");
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
export function readHistory(settingsPath: string, name: string): HistoryDocument {
|
|
467
|
+
const location = historyLocation(settingsPath, name);
|
|
468
|
+
const document = readBytes(location.path);
|
|
469
|
+
const decoded = document.rawBytes.toString("utf8");
|
|
470
|
+
const valid = Buffer.from(decoded, "utf8").equals(document.rawBytes);
|
|
471
|
+
return Object.freeze({
|
|
472
|
+
kind: "history",
|
|
473
|
+
name,
|
|
474
|
+
...location,
|
|
475
|
+
...document,
|
|
476
|
+
rawDocument: valid ? decoded : undefined,
|
|
477
|
+
...(valid ? {} : { readError: "Recovery document is not valid UTF-8; raw bytes are preserved" }),
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
export function listHistory(settingsPath: string): HistoryDocument[] {
|
|
482
|
+
const history: HistoryDocument[] = [];
|
|
483
|
+
for (const [directory, pattern] of [
|
|
484
|
+
[historyDirectory(settingsPath), HISTORY_NAME],
|
|
485
|
+
[rootPath(settingsPath), LEGACY_NAME],
|
|
486
|
+
] as const) {
|
|
487
|
+
if (!checkedDirectory(directory)) continue;
|
|
488
|
+
for (const name of readdirSync(directory).sort()) {
|
|
489
|
+
if (!pattern.test(name)) continue;
|
|
490
|
+
try {
|
|
491
|
+
historyLocation(settingsPath, name);
|
|
492
|
+
} catch (error) {
|
|
493
|
+
if (error instanceof Error && error.message === "Invalid history timestamp") continue;
|
|
494
|
+
throw error;
|
|
495
|
+
}
|
|
496
|
+
const stat = statIfPresent(join(directory, name));
|
|
497
|
+
if (!stat?.isFile() || stat.isSymbolicLink()) continue;
|
|
498
|
+
history.push(readHistory(settingsPath, name));
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
return history.sort(
|
|
502
|
+
(left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt) || left.name.localeCompare(right.name),
|
|
503
|
+
);
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/** Return only after file AND directory fsync. Keep recovery bytes even if a later operation fails. */
|
|
507
|
+
export function archiveConfigDocument(settingsPath: string, rawDocument: string | Buffer): ArchiveReference {
|
|
508
|
+
const bytes = typeof rawDocument === "string" ? encodeDocument(rawDocument) : Buffer.from(rawDocument);
|
|
509
|
+
return mutate(settingsPath, () => {
|
|
510
|
+
const directory = historyDirectory(settingsPath);
|
|
511
|
+
checkedDirectory(directory, true);
|
|
512
|
+
const name = `${new Date().toISOString().replace(/:/gu, "-")}-${randomUUID()}.toml`;
|
|
513
|
+
publish(directory, name, bytes, () => assertAvailable(directory, name));
|
|
514
|
+
return Object.freeze({ name, path: join(directory, name) });
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
export function deleteHistory(settingsPath: string, name: string, expected: HistoryDocument): void {
|
|
519
|
+
if (historyLocation(settingsPath, name).legacy) throw new Error("Legacy recovery files are read-only");
|
|
520
|
+
mutate(settingsPath, () => {
|
|
521
|
+
const current = readHistory(settingsPath, name);
|
|
522
|
+
assertExpected(current, expected);
|
|
523
|
+
unlinkSync(current.path);
|
|
524
|
+
flushMutation(dirname(current.path), current.path);
|
|
525
|
+
});
|
|
526
|
+
}
|