@hit-sudomaker/ccw 0.4.1 → 0.5.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/dist/cleanup.js CHANGED
@@ -1,393 +1,179 @@
1
1
  import path from 'node:path';
2
- import { DATA_CATEGORY_KEYS, knownTitle } from './titles.js';
2
+ import { knownTitle } from './management-catalog.js';
3
+ import { claudeRunning } from './claude-program.js';
3
4
  import { errorCode } from './machine.js';
4
- import { cancelled, claudeRunning, normalizePath, restOf } from './model.js';
5
- const CATEGORIES = DATA_CATEGORY_KEYS;
6
- /** 删除循环内周期复核 Claude 进程:删除可能跨越进程启动 */
7
- const PROCESS_RECHECK_INTERVAL_MS = 1_000;
8
- /** 清理结果仍有保留(新增、再生或共享链接)时标题须警示:清理承诺删除所选数据,保留是异常;
9
- * 卸载/安装的保留项是承诺,不警示;发射点与消费表共用同名常量,新增保留码不得漏登记 */
10
- const RESIDUE_REGENERATED = 'data-remains-or-regenerated';
11
- const RESIDUE_LINK_KEPT = 'cleanup-link-kept';
12
- export const CLEANUP_RESIDUE_CODES = [RESIDUE_REGENERATED, RESIDUE_LINK_KEPT];
5
+ import { normalizePath, restOf, unchanged } from './model.js';
6
+ import { step } from './work.js';
7
+ const CATEGORIES = ['cache', 'history', 'memory', 'backups', 'runtime'];
8
+ const SIZE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB'];
9
+ const BINARY_UNIT_BASE = 1024;
13
10
  const DIRECTORIES = {
14
- backup: 'backups',
15
- backups: 'backups',
16
- cache: 'cache',
17
- 'daemon/dispatch': 'runtime',
18
- 'daemon/pty-pids': 'runtime',
19
- debug: 'cache',
20
- 'file-history': 'history',
21
- 'image-cache': 'cache',
22
- jobs: 'runtime',
23
- logs: 'cache',
24
- 'paste-cache': 'cache',
25
- projects: 'projects',
26
- 'session-env': 'runtime',
27
- sessions: 'runtime',
28
- 'shell-snapshots': 'history',
29
- statsig: 'cache',
30
- tasks: 'runtime',
31
- 'usage-data': 'cache',
32
- 'agent-memory': 'memory',
33
- 'agent-memory-local': 'memory',
11
+ cache: ['cache', 'debug', 'image-cache', 'logs', 'paste-cache', 'statsig', 'usage-data'],
12
+ history: ['file-history', 'shell-snapshots', 'sessions', 'projects'],
13
+ memory: ['agent-memory', 'agent-memory-local', 'projects'],
14
+ backups: ['backup', 'backups'],
15
+ runtime: ['daemon/dispatch', 'daemon/pty-pids', 'jobs', 'session-env', 'tasks'],
34
16
  };
35
17
  const FILES = {
36
- 'daemon.lock': 'runtime',
37
- 'daemon.log': 'cache',
38
- 'daemon.status.json': 'runtime',
39
- 'history.jsonl': 'history',
40
- 'stats-cache.json': 'cache',
18
+ cache: ['daemon.log', 'stats-cache.json'],
19
+ history: ['history.jsonl'],
20
+ memory: [],
21
+ backups: [],
22
+ runtime: ['daemon.lock', 'daemon.status.json'],
41
23
  };
42
- function isCategory(value) {
43
- return CATEGORIES.some(category => category === value);
44
- }
45
- /** 人类可读字节:满 1024 即换算到下一单位(B/KB/MB/GB/TB),保留 1 位小数 */
46
- export function formatBytes(bytes) {
47
- const units = ['B', 'KB', 'MB', 'GB', 'TB'];
48
- let value = bytes * 10n;
49
- let unit = 0;
50
- while (unit < units.length - 1 && value >= 10n * 1024n) {
51
- value = (value + 512n) / 1024n;
24
+ function size(bytes) {
25
+ let value = Number(bytes), unit = 0;
26
+ while (value >= BINARY_UNIT_BASE && unit < SIZE_UNITS.length - 1) {
27
+ value /= BINARY_UNIT_BASE;
52
28
  unit++;
53
29
  }
54
- return unit === 0 ? `${value / 10n} B` : `${value / 10n}.${value % 10n} ${units[unit]}`;
55
- }
56
- function size(files) {
57
- return `${files.length} · ${formatBytes(files.reduce((sum, file) => sum + file.sizeBytes, 0n))}`;
30
+ return `${unit ? value.toFixed(1) : value} ${SIZE_UNITS[unit]}`;
58
31
  }
59
- /** 「文件数 · 逻辑大小」事实的读取面:详情提取与空类别判定跟生产格式同处一地,消费者不反解格式 */
60
- export const dataSizeDetailOf = (item) => item.facts.find(fact => fact.code === 'data-size')?.detail;
61
- export const isEmptyDataSize = (detail) => detail === undefined || detail.startsWith('0 · ');
62
- /** 清点白名单;projects 的记忆独立选择,读取缺口按类别保留 */
63
- async function candidates(ctx, selected) {
64
- const empty = () => ({ files: [], directories: [], problems: [], preserved: [] });
65
- const result = { cache: empty(), history: empty(), memory: empty(), backups: empty(), runtime: empty() };
66
- const groups = (group) => (group === 'projects' ? ['history', 'memory'] : [group]).filter(category => !selected || category === selected);
67
- const problem = (group, file, error) => {
68
- for (const category of groups(group))
69
- result[category].problems.push({ code: errorCode(error), detail: file });
70
- };
71
- const preserve = (group, file) => {
72
- for (const category of groups(group))
73
- result[category].preserved.push({ code: RESIDUE_LINK_KEPT, detail: file });
74
- };
75
- const regularFile = (file, category, sizeBytes) => {
76
- if (!groups(category).length)
77
- return;
78
- result[category].files.push({ file, sizeBytes });
32
+ async function inventory(ctx, category) {
33
+ const files = [];
34
+ const directories = [];
35
+ const links = [];
36
+ const real = await ctx.machine.realpath(ctx.claudeRoot);
37
+ if (real !== null && normalizePath(ctx.platform, real) !== normalizePath(ctx.platform, ctx.claudeRoot))
38
+ throw new Error('linked-parent');
39
+ const belongs = (file) => {
40
+ const parts = path.relative(ctx.claudeRoot, file).split(path.sep);
41
+ return parts[0] !== 'projects' || (parts[2] === 'memory') === (category === 'memory');
79
42
  };
80
- const walk = async (directory, group, isRoot = false) => {
81
- if (!groups(group).length)
82
- return;
83
- const memoryBefore = result.memory.files.length + result.memory.directories.length;
84
- try {
85
- for (const entry of await ctx.machine.entries(directory)) {
86
- const file = path.join(directory, entry.name);
87
- const childGroup = group === 'projects' && entry.name === 'memory' && entry.kind === 'directory' ? 'memory' : group;
88
- if (entry.kind === 'link') {
89
- preserve(childGroup, file);
90
- continue;
91
- }
92
- if (entry.kind === 'directory')
93
- await walk(file, childGroup);
94
- else
95
- regularFile(file, group === 'projects' ? 'history' : group, entry.sizeBytes);
96
- }
97
- if (!isRoot)
98
- for (const category of groups(group)) {
99
- if (group !== 'projects' ||
100
- category !== 'memory' ||
101
- result.memory.files.length + result.memory.directories.length > memoryBefore)
102
- result[category].directories.push(directory);
103
- }
43
+ const visit = async (file, kind, bytes) => {
44
+ if (kind === 'link') {
45
+ if (belongs(file))
46
+ links.push(file);
47
+ return false;
104
48
  }
105
- catch (error) {
106
- problem(group, directory, error);
49
+ if (kind === 'file') {
50
+ if (belongs(file))
51
+ files.push({ file, size: bytes });
52
+ return belongs(file);
107
53
  }
54
+ let removable = belongs(file);
55
+ for (const entry of await ctx.machine.entries(file))
56
+ if (!(await visit(path.join(file, entry.name), entry.kind, entry.sizeBytes)))
57
+ removable = false;
58
+ if (removable)
59
+ directories.push(file);
60
+ return removable;
108
61
  };
109
- try {
110
- if (ctx.platform === 'win32' && /^[\\/]{2}/.test(ctx.claudeRoot))
111
- throw new Error('cleanup-network-root');
112
- const real = await ctx.machine.realpath(ctx.claudeRoot);
113
- if (real !== null && normalizePath(ctx.platform, real) !== normalizePath(ctx.platform, ctx.claudeRoot))
114
- throw new Error('linked-parent');
115
- }
116
- catch (error) {
117
- for (const category of CATEGORIES)
118
- problem(category, ctx.claudeRoot, error);
119
- return result;
120
- }
121
- for (const [kind, roots] of [
122
- ['directory', DIRECTORIES],
123
- ['file', FILES],
124
- ]) {
125
- for (const [relative, group] of Object.entries(roots)) {
126
- if (!groups(group).length)
62
+ for (const [kind, names] of [
63
+ ['directory', DIRECTORIES[category]],
64
+ ['file', FILES[category]],
65
+ ])
66
+ for (const name of names) {
67
+ const file = path.join(ctx.claudeRoot, name);
68
+ const canonical = await ctx.machine.realpath(file);
69
+ if (canonical !== null && normalizePath(ctx.platform, canonical) !== normalizePath(ctx.platform, file)) {
70
+ links.push(file);
127
71
  continue;
128
- const file = path.join(ctx.claudeRoot, relative);
129
- try {
130
- const entry = (await ctx.machine.entries(path.dirname(file))).find(value => value.name === path.basename(file));
131
- if (!entry)
132
- continue;
133
- if (entry.kind === 'link') {
134
- preserve(group, file);
135
- continue;
136
- }
137
- if (entry.kind !== kind)
138
- throw new Error('cleanup-type-changed');
139
- if (entry.kind === 'directory')
140
- await walk(file, group, true);
141
- else if (group !== 'projects')
142
- regularFile(file, group, entry.sizeBytes);
143
- }
144
- catch (error) {
145
- problem(group, file, error);
146
72
  }
73
+ const entry = (await ctx.machine.entries(path.dirname(file))).find(entry => entry.name === path.basename(file));
74
+ if (!entry)
75
+ continue;
76
+ if (entry.kind !== 'link' && entry.kind !== kind)
77
+ throw new Error('cleanup-type-changed');
78
+ await visit(file, entry.kind, entry.sizeBytes);
147
79
  }
148
- }
149
- return result;
150
- }
151
- /** 创建清理域渠道:检查数组归一为聚合,余段即数据类别,clean 是唯一动作 */
152
- export function createCleanupDomain(ctx) {
153
80
  return {
154
- async inspect() {
155
- return { items: await inspectCleanup(ctx), problems: [] };
156
- },
157
- prepare(selection) {
158
- const category = restOf(selection.id);
159
- if (category === undefined || selection.action !== 'clean')
160
- throw new Error('unknown-selection');
161
- return prepareCleanup(ctx, category);
162
- },
81
+ files,
82
+ directories,
83
+ links,
84
+ detail: `${files.length} 个文件 · ${directories.length} 个目录 · ${size(files.reduce((sum, file) => sum + file.size, 0n))}`,
163
85
  };
164
86
  }
165
- async function inspectCleanup(ctx) {
166
- const found = await candidates(ctx);
167
- return CATEGORIES.map(category => {
168
- const inventory = found[category];
169
- return {
170
- id: `data:${category}`,
171
- title: knownTitle(`data:${category}`),
87
+ /** 清点白名单数据,保留配置、凭据、插件和 Skills */
88
+ export async function inspectClaudeData(ctx) {
89
+ const items = await Promise.all(CATEGORIES.map(async (category) => {
90
+ const item = {
91
+ id: 'data:' + category,
92
+ title: knownTitle('data:' + category),
172
93
  kind: 'data',
173
94
  location: ctx.claudeRoot,
174
- facts: [{ code: 'data-size', detail: size(inventory.files) }, ...inventory.preserved, ...inventory.problems],
175
- ...(inventory.problems.length ? { problem: 'cleanup-inspection-incomplete' } : {}),
176
- actions: inventory.files.length || inventory.directories.length || inventory.problems.length ? ['clean'] : [],
177
95
  };
178
- });
179
- }
180
- async function prepareCleanup(ctx, category) {
181
- if (!isCategory(category))
182
- throw new Error('invalid-data-category');
183
- const inventory = (await candidates(ctx, category))[category];
184
- if (inventory.problems.length)
185
- throw new Error('cleanup-inspection-incomplete');
186
- const files = [];
187
- const { directories } = inventory;
188
- for (const file of inventory.files) {
189
- const stamp = await ctx.machine.fingerprint(file.file);
190
- if (stamp !== null)
191
- files.push({ ...file, stamp });
192
- }
193
- let index = 0;
194
- let directoryIndex = 0;
195
- let isComplete = false;
196
- const removed = [];
197
- const operation = {
198
- get changes() {
199
- return [
200
- { code: 'data-delete', detail: `${knownTitle(`data:${category}`)} · ${size(files.slice(index))}` },
201
- { code: 'data-clean-root', detail: ctx.claudeRoot },
202
- { code: 'no-recovery' },
203
- { code: 'keep-settings-credentials' },
204
- ...(category === 'runtime' ? [{ code: 'data-runtime-impact' }] : []),
205
- ...inventory.preserved,
206
- ...(directories.length > directoryIndex
207
- ? [{ code: 'data-empty-directories', detail: `${directories.length - directoryIndex}` }]
208
- : []),
209
- ];
210
- },
211
- async run(report, signal) {
212
- let checkedAtMs = 0;
213
- const checkProcess = async () => {
214
- cancelled(signal);
215
- const isClaudeRunning = await claudeRunning(ctx.machine, signal);
216
- cancelled(signal);
217
- if (isClaudeRunning !== false)
218
- throw new Error('claude-may-be-running');
219
- checkedAtMs = performance.now();
96
+ try {
97
+ const found = await inventory(ctx, category);
98
+ return {
99
+ ...item,
100
+ canClean: found.files.length > 0 || found.directories.length > 0,
101
+ facts: [
102
+ { code: 'data-size', detail: found.detail },
103
+ ...(found.links.length ? [{ code: 'data-links-kept', detail: String(found.links.length) }] : []),
104
+ ],
220
105
  };
221
- await checkProcess();
222
- while (index < files.length) {
223
- cancelled(signal);
224
- if (performance.now() - checkedAtMs >= PROCESS_RECHECK_INTERVAL_MS)
225
- await checkProcess();
226
- const file = files[index];
227
- if (!file)
228
- break;
229
- if ((await ctx.machine.treeStamp(file.file, signal)) === null) {
230
- index++;
231
- report({ state: 'kept', code: 'data-file-absent', detail: file.file });
232
- continue;
233
- }
234
- try {
235
- await ctx.machine.removeTree(file.file, file.stamp);
236
- }
237
- catch (error) {
238
- if ((await ctx.machine.treeStamp(file.file, signal)) !== null)
239
- throw error;
240
- }
241
- removed.push(file);
242
- index++;
243
- report({ state: 'done', code: 'data-file-removed', detail: file.file });
244
- }
245
- while (directoryIndex < directories.length) {
246
- cancelled(signal);
247
- if (performance.now() - checkedAtMs >= PROCESS_RECHECK_INTERVAL_MS)
248
- await checkProcess();
249
- const directory = directories[directoryIndex];
250
- if (!directory)
251
- break;
252
- await ctx.machine.removeEmptyDirectory(directory);
253
- directoryIndex++;
254
- }
255
- cancelled(signal);
256
- const remaining = (await candidates(ctx, category))[category];
257
- if (remaining.problems.length) {
258
- for (const problem of remaining.problems)
259
- report({ state: 'kept', ...problem });
260
- throw new Error('cleanup-inspection-incomplete');
261
- }
262
- await checkProcess();
263
- isComplete = true;
264
- report({ state: 'done', code: 'data-selected-cleared', detail: size(removed) });
265
- for (const preserved of remaining.preserved)
266
- report({ state: 'kept', ...preserved });
267
- if (remaining.files.length)
268
- report({ state: 'kept', code: RESIDUE_REGENERATED, detail: size(remaining.files) });
269
- if (files.length === 0 && directories.length === 0)
270
- report({ state: 'kept', code: 'no-data' });
271
- },
272
- remaining: () => (isComplete ? undefined : operation),
273
- };
274
- return operation;
106
+ }
107
+ catch (error) {
108
+ return { ...item, canClean: false, facts: [], problem: errorCode(error) };
109
+ }
110
+ }));
111
+ return { items, problems: [] };
275
112
  }
276
- /** 删除明确选择的整个配置根;首次删除读取当前内容,继续只处理原目标并保护已删路径的重建 */
277
- export async function prepareClaudeDataRemoval(ctx, verifyPrograms) {
278
- const normalize = (file) => normalizePath(ctx.platform, file);
279
- const contains = (directory, file) => normalize(file) === normalize(directory) || normalize(file).startsWith(`${normalize(directory)}${path.sep}`);
280
- if (contains(ctx.claudeRoot, ctx.home) ||
281
- contains(ctx.claudeRoot, ctx.storage) ||
282
- contains(ctx.storage, ctx.claudeRoot))
283
- throw new Error('invalid-data-root');
284
- if (!contains(ctx.claudeRoot, ctx.stateFile) &&
285
- normalize(ctx.stateFile) !== normalize(path.join(ctx.home, '.claude.json')))
286
- throw new Error('invalid-data-root');
287
- const targets = [
288
- { file: ctx.claudeRoot, kind: 'directory' },
289
- ...(!contains(ctx.claudeRoot, ctx.stateFile) ? [{ file: ctx.stateFile, kind: 'file' }] : []),
290
- ];
291
- const checkTarget = async (target) => {
292
- if (!path.isAbsolute(target.file))
293
- throw new Error('invalid-data-root');
294
- if (ctx.platform === 'win32' && /^[\\/]{2}/.test(target.file))
295
- throw new Error('cleanup-network-root');
296
- const parent = await ctx.machine.realpath(path.dirname(target.file));
297
- const real = await ctx.machine.realpath(target.file);
298
- if ((parent !== null && normalize(parent) !== normalize(path.dirname(target.file))) ||
299
- (real !== null && normalize(real) !== normalize(target.file)))
300
- throw new Error('linked-parent');
301
- const entry = (await ctx.machine.entries(path.dirname(target.file))).find(value => normalize(path.join(path.dirname(target.file), value.name)) === normalize(target.file));
302
- if (entry && entry.kind !== target.kind)
303
- throw new Error('cleanup-type-changed');
304
- return entry !== undefined;
305
- };
306
- const pending = await Promise.all(targets.map(async (target) => ({
307
- ...target,
308
- hasExisted: await checkTarget(target),
309
- hasAttemptedRemoval: false,
310
- stamp: null,
311
- isDone: false,
312
- })));
313
- let isComplete = false;
314
- const checkProcess = async (signal) => {
315
- cancelled(signal);
316
- const isClaudeRunning = await claudeRunning(ctx.machine, signal);
317
- cancelled(signal);
318
- if (isClaudeRunning !== false)
319
- throw new Error(isClaudeRunning ? 'claude-running' : 'process-state-unconfirmed');
320
- };
321
- await checkProcess();
322
- const verify = async () => {
323
- for (const target of pending)
324
- if ((await ctx.machine.treeStamp(target.file)) !== null)
325
- throw new Error('target-changed');
113
+ async function requireStopped(ctx) {
114
+ const running = await claudeRunning(ctx.machine);
115
+ if (running !== false)
116
+ throw new Error(running ? 'claude-running' : 'process-state-unconfirmed');
117
+ }
118
+ /** 删除已确认的类别快照,保留 Claude 配置根目录 */
119
+ export async function prepareDataCleanup(ctx, selection) {
120
+ const category = CATEGORIES.find(value => value === restOf(selection.id));
121
+ if (!category || selection.action !== 'clean')
122
+ throw new Error('unknown-selection');
123
+ const found = await inventory(ctx, category);
124
+ await requireStopped(ctx);
125
+ const files = await Promise.all(found.files.map(async (file) => ({ ...file, stamp: await ctx.machine.fingerprint(file.file) })));
126
+ const before = async () => {
127
+ await requireStopped(ctx);
128
+ await inventory(ctx, category);
129
+ for (const file of files)
130
+ unchanged(await ctx.machine.fingerprint(file.file), file.stamp);
326
131
  };
327
- const operation = {
328
- get changes() {
329
- return [
330
- ...pending
331
- .filter(target => !target.isDone)
332
- .map(target => ({
333
- code: target.kind === 'directory' ? 'claude-data-remove' : 'claude-state-remove',
334
- detail: target.file,
335
- })),
336
- { code: 'claude-data-impact' },
337
- { code: 'no-recovery' },
338
- ];
339
- },
340
- async run(report, signal) {
341
- await checkProcess(signal);
342
- await verifyPrograms();
343
- for (const target of pending) {
344
- const isPresent = await checkTarget(target);
345
- if (isPresent && (target.isDone || !target.hasExisted))
346
- throw new Error('target-changed');
132
+ return {
133
+ ...step([
134
+ { code: 'data-delete', detail: found.detail },
135
+ { code: 'data-root', detail: ctx.claudeRoot },
136
+ { code: 'data-permanent' },
137
+ { code: 'data-keep-configuration' },
138
+ ...(found.links.length ? [{ code: 'data-links-kept', detail: String(found.links.length) }] : []),
139
+ ], async (fact) => {
140
+ if (!fact.dispatched) {
141
+ await before();
142
+ return { state: 'ready' };
347
143
  }
348
- for (const target of pending) {
349
- if (target.isDone)
350
- continue;
351
- await checkProcess(signal);
352
- await checkTarget(target);
353
- const current = await (target.kind === 'file'
354
- ? ctx.machine.fingerprint(target.file, signal)
355
- : ctx.machine.treeStamp(target.file, signal)).catch(error => {
356
- cancelled(signal);
357
- throw error;
358
- });
359
- if (current !== null) {
360
- if (!target.hasExisted)
361
- throw new Error('target-changed');
362
- if (target.hasAttemptedRemoval && current !== target.stamp)
363
- throw new Error('target-changed');
364
- target.stamp = current;
365
- target.hasAttemptedRemoval = true;
366
- await checkProcess(signal);
367
- try {
368
- if (target.kind === 'file')
369
- await ctx.machine.remove(target.file, current);
370
- else
371
- await ctx.machine.removeTree(target.file, current);
372
- }
373
- catch (error) {
374
- if ((await ctx.machine.treeStamp(target.file, signal)) !== null)
375
- throw error;
144
+ const current = await inventory(ctx, category);
145
+ if (current.files.length || current.directories.length)
146
+ return { state: 'blocked', problem: fact.receipt?.failure ?? 'cleanup-incomplete' };
147
+ return { state: 'complete' };
148
+ }, async () => {
149
+ const effects = [];
150
+ try {
151
+ await before();
152
+ for (const file of files) {
153
+ await requireStopped(ctx);
154
+ if (file.stamp !== null)
155
+ await ctx.effects.removeTree(file.file, file.stamp);
156
+ effects.push({ state: 'done', code: 'data-file-removed', detail: file.file });
157
+ }
158
+ for (const directory of found.directories) {
159
+ if ((await ctx.machine.entries(directory)).length)
160
+ continue;
161
+ const stamp = await ctx.machine.treeStamp(directory);
162
+ if (stamp !== null) {
163
+ await requireStopped(ctx);
164
+ await ctx.effects.removeTree(directory, stamp);
376
165
  }
377
166
  }
378
- target.isDone = true;
379
- report({
380
- state: current === null ? 'kept' : 'done',
381
- code: current === null ? 'data-file-absent' : 'claude-data-removed',
382
- detail: target.file,
383
- });
167
+ if (!effects.length)
168
+ effects.push({ state: 'done', code: 'data-cleared' });
169
+ if (found.links.length)
170
+ effects.push({ state: 'kept', code: 'data-links-kept', detail: String(found.links.length) });
171
+ return { receipt: { kind: 'returned', failure: null }, effects };
172
+ }
173
+ catch (error) {
174
+ return { receipt: { kind: 'unknown', failure: errorCode(error) }, effects };
384
175
  }
385
- await verify();
386
- isComplete = true;
387
- report({ state: 'done', code: 'claude-data-cleared' });
388
- },
389
- remaining: () => (isComplete ? undefined : operation),
390
- verify,
176
+ }),
177
+ action: 'clean',
391
178
  };
392
- return operation;
393
179
  }
@@ -0,0 +1,65 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ /**
3
+ * 隔离异步调用链的写入资格
4
+ *
5
+ * @returns 受保护的写入能力,以及授予当前调用链资格的 run 方法
6
+ * @remarks 每次派发检查资格和取消,不中断或撤销已派发操作
7
+ */
8
+ export function createEffectScope(machine) {
9
+ const execution = new AsyncLocalStorage();
10
+ let active;
11
+ return {
12
+ machine: createEffectMachine(machine, () => {
13
+ if (active === undefined || execution.getStore() !== active)
14
+ return false;
15
+ if (active.signal?.aborted)
16
+ throw new Error('cancelled');
17
+ return true;
18
+ }),
19
+ /**
20
+ * 授予 work 调用链写入资格,结束后撤销
21
+ *
22
+ * @param work - Promise 须覆盖全部写入
23
+ * @param cancellation - 已取消时,后续能力派发同步抛出 cancelled
24
+ * @throws 已有调用运行时拒绝为 operation-in-progress;work 异常原样传播
25
+ * @remarks 取消只阻止后续派发,不跳过 work 或强制其失败
26
+ */
27
+ run(work, cancellation) {
28
+ if (active !== undefined)
29
+ return Promise.reject(new Error('operation-in-progress'));
30
+ active = cancellation ? { signal: cancellation } : {};
31
+ return execution.run(active, async () => {
32
+ try {
33
+ return await work();
34
+ }
35
+ finally {
36
+ active = undefined;
37
+ }
38
+ });
39
+ },
40
+ };
41
+ }
42
+ /**
43
+ * 每次调用写入能力前检查资格
44
+ *
45
+ * @param allowed - 同步资格检查,可抛出取消等错误,结果不缓存
46
+ * @throws 无资格时同步抛出 effect-not-authorized;检查异常原样传播
47
+ * @remarks 不复核完成时的资格,也不中断已派发操作
48
+ */
49
+ export function createEffectMachine(machine, allowed) {
50
+ const guarded = (work) => (...args) => {
51
+ if (!allowed())
52
+ throw new Error('effect-not-authorized');
53
+ return work(...args);
54
+ };
55
+ return {
56
+ initialize: guarded((file, text) => machine.initialize(file, text)),
57
+ editJson: guarded((file, edit) => machine.editJson(file, edit)),
58
+ npm: guarded((args, options) => machine.npm(args, options)),
59
+ removeTree: guarded((file, expected, preserveAt) => machine.removeTree(file, expected, preserveAt)),
60
+ replaceTree: guarded((directory, files, expected, preserveAt) => machine.replaceTree(directory, files, expected, preserveAt)),
61
+ execute: guarded((file, args, options) => machine.execute(file, args, options)),
62
+ replaceFile: guarded((file, data, expected, executable) => machine.replaceFile(file, data, expected, executable)),
63
+ ensureUserPath: guarded(directory => machine.ensureUserPath(directory)),
64
+ };
65
+ }