|
1 | | -import { type ConfigDocument, ControlError, MAX_CONFIG_BYTES } from '@fraqjs/cli-protocol'; |
| 1 | +import { type ConfigChanges, type ConfigDocument, type ConfigWorkspace, ControlError } from '@fraqjs/cli-protocol'; |
2 | 2 | import z from 'zod'; |
3 | 3 |
|
| 4 | +import { type FileEdit, FileRegistry } from './files'; |
4 | 5 | import { parseConfigText } from './references'; |
5 | 6 | import { findConfigPath } from './shared'; |
6 | 7 | import { ConfigV1 } from './v1'; |
7 | 8 |
|
8 | | -import { createHash, randomUUID } from 'node:crypto'; |
9 | | -import { readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'; |
| 9 | +import { randomUUID } from 'node:crypto'; |
| 10 | +import { chmodSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'; |
10 | 11 | import path from 'node:path'; |
11 | 12 |
|
12 | 13 | export class ConfigEditor { |
| 14 | + constructor(private readonly replaceFile = renameSync) {} |
| 15 | + |
| 16 | + private scan(): { registry: FileRegistry; workspace: ConfigWorkspace } { |
| 17 | + const registry = new FileRegistry(findConfigPath()); |
| 18 | + let failed = false; |
| 19 | + try { |
| 20 | + const resolved = parseConfigText(registry.read(registry.mainPath), registry.mainPath, { |
| 21 | + onFileAccess: (file, kind) => registry.access(file, kind), |
| 22 | + readFile: (file) => registry.read(file), |
| 23 | + onError: () => { |
| 24 | + failed = true; |
| 25 | + }, |
| 26 | + }); |
| 27 | + if (!ConfigV1.safeParse(resolved).success) failed = true; |
| 28 | + } catch { |
| 29 | + failed = true; |
| 30 | + } |
| 31 | + return { |
| 32 | + registry, |
| 33 | + workspace: { |
| 34 | + root: registry.root, |
| 35 | + revision: registry.revision, |
| 36 | + files: registry.list(), |
| 37 | + ...(failed ? { error: '配置或引用存在错误,请修复后保存。' } : {}), |
| 38 | + }, |
| 39 | + }; |
| 40 | + } |
| 41 | + |
| 42 | + list(): ConfigWorkspace { |
| 43 | + return this.scan().workspace; |
| 44 | + } |
| 45 | + |
13 | 46 | read(): ConfigDocument { |
14 | | - const file = findConfigPath(); |
15 | | - if (statSync(file).size > MAX_CONFIG_BYTES) throw new ControlError('invalid', '配置文件超过 1 MiB,无法在线编辑。'); |
16 | | - const content = readFileSync(file, 'utf8'); |
17 | | - const revision = createHash('sha256').update(realpathSync(file)).update('\0').update(content).digest('hex'); |
18 | | - return { name: path.basename(file), format: file.endsWith('.json') ? 'json' : 'yaml', content, revision }; |
| 47 | + const workspace = this.list(); |
| 48 | + const main = workspace.files.find((file) => file.main); |
| 49 | + if (!main?.editable || main.format === 'text') throw new ControlError('invalid', '主配置无法在线编辑。'); |
| 50 | + return { name: main.name, format: main.format, content: main.content, revision: workspace.revision }; |
19 | 51 | } |
20 | 52 |
|
21 | 53 | save(content: string, revision: string): ConfigDocument { |
22 | | - if (Buffer.byteLength(content) > MAX_CONFIG_BYTES) throw new ControlError('invalid', '配置文件不能超过 1 MiB。'); |
23 | | - if (this.read().revision !== revision) |
24 | | - throw new ControlError('conflict', '配置已被其他操作修改,请重新读取后再保存。'); |
25 | | - const file = findConfigPath(); |
| 54 | + const main = this.list().files.find((file) => file.main); |
| 55 | + if (!main) throw new ControlError('invalid', '找不到主配置。'); |
| 56 | + this.saveFiles({ revision, files: [{ id: main.id, content }] }); |
| 57 | + return this.read(); |
| 58 | + } |
| 59 | + |
| 60 | + saveFiles(changes: ConfigChanges): ConfigWorkspace { |
| 61 | + const { registry, workspace } = this.scan(); |
| 62 | + if (workspace.revision !== changes.revision) |
| 63 | + throw new ControlError('conflict', '配置或引用文件已被修改,请重新读取后再保存。'); |
| 64 | + const edits = registry.edits(changes.files); |
| 65 | + if (!edits.length) throw new ControlError('invalid', '没有需要保存的文件。'); |
| 66 | + const overlays = new Map(edits.map((edit) => [edit.target, edit.content])); |
| 67 | + const validation = new FileRegistry(registry.mainPath); |
| 68 | + let resolved: unknown; |
26 | 69 | try { |
27 | | - const result = ConfigV1.safeParse(parseConfigText(content, file)); |
28 | | - if (!result.success) throw new Error(z.prettifyError(result.error)); |
29 | | - } catch (error) { |
30 | | - throw new ControlError('invalid', error instanceof Error ? error.message : String(error)); |
| 70 | + resolved = parseConfigText( |
| 71 | + overlays.get(realpathSync(registry.mainPath)) ?? registry.read(registry.mainPath), |
| 72 | + registry.mainPath, |
| 73 | + { |
| 74 | + onFileAccess: (file, kind) => validation.access(file, kind), |
| 75 | + readFile: (file) => overlays.get(realpathSync(file)) ?? validation.read(file), |
| 76 | + }, |
| 77 | + ); |
| 78 | + } catch { |
| 79 | + // Parser errors can contain excerpts from references outside the editable directory. |
| 80 | + throw new ControlError('invalid', '无法解析配置或引用文件,请检查语法、引用路径和环境变量。'); |
| 81 | + } |
| 82 | + validation.validateBudget(overlays); |
| 83 | + const result = ConfigV1.safeParse(resolved); |
| 84 | + if (!result.success) { |
| 85 | + const outside = validation.list().some((file) => !file.editable && file.reason === '超出编辑范围'); |
| 86 | + throw new ControlError('invalid', outside ? '配置字段类型或结构不符合要求。' : z.prettifyError(result.error)); |
31 | 87 | } |
32 | | - const target = realpathSync(file); |
33 | | - const temporary = path.join(path.dirname(target), `.${path.basename(target)}.${randomUUID()}.tmp`); |
| 88 | + |
| 89 | + const staged: (FileEdit & { temporary: string; backup: string; committed: boolean })[] = []; |
| 90 | + let preserveBackups = false; |
34 | 91 | try { |
35 | | - writeFileSync(temporary, content, { mode: statSync(target).mode & 0o777, flag: 'wx' }); |
36 | | - if (this.read().revision !== revision || realpathSync(findConfigPath()) !== target) { |
37 | | - throw new ControlError('conflict', '保存期间配置发生变化,请重新读取。'); |
| 92 | + for (const edit of edits) { |
| 93 | + const prefix = path.join(path.dirname(edit.target), `.${path.basename(edit.target)}.${randomUUID()}`); |
| 94 | + const entry = { |
| 95 | + ...edit, |
| 96 | + temporary: `${prefix}.tmp`, |
| 97 | + backup: `${prefix}.bak`, |
| 98 | + committed: false, |
| 99 | + }; |
| 100 | + staged.push(entry); |
| 101 | + writeFileSync(entry.temporary, edit.content, { mode: edit.mode, flag: 'wx' }); |
| 102 | + writeFileSync(entry.backup, edit.original, { mode: edit.mode, flag: 'wx' }); |
| 103 | + chmodSync(entry.temporary, edit.mode); |
| 104 | + chmodSync(entry.backup, edit.mode); |
| 105 | + } |
| 106 | + if (findConfigPath() !== registry.mainPath || !registry.unchanged() || !validation.unchanged()) { |
| 107 | + throw new ControlError('conflict', '保存期间配置或引用文件发生变化。'); |
38 | 108 | } |
39 | | - renameSync(temporary, target); |
40 | | - return this.read(); |
| 109 | + // No await: watcher callbacks cannot start a reload between these replacements. |
| 110 | + for (const edit of staged) { |
| 111 | + if ( |
| 112 | + edit.paths.some((file) => realpathSync(file) !== edit.target) || |
| 113 | + !readFileSync(edit.target).equals(edit.original) |
| 114 | + ) { |
| 115 | + throw new ControlError('conflict', '保存期间文件或符号链接发生变化。'); |
| 116 | + } |
| 117 | + this.replaceFile(edit.temporary, edit.target); |
| 118 | + edit.committed = true; |
| 119 | + } |
| 120 | + } catch (error) { |
| 121 | + for (const entry of staged.filter((entry) => entry.committed).reverse()) { |
| 122 | + try { |
| 123 | + if (realpathSync(entry.target) !== entry.target || readFileSync(entry.target, 'utf8') !== entry.content) |
| 124 | + throw new Error('changed'); |
| 125 | + this.replaceFile(entry.backup, entry.target); |
| 126 | + } catch { |
| 127 | + preserveBackups = true; |
| 128 | + } |
| 129 | + } |
| 130 | + if (preserveBackups) |
| 131 | + throw new ControlError( |
| 132 | + 'internal', |
| 133 | + '保存失败且无法完整恢复;原文件备份保留在同目录的 .bak 文件中,请通过终端处理。', |
| 134 | + ); |
| 135 | + if (error instanceof ControlError) throw error; |
| 136 | + throw new ControlError('internal', '文件写入失败,已恢复原内容。'); |
41 | 137 | } finally { |
42 | | - rmSync(temporary, { force: true }); |
| 138 | + for (const entry of staged) { |
| 139 | + rmSync(entry.temporary, { force: true }); |
| 140 | + if (!preserveBackups) rmSync(entry.backup, { force: true }); |
| 141 | + } |
43 | 142 | } |
| 143 | + return this.list(); |
44 | 144 | } |
45 | 145 | } |
0 commit comments