dsh-devdock-cloudflare 0.0.0-stage → 3.0.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,1072 @@
1
+ /**
2
+ * Cloudflare 平台插件 · Host 实现。
3
+ *
4
+ * 这个模块不认识内核:它拿到一个经过内核裁剪的 `context`(存储、错误构造、
5
+ * 校验函数、llm 探测),返回一份标准平台定义。内核负责把 routes 挂到
6
+ * webServer、把 actions 聚合进 `devdock` 工具。
7
+ *
8
+ * 之所以这样划界:用户可能只装本插件而不装 github / npm,所以不能有任何
9
+ * 反向依赖;同时界面与模型必须走同一条代码路径(one operation, two callers)。
10
+ *
11
+ * @module src/host/platform.js
12
+ */
13
+
14
+ import {
15
+ verifyToken as verifyCfToken,
16
+ listAccounts as listCfAccounts,
17
+ listPagesProjects,
18
+ deletePagesProject,
19
+ createPagesProject,
20
+ listWorkers,
21
+ deleteWorker,
22
+ listZones,
23
+ detectProjectKind,
24
+ collectUploadFiles,
25
+ createPagesDeployment,
26
+ resolveWorkerMain,
27
+ deployWorkerModule,
28
+ dashUrl,
29
+ DNS_RECORD_TYPES,
30
+ listDnsRecords,
31
+ createDnsRecord,
32
+ updateDnsRecord,
33
+ deleteDnsRecord,
34
+ getZoneDetail,
35
+ purgeZoneCache,
36
+ setDevelopmentMode,
37
+ listPagesDeploymentsDetailed,
38
+ rollbackPagesDeployment,
39
+ deletePagesDeployment,
40
+ listPagesEnvVars,
41
+ patchPagesEnvVars,
42
+ listWorkerRoutes,
43
+ createWorkerRoute,
44
+ deleteWorkerRoute,
45
+ fetchUsage,
46
+ cfDashboard,
47
+ } from './cloudflare.js';
48
+ import {
49
+ BUILTIN_PRESETS,
50
+ normalizeFinding,
51
+ runModelReview,
52
+ scanSecrets,
53
+ MAX_FILE_BYTES,
54
+ sortFindings,
55
+ } from 'dsh-devdock-core/src/host/review.js';
56
+
57
+ /**
58
+ * 平台定义工厂。
59
+ *
60
+ * @param {object} context 内核注入的平台上下文
61
+ * @returns {object} PlatformDefinition
62
+ */
63
+ export function cloudflarePlatform(context) {
64
+ const {
65
+ store,
66
+ httpError,
67
+ requireString,
68
+ optionalString,
69
+ optionalBool,
70
+ redact,
71
+ llm,
72
+ reviewModels,
73
+ secrets,
74
+ } = context;
75
+
76
+ /* ---- 以下函数由原 class 方法改写而来(见 platform.js.body) ---- */
77
+
78
+ /**
79
+ * 当前 Cloudflare 账号(带令牌),缺失时给出可执行提示而不是空结果。
80
+ * @returns {Promise<object>}
81
+ */
82
+ async function requireCloudflareAccount_() {
83
+ const account = await store.activeCloudflareAccount();
84
+ if (!account) {
85
+ throw httpError(401, 'NO_ACCOUNT', '还没有登录 Cloudflare。请在 设置 › Cloudflare 中添加一个 API Token 或 Global API Key。');
86
+ }
87
+ return account;
88
+ }
89
+
90
+ /**
91
+ * 把一条已存账号折算成 Cloudflare 客户端要的凭据对象。
92
+ * @param {object} account store 里的账号记录
93
+ * @returns {{kind: string, token?: string, email?: string, key?: string}}
94
+ */
95
+ function cloudflareCredential_(account) {
96
+ if (account.authKind === 'global') {
97
+ return { kind: 'global', email: account.email, key: account.token };
98
+ }
99
+ return { kind: 'token', token: account.token };
100
+ }
101
+
102
+ /**
103
+ * 当前账号的 accountId;账号存在但还没选账户时,自动列账户并取第一个。
104
+ * @returns {Promise<{account: object, accountId: string}>}
105
+ */
106
+ async function cloudflareContext_() {
107
+ const account = await requireCloudflareAccount_();
108
+ if (account.accountId !== '') {
109
+ return { account, accountId: account.accountId };
110
+ }
111
+ const accounts = await listCfAccounts(cloudflareCredential_(account));
112
+ if (accounts.length === 0) {
113
+ throw httpError(400, 'NO_ACCOUNT', '这个 Cloudflare 凭据下没有可用的账户。');
114
+ }
115
+ const chosen = accounts[0];
116
+ await store.updateCloudflareAccount(account.id, {
117
+ accountId: chosen.id,
118
+ accountName: chosen.name,
119
+ });
120
+ return { account, accountId: chosen.id };
121
+ }
122
+
123
+ /**
124
+ * `GET /cf/accounts` — Cloudflare 账号列表(不带令牌)。
125
+ * @returns {Promise<object>}
126
+ */
127
+ async function cloudflareAccounts() {
128
+ return store.cloudflareAccounts();
129
+ }
130
+
131
+ /**
132
+ * `POST /cf/account` — 校验凭据后存储。
133
+ *
134
+ * 支持两种登录方式:
135
+ * - `{ token }` —— API Token(cfut_ / cfat_ 或旧 40 位字母数字)
136
+ * - `{ email, key }` —— Global API Key(cfk_ 或旧 37-45 位十六进制,全权限)
137
+ *
138
+ * @param {object} body `{ token?, email?, key?, authKind?, label? }`
139
+ * @returns {Promise<object>}
140
+ */
141
+ async function cloudflareAccountAdd(body) {
142
+ const wantsGlobal = optionalString(body.key) !== undefined
143
+ || String(body.authKind ?? '') === 'global';
144
+
145
+ let credential;
146
+ if (wantsGlobal) {
147
+ const email = requireString(body, 'email', 'Cloudflare 账户邮箱').trim();
148
+ const key = requireString(body, 'key', 'Global API Key').trim();
149
+ credential = { kind: 'global', email, key };
150
+ } else {
151
+ const token = requireString(body, 'token', 'Cloudflare API Token').trim();
152
+ credential = { kind: 'token', token };
153
+ }
154
+
155
+ const verified = await verifyCfToken(credential);
156
+
157
+ let accountName = '';
158
+ let accountId = '';
159
+ try {
160
+ const accounts = await listCfAccounts(credential);
161
+ if (accounts.length > 0) {
162
+ accountId = accounts[0].id;
163
+ accountName = accounts[0].name;
164
+ }
165
+ } catch { /* 账户列表失败不阻止登录;账号卡里仍可手动触发 */ }
166
+
167
+ const fallback = credential.kind === 'global'
168
+ ? (verified.email || credential.email)
169
+ : (accountName || 'Cloudflare 账号');
170
+ const label = optionalString(body.label) ?? fallback;
171
+
172
+ return store.saveCloudflareAccount({
173
+ authKind: credential.kind,
174
+ login: label,
175
+ email: credential.kind === 'global' ? credential.email : '',
176
+ token: credential.kind === 'global' ? credential.key : credential.token,
177
+ accountId,
178
+ accountName,
179
+ });
180
+ }
181
+
182
+ /**
183
+ * `POST /cf/account/remove`.
184
+ * @param {object} body `{ id }`
185
+ * @returns {Promise<{removed: boolean}>}
186
+ */
187
+ async function cloudflareAccountRemove(body) {
188
+ const id = requireString(body, 'id', '账号 id');
189
+ const removed = await store.deleteCloudflareAccount(id);
190
+ if (!removed) throw httpError(404, 'NOT_FOUND', '找不到这个 Cloudflare 账号,可能已被移除。');
191
+ return { removed: true };
192
+ }
193
+
194
+ /**
195
+ * `POST /cf/account/active`.
196
+ * @param {object} body `{ id }`
197
+ * @returns {Promise<{activeId: string}>}
198
+ */
199
+ async function cloudflareAccountActive(body) {
200
+ const id = requireString(body, 'id', '账号 id');
201
+ const ok = await store.setActiveCloudflareAccount(id);
202
+ if (!ok) throw httpError(404, 'NOT_FOUND', '找不到这个 Cloudflare 账号。');
203
+ return { activeId: id };
204
+ }
205
+
206
+ /**
207
+ * `POST /cf/account/select` — 登录后选择 Cloudflare account。
208
+ * @param {object} body `{ accountId, accountName }`
209
+ * @returns {Promise<object>}
210
+ */
211
+ async function cloudflareAccountSelect(body) {
212
+ const account = await requireCloudflareAccount_();
213
+ const accountId = requireString(body, 'accountId', 'Cloudflare 账户 id');
214
+ return store.updateCloudflareAccount(account.id, {
215
+ accountId,
216
+ accountName: optionalString(body.accountName) ?? '',
217
+ });
218
+ }
219
+
220
+ /**
221
+ * `GET /cf/accounts/list` — 当前凭据可访问的 Cloudflare 账户(选择器用)。
222
+ * @returns {Promise<object>}
223
+ */
224
+ async function cloudflareAccountList() {
225
+ const account = await requireCloudflareAccount_();
226
+ const items = await listCfAccounts(cloudflareCredential_(account));
227
+ return { items, activeAccountId: account.accountId };
228
+ }
229
+
230
+ /**
231
+ * `GET /cf/projects` — Pages 项目列表。
232
+ * @returns {Promise<object>}
233
+ */
234
+ async function cloudflareProjects() {
235
+ const { account, accountId } = await cloudflareContext_();
236
+ const items = await listPagesProjects(cloudflareCredential_(account), accountId);
237
+ await store.touchCloudflareAccount(account.id);
238
+ return { items, accountId };
239
+ }
240
+
241
+ /**
242
+ * `POST /cf/projects/create`.
243
+ * @param {object} body `{ name, productionBranch? }`
244
+ * @returns {Promise<object>}
245
+ */
246
+ async function cloudflareProjectCreate(body) {
247
+ const { account, accountId } = await cloudflareContext_();
248
+ const name = requireString(body, 'name', '项目名');
249
+ const project = await createPagesProject(
250
+ cloudflareCredential_(account),
251
+ accountId,
252
+ name,
253
+ optionalString(body.productionBranch) ?? 'main',
254
+ );
255
+ await store.touchCloudflareAccount(account.id);
256
+ return { project };
257
+ }
258
+
259
+ /**
260
+ * `POST /cf/projects/delete` — 危险操作,需 `confirm: true`。
261
+ * @param {object} body `{ name, confirm }`
262
+ * @returns {Promise<{deleted: boolean}>}
263
+ */
264
+ async function cloudflareProjectDelete(body) {
265
+ const { account, accountId } = await cloudflareContext_();
266
+ const name = requireString(body, 'name', '项目名');
267
+ if (optionalBool(body.confirm, false) !== true) {
268
+ throw httpError(
269
+ 409,
270
+ 'CONFLICT',
271
+ `删除 Pages 项目 ${name} 会移除它的所有部署与域名绑定,无法撤销。请确认后再执行(confirm: true)。`,
272
+ );
273
+ }
274
+ const result = await deletePagesProject(cloudflareCredential_(account), accountId, name);
275
+ await store.touchCloudflareAccount(account.id);
276
+ return result;
277
+ }
278
+
279
+ /**
280
+ * `GET /cf/workers` — Workers 列表。
281
+ * @returns {Promise<object>}
282
+ */
283
+ async function cloudflareWorkers() {
284
+ const { account, accountId } = await cloudflareContext_();
285
+ const items = await listWorkers(cloudflareCredential_(account), accountId);
286
+ await store.touchCloudflareAccount(account.id);
287
+ return { items, accountId };
288
+ }
289
+
290
+ /**
291
+ * `POST /cf/workers/delete` — 危险操作,需 `confirm: true`。
292
+ * @param {object} body `{ name, confirm }`
293
+ * @returns {Promise<{deleted: boolean}>}
294
+ */
295
+ async function cloudflareWorkerDelete(body) {
296
+ const { account, accountId } = await cloudflareContext_();
297
+ const name = requireString(body, 'name', 'Worker 名');
298
+ if (optionalBool(body.confirm, false) !== true) {
299
+ throw httpError(
300
+ 409,
301
+ 'CONFLICT',
302
+ `删除 Worker ${name} 会移除它的线上代码,无法撤销。请确认后再执行(confirm: true)。`,
303
+ );
304
+ }
305
+ const result = await deleteWorker(cloudflareCredential_(account), accountId, name);
306
+ await store.touchCloudflareAccount(account.id);
307
+ return result;
308
+ }
309
+
310
+ /**
311
+ * `GET /cf/zones` — 域名列表。
312
+ * @returns {Promise<object>}
313
+ */
314
+ async function cloudflareZones() {
315
+ const { account, accountId } = await cloudflareContext_();
316
+ const items = await listZones(cloudflareCredential_(account), accountId);
317
+ await store.touchCloudflareAccount(account.id);
318
+ return { items, accountId };
319
+ }
320
+
321
+ /**
322
+ * `GET /cf/detect?path=` — 探测目录是 Pages 还是 Worker 项目。
323
+ * @param {{path: string}} query
324
+ * @returns {Promise<object>}
325
+ */
326
+ async function cloudflareDetect(query) {
327
+ const dir = requireString(query, 'path', '目录路径');
328
+ const kind = await detectProjectKind(dir);
329
+ return { kind };
330
+ }
331
+
332
+ /**
333
+ * `POST /cf/deploy` — 一键部署 Pages 或 Worker。
334
+ *
335
+ * @param {object} body `{ path, kind?, project?, name?, branch?, environment? }`
336
+ * @returns {Promise<object>}
337
+ */
338
+ async function cloudflareDeploy(body) {
339
+ const dir = requireString(body, 'path', '目录路径');
340
+ const { account, accountId } = await cloudflareContext_();
341
+ const requestedKind = optionalString(body.kind);
342
+ const detected = requestedKind ? { type: requestedKind, dir } : await detectProjectKind(dir);
343
+
344
+ if (!detected || (detected.type !== 'pages' && detected.type !== 'worker')) {
345
+ throw httpError(
346
+ 400,
347
+ 'BAD_REQUEST',
348
+ '这个目录既不是 Pages 静态产物(缺 dist/build/index.html),也不是 Worker 项目(缺 wrangler 配置)。'
349
+ + '请先构建前端产物,或初始化 wrangler.toml 后再部署。',
350
+ );
351
+ }
352
+
353
+ if (detected.type === 'pages') {
354
+ const project = optionalString(body.project);
355
+ if (!project) {
356
+ throw httpError(400, 'BAD_REQUEST', '部署 Pages 需要指定项目名(project),或先在面板里选择/新建一个项目。');
357
+ }
358
+ const deployment = await createPagesDeployment(
359
+ cloudflareCredential_(account),
360
+ accountId,
361
+ project,
362
+ { directory: detected.dir, branch: optionalString(body.branch) },
363
+ );
364
+ await store.touchCloudflareAccount(account.id);
365
+ return {
366
+ kind: 'pages',
367
+ project,
368
+ deployment,
369
+ dashUrl: dashUrl(accountId, `workers-and-pages/view/pages/${project}`),
370
+ };
371
+ }
372
+
373
+ const name = optionalString(body.name);
374
+ if (!name) {
375
+ throw httpError(400, 'BAD_REQUEST', '部署 Worker 需要指定 Worker 名(name)。');
376
+ }
377
+ const mainFile = await resolveWorkerMain(detected.dir);
378
+ if (!mainFile) {
379
+ throw httpError(400, 'BAD_REQUEST', '找不到 Worker 入口文件(wrangler 配置里的 main,或 src/index.js / index.js)。');
380
+ }
381
+ const { readFile } = await import('node:fs/promises');
382
+ const { join } = await import('node:path');
383
+ let bytes;
384
+ try {
385
+ bytes = await readFile(join(detected.dir, mainFile));
386
+ } catch {
387
+ throw httpError(400, 'BAD_REQUEST', `无法读取 Worker 入口文件 ${mainFile}。`);
388
+ }
389
+ const result = await deployWorkerModule(cloudflareCredential_(account), accountId, name, {
390
+ mainFile,
391
+ bytes,
392
+ });
393
+ await store.touchCloudflareAccount(account.id);
394
+ return {
395
+ kind: 'worker',
396
+ name,
397
+ url: result.url,
398
+ dashUrl: dashUrl(accountId, `workers/view/${name}`),
399
+ };
400
+ }
401
+
402
+ /**
403
+ * `POST /cf/review` — 部署前审查(复用 review 引擎)。
404
+ *
405
+ * @param {object} body `{ path, kind?, presetIds?, customPrompt?, provider?, model?, reasoningEffort? }`
406
+ * @returns {Promise<object>}
407
+ */
408
+ async function cloudflareReview(body) {
409
+ const dir = requireString(body, 'path', '目录路径');
410
+ const requestedKind = optionalString(body.kind);
411
+ const detected = requestedKind ? { type: requestedKind, dir } : await detectProjectKind(dir);
412
+
413
+ const files = [];
414
+ const chunks = [];
415
+ let truncated = false;
416
+
417
+ if (detected && detected.type === 'pages') {
418
+ const collected = await collectUploadFiles(detected.dir);
419
+ if (collected.exceeded) truncated = true;
420
+ for (const row of collected.files) {
421
+ if (/(^|\/)node_modules\//.test(row.path)) continue;
422
+ let text = '';
423
+ try {
424
+ text = row.bytes.toString('utf8');
425
+ } catch { text = ''; }
426
+ if (text.includes('\u0000')) continue;
427
+ files.push({ path: row.path });
428
+ if (text !== '') chunks.push({ path: row.path, text: text.slice(0, MAX_FILE_BYTES) });
429
+ }
430
+ } else if (detected && detected.type === 'worker') {
431
+ const mainFile = await resolveWorkerMain(detected.dir);
432
+ if (mainFile) {
433
+ try {
434
+ const { readFile } = await import('node:fs/promises');
435
+ const { join } = await import('node:path');
436
+ const text = (await readFile(join(detected.dir, mainFile))).toString('utf8');
437
+ files.push({ path: mainFile });
438
+ chunks.push({ path: mainFile, text: text.slice(0, MAX_FILE_BYTES) });
439
+ } catch { /* 读不到就跳过 */ }
440
+ }
441
+ } else {
442
+ return {
443
+ reviewId: `cfreview_${Date.now().toString(36)}`,
444
+ scope: 'cloudflare',
445
+ files: [],
446
+ findings: [],
447
+ summary: '这个目录不是可部署的 Pages / Worker 项目,无需审查。',
448
+ degraded: true,
449
+ };
450
+ }
451
+
452
+ const ruleFindings = [];
453
+ for (const chunk of chunks) {
454
+ ruleFindings.push(...scanSecrets(chunk.text, { file: chunk.path }));
455
+ }
456
+ for (const row of files) {
457
+ if (/^\.env($|\.)/.test(row.path)) {
458
+ ruleFindings.push(normalizeFinding({
459
+ severity: 'blocker',
460
+ category: 'secrets',
461
+ title: '产物里包含环境变量文件',
462
+ detail: '.env 会被上传到公开的 Pages 站点,等于公开密钥。请从产物中移除 .env*,改用环境变量注入。',
463
+ file: row.path,
464
+ }));
465
+ }
466
+ }
467
+
468
+ const presetIds = Array.isArray(body.presetIds)
469
+ ? body.presetIds.filter((id) => typeof id === 'string' && id !== '')
470
+ : [];
471
+ const stored = await store.reviewPresets();
472
+ const chosen = [
473
+ ...BUILTIN_PRESETS.filter((preset) => presetIds.includes(preset.id)),
474
+ ...stored.filter((preset) => presetIds.includes(preset.id)),
475
+ ];
476
+ const customPrompt = optionalString(body.customPrompt) ?? '';
477
+ const llm = getLlm();
478
+ let provider = optionalString(body.provider);
479
+ let model = optionalString(body.model);
480
+ if (llm && (!provider || !model)) {
481
+ try {
482
+ const fallback = await reviewModels();
483
+ if (fallback.default) {
484
+ provider = provider ?? fallback.default.provider;
485
+ model = model ?? fallback.default.model;
486
+ }
487
+ } catch { /* 保留调用方给的值 */ }
488
+ }
489
+
490
+ let modelFindings = [];
491
+ let summary = '';
492
+ let usage;
493
+ let degraded = false;
494
+ if (chunks.length === 0) {
495
+ summary = '没有可审查的文本内容。';
496
+ } else if (!llm) {
497
+ degraded = true;
498
+ summary = '宿主未提供 llm 服务,本次只执行了规则检查(敏感信息扫描)。';
499
+ } else if (!provider || !model) {
500
+ degraded = true;
501
+ summary = '未找到可用的模型,本次只执行了规则检查(敏感信息扫描)。';
502
+ } else {
503
+ const instructions = [
504
+ ...chosen.map((preset) => `## ${preset.title}\n${preset.prompt}`),
505
+ ...(customPrompt ? [`## 用户补充要求\n${customPrompt}`] : []),
506
+ ].join('\n\n');
507
+ const promptParts = [
508
+ instructions,
509
+ '## 审查范围',
510
+ '这是即将部署到 Cloudflare 的文件内容(Pages 静态产物或 Worker 入口)。',
511
+ `## 文件(${files.length} 个)`,
512
+ files.map((row) => `- ${row.path}`).join('\n'),
513
+ '## 内容',
514
+ chunks.map((chunk) => `### ${chunk.path}\n\`\`\`\n${chunk.text}\n\`\`\``).join('\n\n'),
515
+ ].filter(Boolean);
516
+ try {
517
+ const result = await runModelReview(llm, {
518
+ provider,
519
+ model,
520
+ reasoningEffort: optionalString(body.reasoningEffort),
521
+ prompt: promptParts.join('\n\n'),
522
+ });
523
+ modelFindings = result.findings.map(normalizeFinding);
524
+ summary = result.summary;
525
+ usage = result.usage;
526
+ } catch (error) {
527
+ degraded = true;
528
+ summary = `模型审查失败(${String(error && error.message ? error.message : error)}),本次只执行了规则检查。`;
529
+ }
530
+ }
531
+
532
+ const findings = sortFindings([...ruleFindings, ...modelFindings]);
533
+ if (summary === '') {
534
+ summary = findings.length === 0 ? '未发现明显问题。' : `共发现 ${findings.length} 处需要关注的问题。`;
535
+ }
536
+ return {
537
+ reviewId: `cfreview_${Date.now().toString(36)}`,
538
+ scope: 'cloudflare',
539
+ kind: detected?.type ?? null,
540
+ files,
541
+ findings,
542
+ summary,
543
+ usage,
544
+ degraded,
545
+ truncated,
546
+ };
547
+ }
548
+
549
+ /**
550
+ * `POST /cf/worker/init` — 在当前目录生成一个最小可部署的 Worker 项目。
551
+ *
552
+ * 只写两个文件:`wrangler.toml` 与 `src/index.js`。已存在同名文件时
553
+ * **不覆盖**,而是返回已存在清单,避免毁掉用户手写的内容。
554
+ *
555
+ * @param {object} body `{ path, name? }`
556
+ * @returns {Promise<{created: string[], skipped: string[], name: string}>}
557
+ */
558
+ async function cloudflareWorkerInit(body) {
559
+ const dir = requireString(body, 'path', '目录路径');
560
+ const { readFile: readF, writeFile: writeF, mkdir: mkdirF } = await import('node:fs/promises');
561
+ const { join } = await import('node:path');
562
+
563
+ // 名字默认取目录名,规范成 Cloudflare 允许的形态(字母数字与连字符)。
564
+ const fallback = dir.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || 'my-worker';
565
+ const rawName = optionalString(body.name) ?? fallback;
566
+ const name = rawName.toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '') || 'my-worker';
567
+
568
+ const files = {
569
+ 'wrangler.toml': [
570
+ `name = "${name}"`,
571
+ 'main = "src/index.js"',
572
+ 'compatibility_date = "' + new Date().toISOString().slice(0, 10) + '"',
573
+ '',
574
+ ].join('\n'),
575
+ 'src/index.js': [
576
+ 'export default {',
577
+ ' async fetch(request, env, ctx) {',
578
+ ' return new Response("Hello from ' + name + '!", {',
579
+ ' headers: { "content-type": "text/plain; charset=utf-8" },',
580
+ ' });',
581
+ ' },',
582
+ '};',
583
+ '',
584
+ ].join('\n'),
585
+ };
586
+
587
+ const created = [];
588
+ const skipped = [];
589
+ for (const [rel, content] of Object.entries(files)) {
590
+ const abs = join(dir, rel);
591
+ let exists = false;
592
+ try {
593
+ await readF(abs, 'utf8');
594
+ exists = true;
595
+ } catch { exists = false; }
596
+ if (exists) { skipped.push(rel); continue; }
597
+ try {
598
+ await mkdirF(join(dir, rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '.'), { recursive: true });
599
+ await writeF(abs, content, 'utf8');
600
+ created.push(rel);
601
+ } catch (error) {
602
+ throw httpError(500, 'INTERNAL', `写入 ${rel} 失败:${error.message}`);
603
+ }
604
+ }
605
+ return { created, skipped, name };
606
+ }
607
+
608
+ /* ---------------- Cloudflare:域名与 DNS ---------------- */
609
+
610
+ /**
611
+ * `GET /cf/zones/detail?zoneId=` — 域名详情。
612
+ * @param {{zoneId: string}} query
613
+ * @returns {Promise<object>}
614
+ */
615
+ async function cloudflareZoneDetail(query) {
616
+ const { account, accountId } = await cloudflareContext_();
617
+ const zoneId = requireString(query, 'zoneId', '域名 id');
618
+ const zone = await getZoneDetail(cloudflareCredential_(account), zoneId);
619
+ await store.touchCloudflareAccount(account.id);
620
+ return { zone, accountId };
621
+ }
622
+
623
+ /**
624
+ * `GET /cf/dns?zoneId=&type=&name=` — DNS 记录列表。
625
+ * @param {{zoneId: string, type?: string, name?: string}} query
626
+ * @returns {Promise<object>}
627
+ */
628
+ async function cloudflareDnsList(query) {
629
+ const { account } = await cloudflareContext_();
630
+ const zoneId = requireString(query, 'zoneId', '域名 id');
631
+ const result = await listDnsRecords(cloudflareCredential_(account), zoneId, {
632
+ type: optionalString(query.type),
633
+ name: optionalString(query.name),
634
+ });
635
+ await store.touchCloudflareAccount(account.id);
636
+ return { ...result, types: DNS_RECORD_TYPES };
637
+ }
638
+
639
+ /**
640
+ * `POST /cf/dns/create` — 新增 DNS 记录。
641
+ * @param {object} body `{ zoneId, type, name, content, ttl?, proxied?, priority? }`
642
+ * @returns {Promise<object>}
643
+ */
644
+ async function cloudflareDnsCreate(body) {
645
+ const { account } = await cloudflareContext_();
646
+ const zoneId = requireString(body, 'zoneId', '域名 id');
647
+ const record = await createDnsRecord(cloudflareCredential_(account), zoneId, {
648
+ type: requireString(body, 'type', '记录类型'),
649
+ name: requireString(body, 'name', '记录名称'),
650
+ content: requireString(body, 'content', '记录内容'),
651
+ ttl: Number.isFinite(body.ttl) ? Number(body.ttl) : 1,
652
+ proxied: optionalBool(body.proxied, false),
653
+ priority: Number.isFinite(body.priority) ? Number(body.priority) : undefined,
654
+ });
655
+ await store.touchCloudflareAccount(account.id);
656
+ return { record };
657
+ }
658
+
659
+ /**
660
+ * `POST /cf/dns/update` — 修改 DNS 记录。
661
+ * @param {object} body `{ zoneId, recordId, ...patch }`
662
+ * @returns {Promise<object>}
663
+ */
664
+ async function cloudflareDnsUpdate(body) {
665
+ const { account } = await cloudflareContext_();
666
+ const zoneId = requireString(body, 'zoneId', '域名 id');
667
+ const recordId = requireString(body, 'recordId', '记录 id');
668
+ const patch = {};
669
+ if (body.type !== undefined) patch.type = body.type;
670
+ if (body.name !== undefined) patch.name = body.name;
671
+ if (body.content !== undefined) patch.content = body.content;
672
+ if (body.ttl !== undefined) patch.ttl = Number(body.ttl);
673
+ if (body.proxied !== undefined) patch.proxied = optionalBool(body.proxied, false);
674
+ if (body.priority !== undefined) patch.priority = Number(body.priority);
675
+ const record = await updateDnsRecord(cloudflareCredential_(account), zoneId, recordId, patch);
676
+ await store.touchCloudflareAccount(account.id);
677
+ return { record };
678
+ }
679
+
680
+ /**
681
+ * `POST /cf/dns/delete` — 删除 DNS 记录,需 `confirm: true`。
682
+ * @param {object} body `{ zoneId, recordId, confirm }`
683
+ * @returns {Promise<{deleted: boolean}>}
684
+ */
685
+ async function cloudflareDnsDelete(body) {
686
+ const { account } = await cloudflareContext_();
687
+ const zoneId = requireString(body, 'zoneId', '域名 id');
688
+ const recordId = requireString(body, 'recordId', '记录 id');
689
+ if (optionalBool(body.confirm, false) !== true) {
690
+ throw httpError(409, 'CONFLICT', '删除 DNS 记录会立即影响域名解析,请确认后再执行(confirm: true)。');
691
+ }
692
+ const result = await deleteDnsRecord(cloudflareCredential_(account), zoneId, recordId);
693
+ await store.touchCloudflareAccount(account.id);
694
+ return result;
695
+ }
696
+
697
+ /**
698
+ * `POST /cf/zones/purge` — 清除域名缓存。
699
+ * @param {object} body `{ zoneId }`
700
+ * @returns {Promise<object>}
701
+ */
702
+ async function cloudflareZonePurge(body) {
703
+ const { account } = await cloudflareContext_();
704
+ const zoneId = requireString(body, 'zoneId', '域名 id');
705
+ const result = await purgeZoneCache(cloudflareCredential_(account), zoneId);
706
+ await store.touchCloudflareAccount(account.id);
707
+ return result;
708
+ }
709
+
710
+ /**
711
+ * `POST /cf/zones/development` — 开关开发模式。
712
+ * @param {object} body `{ zoneId, enabled }`
713
+ * @returns {Promise<object>}
714
+ */
715
+ async function cloudflareZoneDevelopment(body) {
716
+ const { account } = await cloudflareContext_();
717
+ const zoneId = requireString(body, 'zoneId', '域名 id');
718
+ if (typeof body.enabled !== 'boolean') {
719
+ throw httpError(400, 'BAD_REQUEST', 'enabled 必须是布尔值');
720
+ }
721
+ const result = await setDevelopmentMode(cloudflareCredential_(account), zoneId, body.enabled);
722
+ await store.touchCloudflareAccount(account.id);
723
+ return result;
724
+ }
725
+
726
+ /* ---------------- Cloudflare:部署历史与回滚 ---------------- */
727
+
728
+ /**
729
+ * `GET /cf/projects/deployments?name=` — 部署历史。
730
+ * @param {{name: string}} query
731
+ * @returns {Promise<object>}
732
+ */
733
+ async function cloudflareProjectDeployments(query) {
734
+ const { account, accountId } = await cloudflareContext_();
735
+ const name = requireString(query, 'name', '项目名');
736
+ const items = await listPagesDeploymentsDetailed(cloudflareCredential_(account), accountId, name);
737
+ await store.touchCloudflareAccount(account.id);
738
+ return { items, project: name };
739
+ }
740
+
741
+ /**
742
+ * `POST /cf/projects/rollback` — 回滚到指定部署。
743
+ * @param {object} body `{ name, deploymentId }`
744
+ * @returns {Promise<object>}
745
+ */
746
+ async function cloudflareProjectRollback(body) {
747
+ const { account, accountId } = await cloudflareContext_();
748
+ const name = requireString(body, 'name', '项目名');
749
+ const deploymentId = requireString(body, 'deploymentId', '部署 id');
750
+ const deployment = await rollbackPagesDeployment(
751
+ cloudflareCredential_(account), accountId, name, deploymentId,
752
+ );
753
+ await store.touchCloudflareAccount(account.id);
754
+ return { deployment };
755
+ }
756
+
757
+ /**
758
+ * `POST /cf/projects/deployments/delete` — 删除一次部署,需 `confirm: true`。
759
+ * @param {object} body `{ name, deploymentId, confirm }`
760
+ * @returns {Promise<{deleted: boolean}>}
761
+ */
762
+ async function cloudflareProjectDeploymentDelete(body) {
763
+ const { account, accountId } = await cloudflareContext_();
764
+ const name = requireString(body, 'name', '项目名');
765
+ const deploymentId = requireString(body, 'deploymentId', '部署 id');
766
+ if (optionalBool(body.confirm, false) !== true) {
767
+ throw httpError(409, 'CONFLICT', '删除部署会移除这次的构建产物与预览地址,请确认后再执行(confirm: true)。');
768
+ }
769
+ const result = await deletePagesDeployment(
770
+ cloudflareCredential_(account), accountId, name, deploymentId,
771
+ );
772
+ await store.touchCloudflareAccount(account.id);
773
+ return result;
774
+ }
775
+
776
+ /* ---------------- Cloudflare:环境变量 ---------------- */
777
+
778
+ /**
779
+ * `GET /cf/projects/env?name=` — 环境变量(值被 Cloudflare 隐藏)。
780
+ * @param {{name: string}} query
781
+ * @returns {Promise<object>}
782
+ */
783
+ async function cloudflareProjectEnv(query) {
784
+ const { account, accountId } = await cloudflareContext_();
785
+ const name = requireString(query, 'name', '项目名');
786
+ const result = await listPagesEnvVars(cloudflareCredential_(account), accountId, name);
787
+ await store.touchCloudflareAccount(account.id);
788
+ return result;
789
+ }
790
+
791
+ /**
792
+ * `POST /cf/projects/env` — 写入环境变量。
793
+ * @param {object} body `{ name, vars: Record<string, {value, type?}> }`
794
+ * @returns {Promise<object>}
795
+ */
796
+ async function cloudflareProjectEnvSave(body) {
797
+ const { account, accountId } = await cloudflareContext_();
798
+ const name = requireString(body, 'name', '项目名');
799
+ if (!body.vars || typeof body.vars !== 'object' || Array.isArray(body.vars)) {
800
+ throw httpError(400, 'BAD_REQUEST', 'vars 必须是键值对象');
801
+ }
802
+ const result = await patchPagesEnvVars(
803
+ cloudflareCredential_(account), accountId, name, body.vars,
804
+ );
805
+ await store.touchCloudflareAccount(account.id);
806
+ return result;
807
+ }
808
+
809
+ /* ---------------- Cloudflare:Worker 详情与路由 ---------------- */
810
+
811
+ /**
812
+ * `GET /cf/routes` — Worker 路由列表。
813
+ * @returns {Promise<object>}
814
+ */
815
+ async function cloudflareRoutes() {
816
+ const { account, accountId } = await cloudflareContext_();
817
+ const items = await listWorkerRoutes(cloudflareCredential_(account), accountId);
818
+ await store.touchCloudflareAccount(account.id);
819
+ return { items, accountId };
820
+ }
821
+
822
+ /**
823
+ * `POST /cf/routes/create` — 新增 Worker 路由。
824
+ * @param {object} body `{ pattern, script }`
825
+ * @returns {Promise<object>}
826
+ */
827
+ async function cloudflareRouteCreate(body) {
828
+ const { account, accountId } = await cloudflareContext_();
829
+ const pattern = requireString(body, 'pattern', '路由 pattern');
830
+ const script = requireString(body, 'script', 'Worker 名');
831
+ const route = await createWorkerRoute(
832
+ cloudflareCredential_(account), accountId, optionalString(body.zoneId) ?? '', pattern, script,
833
+ );
834
+ await store.touchCloudflareAccount(account.id);
835
+ return { route };
836
+ }
837
+
838
+ /**
839
+ * `POST /cf/routes/delete` — 删除 Worker 路由,需 `confirm: true`。
840
+ * @param {object} body `{ routeId, confirm }`
841
+ * @returns {Promise<{deleted: boolean}>}
842
+ */
843
+ async function cloudflareRouteDelete(body) {
844
+ const { account, accountId } = await cloudflareContext_();
845
+ const routeId = requireString(body, 'routeId', '路由 id');
846
+ if (optionalBool(body.confirm, false) !== true) {
847
+ throw httpError(409, 'CONFLICT', '删除 Worker 路由会立即停止该路径的转发,请确认后再执行(confirm: true)。');
848
+ }
849
+ const result = await deleteWorkerRoute(cloudflareCredential_(account), accountId, routeId);
850
+ await store.touchCloudflareAccount(account.id);
851
+ return result;
852
+ }
853
+
854
+ /* ---------------- Cloudflare:用量与仪表盘 ---------------- */
855
+
856
+ /**
857
+ * `GET /cf/usage` — 账号用量(请求数/错误数)。
858
+ * @returns {Promise<object>}
859
+ */
860
+ async function cloudflareUsage() {
861
+ const { account, accountId } = await cloudflareContext_();
862
+ const result = await fetchUsage(cloudflareCredential_(account), accountId);
863
+ // 用量读取失败不算「用过」,但也不该报错。
864
+ if (result.unavailable !== true) await store.touchCloudflareAccount(account.id);
865
+ return result;
866
+ }
867
+
868
+ /**
869
+ * `GET /cf/dashboard` — 设置页多卡信息面板的数据源。
870
+ * @returns {Promise<object>}
871
+ */
872
+ async function cloudflareDashboard() {
873
+ const { account, accountId } = await cloudflareContext_();
874
+ const result = await cfDashboard(cloudflareCredential_(account), accountId);
875
+ await store.touchCloudflareAccount(account.id);
876
+ return {
877
+ accountId,
878
+ accountName: account.accountName || accountId,
879
+ ...result,
880
+ };
881
+ }
882
+
883
+
884
+ /* ---------------- 平台定义 ---------------- */
885
+
886
+ return {
887
+ id: 'cloudflare',
888
+ label: 'Cloudflare',
889
+ order: 30,
890
+ icon: 'CloudflareMark',
891
+ start() {
892
+ /* 没有需要在挂载时注册的副作用;账号与资源都是按需读取。 */
893
+ },
894
+ host: {
895
+ accounts: cloudflareAccounts,
896
+ accountAdd: cloudflareAccountAdd,
897
+ accountRemove: cloudflareAccountRemove,
898
+ accountActive: cloudflareAccountActive,
899
+ accountSelect: cloudflareAccountSelect,
900
+ accountList: cloudflareAccountList,
901
+ projects: cloudflareProjects,
902
+ projectCreate: cloudflareProjectCreate,
903
+ projectDelete: cloudflareProjectDelete,
904
+ workers: cloudflareWorkers,
905
+ workerDelete: cloudflareWorkerDelete,
906
+ workerInit: cloudflareWorkerInit,
907
+ zones: cloudflareZones,
908
+ zoneDetail: cloudflareZoneDetail,
909
+ zonePurge: cloudflareZonePurge,
910
+ zoneDevelopment: cloudflareZoneDevelopment,
911
+ dnsList: cloudflareDnsList,
912
+ dnsCreate: cloudflareDnsCreate,
913
+ dnsUpdate: cloudflareDnsUpdate,
914
+ dnsDelete: cloudflareDnsDelete,
915
+ deployments: cloudflareProjectDeployments,
916
+ rollback: cloudflareProjectRollback,
917
+ deploymentDelete: cloudflareProjectDeploymentDelete,
918
+ env: cloudflareProjectEnv,
919
+ envSave: cloudflareProjectEnvSave,
920
+ routes: cloudflareRoutes,
921
+ routeCreate: cloudflareRouteCreate,
922
+ routeDelete: cloudflareRouteDelete,
923
+ usage: cloudflareUsage,
924
+ dashboard: cloudflareDashboard,
925
+ detect: cloudflareDetect,
926
+ deploy: cloudflareDeploy,
927
+ review: cloudflareReview,
928
+ },
929
+ routes: [
930
+ { path: '/cf/accounts', method: 'GET', run: async () => cloudflareAccounts() },
931
+ { path: '/cf/account', method: 'POST', run: async ({ body }) => cloudflareAccountAdd(body) },
932
+ { path: '/cf/account/remove', method: 'POST', run: async ({ body }) => cloudflareAccountRemove(body) },
933
+ { path: '/cf/account/active', method: 'POST', run: async ({ body }) => cloudflareAccountActive(body) },
934
+ { path: '/cf/account/select', method: 'POST', run: async ({ body }) => cloudflareAccountSelect(body) },
935
+ { path: '/cf/accounts/list', method: 'GET', run: async () => cloudflareAccountList() },
936
+ { path: '/cf/projects', method: 'GET', run: async () => cloudflareProjects() },
937
+ { path: '/cf/projects/create', method: 'POST', run: async ({ body }) => cloudflareProjectCreate(body) },
938
+ { path: '/cf/projects/delete', method: 'POST', run: async ({ body }) => cloudflareProjectDelete(body) },
939
+ { path: '/cf/workers', method: 'GET', run: async () => cloudflareWorkers() },
940
+ { path: '/cf/workers/delete', method: 'POST', run: async ({ body }) => cloudflareWorkerDelete(body) },
941
+ { path: '/cf/zones', method: 'GET', run: async () => cloudflareZones() },
942
+ { path: '/cf/detect', method: 'GET', run: async ({ query }) => cloudflareDetect({ path: query('path') }) },
943
+ { path: '/cf/deploy', method: 'POST', run: async ({ body }) => cloudflareDeploy(body) },
944
+ { path: '/cf/review', method: 'POST', run: async ({ body }) => cloudflareReview(body) },
945
+ { path: '/cf/zones/detail', method: 'GET', run: async ({ query }) => cloudflareZoneDetail({ zoneId: query('zoneId') }) },
946
+ { path: '/cf/worker/init', method: 'POST', run: async ({ body }) => cloudflareWorkerInit(body) },
947
+ { path: '/cf/dns', method: 'GET', run: async ({ query }) => cloudflareDnsList({ zoneId: query('zoneId'), type: query('type'), name: query('name') }) },
948
+ { path: '/cf/dns/create', method: 'POST', run: async ({ body }) => cloudflareDnsCreate(body) },
949
+ { path: '/cf/dns/update', method: 'POST', run: async ({ body }) => cloudflareDnsUpdate(body) },
950
+ { path: '/cf/dns/delete', method: 'POST', run: async ({ body }) => cloudflareDnsDelete(body) },
951
+ { path: '/cf/zones/purge', method: 'POST', run: async ({ body }) => cloudflareZonePurge(body) },
952
+ { path: '/cf/zones/development', method: 'POST', run: async ({ body }) => cloudflareZoneDevelopment(body) },
953
+ { path: '/cf/projects/deployments', method: 'GET', run: async ({ query }) => cloudflareProjectDeployments({ name: query('name') }) },
954
+ { path: '/cf/projects/rollback', method: 'POST', run: async ({ body }) => cloudflareProjectRollback(body) },
955
+ { path: '/cf/projects/deployments/delete', method: 'POST', run: async ({ body }) => cloudflareProjectDeploymentDelete(body) },
956
+ { path: '/cf/projects/env', method: 'GET', run: async ({ query }) => cloudflareProjectEnv({ name: query('name') }) },
957
+ { path: '/cf/projects/env', method: 'POST', run: async ({ body }) => cloudflareProjectEnvSave(body) },
958
+ { path: '/cf/routes', method: 'GET', run: async () => cloudflareRoutes() },
959
+ { path: '/cf/routes/create', method: 'POST', run: async ({ body }) => cloudflareRouteCreate(body) },
960
+ { path: '/cf/routes/delete', method: 'POST', run: async ({ body }) => cloudflareRouteDelete(body) },
961
+ { path: '/cf/usage', method: 'GET', run: async () => cloudflareUsage() },
962
+ { path: '/cf/dashboard', method: 'GET', run: async () => cloudflareDashboard() },
963
+ ],
964
+ actions: [
965
+ {
966
+ id: 'overview',
967
+ description: '查看账户概览:Pages 项目、Workers、域名、路由的数量与最近部署',
968
+ run: async () => cloudflareDashboard(),
969
+ render: (v) => `【Cloudflare】Pages ${v.counts.pages} · Workers ${v.counts.workers}`
970
+ + ` · 域名 ${v.counts.zones} · 路由 ${v.counts.routes}`,
971
+ },
972
+ {
973
+ id: 'projects',
974
+ description: '列出 Pages 项目',
975
+ run: async () => cloudflareProjects(),
976
+ render: (v) => (v.items.length === 0
977
+ ? '【Cloudflare】没有 Pages 项目。'
978
+ : ['【Cloudflare】Pages 项目:', ...v.items.map((p) => ` ${p.name}${p.latestUrl ? ' · ' + p.latestUrl : ''}`)].join('\n')),
979
+ },
980
+ {
981
+ id: 'workers',
982
+ description: '列出 Workers',
983
+ run: async () => cloudflareWorkers(),
984
+ render: (v) => (v.items.length === 0
985
+ ? '【Cloudflare】没有 Workers。'
986
+ : ['【Cloudflare】Workers:', ...v.items.map((w) => ` ${w.name}`)].join('\n')),
987
+ },
988
+ {
989
+ id: 'zones',
990
+ description: '列出域名',
991
+ run: async () => cloudflareZones(),
992
+ render: (v) => (v.items.length === 0
993
+ ? '【Cloudflare】没有域名。'
994
+ : ['【Cloudflare】域名:', ...v.items.map((z) => ` ${z.name}(${z.status})`)].join('\n')),
995
+ },
996
+ {
997
+ id: 'routes',
998
+ description: '列出 Worker 路由',
999
+ run: async () => cloudflareRoutes(),
1000
+ render: (v) => (v.items.length === 0
1001
+ ? '【Cloudflare】没有 Worker 路由。'
1002
+ : ['【Cloudflare】Worker 路由:', ...v.items.map((r) => ` ${r.pattern} → ${r.script}`)].join('\n')),
1003
+ },
1004
+ {
1005
+ id: 'dns',
1006
+ description: '列出某个域名的 DNS 记录(需要 zoneId)',
1007
+ parameters: { zoneId: { type: 'string', description: '域名 id,可先用 zones 取得' } },
1008
+ run: async (args) => {
1009
+ const zoneId = optionalString(args?.zoneId);
1010
+ if (!zoneId) throw httpError(400, 'BAD_REQUEST', 'dns 需要 zoneId,请先调用 zones 取得域名 id。');
1011
+ return cloudflareDnsList({ zoneId });
1012
+ },
1013
+ render: (v) => (v.items.length === 0
1014
+ ? '【Cloudflare】这个域名没有 DNS 记录。'
1015
+ : ['【Cloudflare】DNS 记录:', ...v.items.map((r) => ` ${r.type} ${r.name} → ${r.content}${r.proxied ? '(已代理)' : ''}`)].join('\n')),
1016
+ },
1017
+ {
1018
+ id: 'usage',
1019
+ description: '查看用量:Worker 请求与错误数、Pages 函数调用',
1020
+ run: async () => cloudflareUsage(),
1021
+ render: (v) => (v.unavailable === true
1022
+ ? `【Cloudflare】用量数据不可用:${v.message || ''}`
1023
+ : `【Cloudflare】Worker 请求 ${v.workers?.requests ?? 0}(错误 ${v.workers?.errors ?? 0})`
1024
+ + ` · Pages 函数 ${v.pagesFunctions?.requests ?? 0}`),
1025
+ },
1026
+ {
1027
+ id: 'detect',
1028
+ description: '探测目录是可部署的 Pages 静态产物还是 Worker 项目',
1029
+ run: async (args, toolContext) => {
1030
+ const dir = optionalString(args?.path)
1031
+ ?? (typeof toolContext?.resolvePath === 'function' ? await toolContext.resolvePath() : process.cwd());
1032
+ return cloudflareDetect({ path: dir });
1033
+ },
1034
+ render: (v) => (v.kind
1035
+ ? `【Cloudflare】检测为 ${v.kind.type === 'pages' ? 'Pages 静态站点' : 'Worker 项目'}(${v.kind.dir})`
1036
+ : '【Cloudflare】这个目录既不是 Pages 静态产物,也不是 Worker 项目。'),
1037
+ },
1038
+ {
1039
+ id: 'deploy',
1040
+ description: '部署 Pages 或 Worker(需要 path;kind 省略时自动探测)',
1041
+ parameters: {
1042
+ kind: { type: 'string', enum: ['pages', 'worker'] },
1043
+ project: { type: 'string', description: 'Pages 项目名' },
1044
+ name: { type: 'string', description: 'Worker 名' },
1045
+ },
1046
+ run: async (args, toolContext) => {
1047
+ const dir = optionalString(args?.path)
1048
+ ?? (typeof toolContext?.resolvePath === 'function' ? await toolContext.resolvePath() : process.cwd());
1049
+ return cloudflareDeploy({
1050
+ path: dir,
1051
+ kind: optionalString(args?.kind),
1052
+ project: optionalString(args?.project),
1053
+ name: optionalString(args?.name),
1054
+ });
1055
+ },
1056
+ render: (v) => (v.kind === 'pages'
1057
+ ? `【Cloudflare】Pages「${v.project}」部署完成:${v.deployment?.url || ''}`
1058
+ : `【Cloudflare】Worker「${v.name}」部署完成:${v.url || ''}`),
1059
+ },
1060
+ {
1061
+ id: 'review',
1062
+ description: '部署前审查:检查即将上传的文件(敏感信息与 .env)',
1063
+ run: async (args, toolContext) => {
1064
+ const dir = optionalString(args?.path)
1065
+ ?? (typeof toolContext?.resolvePath === 'function' ? await toolContext.resolvePath() : process.cwd());
1066
+ return cloudflareReview({ path: dir, kind: optionalString(args?.kind) });
1067
+ },
1068
+ render: (v) => `【Cloudflare】审查:${v.summary}`,
1069
+ },
1070
+ ],
1071
+ };
1072
+ }