ai-profile-switch 0.0.0-stage → 2.2.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,71 @@
1
+ import {
2
+ META_FILE, PROFILE_NAME_REGEX, PROFILE_NAME_MAX_LENGTH, RESERVED_NAMES, SHAREABLE_ENTRIES,
3
+ } from './constants.mjs';
4
+ import { readJsonFile, writeJsonFile } from './json-fs.mjs';
5
+
6
+ const DEFAULT_META = {
7
+ version: 1,
8
+ activeProfile: null,
9
+ shareSettings: true,
10
+ profiles: [],
11
+ };
12
+
13
+ export function readMeta() {
14
+ const meta = readJsonFile(META_FILE, DEFAULT_META);
15
+ if (!meta || !Array.isArray(meta.profiles)
16
+ || meta.profiles.some(name => typeof name !== 'string'
17
+ || !PROFILE_NAME_REGEX.test(name) || name.length > PROFILE_NAME_MAX_LENGTH
18
+ || RESERVED_NAMES.includes(name))
19
+ || new Set(meta.profiles).size !== meta.profiles.length
20
+ || (meta.activeProfile !== null && !meta.profiles.includes(meta.activeProfile))
21
+ || typeof meta.shareSettings !== 'boolean'
22
+ || (meta.shared !== undefined && (!Array.isArray(meta.shared)
23
+ || meta.shared.some(entry => !SHAREABLE_ENTRIES.includes(entry))
24
+ || new Set(meta.shared).size !== meta.shared.length))) {
25
+ throw new Error(`Invalid profile metadata in ${META_FILE}. Restore it before continuing.`);
26
+ }
27
+ return meta;
28
+ }
29
+
30
+ export function writeMeta(meta) {
31
+ writeJsonFile(META_FILE, meta);
32
+ }
33
+
34
+ export function getActiveProfile() {
35
+ return readMeta().activeProfile;
36
+ }
37
+
38
+ export function setActiveProfile(name) {
39
+ const meta = readMeta();
40
+ if (!meta.profiles.includes(name)) {
41
+ throw new Error(`Profile "${name}" does not exist`);
42
+ }
43
+ meta.activeProfile = name;
44
+ writeMeta(meta);
45
+ }
46
+
47
+ export function addProfileToMeta(name) {
48
+ const meta = readMeta();
49
+ if (!meta.profiles.includes(name)) {
50
+ meta.profiles.push(name);
51
+ }
52
+ writeMeta(meta);
53
+ }
54
+
55
+ export function getSharedEntries() {
56
+ return readMeta().shared ?? [];
57
+ }
58
+
59
+ export function setSharedEntries(entries) {
60
+ const meta = readMeta();
61
+ writeMeta({ ...meta, shared: entries });
62
+ }
63
+
64
+ export function removeProfileFromMeta(name) {
65
+ const meta = readMeta();
66
+ meta.profiles = meta.profiles.filter(p => p !== name);
67
+ if (meta.activeProfile === name) {
68
+ meta.activeProfile = meta.profiles[0] || null;
69
+ }
70
+ writeMeta(meta);
71
+ }
@@ -0,0 +1,40 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+
4
+ export const HOME = homedir();
5
+ export const IS_WINDOWS = process.platform === 'win32';
6
+ export const PROFILES_DIR = join(HOME, '.claude-profiles');
7
+ export const SHARED_DIR = join(PROFILES_DIR, '_shared');
8
+ export const META_FILE = join(PROFILES_DIR, 'meta.json');
9
+
10
+ export const DEFAULT_CLAUDE_DIR = join(HOME, '.claude');
11
+
12
+ export const PROFILE_NAME_REGEX = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
13
+ export const PROFILE_NAME_MAX_LENGTH = 30;
14
+ export const RESERVED_NAMES = ['_shared', 'default'];
15
+
16
+ // Files/dirs that are shared across profiles (symlinked)
17
+ export const SHARED_FILES = ['settings.json'];
18
+ export const SHARED_DIRS = ['commands'];
19
+
20
+ // Files/dirs that are profile-specific (copied independently)
21
+ export const PROFILE_FILES = [
22
+ '.claude.json', '.credentials.json', 'settings.local.json', 'history.jsonl', 'CLAUDE.md',
23
+ 'keybindings.json', 'pre-launch.sh', 'pre-launch.fish', 'pre-launch.ps1',
24
+ ];
25
+ export const PROFILE_DIRS = [
26
+ 'plugins', 'projects', 'plans', 'skills', 'agents', 'rules', 'hooks',
27
+ 'file-history', 'output-styles', 'agent-memory', 'workflows', 'themes', 'tasks',
28
+ ];
29
+
30
+ // Profile entries a user may opt into sharing with `cpf share add`.
31
+ // Account data (.claude.json, history, projects, plugins) always stays per profile.
32
+ export const SHAREABLE_ENTRIES = [
33
+ 'CLAUDE.md', 'keybindings.json', 'skills', 'agents', 'rules', 'hooks',
34
+ 'output-styles', 'workflows', 'themes',
35
+ ];
36
+ export const SHAREABLE_FILES = ['CLAUDE.md', 'keybindings.json'];
37
+ // Skills are linked one by one so each account keeps its own synced skills.
38
+ export const ACCOUNT_SKILL_ENTRIES = ['synced'];
39
+
40
+ export const SELF_PKG = 'ai-profile-switch';
@@ -0,0 +1,30 @@
1
+ import { readFileSync, writeFileSync, renameSync, unlinkSync, mkdirSync } from 'node:fs';
2
+ import { dirname, join, basename } from 'node:path';
3
+
4
+ export function readJsonFile(filePath, fallback = {}) {
5
+ let raw;
6
+ try {
7
+ raw = readFileSync(filePath, 'utf8').replace(/^\uFEFF/, '');
8
+ } catch (err) {
9
+ if (err.code === 'ENOENT') return structuredClone(fallback);
10
+ throw err;
11
+ }
12
+ try {
13
+ return JSON.parse(raw);
14
+ } catch (err) {
15
+ throw new Error(`Invalid JSON in ${filePath}: ${err.message}`);
16
+ }
17
+ }
18
+
19
+ export function writeJsonFile(filePath, data) {
20
+ mkdirSync(dirname(filePath), { recursive: true });
21
+ const content = JSON.stringify(data, null, 2) + '\n';
22
+ const tmp = join(dirname(filePath), `.${basename(filePath)}.${process.pid}.tmp`);
23
+ writeFileSync(tmp, content);
24
+ try {
25
+ renameSync(tmp, filePath);
26
+ } catch (err) {
27
+ try { unlinkSync(tmp); } catch {}
28
+ throw err;
29
+ }
30
+ }
@@ -0,0 +1,395 @@
1
+ import {
2
+ existsSync, mkdirSync, rmSync, symlinkSync, copyFileSync, writeFileSync,
3
+ readFileSync, lstatSync, statSync, readlinkSync, readdirSync, realpathSync,
4
+ mkdtempSync, renameSync, chmodSync,
5
+ } from 'node:fs';
6
+ import { join, resolve, dirname, basename, relative, isAbsolute, sep } from 'node:path';
7
+ import {
8
+ HOME, DEFAULT_CLAUDE_DIR, IS_WINDOWS, PROFILES_DIR, SHARED_DIR,
9
+ PROFILE_NAME_REGEX, PROFILE_NAME_MAX_LENGTH, RESERVED_NAMES,
10
+ SHARED_FILES, SHARED_DIRS, PROFILE_FILES, PROFILE_DIRS,
11
+ } from './constants.mjs';
12
+ import { createHash } from 'node:crypto';
13
+ import { addProfileToMeta, removeProfileFromMeta, readMeta, writeMeta } from './config.mjs';
14
+ import { warn } from './ui.mjs';
15
+
16
+ export function pathExists(path) {
17
+ try { lstatSync(path); return true; } catch (err) {
18
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return false;
19
+ throw err;
20
+ }
21
+ }
22
+
23
+ export function createLink(target, link, isDir, copySource = resolve(dirname(link), target)) {
24
+ if (pathExists(link)) return;
25
+ if (IS_WINDOWS && isDir) {
26
+ symlinkSync(resolve(dirname(link), target), link, 'junction');
27
+ return;
28
+ }
29
+ try {
30
+ symlinkSync(target, link, isDir ? 'dir' : 'file');
31
+ } catch (err) {
32
+ if (!IS_WINDOWS || isDir || !['EPERM', 'ENOTSUP'].includes(err.code)) throw err;
33
+ copyFileSync(copySource, link);
34
+ warn(`Symlink unavailable: copied shared file instead (${link}).`);
35
+ warn('Enable Windows Developer Mode for full shared-settings sync.');
36
+ }
37
+ }
38
+
39
+ export function validateProfileName(name) {
40
+ if (!name) return 'Profile name cannot be empty';
41
+ if (name.length > PROFILE_NAME_MAX_LENGTH) {
42
+ return `Profile name must be ${PROFILE_NAME_MAX_LENGTH} characters or fewer`;
43
+ }
44
+ if (RESERVED_NAMES.includes(name)) return `"${name}" is a reserved name`;
45
+ if (IS_WINDOWS && /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(name)) {
46
+ return `"${name}" is a reserved Windows device name`;
47
+ }
48
+ if (!PROFILE_NAME_REGEX.test(name)) {
49
+ return 'Only lowercase letters, numbers, and hyphens allowed (must start/end with letter or number)';
50
+ }
51
+ return null;
52
+ }
53
+
54
+ export function profileDir(name) {
55
+ return join(PROFILES_DIR, name);
56
+ }
57
+
58
+ export function profileExists(name) {
59
+ return existsSync(profileDir(name));
60
+ }
61
+
62
+ export function ensureShared() {
63
+ mkdirSync(SHARED_DIR, { recursive: true });
64
+ for (const file of SHARED_FILES) {
65
+ const path = join(SHARED_DIR, file);
66
+ if (!pathExists(path)) writeFileSync(path, '{}');
67
+ }
68
+ for (const dir of SHARED_DIRS) mkdirSync(join(SHARED_DIR, dir), { recursive: true });
69
+ }
70
+
71
+ export function createProfile(name, shareSettings = true) {
72
+ const error = validateProfileName(name);
73
+ if (error) throw new Error(error);
74
+ readMeta();
75
+ const dir = profileDir(name);
76
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
77
+ if (shareSettings) {
78
+ ensureShared();
79
+ for (const file of SHARED_FILES) createLink(join('..', '_shared', file), join(dir, file), false);
80
+ for (const entry of SHARED_DIRS) createLink(join('..', '_shared', entry), join(dir, entry), true);
81
+ }
82
+ for (const entry of PROFILE_DIRS) mkdirSync(join(dir, entry), { recursive: true });
83
+ addProfileToMeta(name);
84
+ }
85
+
86
+ export function assertRegisteredProfile(name) {
87
+ const error = validateProfileName(name);
88
+ if (error) throw new Error(error);
89
+ const meta = readMeta();
90
+ if (!meta.profiles.includes(name)) throw new Error(`Profile "${name}" is not registered`);
91
+ const dir = profileDir(name);
92
+ if (!pathExists(dir)) throw new Error(`Profile "${name}" directory is missing`);
93
+ const entry = lstatSync(dir);
94
+ if (entry.isSymbolicLink() || !entry.isDirectory()) {
95
+ throw new Error(`Profile "${name}" must be a directory, not a symbolic link or file`);
96
+ }
97
+ return meta;
98
+ }
99
+
100
+ export function removeProfile(name) {
101
+ assertRegisteredProfile(name);
102
+ rmSync(profileDir(name), { recursive: true, force: true });
103
+ removeProfileFromMeta(name);
104
+ }
105
+
106
+ export function renameProfile(oldName, newName) {
107
+ const meta = assertRegisteredProfile(oldName);
108
+ const error = validateProfileName(newName);
109
+ if (error) throw new Error(error);
110
+ if (oldName === newName) return false;
111
+ const oldDir = profileDir(oldName);
112
+ const newDir = profileDir(newName);
113
+ if (meta.profiles.includes(newName) || pathExists(newDir)) {
114
+ throw new Error(`Profile "${newName}" already exists`);
115
+ }
116
+
117
+ renameSync(oldDir, newDir);
118
+ try {
119
+ writeMeta({
120
+ ...meta,
121
+ profiles: meta.profiles.map(name => name === oldName ? newName : name),
122
+ activeProfile: meta.activeProfile === oldName ? newName : meta.activeProfile,
123
+ });
124
+ } catch (err) {
125
+ try {
126
+ if (pathExists(oldDir)) throw new Error(`Original path is now occupied: ${oldDir}`);
127
+ renameSync(newDir, oldDir);
128
+ } catch (rollbackError) {
129
+ throw new Error(`Profile rename rollback failed. Profile data is preserved at ${newDir}. Restore it to ${oldDir} before continuing.`, {
130
+ cause: new AggregateError([err, rollbackError]),
131
+ });
132
+ }
133
+ throw err;
134
+ }
135
+ return true;
136
+ }
137
+
138
+ export function listProfiles() {
139
+ return readMeta().profiles;
140
+ }
141
+
142
+ export function migrationSource(sourceDir) {
143
+ const directory = resolve(sourceDir);
144
+ const configured = process.env.CLAUDE_CONFIG_DIR;
145
+ const useRootConfig = directory === resolve(DEFAULT_CLAUDE_DIR)
146
+ && (!configured || directory !== resolve(configured));
147
+ return {
148
+ directory,
149
+ userConfig: useRootConfig ? join(HOME, '.claude.json') : join(directory, '.claude.json'),
150
+ };
151
+ }
152
+
153
+ export function canonicalPath(path) {
154
+ if (pathExists(path)) return realpathSync(path);
155
+ return join(canonicalPath(dirname(path)), basename(path));
156
+ }
157
+
158
+ function pathsOverlap(left, right) {
159
+ const distance = relative(left, right);
160
+ return distance === '' || (distance !== '..' && !distance.startsWith(`..${sep}`) && !isAbsolute(distance));
161
+ }
162
+
163
+ export function linkTarget(path) {
164
+ return resolve(realpathSync(dirname(path)), readlinkSync(path));
165
+ }
166
+
167
+ export function copyEntry(source, destination) {
168
+ const info = lstatSync(source);
169
+ if (info.isSymbolicLink()) {
170
+ const target = linkTarget(source);
171
+ const kind = existsSync(source) && statSync(source).isDirectory() ? 'dir' : 'file';
172
+ createLink(target, destination, kind === 'dir');
173
+ } else if (info.isDirectory()) {
174
+ mkdirSync(destination, { recursive: true, mode: info.mode & 0o777 });
175
+ for (const entry of readdirSync(source)) copyEntry(join(source, entry), join(destination, entry));
176
+ } else if (info.isFile()) {
177
+ copyFileSync(source, destination);
178
+ } else {
179
+ throw new Error(`Unsupported migration entry: ${source}`);
180
+ }
181
+ }
182
+
183
+ export function identicalEntries(source, destination) {
184
+ let from = lstatSync(source);
185
+ let to = lstatSync(destination);
186
+ if (from.isSymbolicLink() && to.isSymbolicLink() && linkTarget(source) === linkTarget(destination)) return true;
187
+ if (from.isSymbolicLink()) {
188
+ if (!existsSync(source)) return false;
189
+ from = statSync(source);
190
+ }
191
+ if (to.isSymbolicLink()) {
192
+ if (!existsSync(destination)) return false;
193
+ to = statSync(destination);
194
+ }
195
+ if (from.isFile() && to.isFile()) return readFileSync(source).equals(readFileSync(destination));
196
+ if (!from.isDirectory() || !to.isDirectory()) return false;
197
+ const entries = readdirSync(source).sort();
198
+ const existing = readdirSync(destination).sort();
199
+ return entries.length === existing.length && entries.every((entry, index) =>
200
+ entry === existing[index] && identicalEntries(join(source, entry), join(destination, entry)));
201
+ }
202
+
203
+ export function emptyEntry(path) {
204
+ const info = lstatSync(path);
205
+ if (info.isSymbolicLink()) return false;
206
+ if (info.isDirectory()) return readdirSync(path).length === 0;
207
+ if (!info.isFile()) return false;
208
+ const content = readFileSync(path, 'utf8').trim();
209
+ return content === '' || (path.endsWith('.json') && content === '{}');
210
+ }
211
+
212
+ function validateJson(source) {
213
+ if (!source.endsWith('.json')) return;
214
+ let value;
215
+ try { value = JSON.parse(readFileSync(source, 'utf8').replace(/^\uFEFF/, '')); } catch {
216
+ throw new Error(`Invalid JSON in migration source: ${source}`);
217
+ }
218
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
219
+ throw new Error(`Expected a JSON object in migration source: ${source}`);
220
+ }
221
+ }
222
+
223
+ function stageEntry(source, destination) {
224
+ if (!pathExists(source)) return;
225
+ if (pathExists(destination)) {
226
+ if (identicalEntries(source, destination) || emptyEntry(source)) return;
227
+ if (!emptyEntry(destination)) throw new Error(`Migration conflict: ${destination}`);
228
+ rmSync(destination, { recursive: true, force: true });
229
+ }
230
+ copyEntry(source, destination);
231
+ }
232
+
233
+ function migrationFingerprint(path) {
234
+ const hash = createHash('sha256');
235
+ const visit = current => {
236
+ const entry = lstatSync(current);
237
+ hash.update(JSON.stringify([
238
+ relative(path, current), entry.mode, entry.dev, entry.ino, entry.mtimeMs,
239
+ // Moving the root into a backup changes its ctime without changing its data.
240
+ current === path ? null : entry.ctimeMs,
241
+ ]));
242
+ if (entry.isSymbolicLink()) hash.update(readlinkSync(current));
243
+ else if (entry.isDirectory()) {
244
+ for (const name of readdirSync(current).sort()) visit(join(current, name));
245
+ } else if (entry.isFile()) hash.update(readFileSync(current));
246
+ };
247
+ try {
248
+ visit(path);
249
+ return hash.digest('hex');
250
+ } catch (err) {
251
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return null;
252
+ throw err;
253
+ }
254
+ }
255
+
256
+ function prepareMigration(source, profileName, shareSettings, stage) {
257
+ const target = profileDir(profileName);
258
+ const stagedProfile = join(stage, 'profile');
259
+ const stagedShared = join(stage, '_shared');
260
+ for (const [current, staged] of [[target, stagedProfile], [SHARED_DIR, stagedShared]]) {
261
+ if (current === SHARED_DIR && !shareSettings) continue;
262
+ if (pathExists(current)) {
263
+ if (!lstatSync(current).isDirectory()) throw new Error(`Migration target must be a directory: ${current}`);
264
+ copyEntry(current, staged);
265
+ } else mkdirSync(staged, { mode: 0o700 });
266
+ }
267
+ for (const file of PROFILE_FILES) {
268
+ const from = file === '.claude.json' ? source.userConfig : join(source.directory, file);
269
+ if (!pathExists(from)) continue;
270
+ validateJson(from);
271
+ const destination = join(stagedProfile, file);
272
+ if (file === '.claude.json' || file === '.credentials.json') {
273
+ if (pathExists(destination) && !emptyEntry(destination)
274
+ && !readFileSync(from).equals(readFileSync(destination))) {
275
+ throw new Error(`Migration conflict: ${join(target, file)}`);
276
+ }
277
+ if (pathExists(destination)) rmSync(destination, { force: true });
278
+ writeFileSync(destination, readFileSync(from), { mode: 0o600 });
279
+ } else stageEntry(from, destination);
280
+ }
281
+ for (const entry of PROFILE_DIRS) {
282
+ stageEntry(join(source.directory, entry), join(stagedProfile, entry));
283
+ if (!pathExists(join(stagedProfile, entry))) mkdirSync(join(stagedProfile, entry));
284
+ }
285
+ for (const entry of [...SHARED_FILES, ...SHARED_DIRS]) {
286
+ const shared = shareSettings ? stagedShared : stagedProfile;
287
+ const from = join(source.directory, entry);
288
+ if (pathExists(from)) validateJson(from);
289
+ stageEntry(from, join(shared, entry));
290
+ if (!shareSettings) continue;
291
+ const isDir = SHARED_DIRS.includes(entry);
292
+ if (!pathExists(join(shared, entry))) {
293
+ if (isDir) mkdirSync(join(shared, entry));
294
+ else writeFileSync(join(shared, entry), '{}');
295
+ }
296
+ const link = join(stagedProfile, entry);
297
+ if (pathExists(link)) {
298
+ const original = join(target, entry);
299
+ const linkedShared = lstatSync(link).isSymbolicLink()
300
+ && canonicalPath(linkTarget(link)) === canonicalPath(join(SHARED_DIR, entry));
301
+ if (!linkedShared && !identicalEntries(link, join(shared, entry)) && !emptyEntry(link)) {
302
+ throw new Error(`Migration conflict: ${original}`);
303
+ }
304
+ rmSync(link, { recursive: true, force: true });
305
+ }
306
+ const linkPath = IS_WINDOWS ? join(SHARED_DIR, entry) : join('..', '_shared', entry);
307
+ createLink(linkPath, link, isDir, join(shared, entry));
308
+ }
309
+ chmodSync(stagedProfile, 0o700);
310
+ return shareSettings
311
+ ? [[stagedShared, SHARED_DIR], [stagedProfile, target]]
312
+ : [[stagedProfile, target]];
313
+ }
314
+
315
+ // Windows and WSL1 refuse to move a folder while a running session keeps a file in it open.
316
+ function moveAside(destination, backup) {
317
+ try {
318
+ renameSync(destination, backup);
319
+ } catch (err) {
320
+ if (!['EPERM', 'EACCES', 'EBUSY'].includes(err.code)) throw err;
321
+ throw new Error(`Migration destination is in use: ${destination}. Close Claude sessions using the source and destination, then retry.`, { cause: err });
322
+ }
323
+ }
324
+
325
+ export function migrateDir(sourceDir, profileName, shareSettings = true) {
326
+ const error = validateProfileName(profileName);
327
+ if (error) throw new Error(error);
328
+ readMeta();
329
+ const source = migrationSource(sourceDir);
330
+ if (!existsSync(source.directory) && !existsSync(source.userConfig)) {
331
+ throw new Error(`Claude configuration not found: ${source.directory}`);
332
+ }
333
+ if (existsSync(source.directory) && !statSync(source.directory).isDirectory()) {
334
+ throw new Error(`Migration source must be a directory: ${source.directory}`);
335
+ }
336
+ const from = canonicalPath(source.directory);
337
+ for (const path of [profileDir(profileName), ...(shareSettings ? [SHARED_DIR] : [])]) {
338
+ const to = canonicalPath(path);
339
+ if (pathsOverlap(from, to) || pathsOverlap(to, from)) {
340
+ throw new Error(`Migration source and target overlap: ${source.directory} and ${path}`);
341
+ }
342
+ }
343
+ const originals = [profileDir(profileName), ...(shareSettings ? [SHARED_DIR] : [])];
344
+ const fingerprints = new Map(originals.map(path => [path, migrationFingerprint(path)]));
345
+ mkdirSync(PROFILES_DIR, { recursive: true });
346
+ const stage = mkdtempSync(join(PROFILES_DIR, '.migration-'));
347
+ chmodSync(stage, 0o700);
348
+ const published = [];
349
+ let cleanup = true;
350
+ try {
351
+ const entries = prepareMigration(source, profileName, shareSettings, stage);
352
+ const backups = entries.flatMap(([, destination], index) => pathExists(destination)
353
+ ? [{ original: destination, backup: join(stage, `backup-${index}`) }] : []);
354
+ if (backups.length) {
355
+ writeFileSync(join(stage, 'backup-info.json'), JSON.stringify({
356
+ profile: profileName, source: source.directory, backups,
357
+ }, null, 2) + '\n', { mode: 0o600 });
358
+ }
359
+ for (const destination of originals) {
360
+ if (migrationFingerprint(destination) !== fingerprints.get(destination)) {
361
+ throw new Error(`Migration destination changed while preparing: ${destination}. Close Claude sessions using the source and destination, then retry.`);
362
+ }
363
+ }
364
+ for (const [staged, destination] of entries) {
365
+ const backup = join(stage, `backup-${published.length}`);
366
+ const hadOriginal = pathExists(destination);
367
+ if (hadOriginal) moveAside(destination, backup);
368
+ published.push({ destination, backup, hadOriginal });
369
+ if (hadOriginal && migrationFingerprint(backup) !== fingerprints.get(destination)) {
370
+ throw new Error(`Migration destination changed before replacement: ${destination}. Close Claude sessions using the source and destination, then retry.`);
371
+ }
372
+ renameSync(staged, destination);
373
+ }
374
+ addProfileToMeta(profileName);
375
+ if (backups.length) cleanup = false;
376
+ return { backupPath: backups.length ? stage : null };
377
+ } catch (err) {
378
+ const rollbackErrors = [];
379
+ for (const { destination, backup, hadOriginal } of published.reverse()) {
380
+ try {
381
+ rmSync(destination, { recursive: true, force: true });
382
+ if (hadOriginal) renameSync(backup, destination);
383
+ } catch (rollbackError) {
384
+ rollbackErrors.push(rollbackError);
385
+ }
386
+ }
387
+ if (rollbackErrors.length > 0) {
388
+ cleanup = false;
389
+ throw new Error(`Migration rollback failed. Original backups were preserved in ${stage}. Restore them before continuing.`, { cause: err });
390
+ }
391
+ throw err;
392
+ } finally {
393
+ if (cleanup) rmSync(stage, { recursive: true, force: true });
394
+ }
395
+ }
@@ -0,0 +1,148 @@
1
+ import { createInterface, emitKeypressEvents } from 'node:readline';
2
+ import { PassThrough } from 'node:stream';
3
+ import { color, cursorControl, sym } from './ui.mjs';
4
+
5
+ function rl() {
6
+ return createInterface({ input: process.stdin, output: process.stdout });
7
+ }
8
+
9
+ function readKeys(onKey) {
10
+ const input = process.stdin;
11
+ const wasRaw = Boolean(input.isRaw);
12
+ const wasFlowing = input.readableFlowing === true;
13
+ // Keep readline's decoder off stdin so it cannot consume later text prompts.
14
+ const keys = new PassThrough();
15
+ emitKeypressEvents(keys);
16
+ keys.on('keypress', onKey);
17
+ const onData = chunk => keys.write(chunk);
18
+ input.on('data', onData);
19
+ if (!wasRaw) input.setRawMode(true);
20
+ input.resume();
21
+
22
+ return () => {
23
+ input.removeListener('data', onData);
24
+ keys.removeListener('keypress', onKey);
25
+ keys.destroy();
26
+ if (!wasRaw) input.setRawMode(false);
27
+ if (wasFlowing) input.resume();
28
+ else input.pause();
29
+ };
30
+ }
31
+
32
+ export async function text(message, defaultVal) {
33
+ const suffix = defaultVal !== undefined ? color.dim(` (${defaultVal})`) : '';
34
+ const r = rl();
35
+ const cursor = cursorControl();
36
+ return new Promise((resolve) => {
37
+ r.question(`${color.cyan('?')} ${message}${suffix}\n ${color.dim(sym.arrow)} `, (answer) => {
38
+ r.close();
39
+ const result = answer.trim() || defaultVal || '';
40
+ // Replace 2-line prompt with single completed line: ✓ message … answer
41
+ if (cursor.enabled) {
42
+ process.stdout.write(`${cursor.up(2)}\r${cursor.clearLine}${color.green(sym.check)} ${message} ${color.dim(sym.dots)} ${color.cyan(result)}\n${cursor.clearDown}`);
43
+ }
44
+ resolve(result);
45
+ });
46
+ });
47
+ }
48
+
49
+ export async function number(message, defaultVal) {
50
+ const val = await text(message, defaultVal?.toString());
51
+ const n = parseInt(val, 10);
52
+ if (isNaN(n) || n < 1) return defaultVal ?? 1;
53
+ return n;
54
+ }
55
+
56
+ export async function confirm(message, defaultVal = true) {
57
+ if (!process.stdin.isTTY) {
58
+ return defaultVal;
59
+ }
60
+
61
+ return new Promise((resolve) => {
62
+ let selected = defaultVal;
63
+ const cursor = cursorControl();
64
+
65
+ const render = (final = false) => {
66
+ const prefix = final ? color.green(sym.check) : color.cyan('?');
67
+ const sep = final ? color.dim(` ${sym.dots} `) : color.dim(` ${sym.arrow} `);
68
+ const no = !selected ? color.cyan('No') : color.dim('No');
69
+ const yes = selected ? color.cyan('Yes') : color.dim('Yes');
70
+ process.stdout.write(`\r${cursor.clearLine}${prefix} ${message}${sep}${no} ${color.dim('/')} ${yes}`);
71
+ };
72
+
73
+ render();
74
+
75
+ const stop = readKeys((character, key) => {
76
+ if (key.name === 'left' || key.name === 'right' || key.name === 'tab') {
77
+ selected = !selected;
78
+ render();
79
+ } else if (character === 'y' || character === 'Y') {
80
+ selected = true;
81
+ render();
82
+ } else if (character === 'n' || character === 'N') {
83
+ selected = false;
84
+ render();
85
+ } else if (key.name === 'return' || key.name === 'enter') {
86
+ stop();
87
+ render(true);
88
+ process.stdout.write('\n');
89
+ resolve(selected);
90
+ } else if (key.ctrl && key.name === 'c') {
91
+ stop();
92
+ process.stdout.write('\n');
93
+ process.exit(0);
94
+ }
95
+ });
96
+ });
97
+ }
98
+
99
+ export async function select(message, choices, { output = process.stdout, initial = 0 } = {}) {
100
+ return new Promise((resolve) => {
101
+ let selected = Math.max(0, Math.min(initial, choices.length - 1));
102
+ let rendered = false;
103
+ const cursor = cursorControl(output);
104
+
105
+ const render = () => {
106
+ if (rendered) {
107
+ output.write(cursor.up(choices.length));
108
+ }
109
+ choices.forEach((choice, i) => {
110
+ const label = typeof choice === 'string' ? choice : choice.label;
111
+ const prefix = i === selected ? color.cyan(` ${sym.cursor} `) : ' ';
112
+ output.write(`${cursor.clearLine}${prefix}${label}\n`);
113
+ });
114
+ rendered = true;
115
+ };
116
+
117
+ if (!process.stdin.isTTY) {
118
+ // Non-interactive: pick first choice without rendering menu
119
+ resolve(typeof choices[selected] === 'string' ? choices[selected] : choices[selected].value);
120
+ return;
121
+ }
122
+
123
+ output.write(`${color.cyan('?')} ${message}\n`);
124
+ render();
125
+
126
+ const stop = readKeys((character, key) => {
127
+ if (key.name === 'up') {
128
+ selected = (selected - 1 + choices.length) % choices.length;
129
+ render();
130
+ } else if (key.name === 'down') {
131
+ selected = (selected + 1) % choices.length;
132
+ render();
133
+ } else if (key.name === 'return' || key.name === 'enter') {
134
+ stop();
135
+ const choice = choices[selected];
136
+ const value = typeof choice === 'string' ? choice : choice.value;
137
+ if (cursor.enabled) {
138
+ output.write(`${cursor.up(choices.length + 1)}\r${cursor.clearLine}${color.green(sym.check)} ${message} ${color.dim(sym.dots)} ${color.cyan(value)}\n${cursor.clearDown}`);
139
+ }
140
+ resolve(value);
141
+ } else if (key.ctrl && key.name === 'c') {
142
+ stop();
143
+ output.write('\n');
144
+ resolve(null);
145
+ }
146
+ });
147
+ });
148
+ }