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.
package/client.js ADDED
@@ -0,0 +1,1696 @@
1
+ /**
2
+ * DevDock · Cloudflare · 浏览器半边。
3
+ *
4
+ * 三段界面(设置页那一块、左栏仪表盘、工作区部署标签页)都在这里,
5
+ * 共用组件与样式来自内核:`require('dsh-devdock-core/client')`。
6
+ *
7
+ * ## 路由前缀
8
+ *
9
+ * 内核把平台路由挂在 `/api/push/<平台 id>` 之下,所以本包声明的
10
+ * `route.path = '/cf/accounts'` 实际是 `/api/push/cloudflare/cf/accounts`。
11
+ * 客户端因此用 `core.API + '/cloudflare'` 作为 API 前缀,再拼自己的
12
+ * `/cf/...` 子路径。少写这一段会得到 404,而且看起来像「后端没实现」。
13
+ *
14
+ * ## 面板
15
+ *
16
+ * 界面不再由内核判断"当前是哪个平台",而是通过 registerPanel 交给
17
+ * 内核的注册表:内核只负责三个固定入口,平台自己决定入口里画什么。
18
+ */
19
+ window.__ModuleLoader__.load({
20
+ // Must equal package.json `name`: the loader keys client modules by package
21
+ // name, so a mismatch registers the module under an id nobody resolves and
22
+ // every surface vanishes while the Host half still reports active.
23
+ id: 'dsh-devdock-cloudflare',
24
+ factory: (require) => {
25
+ 'use strict';
26
+ const module = { exports: {} };
27
+ const exports = module.exports;
28
+
29
+ const core = require('dsh-devdock-core/client');
30
+ const { h, React, Icon, Btn, Modal, TabRow, t, api, copyText, relativeTime } = core;
31
+ const { useState, useEffect, useRef, useCallback } = React;
32
+
33
+ /** 本平台的路由前缀:内核前缀 + 平台 id。 */
34
+ const API = core.API + '/cloudflare';
35
+ /** 内联提示的存活时间(内核统一)。 */
36
+ const TOAST_MS = core.TOAST_MS;
37
+ /** 审查严重度 → 文案键(审查规则在内核,映射也归内核)。 */
38
+ const SEVERITY_LABEL = core.SEVERITY_LABEL;
39
+ /** 骨架行(各平台的空态共用)。 */
40
+ const CONTRIB_SKELETON = core.CONTRIB_SKELETON;
41
+ const CloudflareMark = core.CloudflareMark;
42
+ const readViewPref = core.readViewPref;
43
+ const writeViewPref = core.writeViewPref;
44
+
45
+ /* ────────────────────────────── 文案 ────────────────────────────────── */
46
+
47
+ /**
48
+ * Cloudflare 的全部措辞。由 scripts 从元包抽取后固化在这里——124 条
49
+ * 逐条重写是纯粹的浪费,而键名与措辞都已被测试覆盖。
50
+ *
51
+ * 注意:这里只登记自己的键,通用键(取消/确认/加载中…)仍由内核提供。
52
+ */
53
+ const ZH = {
54
+ cfSection: 'Cloudflare',
55
+ cfAuthGlobal: 'Global API Key(全权限,免勾选)',
56
+ cfAuthToken: 'API Token(可细粒度)',
57
+ cfAuthGlobalShort: 'Global API Key',
58
+ cfAuthTokenShort: 'API Token',
59
+ cfTokenPlaceholder: '粘贴 Cloudflare API Token',
60
+ cfKeyPlaceholder: 'cfk_... 或旧版十六进制',
61
+ cfEmailPlaceholder: 'Cloudflare 账户邮箱',
62
+ cfGlobalHint: 'Global API Key 拥有账户全部权限,只需邮箱 + Key,不用逐个勾选。在 My Profile › API Tokens 页底部「Global API Key」处点 View 获取(新版以 cfk_ 开头)。',
63
+ cfAdd: '添加账号',
64
+ cfCurrent: '当前',
65
+ cfSwitch: '切换',
66
+ cfRemove: '移除',
67
+ cfTokenHint: 'Token 需含 Account:Read、Workers Scripts:Edit、Pages:Edit、Zone:Read 等权限组',
68
+ cfTokenPage: '去 Cloudflare 生成 Token',
69
+ cfNoAccountHint: '在设置里添加一个 API Token 或 Global API Key',
70
+ cfOverviewTitle: '项目概览',
71
+ cfOverviewPages: 'Pages 项目',
72
+ cfOverviewWorkers: 'Workers',
73
+ cfOverviewZones: '域名',
74
+ cfOverviewLoading: '正在读取概览…',
75
+ cfSelectAccount: '选择账户',
76
+ cfSelectAccountHint: '一个凭据可能属于多个账户,选一个作为当前账户',
77
+ cfProjectsTitle: 'Pages 项目',
78
+ cfWorkersTitle: 'Workers',
79
+ cfZonesTitle: '域名',
80
+ cfOpenDash: '在控制台打开',
81
+ cfEmpty: '没有数据',
82
+ cfNeedAccount: '请先登录 Cloudflare 账号',
83
+ cfNoAccountLong: '在 设置 › DevDock › Cloudflare 里添加一个 API Token 或 Global API Key。',
84
+ cfNewProject: '新建项目',
85
+ cfNewProjectHint: '项目名会成为 <名称>.pages.dev 的默认站点;之后可在控制台绑定自定义域名。',
86
+ cfProjectName: '项目名',
87
+ cfCreate: '创建',
88
+ cfDelete: '删除',
89
+ cfDeleteConfirm: '确认删除',
90
+ cfDeployTitle: '部署',
91
+ cfDetecting: '正在探测目录…',
92
+ cfDetectPages: '识别为 Pages 静态站点',
93
+ cfDetectWorker: '识别为 Worker 项目',
94
+ cfDetectNone: '这个目录既不是 Pages 静态产物,也不是 Worker 项目',
95
+ cfNeedDir: '先选一个目录',
96
+ cfNeedDirHint: '部署需要读取这个目录里的产物或 Worker 源码。可以在上方「选择目录」里指定。',
97
+ cfPickProject: '选择 Pages 项目…',
98
+ cfBranchOptional: '分支(可选,留空用生产分支)',
99
+ cfDeployAction: '部署',
100
+ cfDeploying: '部署中…',
101
+ cfDeployedPages: 'Pages 部署完成',
102
+ cfDeployedWorker: 'Worker 部署完成',
103
+ cfDeployUrl: '访问地址',
104
+ cfDeployOpenDash: '在控制台查看',
105
+ cfReviewOpen: '部署前审查',
106
+ cfReviewHint: '先检查即将上传的文件,再决定是否部署。规则扫描(敏感信息)始终执行,模型审查可选。',
107
+ cfReviewBlocker: '存在阻断级问题。仍可部署,但请确认这些内容确实要公开。',
108
+ cfReviewNone: '未发现明显问题',
109
+ cfNeedWorker: '请填写 Worker 名',
110
+ cfSource: '关联仓库',
111
+ cfBranch: '分支',
112
+ cfOverviewRoutes: '路由',
113
+ cfEnvTitle: '环境变量',
114
+ cfEnvAdd: '添加',
115
+ cfEnvKey: '键名(如 API_KEY)',
116
+ cfEnvValue: '值',
117
+ cfEnvSecret: '作为密钥保存',
118
+ cfEnvPlain: '普通',
119
+ cfEnvEmpty: '还没有环境变量',
120
+ cfEnvSaved: '环境变量已保存',
121
+ cfSave: '保存',
122
+ cfEdit: '编辑',
123
+ cfDnsEdit: '编辑 DNS 记录',
124
+ cfDnsNew: '新增 DNS 记录',
125
+ cfDnsUpdated: 'DNS 记录已更新',
126
+ cfDeployments: '部署历史',
127
+ cfNoDeployments: '还没有部署记录',
128
+ cfZoneStatus: '域名状态',
129
+ cfZonePendingCount: '{n} 个待生效',
130
+ cfRecentDeployments: '最近部署',
131
+ cfDeploySkipped: '跳过',
132
+ cfDeployOk: '成功',
133
+ cfUsageTitle: '用量',
134
+ cfUsageHint: '近 24 小时',
135
+ cfUsageWorkerRequests: 'Worker 请求',
136
+ cfUsageWorkerErrors: 'Worker 错误',
137
+ cfUsagePagesRequests: 'Pages 函数',
138
+ cfPartialWarn: '部分信息未读取',
139
+ cfPanelTitle: 'Cloudflare 资源',
140
+ cfRoutesTitle: '路由',
141
+ cfAddRoute: '新增路由',
142
+ cfRouteScript: 'Worker 名',
143
+ cfRoutePattern: '路由 pattern(如 example.com/*)',
144
+ cfNoRoutes: '还没有 Worker 路由',
145
+ cfRouteAdded: '路由已新增',
146
+ cfZoneActions: '域名操作',
147
+ cfPurgeCache: '清缓存',
148
+ cfDevModeOnShort: '开发模式:开',
149
+ cfDevModeOffShort: '开发模式:关',
150
+ cfDevModeOn: '开发模式已开启',
151
+ cfDevModeOff: '开发模式已关闭',
152
+ cfCachePurged: '缓存已清除',
153
+ cfAddDns: '新增 DNS',
154
+ cfDnsName: '记录名(@ 或子域)',
155
+ cfDnsContent: '内容(IP / 目标 / 文本)',
156
+ cfDnsProxied: '走 Cloudflare 代理',
157
+ cfDnsAdded: 'DNS 记录已新增',
158
+ cfDnsDeleted: 'DNS 记录已删除',
159
+ cfNoDns: '这个域名没有 DNS 记录',
160
+ cfProxied: '已代理',
161
+ cfExpand: '展开部署历史',
162
+ cfExpandDns: '展开 DNS 记录',
163
+ cfCollapse: '收起',
164
+ cfRollback: '回滚',
165
+ cfRolledBack: '已回滚到该部署',
166
+ cfCreated: '已创建',
167
+ cfDeleted: '已删除',
168
+ cfNoDeployment: '还没有部署',
169
+ cfCreateWorker: '新建 Worker 项目',
170
+ cfNothingToDo: '文件已存在,未做改动',
171
+ cfCreateWorkerHint: '在当前目录生成 wrangler.toml 与入口文件,之后可直接部署。',
172
+ cfWorkerNameLabel: 'Worker 名',
173
+ cfWorkerInit: '生成项目文件',
174
+ cfWorkerInited: '已生成 Worker 项目文件',
175
+ cfLinkWorker: '关联 Worker',
176
+ cfNotAProject: '当前目录不是 Pages 静态产物,也不是 Worker 项目',
177
+ cfNotAProjectHint: '可以在下面新建一个 Worker 项目,或先构建前端产物再部署。',
178
+ };
179
+
180
+ const EN = {
181
+ cfSection: 'Cloudflare',
182
+ cfAuthGlobal: 'Global API Key (full access)',
183
+ cfAuthToken: 'API Token (scoped)',
184
+ cfAuthGlobalShort: 'Global API Key',
185
+ cfAuthTokenShort: 'API Token',
186
+ cfTokenPlaceholder: 'Paste a Cloudflare API Token',
187
+ cfKeyPlaceholder: 'cfk_... or legacy hex',
188
+ cfEmailPlaceholder: 'Cloudflare account email',
189
+ cfGlobalHint: 'A Global API Key carries every account permission — just email + key. Get it under My Profile › API Tokens, bottom section (new keys start with cfk_).',
190
+ cfAdd: 'Add account',
191
+ cfCurrent: 'Current',
192
+ cfSwitch: 'Switch',
193
+ cfRemove: 'Remove',
194
+ cfTokenHint: 'The token needs Account:Read, Workers Scripts:Edit, Pages:Edit, Zone:Read and similar permission groups',
195
+ cfTokenPage: 'Create a token on Cloudflare',
196
+ cfNoAccountHint: 'Add a Cloudflare API Token or Global API Key in Settings',
197
+ cfOverviewTitle: 'Project overview',
198
+ cfOverviewPages: 'Pages projects',
199
+ cfOverviewWorkers: 'Workers',
200
+ cfOverviewZones: 'Zones',
201
+ cfOverviewLoading: 'Reading overview…',
202
+ cfSelectAccount: 'Choose account',
203
+ cfSelectAccountHint: 'A credential can belong to several accounts — pick the current one',
204
+ cfProjectsTitle: 'Pages projects',
205
+ cfWorkersTitle: 'Workers',
206
+ cfZonesTitle: 'Zones',
207
+ cfOpenDash: 'Open in dashboard',
208
+ cfEmpty: 'No data',
209
+ cfNeedAccount: 'Sign in to Cloudflare first',
210
+ cfNoAccountLong: 'Add a Cloudflare API Token or Global API Key under Settings › DevDock › Cloudflare.',
211
+ cfNewProject: 'New project',
212
+ cfNewProjectHint: 'The name becomes the default <name>.pages.dev site; add a custom domain in the dashboard later.',
213
+ cfProjectName: 'Project name',
214
+ cfCreate: 'Create',
215
+ cfDelete: 'Delete',
216
+ cfDeleteConfirm: 'Confirm delete',
217
+ cfDeployTitle: 'Deploy',
218
+ cfDetecting: 'Detecting folder…',
219
+ cfDetectPages: 'Detected a Pages static site',
220
+ cfDetectWorker: 'Detected a Worker project',
221
+ cfDetectNone: 'This folder is neither a Pages static build nor a Worker project',
222
+ cfNeedDir: 'Choose a folder first',
223
+ cfNeedDirHint: 'Deploying reads the build output or Worker source from this folder. Use Choose folder above.',
224
+ cfPickProject: 'Pick a Pages project…',
225
+ cfBranchOptional: 'Branch (optional, defaults to production)',
226
+ cfDeployAction: 'Deploy',
227
+ cfDeploying: 'Deploying…',
228
+ cfDeployedPages: 'Pages deployment finished',
229
+ cfDeployedWorker: 'Worker deployment finished',
230
+ cfDeployUrl: 'URL',
231
+ cfDeployOpenDash: 'Open in dashboard',
232
+ cfReviewOpen: 'Pre-deploy review',
233
+ cfReviewHint: 'Review the files that would be uploaded before deploying. Secret scanning always runs; model review is optional.',
234
+ cfReviewBlocker: 'Blocking issues found. You can still deploy, but make sure this content is meant to be public.',
235
+ cfReviewNone: 'No problems found',
236
+ cfNeedWorker: 'Enter a Worker name',
237
+ cfSource: 'Linked repo',
238
+ cfBranch: 'Branch',
239
+ cfOverviewRoutes: 'Routes',
240
+ cfEnvTitle: 'Environment variables',
241
+ cfEnvAdd: 'Add',
242
+ cfEnvKey: 'Key (e.g. API_KEY)',
243
+ cfEnvValue: 'Value',
244
+ cfEnvSecret: 'Store as secret',
245
+ cfEnvPlain: 'plain',
246
+ cfEnvEmpty: 'No environment variables yet',
247
+ cfEnvSaved: 'Environment variable saved',
248
+ cfSave: 'Save',
249
+ cfEdit: 'Edit',
250
+ cfDnsEdit: 'Edit DNS record',
251
+ cfDnsNew: 'New DNS record',
252
+ cfDnsUpdated: 'DNS record updated',
253
+ cfDeployments: 'Deployments',
254
+ cfNoDeployments: 'No deployments yet',
255
+ cfZoneStatus: 'Zone status',
256
+ cfZonePendingCount: '{n} pending',
257
+ cfRecentDeployments: 'Recent deployments',
258
+ cfDeploySkipped: 'skipped',
259
+ cfDeployOk: 'ok',
260
+ cfUsageTitle: 'Usage',
261
+ cfUsageHint: 'last 24h',
262
+ cfUsageWorkerRequests: 'Worker requests',
263
+ cfUsageWorkerErrors: 'Worker errors',
264
+ cfUsagePagesRequests: 'Pages functions',
265
+ cfPartialWarn: 'Some data unavailable',
266
+ cfPanelTitle: 'Cloudflare resources',
267
+ cfRoutesTitle: 'Routes',
268
+ cfAddRoute: 'Add route',
269
+ cfRouteScript: 'Worker name',
270
+ cfRoutePattern: 'Route pattern (e.g. example.com/*)',
271
+ cfNoRoutes: 'No worker routes yet',
272
+ cfRouteAdded: 'Route added',
273
+ cfZoneActions: 'Zone actions',
274
+ cfPurgeCache: 'Purge cache',
275
+ cfDevModeOnShort: 'Dev mode: on',
276
+ cfDevModeOffShort: 'Dev mode: off',
277
+ cfDevModeOn: 'Development mode enabled',
278
+ cfDevModeOff: 'Development mode disabled',
279
+ cfCachePurged: 'Cache purged',
280
+ cfAddDns: 'Add DNS',
281
+ cfDnsName: 'Name (@ or subdomain)',
282
+ cfDnsContent: 'Content (IP / target / text)',
283
+ cfDnsProxied: 'Proxy through Cloudflare',
284
+ cfDnsAdded: 'DNS record added',
285
+ cfDnsDeleted: 'DNS record deleted',
286
+ cfNoDns: 'This zone has no DNS records',
287
+ cfProxied: 'proxied',
288
+ cfExpand: 'Expand deployments',
289
+ cfExpandDns: 'Expand DNS records',
290
+ cfCollapse: 'Collapse',
291
+ cfRollback: 'Rollback',
292
+ cfRolledBack: 'Rolled back to that deployment',
293
+ cfCreated: 'Created',
294
+ cfDeleted: 'Deleted',
295
+ cfNoDeployment: 'No deployment yet',
296
+ cfCreateWorker: 'Create Worker project',
297
+ cfNothingToDo: 'Files already exist, nothing changed',
298
+ cfCreateWorkerHint: 'Generate wrangler.toml and an entry file here, then deploy directly.',
299
+ cfWorkerNameLabel: 'Worker name',
300
+ cfWorkerInit: 'Generate project files',
301
+ cfWorkerInited: 'Worker project files created',
302
+ cfLinkWorker: 'Link Worker',
303
+ cfNotAProject: 'This folder is neither a Pages build nor a Worker project',
304
+ cfNotAProjectHint: 'Create a Worker project below, or build your frontend output first.',
305
+ };
306
+
307
+ /* ──────────────────────────── 界面 ─────────────────────────────────── */
308
+
309
+ /* ───────────── Cloudflare 模块:账号卡片 + 概览 ───────────── */
310
+
311
+ /** 大数字缩写:1234 -> 1.2k,1234567 -> 1.2M。 */
312
+ function formatCount(n) {
313
+ const v = Number(n);
314
+ if (!Number.isFinite(v) || v < 0) return '—';
315
+ if (v < 1000) return String(v);
316
+ if (v < 1e6) return (v / 1000).toFixed(v < 1e4 ? 1 : 0) + 'k';
317
+ if (v < 1e9) return (v / 1e6).toFixed(1) + 'M';
318
+ return (v / 1e9).toFixed(1) + 'B';
319
+ }
320
+
321
+ /** 由 CloudflareAccountCards 等刷新。 */
322
+ const cloudflareAccountCache = [];
323
+
324
+ /**
325
+ * Cloudflare 账号卡片(设置页用)。
326
+ *
327
+ * 两种登录方式:Global API Key(邮箱 + Key,全权限免勾选)与 API Token
328
+ * (可细粒度,需勾权限)。默认 Global Key —— 用户不必逐个勾权限组。
329
+ *
330
+ * @param {{ctx: object, onChanged?: () => void}} props
331
+ */
332
+ function CloudflareAccountCards(props) {
333
+ const ctx = props.ctx;
334
+ const [data, setData] = useState(null);
335
+ const [adding, setAdding] = useState(false);
336
+ const [authKind, setAuthKind] = useState(() => readViewPref('cf.authKind', 'global'));
337
+ const [token, setToken] = useState('');
338
+ const [email, setEmail] = useState('');
339
+ const [busy, setBusy] = useState('');
340
+ const [error, setError] = useState('');
341
+ const aliveRef = useRef(true);
342
+
343
+ useEffect(() => {
344
+ aliveRef.current = true;
345
+ return () => { aliveRef.current = false; };
346
+ }, []);
347
+
348
+ const load = useCallback(async () => {
349
+ try {
350
+ const next = await api(ctx, API + '/cf/accounts');
351
+ cloudflareAccountCache.length = 0;
352
+ if (next && Array.isArray(next.accounts)) cloudflareAccountCache.push(...next.accounts);
353
+ if (aliveRef.current) setData(next || { accounts: [], activeId: null });
354
+ } catch (err) {
355
+ if (aliveRef.current) setError(err.message);
356
+ }
357
+ }, [ctx]);
358
+
359
+ useEffect(() => { load(); }, [load]);
360
+
361
+ const run = async (label, action) => {
362
+ setBusy(label);
363
+ setError('');
364
+ try {
365
+ await action();
366
+ await load();
367
+ if (typeof props.onChanged === 'function') props.onChanged();
368
+ } catch (err) {
369
+ if (aliveRef.current) setError(err.message);
370
+ } finally {
371
+ if (aliveRef.current) setBusy('');
372
+ }
373
+ };
374
+
375
+ const add = () => run('add', async () => {
376
+ const value = String(token || '').trim();
377
+ const mail = String(email || '').trim();
378
+ if (value === '') return;
379
+ if (authKind === 'global' && mail === '') return;
380
+ const body = authKind === 'global'
381
+ ? { authKind: 'global', email: mail, key: value }
382
+ : { authKind: 'token', token: value };
383
+ await api(ctx, API + '/cf/account', { method: 'POST', body });
384
+ if (aliveRef.current) { setToken(''); setEmail(''); setAdding(false); }
385
+ });
386
+
387
+ const list = (data && data.accounts) || [];
388
+ const activeId = data ? data.activeId : null;
389
+
390
+ const tokenField = h('input', {
391
+ className: 'dsh-push-input dsh-push-acc-token',
392
+ type: 'password',
393
+ value: token,
394
+ placeholder: authKind === 'global' ? t('cfKeyPlaceholder') : t('cfTokenPlaceholder'),
395
+ spellCheck: false,
396
+ onChange: (e) => setToken(e.target.value),
397
+ });
398
+
399
+ const kindSwitch = h('div', { className: 'dsh-push-inline' },
400
+ h(Btn, {
401
+ mini: true,
402
+ active: authKind === 'global',
403
+ onClick: () => { setAuthKind('global'); writeViewPref('cf.authKind', 'global'); },
404
+ }, t('cfAuthGlobal')),
405
+ h(Btn, {
406
+ mini: true,
407
+ active: authKind === 'token',
408
+ onClick: () => { setAuthKind('token'); writeViewPref('cf.authKind', 'token'); },
409
+ }, t('cfAuthToken')));
410
+
411
+ const emailField = h('input', {
412
+ className: 'dsh-push-input',
413
+ type: 'email',
414
+ value: email,
415
+ placeholder: t('cfEmailPlaceholder'),
416
+ spellCheck: false,
417
+ onChange: (e) => setEmail(e.target.value),
418
+ });
419
+
420
+ const addPanel = h('div', { className: 'dsh-push-acc-panel' },
421
+ kindSwitch,
422
+ authKind === 'global' ? emailField : null,
423
+ tokenField,
424
+ h('div', { className: 'dsh-push-hint' }, authKind === 'global' ? t('cfGlobalHint') : t('cfTokenHint')),
425
+ h('div', { className: 'dsh-push-inline' },
426
+ h(Btn, {
427
+ kind: 'primary',
428
+ disabled: busy === 'add' || token.trim() === '' || (authKind === 'global' && email.trim() === ''),
429
+ onClick: add,
430
+ }, t('cfAdd')),
431
+ h(Btn, { disabled: Boolean(busy), onClick: () => { setAdding(false); setToken(''); setEmail(''); } }, t('cancel')),
432
+ h('button', {
433
+ type: 'button',
434
+ className: 'dsh-push-linklike',
435
+ onClick: () => { try { window.open('https://dash.cloudflare.com/profile/api-tokens', '_blank'); } catch { /* ignore */ } },
436
+ }, t('cfTokenPage'))));
437
+
438
+ const addRow = h('button', {
439
+ type: 'button',
440
+ className: 'dsh-push-acc-addrow',
441
+ onClick: () => setAdding(true),
442
+ }, h(Icon, { name: 'plus', size: 12 }), t('cfAdd'));
443
+
444
+ const emptyCard = h('button', {
445
+ type: 'button',
446
+ className: 'dsh-push-acc-card dsh-push-acc-card--empty',
447
+ onClick: () => setAdding(true),
448
+ },
449
+ h(CloudflareMark, { size: 20 }),
450
+ h('span', { className: 'dsh-push-acc-card-empty' }, t('cfAdd')),
451
+ h('span', { className: 'dsh-push-acc-card-hint' }, t('cfNoAccountHint')));
452
+
453
+ const accountCard = (account) => h('div', {
454
+ key: account.id,
455
+ className: 'dsh-push-acc-card',
456
+ },
457
+ h(CloudflareMark, { size: 22 }),
458
+ h('div', { className: 'dsh-push-acc-card-main' },
459
+ h('div', { className: 'dsh-push-acc-card-name' }, account.login),
460
+ h('div', { className: 'dsh-push-acc-card-sub' },
461
+ h('span', { className: 'dsh-push-acc-card-login' },
462
+ account.authKind === 'global' ? t('cfAuthGlobalShort') : t('cfAuthTokenShort')),
463
+ account.accountName
464
+ ? h('span', { className: 'dsh-push-acc-card-login' }, account.accountName)
465
+ : null,
466
+ account.id === activeId
467
+ ? h('span', { className: 'dsh-push-pill' }, t('cfCurrent'))
468
+ : null)),
469
+ h('div', { className: 'dsh-push-inline' },
470
+ account.id === activeId
471
+ ? null
472
+ : h(Btn, {
473
+ mini: true,
474
+ disabled: Boolean(busy),
475
+ onClick: () => run('switch', () => api(ctx, API + '/cf/account/active', {
476
+ method: 'POST',
477
+ body: { id: account.id },
478
+ })),
479
+ }, t('cfSwitch')),
480
+ h('button', {
481
+ type: 'button',
482
+ className: 'dsh-push-iconbtn',
483
+ title: t('cfRemove'),
484
+ 'aria-label': t('cfRemove'),
485
+ disabled: Boolean(busy),
486
+ onClick: () => run('remove', () => api(ctx, API + '/cf/account/remove', {
487
+ method: 'POST',
488
+ body: { id: account.id },
489
+ })),
490
+ }, h(Icon, { name: 'close', size: 12 }))));
491
+
492
+ return h('div', { className: 'dsh-push-cf-accounts' },
493
+ error ? h('div', { className: 'dsh-push-error' }, error) : null,
494
+ list.length === 0
495
+ ? (adding ? addPanel : emptyCard)
496
+ : h('div', { className: 'dsh-push-acc-cards' },
497
+ list.map(accountCard),
498
+ adding ? addPanel : addRow));
499
+ }
500
+
501
+ /**
502
+ * 设置页的 Cloudflare 信息面板。
503
+ *
504
+ * 不是一个孤零零的计数条:把「有多少资源 / 域名状态 / 最近部署 / 用量」
505
+ * 全部平铺出来,用户不用切到左栏就能判断账号是否健康、最近有没有上线。
506
+ *
507
+ * 数据来自 `GET /cf/dashboard`(聚合)+ `GET /cf/usage`(用量,可降级)。
508
+ *
509
+ * @param {{ctx: object, reloadKey?: number}} props
510
+ */
511
+ function CloudflareOverviewCard(props) {
512
+ const ctx = props.ctx;
513
+ const [data, setData] = useState(null);
514
+ const [usage, setUsage] = useState(null);
515
+ const [error, setError] = useState('');
516
+ const [busy, setBusy] = useState(false);
517
+ const aliveRef = useRef(true);
518
+
519
+ useEffect(() => {
520
+ aliveRef.current = true;
521
+ return () => { aliveRef.current = false; };
522
+ }, []);
523
+
524
+ const load = useCallback(async () => {
525
+ setError('');
526
+ try {
527
+ const next = await api(ctx, API + '/cf/dashboard');
528
+ if (aliveRef.current) setData(next);
529
+ } catch (err) {
530
+ if (aliveRef.current) setData(null);
531
+ if (err.code !== 'NO_ACCOUNT' && aliveRef.current) setError(err.message);
532
+ return;
533
+ }
534
+ // 用量与仪表盘分开取:用量失败不该让整张卡空掉。
535
+ try {
536
+ const u = await api(ctx, API + '/cf/usage');
537
+ if (aliveRef.current) setUsage(u);
538
+ } catch {
539
+ if (aliveRef.current) setUsage({ unavailable: true, message: '用量数据暂不可用' });
540
+ }
541
+ }, [ctx]);
542
+
543
+ useEffect(() => { load(); }, [load, props.reloadKey]);
544
+
545
+ const refresh = async () => {
546
+ setBusy(true);
547
+ await load();
548
+ if (aliveRef.current) setBusy(false);
549
+ };
550
+
551
+ const dash = (path) => 'https://dash.cloudflare.com/'
552
+ + encodeURIComponent(data ? data.accountId : '') + '/' + path;
553
+
554
+ const openDash = (path) => {
555
+ try { window.open(dash(path), '_blank', 'noopener'); } catch { /* ignore */ }
556
+ };
557
+
558
+ const counts = data ? data.counts : null;
559
+ const cells = [
560
+ { key: 'pages', label: t('cfOverviewPages'), value: counts ? counts.pages : null, path: 'workers-and-pages' },
561
+ { key: 'workers', label: t('cfOverviewWorkers'), value: counts ? counts.workers : null, path: 'workers-and-pages' },
562
+ { key: 'zones', label: t('cfOverviewZones'), value: counts ? counts.zones : null, path: 'domains' },
563
+ { key: 'routes', label: t('cfOverviewRoutes'), value: counts ? counts.routes : null, path: 'workers-and-pages' },
564
+ ];
565
+
566
+ const countGrid = h('div', { className: 'dsh-push-cf-stat-grid' },
567
+ cells.map((cell) => h('button', {
568
+ key: cell.key,
569
+ type: 'button',
570
+ className: 'dsh-push-cf-stat',
571
+ title: t('cfOpenDash'),
572
+ onClick: () => openDash(cell.path),
573
+ },
574
+ h('span', { className: 'dsh-push-cf-stat-value' }, cell.value === null ? '—' : String(cell.value)),
575
+ h('span', { className: 'dsh-push-cf-stat-label' }, cell.label))));
576
+
577
+ /* 域名状态:active / pending 一眼看出有没有解析没生效的域名。 */
578
+ const zoneBlock = data && data.zones
579
+ ? h('div', { className: 'dsh-push-cf-mini' },
580
+ h('div', { className: 'dsh-push-cf-mini-head' },
581
+ h('span', null, t('cfZoneStatus')),
582
+ data.zones.pending > 0
583
+ ? h('span', { className: 'dsh-push-pill dsh-push-pill--warn' },
584
+ t('cfZonePendingCount', { n: data.zones.pending }))
585
+ : null),
586
+ data.zones.items.length === 0
587
+ ? h('div', { className: 'dsh-push-hint' }, t('cfEmpty'))
588
+ : h('div', { className: 'dsh-push-cf-zone-list' },
589
+ data.zones.items.map((z) => h('div', { key: z.id, className: 'dsh-push-cf-zone-row' },
590
+ h('span', { className: 'dsh-push-mono' }, z.name),
591
+ h('span', {
592
+ className: 'dsh-push-pill ' + (z.status === 'active'
593
+ ? 'dsh-push-pill--ok' : 'dsh-push-pill--warn'),
594
+ }, z.status)))))
595
+ : null;
596
+
597
+ /* 最近部署:哪次上线、什么时候、成功没有。 */
598
+ const deployBlock = data && data.recentDeployments && data.recentDeployments.length > 0
599
+ ? h('div', { className: 'dsh-push-cf-mini' },
600
+ h('div', { className: 'dsh-push-cf-mini-head' }, h('span', null, t('cfRecentDeployments'))),
601
+ h('div', { className: 'dsh-push-cf-deploy-list' },
602
+ data.recentDeployments.map((d) => h('div', { key: d.project + d.id, className: 'dsh-push-cf-deploy-row' },
603
+ h('span', { className: 'dsh-push-mono' }, d.project),
604
+ h('span', { className: 'dsh-push-hint' }, relativeTime(d.createdOn)),
605
+ h('span', {
606
+ className: 'dsh-push-pill ' + (d.isSkipped ? 'dsh-push-pill--warn' : 'dsh-push-pill--ok'),
607
+ }, d.isSkipped ? t('cfDeploySkipped') : t('cfDeployOk'))))))
608
+ : null;
609
+
610
+ /* 用量:GraphQL 可能因权限失败,失败就整块隐藏而不是显示错误。 */
611
+ const usageBlock = usage && usage.unavailable !== true
612
+ ? h('div', { className: 'dsh-push-cf-mini' },
613
+ h('div', { className: 'dsh-push-cf-mini-head' },
614
+ h('span', null, t('cfUsageTitle')),
615
+ h('span', { className: 'dsh-push-hint' }, t('cfUsageHint'))),
616
+ h('div', { className: 'dsh-push-cf-usage-grid' },
617
+ h('div', { className: 'dsh-push-cf-usage-cell' },
618
+ h('span', { className: 'dsh-push-cf-usage-value' }, formatCount(usage.workers.requests)),
619
+ h('span', { className: 'dsh-push-cf-usage-label' }, t('cfUsageWorkerRequests'))),
620
+ h('div', { className: 'dsh-push-cf-usage-cell' },
621
+ h('span', { className: 'dsh-push-cf-usage-value' }, formatCount(usage.workers.errors)),
622
+ h('span', { className: 'dsh-push-cf-usage-label' }, t('cfUsageWorkerErrors'))),
623
+ h('div', { className: 'dsh-push-cf-usage-cell' },
624
+ h('span', { className: 'dsh-push-cf-usage-value' }, formatCount(usage.pagesFunctions.requests)),
625
+ h('span', { className: 'dsh-push-cf-usage-label' }, t('cfUsagePagesRequests')))))
626
+ : null;
627
+
628
+ const warnings = data && data.warnings && data.warnings.length > 0
629
+ ? h('div', { className: 'dsh-push-hint dsh-push-cf-warn' },
630
+ t('cfPartialWarn') + ':' + data.warnings.join(';'))
631
+ : null;
632
+
633
+ const body = data === null && error === ''
634
+ ? h('div', { className: 'dsh-push-hint' }, t('cfOverviewLoading'))
635
+ : h('div', { className: 'dsh-push-cf-dashboard' },
636
+ countGrid,
637
+ zoneBlock,
638
+ deployBlock,
639
+ usageBlock,
640
+ warnings);
641
+
642
+ return h('div', { className: 'dsh-push-group' },
643
+ h('div', { className: 'dsh-push-group-head' },
644
+ h('span', null, data && data.accountName ? data.accountName : t('cfOverviewTitle')),
645
+ h('div', { className: 'dsh-push-inline' },
646
+ h(Btn, { mini: true, onClick: () => openDash(''), title: t('cfOpenDash') },
647
+ h(Icon, { name: 'external', size: 11 })),
648
+ h(Btn, { mini: true, disabled: busy, onClick: refresh }, busy ? t('loading') : t('refresh')))),
649
+ error ? h('div', { className: 'dsh-push-error' }, error) : null,
650
+ body);
651
+ }
652
+
653
+ /**
654
+ * 设置页的 Cloudflare 一页:账号卡片 + 项目概览。
655
+ * @param {{ctx: object, reloadKey?: number}} props
656
+ */
657
+ function CloudflareSection(props) {
658
+ const ctx = props.ctx;
659
+ const [reloadKey, setReloadKey] = useState(0);
660
+ return h('div', { className: 'dsh-push-npm-settings' },
661
+ h(CloudflareAccountCards, { ctx, onChanged: () => setReloadKey((n) => n + 1) }),
662
+ h(CloudflareOverviewCard, { ctx, reloadKey }));
663
+ }
664
+
665
+ /**
666
+ * Cloudflare 账户下拉(一个凭据可能属于多个账户)。
667
+ * @param {{ctx: object, onChange?: () => void, onError?: (m: string) => void}} props
668
+ */
669
+ function CloudflareAccountPicker(props) {
670
+ const ctx = props.ctx;
671
+ const [accounts, setAccounts] = useState([]);
672
+ const [activeAccountId, setActiveAccountId] = useState('');
673
+ const [busy, setBusy] = useState(false);
674
+
675
+ const loadAccountList = useCallback(async () => {
676
+ try {
677
+ const next = await api(ctx, API + '/cf/accounts/list');
678
+ if (next && Array.isArray(next.items)) setAccounts(next.items);
679
+ if (next && next.activeAccountId) setActiveAccountId(next.activeAccountId);
680
+ } catch { /* 保留旧值 */ }
681
+ }, [ctx]);
682
+
683
+ useEffect(() => { loadAccountList(); }, [loadAccountList]);
684
+
685
+ const switchTo = async (accountId, accountName) => {
686
+ if (!accountId) return;
687
+ setBusy(true);
688
+ try {
689
+ await api(ctx, API + '/cf/account/select', { method: 'POST', body: { accountId, accountName } });
690
+ setActiveAccountId(accountId);
691
+ if (typeof props.onChange === 'function') props.onChange();
692
+ } catch (err) {
693
+ if (typeof props.onError === 'function') props.onError(err.message);
694
+ } finally {
695
+ setBusy(false);
696
+ }
697
+ };
698
+
699
+ if (accounts.length === 0) return null;
700
+ return h('div', { className: 'dsh-push-cf-picker', title: t('cfSelectAccountHint') },
701
+ h(CloudflareMark, { size: 14 }),
702
+ h('span', { className: 'dsh-push-hint' }, t('cfSelectAccount')),
703
+ h('select', {
704
+ className: 'dsh-push-select',
705
+ value: activeAccountId,
706
+ disabled: busy,
707
+ onChange: (e) => {
708
+ const row = accounts.find((a) => a.id === e.target.value);
709
+ switchTo(e.target.value, row ? row.name : '');
710
+ },
711
+ }, accounts.map((account) => h('option', {
712
+ key: account.id,
713
+ value: account.id,
714
+ }, account.name || account.id))));
715
+ }
716
+
717
+
718
+
719
+ /* ───────────── Cloudflare 左栏仪表盘 ───────────── */
720
+
721
+ /**
722
+ * Cloudflare 面板(左栏 main 页):四块内嵌管理界面。
723
+ *
724
+ * Pages —— 项目列表、部署历史、回滚、删除
725
+ * Workers—— 列表、详情、删除
726
+ * 域名 —— 列表、DNS 记录增删改查、清缓存、开发模式
727
+ * 路由 —— Worker 路由列表、新增、删除
728
+ *
729
+ * 所有操作都走 Host API,因此不必打开浏览器;控制台链接只作为补充入口
730
+ * 保留在每行末尾。
731
+ *
732
+ * @param {{ctx: object, reloadKey?: number}} props
733
+ */
734
+ function CloudflarePanel(props) {
735
+ const ctx = props.ctx;
736
+ const [tab, setTab] = useState('pages');
737
+ const [loading, setLoading] = useState(true);
738
+ const [needAccount, setNeedAccount] = useState(false);
739
+ const [error, setError] = useState('');
740
+ const [busy, setBusy] = useState('');
741
+ const [accountId, setAccountId] = useState('');
742
+ const [notice, setNotice] = useState('');
743
+
744
+ const [projects, setProjects] = useState([]);
745
+ const [workers, setWorkers] = useState([]);
746
+ const [zones, setZones] = useState([]);
747
+ const [routes, setRoutes] = useState([]);
748
+
749
+ // 展开的详情(同一时刻只展开一个)
750
+ const [openProject, setOpenProject] = useState('');
751
+ const [deployments, setDeployments] = useState(null);
752
+ const [envs, setEnvs] = useState(null);
753
+ const [envForm, setEnvForm] = useState({ open: false, key: '', value: '', secret: false });
754
+ const [openZone, setOpenZone] = useState('');
755
+ const [dns, setDns] = useState(null);
756
+ const [zoneDetail, setZoneDetail] = useState(null);
757
+
758
+ // 表单
759
+ const [newProject, setNewProject] = useState({ open: false, name: '' });
760
+ const [dnsForm, setDnsForm] = useState({ open: false, type: 'A', name: '', content: '', proxied: false, editingId: '' });
761
+ const [routeForm, setRouteForm] = useState({ open: false, script: '', pattern: '' });
762
+ const [deleteArm, setDeleteArm] = useState('');
763
+
764
+ const aliveRef = useRef(true);
765
+ useEffect(() => {
766
+ aliveRef.current = true;
767
+ return () => { aliveRef.current = false; };
768
+ }, []);
769
+
770
+ useEffect(() => {
771
+ if (!notice) return undefined;
772
+ const id = setTimeout(() => { if (aliveRef.current) setNotice(''); }, TOAST_MS);
773
+ return () => clearTimeout(id);
774
+ }, [notice]);
775
+
776
+ const run = useCallback(async (fn, label) => {
777
+ if (label) setBusy(label);
778
+ setError('');
779
+ try {
780
+ const result = await fn();
781
+ return result;
782
+ } catch (err) {
783
+ if (aliveRef.current) setError(err.message);
784
+ return null;
785
+ } finally {
786
+ if (aliveRef.current && label) setBusy('');
787
+ }
788
+ }, []);
789
+
790
+ const loadAll = useCallback(async () => {
791
+ setError('');
792
+ const [p, w, z] = await Promise.all([
793
+ run(() => api(ctx, API + '/cf/projects')),
794
+ run(() => api(ctx, API + '/cf/workers')),
795
+ run(() => api(ctx, API + '/cf/zones')),
796
+ ]);
797
+ if (!aliveRef.current) return;
798
+ if (p === null && w === null && z === null) {
799
+ setNeedAccount(true);
800
+ setLoading(false);
801
+ return;
802
+ }
803
+ setNeedAccount(false);
804
+ if (p) { setProjects(p.items || []); setAccountId(p.accountId || ''); }
805
+ if (w) setWorkers(w.items || []);
806
+ if (z) setZones(z.items || []);
807
+ // 路由单独取:权限不足时不影响前三块
808
+ const r = await run(() => api(ctx, API + '/cf/routes'));
809
+ if (aliveRef.current && r) setRoutes(r.items || []);
810
+ if (aliveRef.current) setLoading(false);
811
+ }, [ctx, run]);
812
+
813
+ useEffect(() => { setLoading(true); loadAll(); }, [loadAll, props.reloadKey]);
814
+
815
+ const openDash = (path) => {
816
+ try {
817
+ window.open('https://dash.cloudflare.com/' + encodeURIComponent(accountId) + '/' + path, '_blank', 'noopener');
818
+ } catch { /* ignore */ }
819
+ };
820
+
821
+ /* ---------- Pages ---------- */
822
+ const toggleProject = async (name) => {
823
+ if (openProject === name) { setOpenProject(''); setDeployments(null); return; }
824
+ setOpenProject(name);
825
+ setDeployments(null);
826
+ setEnvs(null);
827
+ const [data, env] = await Promise.all([
828
+ run(() => api(ctx, API + '/cf/projects/deployments?name=' + encodeURIComponent(name)), 'deployments'),
829
+ run(() => api(ctx, API + '/cf/projects/env?name=' + encodeURIComponent(name))),
830
+ ]);
831
+ if (!aliveRef.current) return;
832
+ if (data) setDeployments(data.items || []);
833
+ if (env) setEnvs(env.production || []);
834
+ };
835
+
836
+ const createProject = async () => {
837
+ const name = newProject.name.trim();
838
+ if (!name) return;
839
+ const ok = await run(() => api(ctx, API + '/cf/projects/create', { method: 'POST', body: { name } }), 'create');
840
+ if (ok) {
841
+ if (aliveRef.current) { setNewProject({ open: false, name: '' }); setNotice(t('cfCreated')); }
842
+ await loadAll();
843
+ }
844
+ };
845
+
846
+ /** 保存一条环境变量(同名覆盖)。 */
847
+ const saveEnv = async (project) => {
848
+ const key = envForm.key.trim();
849
+ const value = envForm.value;
850
+ if (!key) return;
851
+ const vars = {};
852
+ vars[key] = { value, type: envForm.secret ? 'secret_text' : 'plain_text' };
853
+ const ok = await run(() => api(ctx, API + '/cf/projects/env', {
854
+ method: 'POST',
855
+ body: { name: project, vars },
856
+ }), 'env');
857
+ if (ok) {
858
+ if (aliveRef.current) { setEnvForm({ open: false, key: '', value: '', secret: false }); setNotice(t('cfEnvSaved')); }
859
+ const env = await run(() => api(ctx, API + '/cf/projects/env?name=' + encodeURIComponent(project)));
860
+ if (aliveRef.current && env) setEnvs(env.production || []);
861
+ }
862
+ };
863
+
864
+ const rollback = async (project, deploymentId) => {
865
+ const ok = await run(() => api(ctx, API + '/cf/projects/rollback', {
866
+ method: 'POST',
867
+ body: { name: project, deploymentId },
868
+ }), 'rollback');
869
+ if (ok) {
870
+ if (aliveRef.current) setNotice(t('cfRolledBack'));
871
+ const data = await run(() => api(ctx, API + '/cf/projects/deployments?name=' + encodeURIComponent(project)));
872
+ if (aliveRef.current && data) setDeployments(data.items || []);
873
+ }
874
+ };
875
+
876
+ const deleteDeployment = async (project, deploymentId) => {
877
+ const ok = await run(() => api(ctx, API + '/cf/projects/deployments/delete', {
878
+ method: 'POST',
879
+ body: { name: project, deploymentId, confirm: true },
880
+ }), 'delete');
881
+ if (ok) {
882
+ const data = await run(() => api(ctx, API + '/cf/projects/deployments?name=' + encodeURIComponent(project)));
883
+ if (aliveRef.current && data) setDeployments(data.items || []);
884
+ }
885
+ };
886
+
887
+ const deleteProject = async (name) => {
888
+ const ok = await run(() => api(ctx, API + '/cf/projects/delete', {
889
+ method: 'POST', body: { name, confirm: true },
890
+ }), 'delete');
891
+ if (ok) { if (aliveRef.current) setNotice(t('cfDeleted')); await loadAll(); }
892
+ };
893
+
894
+ /* ---------- Workers ---------- */
895
+ const deleteWorkerByName = async (name) => {
896
+ const ok = await run(() => api(ctx, API + '/cf/workers/delete', {
897
+ method: 'POST', body: { name, confirm: true },
898
+ }), 'delete');
899
+ if (ok) { if (aliveRef.current) setNotice(t('cfDeleted')); await loadAll(); }
900
+ };
901
+
902
+ /* ---------- 域名 / DNS ---------- */
903
+ const toggleZone = async (zone) => {
904
+ if (openZone === zone.id) { setOpenZone(''); setDns(null); setZoneDetail(null); return; }
905
+ setOpenZone(zone.id);
906
+ setDns(null);
907
+ setZoneDetail(null);
908
+ const [records, detail] = await Promise.all([
909
+ run(() => api(ctx, API + '/cf/dns?zoneId=' + encodeURIComponent(zone.id))),
910
+ run(() => api(ctx, API + '/cf/zones/detail?zoneId=' + encodeURIComponent(zone.id))),
911
+ ]);
912
+ if (!aliveRef.current) return;
913
+ if (records) setDns(records.items || []);
914
+ if (detail) setZoneDetail(detail.zone || null);
915
+ };
916
+
917
+ const reloadDns = async (zoneId) => {
918
+ const data = await run(() => api(ctx, API + '/cf/dns?zoneId=' + encodeURIComponent(zoneId)));
919
+ if (aliveRef.current && data) setDns(data.items || []);
920
+ };
921
+
922
+ const addDns = async () => {
923
+ const zoneId = openZone;
924
+ if (!zoneId) return;
925
+ const name = dnsForm.name.trim();
926
+ const content = dnsForm.content.trim();
927
+ if (!name || !content) return;
928
+
929
+ if (dnsForm.editingId !== '') {
930
+ // 编辑已有记录:只提交变化的字段(整条重写会让 Cloudflare 重置 TTL)。
931
+ const body = {
932
+ zoneId,
933
+ recordId: dnsForm.editingId,
934
+ type: dnsForm.type,
935
+ name,
936
+ content,
937
+ proxied: dnsForm.proxied,
938
+ };
939
+ const ok = await run(() => api(ctx, API + '/cf/dns/update', { method: 'POST', body }), 'dns');
940
+ if (ok) {
941
+ if (aliveRef.current) {
942
+ setDnsForm({ open: false, type: 'A', name: '', content: '', proxied: false, editingId: '' });
943
+ setNotice(t('cfDnsUpdated'));
944
+ }
945
+ await reloadDns(zoneId);
946
+ }
947
+ return;
948
+ }
949
+
950
+ const body = { zoneId, type: dnsForm.type, name, content, proxied: dnsForm.proxied };
951
+ const ok = await run(() => api(ctx, API + '/cf/dns/create', { method: 'POST', body }), 'dns');
952
+ if (ok) {
953
+ if (aliveRef.current) {
954
+ setDnsForm({ open: false, type: 'A', name: '', content: '', proxied: false, editingId: '' });
955
+ setNotice(t('cfDnsAdded'));
956
+ }
957
+ await reloadDns(zoneId);
958
+ }
959
+ };
960
+
961
+ /** 把一条记录填进表单,切换成编辑模式。 */
962
+ const editDns = (record) => {
963
+ setDnsForm({
964
+ open: true,
965
+ type: record.type,
966
+ name: record.name,
967
+ content: record.content,
968
+ proxied: record.proxied,
969
+ editingId: record.id,
970
+ });
971
+ };
972
+
973
+ const removeDns = async (recordId) => {
974
+ const zoneId = openZone;
975
+ if (!zoneId) return;
976
+ const ok = await run(() => api(ctx, API + '/cf/dns/delete', {
977
+ method: 'POST', body: { zoneId, recordId, confirm: true },
978
+ }), 'dns');
979
+ if (ok) { if (aliveRef.current) setNotice(t('cfDnsDeleted')); await reloadDns(zoneId); }
980
+ };
981
+
982
+ const purge = async () => {
983
+ const zoneId = openZone;
984
+ if (!zoneId) return;
985
+ const ok = await run(() => api(ctx, API + '/cf/zones/purge', { method: 'POST', body: { zoneId } }), 'purge');
986
+ if (ok && aliveRef.current) setNotice(t('cfCachePurged'));
987
+ };
988
+
989
+ const toggleDevMode = async () => {
990
+ const zoneId = openZone;
991
+ if (!zoneId || !zoneDetail) return;
992
+ const next = !zoneDetail.developmentMode;
993
+ const ok = await run(() => api(ctx, API + '/cf/zones/development', {
994
+ method: 'POST', body: { zoneId, enabled: next },
995
+ }), 'devmode');
996
+ if (ok && aliveRef.current) {
997
+ setZoneDetail(Object.assign({}, zoneDetail, { developmentMode: next }));
998
+ setNotice(next ? t('cfDevModeOn') : t('cfDevModeOff'));
999
+ }
1000
+ };
1001
+
1002
+ /* ---------- 路由 ---------- */
1003
+ const addRoute = async () => {
1004
+ const script = routeForm.script.trim();
1005
+ const pattern = routeForm.pattern.trim();
1006
+ if (!script || !pattern) return;
1007
+ const ok = await run(() => api(ctx, API + '/cf/routes/create', {
1008
+ method: 'POST', body: { script, pattern },
1009
+ }), 'route');
1010
+ if (ok) {
1011
+ if (aliveRef.current) { setRouteForm({ open: false, script: '', pattern: '' }); setNotice(t('cfRouteAdded')); }
1012
+ const r = await run(() => api(ctx, API + '/cf/routes'));
1013
+ if (aliveRef.current && r) setRoutes(r.items || []);
1014
+ }
1015
+ };
1016
+
1017
+ const removeRoute = async (routeId) => {
1018
+ const ok = await run(() => api(ctx, API + '/cf/routes/delete', {
1019
+ method: 'POST', body: { routeId, confirm: true },
1020
+ }), 'route');
1021
+ if (ok) {
1022
+ const r = await run(() => api(ctx, API + '/cf/routes'));
1023
+ if (aliveRef.current && r) setRoutes(r.items || []);
1024
+ }
1025
+ };
1026
+
1027
+ /* ---------- 渲染 ---------- */
1028
+ if (needAccount) {
1029
+ return h('div', { className: 'dsh-push-pickguide' },
1030
+ h(CloudflareMark, { size: 28 }),
1031
+ h('div', { className: 'dsh-push-pickguide-title' }, t('cfNeedAccount')),
1032
+ h('div', { className: 'dsh-push-pickguide-text' }, t('cfNoAccountLong')));
1033
+ }
1034
+
1035
+ if (loading) {
1036
+ return h('div', { className: 'dsh-push-skel', 'aria-hidden': 'true' },
1037
+ CONTRIB_SKELETON.map((row) => h('div', { key: row, className: 'dsh-push-skel-row' })));
1038
+ }
1039
+
1040
+ const armBtn = (key, onConfirm, title) => h('button', {
1041
+ type: 'button',
1042
+ className: 'dsh-push-iconbtn',
1043
+ title: deleteArm === key ? t('cfDeleteConfirm') : (title || t('cfDelete')),
1044
+ 'aria-label': t('cfDelete'),
1045
+ disabled: Boolean(busy),
1046
+ onClick: () => {
1047
+ if (deleteArm !== key) { setDeleteArm(key); return; }
1048
+ setDeleteArm('');
1049
+ onConfirm();
1050
+ },
1051
+ }, h(Icon, { name: 'close', size: 12 }));
1052
+
1053
+ /* Pages */
1054
+ const pagesBody = projects.length === 0
1055
+ ? h('div', { className: 'dsh-push-hint' }, t('cfEmpty'))
1056
+ : h('div', { className: 'dsh-push-rows' }, projects.map((p) => {
1057
+ const open = openProject === p.name;
1058
+ return h('div', { key: p.name, className: 'dsh-push-cf-item' },
1059
+ h('div', { className: 'dsh-push-row' },
1060
+ h('button', {
1061
+ type: 'button',
1062
+ className: 'dsh-push-cf-expand',
1063
+ title: open ? t('cfCollapse') : t('cfExpand'),
1064
+ onClick: () => toggleProject(p.name),
1065
+ }, h(Icon, { name: open ? 'chevronDown' : 'chevron', size: 11 })),
1066
+ h('div', { className: 'dsh-push-row-label' },
1067
+ h('div', { className: 'dsh-push-row-title dsh-push-mono' }, p.name),
1068
+ h('div', { className: 'dsh-push-row-hint' },
1069
+ [p.latestUrl, p.repoName ? p.repoOwner + '/' + p.repoName : null]
1070
+ .filter(Boolean).join(' · ') || t('cfNoDeployment'))),
1071
+ h('div', { className: 'dsh-push-row-control' },
1072
+ h(Btn, { mini: true, title: t('cfOpenDash'), onClick: () => openDash('workers-and-pages/view/pages/' + p.name) },
1073
+ h(Icon, { name: 'external', size: 11 })),
1074
+ armBtn('p:' + p.name, () => deleteProject(p.name)))),
1075
+ open
1076
+ ? h('div', { className: 'dsh-push-cf-sub' },
1077
+ h('div', { className: 'dsh-push-cf-sub-head' },
1078
+ h('span', null, t('cfDeployments')),
1079
+ h(Btn, {
1080
+ mini: true,
1081
+ disabled: Boolean(busy),
1082
+ onClick: () => toggleProject(p.name),
1083
+ }, t('refresh'))),
1084
+ deployments === null
1085
+ ? h('div', { className: 'dsh-push-hint' }, t('loading'))
1086
+ : deployments.length === 0
1087
+ ? h('div', { className: 'dsh-push-hint' }, t('cfNoDeployments'))
1088
+ : h('div', { className: 'dsh-push-cf-deploy-list' },
1089
+ deployments.map((d) => h('div', { key: d.id, className: 'dsh-push-cf-deploy-row' },
1090
+ h('span', { className: 'dsh-push-mono' }, d.shortId),
1091
+ h('span', { className: 'dsh-push-hint' },
1092
+ d.environment + ' · ' + relativeTime(d.createdOn)
1093
+ + (d.branch ? ' · ' + d.branch : '')),
1094
+ h('span', { className: 'dsh-push-page-spacer' }),
1095
+ h(Btn, {
1096
+ mini: true,
1097
+ disabled: Boolean(busy),
1098
+ title: t('cfRollback'),
1099
+ onClick: () => rollback(p.name, d.id),
1100
+ }, t('cfRollback')),
1101
+ armBtn('d:' + d.id, () => deleteDeployment(p.name, d.id))))),
1102
+ h('div', { className: 'dsh-push-cf-sub-head dsh-push-cf-envhead' },
1103
+ h('span', null, t('cfEnvTitle')),
1104
+ h(Btn, {
1105
+ mini: true,
1106
+ disabled: Boolean(busy),
1107
+ onClick: () => setEnvForm({ open: !envForm.open, key: '', value: '', secret: false }),
1108
+ }, t('cfEnvAdd'))),
1109
+ envForm.open
1110
+ ? h('div', { className: 'dsh-push-form dsh-push-cf-envform' },
1111
+ h('input', {
1112
+ className: 'dsh-push-input',
1113
+ value: envForm.key,
1114
+ placeholder: t('cfEnvKey'),
1115
+ spellCheck: false,
1116
+ onChange: (e) => setEnvForm(Object.assign({}, envForm, { key: e.target.value })),
1117
+ }),
1118
+ h('input', {
1119
+ className: 'dsh-push-input',
1120
+ value: envForm.value,
1121
+ placeholder: t('cfEnvValue'),
1122
+ spellCheck: false,
1123
+ onChange: (e) => setEnvForm(Object.assign({}, envForm, { value: e.target.value })),
1124
+ }),
1125
+ h('div', { className: 'dsh-push-inline' },
1126
+ h('label', { className: 'dsh-push-cf-check' },
1127
+ h('input', {
1128
+ type: 'checkbox',
1129
+ checked: envForm.secret,
1130
+ onChange: (e) => setEnvForm(Object.assign({}, envForm, { secret: e.target.checked })),
1131
+ }),
1132
+ t('cfEnvSecret')),
1133
+ h('span', { className: 'dsh-push-page-spacer' }),
1134
+ h(Btn, { kind: 'primary', mini: true, disabled: Boolean(busy), onClick: () => saveEnv(p.name) }, t('cfSave')),
1135
+ h(Btn, { mini: true, onClick: () => setEnvForm({ open: false, key: '', value: '', secret: false }) }, t('cancel'))))
1136
+ : null,
1137
+ envs === null
1138
+ ? null
1139
+ : envs.length === 0
1140
+ ? h('div', { className: 'dsh-push-hint' }, t('cfEnvEmpty'))
1141
+ : h('div', { className: 'dsh-push-cf-envlist' },
1142
+ envs.map((e) => h('div', { key: e.key, className: 'dsh-push-cf-envrow' },
1143
+ h('span', { className: 'dsh-push-mono' }, e.key),
1144
+ h('span', { className: 'dsh-push-pill dsh-push-pill--muted' },
1145
+ e.type === 'secret_text' ? t('cfEnvSecret') : t('cfEnvPlain'))))))
1146
+ : null);
1147
+ }));
1148
+
1149
+ /* Workers */
1150
+ const workersBody = workers.length === 0
1151
+ ? h('div', { className: 'dsh-push-hint' }, t('cfEmpty'))
1152
+ : h('div', { className: 'dsh-push-rows' }, workers.map((w) => h('div', { key: w.name, className: 'dsh-push-row' },
1153
+ h('div', { className: 'dsh-push-row-label' },
1154
+ h('div', { className: 'dsh-push-row-title dsh-push-mono' }, w.name),
1155
+ h('div', { className: 'dsh-push-row-hint' }, relativeTime(w.modifiedOn))),
1156
+ h('div', { className: 'dsh-push-row-control' },
1157
+ h(Btn, { mini: true, title: t('cfOpenDash'), onClick: () => openDash('workers/view/' + w.name) },
1158
+ h(Icon, { name: 'external', size: 11 })),
1159
+ armBtn('w:' + w.name, () => deleteWorkerByName(w.name))))));
1160
+
1161
+ /* 域名 */
1162
+ const zonesBody = zones.length === 0
1163
+ ? h('div', { className: 'dsh-push-hint' }, t('cfEmpty'))
1164
+ : h('div', { className: 'dsh-push-rows' }, zones.map((z) => {
1165
+ const open = openZone === z.id;
1166
+ return h('div', { key: z.id, className: 'dsh-push-cf-item' },
1167
+ h('div', { className: 'dsh-push-row' },
1168
+ h('button', {
1169
+ type: 'button',
1170
+ className: 'dsh-push-cf-expand',
1171
+ title: open ? t('cfCollapse') : t('cfExpandDns'),
1172
+ onClick: () => toggleZone(z),
1173
+ }, h(Icon, { name: open ? 'chevronDown' : 'chevron', size: 11 })),
1174
+ h('div', { className: 'dsh-push-row-label' },
1175
+ h('div', { className: 'dsh-push-row-title dsh-push-mono' }, z.name),
1176
+ h('div', { className: 'dsh-push-row-hint' },
1177
+ z.status + (zoneDetail && open && zoneDetail.plan ? ' · ' + zoneDetail.plan : ''))),
1178
+ h('div', { className: 'dsh-push-row-control' },
1179
+ h(Btn, { mini: true, title: t('cfOpenDash'), onClick: () => openDash('zones/' + z.id) },
1180
+ h(Icon, { name: 'external', size: 11 })))),
1181
+ open
1182
+ ? h('div', { className: 'dsh-push-cf-sub' },
1183
+ h('div', { className: 'dsh-push-cf-sub-head' },
1184
+ h('span', null, t('cfZoneActions')),
1185
+ h('div', { className: 'dsh-push-inline' },
1186
+ h(Btn, { mini: true, disabled: Boolean(busy), onClick: purge }, t('cfPurgeCache')),
1187
+ zoneDetail
1188
+ ? h(Btn, {
1189
+ mini: true,
1190
+ active: zoneDetail.developmentMode,
1191
+ disabled: Boolean(busy),
1192
+ onClick: toggleDevMode,
1193
+ }, zoneDetail.developmentMode ? t('cfDevModeOnShort') : t('cfDevModeOffShort'))
1194
+ : null,
1195
+ h(Btn, {
1196
+ mini: true,
1197
+ disabled: Boolean(busy),
1198
+ onClick: () => setDnsForm({ open: true, type: 'A', name: '', content: '', proxied: false, editingId: '' }),
1199
+ }, t('cfAddDns')))),
1200
+ dnsForm.open
1201
+ ? h('div', { className: 'dsh-push-form dsh-push-cf-dnsform' },
1202
+ h('div', { className: 'dsh-push-cf-sub-head' },
1203
+ h('span', null, dnsForm.editingId !== '' ? t('cfDnsEdit') : t('cfDnsNew'))),
1204
+ h('div', { className: 'dsh-push-inline' },
1205
+ h('select', {
1206
+ className: 'dsh-push-select',
1207
+ value: dnsForm.type,
1208
+ onChange: (e) => setDnsForm(Object.assign({}, dnsForm, { type: e.target.value })),
1209
+ }, (dns && dns.types ? dns.types : [{ id: 'A', label: 'A' }]).map((ty) => h('option', { key: ty.id, value: ty.id }, ty.label))),
1210
+ h('input', {
1211
+ className: 'dsh-push-input',
1212
+ value: dnsForm.name,
1213
+ placeholder: t('cfDnsName'),
1214
+ spellCheck: false,
1215
+ onChange: (e) => setDnsForm(Object.assign({}, dnsForm, { name: e.target.value })),
1216
+ })),
1217
+ h('input', {
1218
+ className: 'dsh-push-input',
1219
+ value: dnsForm.content,
1220
+ placeholder: t('cfDnsContent'),
1221
+ spellCheck: false,
1222
+ onChange: (e) => setDnsForm(Object.assign({}, dnsForm, { content: e.target.value })),
1223
+ }),
1224
+ h('div', { className: 'dsh-push-inline' },
1225
+ ['A', 'AAAA', 'CNAME'].includes(dnsForm.type)
1226
+ ? h('label', { className: 'dsh-push-cf-check' },
1227
+ h('input', {
1228
+ type: 'checkbox',
1229
+ checked: dnsForm.proxied,
1230
+ onChange: (e) => setDnsForm(Object.assign({}, dnsForm, { proxied: e.target.checked })),
1231
+ }),
1232
+ t('cfDnsProxied'))
1233
+ : null,
1234
+ h('span', { className: 'dsh-push-page-spacer' }),
1235
+ h(Btn, { kind: 'primary', mini: true, disabled: Boolean(busy), onClick: addDns }, t('cfCreate')),
1236
+ h(Btn, { mini: true, onClick: () => setDnsForm({ open: false, type: 'A', name: '', content: '', proxied: false, editingId: '' }) }, t('cancel'))))
1237
+ : null,
1238
+ dns === null
1239
+ ? h('div', { className: 'dsh-push-hint' }, t('loading'))
1240
+ : dns.length === 0
1241
+ ? h('div', { className: 'dsh-push-hint' }, t('cfNoDns'))
1242
+ : h('div', { className: 'dsh-push-cf-dnslist' },
1243
+ dns.map((r) => h('div', { key: r.id, className: 'dsh-push-cf-dnsrow' },
1244
+ h('span', { className: 'dsh-push-pill dsh-push-pill--muted' }, r.type),
1245
+ h('span', { className: 'dsh-push-mono' }, r.name),
1246
+ h('span', { className: 'dsh-push-hint' }, r.content),
1247
+ r.proxied ? h('span', { className: 'dsh-push-pill dsh-push-pill--ok' }, t('cfProxied')) : null,
1248
+ h('span', { className: 'dsh-push-page-spacer' }),
1249
+ h(Btn, { mini: true, title: t('cfEdit'), onClick: () => editDns(r) },
1250
+ h(Icon, { name: 'gear', size: 10 })),
1251
+ armBtn('r:' + r.id, () => removeDns(r.id))))))
1252
+ : null);
1253
+ }));
1254
+
1255
+ /* 路由 */
1256
+ const routesBody = h('div', null,
1257
+ routeForm.open
1258
+ ? h('div', { className: 'dsh-push-form' },
1259
+ h('input', {
1260
+ className: 'dsh-push-input',
1261
+ value: routeForm.script,
1262
+ placeholder: t('cfRouteScript'),
1263
+ spellCheck: false,
1264
+ onChange: (e) => setRouteForm(Object.assign({}, routeForm, { script: e.target.value })),
1265
+ }),
1266
+ h('input', {
1267
+ className: 'dsh-push-input',
1268
+ value: routeForm.pattern,
1269
+ placeholder: t('cfRoutePattern'),
1270
+ spellCheck: false,
1271
+ onChange: (e) => setRouteForm(Object.assign({}, routeForm, { pattern: e.target.value })),
1272
+ }),
1273
+ h('div', { className: 'dsh-push-inline' },
1274
+ h(Btn, { kind: 'primary', mini: true, disabled: Boolean(busy), onClick: addRoute }, t('cfCreate')),
1275
+ h(Btn, { mini: true, onClick: () => setRouteForm({ open: false, script: '', pattern: '' }) }, t('cancel'))))
1276
+ : null,
1277
+ routes.length === 0
1278
+ ? h('div', { className: 'dsh-push-hint' }, t('cfNoRoutes'))
1279
+ : h('div', { className: 'dsh-push-rows' }, routes.map((r) => h('div', { key: r.id, className: 'dsh-push-row' },
1280
+ h('div', { className: 'dsh-push-row-label' },
1281
+ h('div', { className: 'dsh-push-row-title dsh-push-mono' }, r.pattern),
1282
+ h('div', { className: 'dsh-push-row-hint' }, '→ ' + r.script)),
1283
+ h('div', { className: 'dsh-push-row-control' },
1284
+ armBtn('rt:' + r.id, () => removeRoute(r.id)))))));
1285
+
1286
+ const tabOptions = [
1287
+ { value: 'pages', label: t('cfProjectsTitle') + ' ' + projects.length },
1288
+ { value: 'workers', label: t('cfWorkersTitle') + ' ' + workers.length },
1289
+ { value: 'zones', label: t('cfZonesTitle') + ' ' + zones.length },
1290
+ { value: 'routes', label: t('cfRoutesTitle') + ' ' + routes.length },
1291
+ ];
1292
+
1293
+ const actionRow = h('div', { className: 'dsh-push-inline dsh-push-cf-actions' },
1294
+ tab === 'pages'
1295
+ ? h(Btn, { mini: true, disabled: Boolean(busy), onClick: () => setNewProject({ open: !newProject.open, name: '' }) }, t('cfNewProject'))
1296
+ : null,
1297
+ tab === 'routes'
1298
+ ? h(Btn, { mini: true, disabled: Boolean(busy), onClick: () => setRouteForm({ open: !routeForm.open, script: '', pattern: '' }) }, t('cfAddRoute'))
1299
+ : null,
1300
+ h('span', { className: 'dsh-push-page-spacer' }),
1301
+ h(Btn, { mini: true, disabled: Boolean(busy), onClick: loadAll }, busy ? t('loading') : t('refresh')));
1302
+
1303
+ return h('div', null,
1304
+ h('div', { className: 'dsh-push-group' },
1305
+ h('div', { className: 'dsh-push-group-head' },
1306
+ h('span', null, t('cfPanelTitle')),
1307
+ h(CloudflareAccountPicker, { ctx, onError: setError, onChange: loadAll })),
1308
+ error ? h('div', { className: 'dsh-push-error' }, error) : null,
1309
+ notice ? h('div', { className: 'dsh-push-hint dsh-push-cf-notice' }, notice) : null,
1310
+ h('div', { className: 'dsh-push-modal-tabs' }, h(TabRow, { options: tabOptions, value: tab, onChange: setTab })),
1311
+ actionRow,
1312
+ newProject.open
1313
+ ? h('div', { className: 'dsh-push-form' },
1314
+ h('input', {
1315
+ className: 'dsh-push-input',
1316
+ value: newProject.name,
1317
+ placeholder: t('cfProjectName'),
1318
+ spellCheck: false,
1319
+ onChange: (e) => setNewProject({ open: true, name: e.target.value }),
1320
+ }),
1321
+ h('div', { className: 'dsh-push-hint' }, t('cfNewProjectHint')),
1322
+ h('div', { className: 'dsh-push-inline' },
1323
+ h(Btn, { kind: 'primary', mini: true, disabled: busy === 'create' || newProject.name.trim() === '', onClick: createProject }, t('cfCreate')),
1324
+ h(Btn, { mini: true, onClick: () => setNewProject({ open: false, name: '' }) }, t('cancel'))))
1325
+ : null,
1326
+ tab === 'pages' ? pagesBody
1327
+ : tab === 'workers' ? workersBody
1328
+ : tab === 'zones' ? zonesBody : routesBody));
1329
+ }
1330
+
1331
+
1332
+
1333
+ /* ───────────── Cloudflare 工作区标签页(部署) ───────────── */
1334
+
1335
+ /**
1336
+ * 工作区标签页的 Cloudflare 一页:项目级部署。
1337
+ * @param {{ctx: object, scope?: {cwd: string, repoRoot?: string}}} props
1338
+ */
1339
+ function CloudflareWorkspaceTab(props) {
1340
+ const ctx = props.ctx;
1341
+ const cwd = (props.scope && (props.scope.repoRoot || props.scope.cwd)) || '';
1342
+ const [kind, setKind] = useState(null);
1343
+ const [detecting, setDetecting] = useState(false);
1344
+ const [projects, setProjects] = useState(null);
1345
+ const [project, setProject] = useState('');
1346
+ const [workerName, setWorkerName] = useState('');
1347
+ const [branch, setBranch] = useState('');
1348
+ const [busy, setBusy] = useState('');
1349
+ const [error, setError] = useState('');
1350
+ const [result, setResult] = useState(null);
1351
+ const [reviewOpen, setReviewOpen] = useState(false);
1352
+ const [notice, setNotice] = useState('');
1353
+ const [initOpen, setInitOpen] = useState(false);
1354
+ const [initName, setInitName] = useState('');
1355
+ const aliveRef = useRef(true);
1356
+
1357
+ useEffect(() => {
1358
+ aliveRef.current = true;
1359
+ return () => { aliveRef.current = false; };
1360
+ }, []);
1361
+
1362
+ useEffect(() => {
1363
+ if (!notice) return undefined;
1364
+ const id = setTimeout(() => { if (aliveRef.current) setNotice(''); }, TOAST_MS);
1365
+ return () => clearTimeout(id);
1366
+ }, [notice]);
1367
+
1368
+ const detect = useCallback(async () => {
1369
+ if (!cwd) return;
1370
+ setDetecting(true);
1371
+ setError('');
1372
+ try {
1373
+ const data = await api(ctx, API + '/cf/detect?path=' + encodeURIComponent(cwd));
1374
+ if (aliveRef.current) setKind(data && data.kind ? data.kind.type : null);
1375
+ } catch (err) {
1376
+ if (aliveRef.current) { setError(err.message); setKind(null); }
1377
+ } finally {
1378
+ if (aliveRef.current) setDetecting(false);
1379
+ }
1380
+ }, [ctx, cwd]);
1381
+
1382
+ const loadProjects = useCallback(async () => {
1383
+ try {
1384
+ const data = await api(ctx, API + '/cf/projects');
1385
+ if (!aliveRef.current) return;
1386
+ const items = data.items || [];
1387
+ setProjects(items);
1388
+ if (items.length === 1) setProject(items[0].name);
1389
+ } catch (err) {
1390
+ if (aliveRef.current && err.code !== 'NO_ACCOUNT') setError(err.message);
1391
+ if (aliveRef.current) setProjects([]);
1392
+ }
1393
+ }, [ctx]);
1394
+
1395
+ useEffect(() => { detect(); loadProjects(); }, [detect, loadProjects]);
1396
+
1397
+ const deploy = async () => {
1398
+ setBusy('deploy');
1399
+ setError('');
1400
+ setResult(null);
1401
+ try {
1402
+ const body = {
1403
+ path: cwd,
1404
+ kind,
1405
+ project: kind === 'pages' ? project.trim() : undefined,
1406
+ name: kind === 'worker' ? workerName.trim() : undefined,
1407
+ branch: kind === 'pages' && branch.trim() !== '' ? branch.trim() : undefined,
1408
+ };
1409
+ const data = await api(ctx, API + '/cf/deploy', { method: 'POST', body });
1410
+ if (aliveRef.current) setResult(data);
1411
+ } catch (err) {
1412
+ if (aliveRef.current) setError(err.message);
1413
+ } finally {
1414
+ if (aliveRef.current) setBusy('');
1415
+ }
1416
+ };
1417
+
1418
+ const initWorker = async () => {
1419
+ setBusy('init');
1420
+ setError('');
1421
+ try {
1422
+ const data = await api(ctx, API + '/cf/worker/init', {
1423
+ method: 'POST',
1424
+ body: { path: cwd, name: initName.trim() || undefined },
1425
+ });
1426
+ if (aliveRef.current) {
1427
+ setInitOpen(false);
1428
+ setInitName('');
1429
+ setNotice(data.created.length > 0 ? t('cfWorkerInited') : t('cfNothingToDo'));
1430
+ }
1431
+ await detect();
1432
+ if (aliveRef.current) setWorkerName(data.name);
1433
+ } catch (err) {
1434
+ if (aliveRef.current) setError(err.message);
1435
+ } finally {
1436
+ if (aliveRef.current) setBusy('');
1437
+ }
1438
+ };
1439
+
1440
+ const copyUrl = async (url) => {
1441
+ const ok = await copyText(url);
1442
+ if (aliveRef.current) setNotice(ok ? t('copied') : t('copyFailed'));
1443
+ };
1444
+
1445
+ if (!cwd) {
1446
+ return h('div', { className: 'dsh-push-pickguide' },
1447
+ h(CloudflareMark, { size: 28 }),
1448
+ h('div', { className: 'dsh-push-pickguide-title' }, t('cfNeedDir')),
1449
+ h('div', { className: 'dsh-push-pickguide-text' }, t('cfNeedDirHint')));
1450
+ }
1451
+
1452
+ const kindHint = detecting
1453
+ ? h('div', { className: 'dsh-push-hint' }, t('cfDetecting'))
1454
+ : kind === 'pages'
1455
+ ? h('div', { className: 'dsh-push-cf-kind' }, t('cfDetectPages'))
1456
+ : kind === 'worker'
1457
+ ? h('div', { className: 'dsh-push-cf-kind' }, t('cfDetectWorker'))
1458
+ : h('div', { className: 'dsh-push-cf-empty-state' },
1459
+ h('div', { className: 'dsh-push-hint' }, t('cfNotAProject')),
1460
+ h('div', { className: 'dsh-push-hint' }, t('cfNotAProjectHint')));
1461
+
1462
+ /* 不是可部署项目时,直接给一条「新建 Worker 项目」的路。 */
1463
+ const initBlock = kind === null && !detecting
1464
+ ? (initOpen
1465
+ ? h('div', { className: 'dsh-push-form' },
1466
+ h('input', {
1467
+ className: 'dsh-push-input',
1468
+ value: initName,
1469
+ placeholder: t('cfWorkerNameLabel'),
1470
+ spellCheck: false,
1471
+ onChange: (e) => setInitName(e.target.value),
1472
+ }),
1473
+ h('div', { className: 'dsh-push-hint' }, t('cfCreateWorkerHint')),
1474
+ h('div', { className: 'dsh-push-inline' },
1475
+ h(Btn, { kind: 'primary', mini: true, disabled: busy === 'init', onClick: initWorker }, t('cfWorkerInit')),
1476
+ h(Btn, { mini: true, onClick: () => { setInitOpen(false); setInitName(''); } }, t('cancel'))))
1477
+ : h('div', { className: 'dsh-push-inline' },
1478
+ h(Btn, { mini: true, onClick: () => setInitOpen(true) }, t('cfCreateWorker'))))
1479
+ : null;
1480
+
1481
+ const projectSelect = kind === 'pages' && projects && projects.length > 0
1482
+ ? h('select', {
1483
+ className: 'dsh-push-select',
1484
+ value: project,
1485
+ onChange: (e) => setProject(e.target.value),
1486
+ },
1487
+ h('option', { value: '' }, t('cfPickProject')),
1488
+ projects.map((p) => h('option', { key: p.name, value: p.name }, p.name)))
1489
+ : null;
1490
+
1491
+ const deployForm = kind === null
1492
+ ? null
1493
+ : h('div', { className: 'dsh-push-group' },
1494
+ kind === 'pages'
1495
+ ? (projectSelect || h('input', {
1496
+ className: 'dsh-push-input',
1497
+ value: project,
1498
+ placeholder: t('cfProjectName'),
1499
+ spellCheck: false,
1500
+ onChange: (e) => setProject(e.target.value),
1501
+ }))
1502
+ : h('input', {
1503
+ className: 'dsh-push-input',
1504
+ value: workerName,
1505
+ placeholder: t('cfNeedWorker'),
1506
+ spellCheck: false,
1507
+ onChange: (e) => setWorkerName(e.target.value),
1508
+ }),
1509
+ kind === 'pages'
1510
+ ? h('input', {
1511
+ className: 'dsh-push-input',
1512
+ value: branch,
1513
+ placeholder: t('cfBranchOptional'),
1514
+ spellCheck: false,
1515
+ onChange: (e) => setBranch(e.target.value),
1516
+ })
1517
+ : null,
1518
+ h('div', { className: 'dsh-push-inline' },
1519
+ h(Btn, {
1520
+ kind: 'primary',
1521
+ disabled: Boolean(busy) || (kind === 'pages' && project.trim() === '') || (kind === 'worker' && workerName.trim() === ''),
1522
+ onClick: deploy,
1523
+ }, busy === 'deploy' ? t('cfDeploying') : t('cfDeployAction')),
1524
+ h(Btn, { disabled: Boolean(busy), onClick: () => setReviewOpen(true) }, t('cfReviewOpen'))));
1525
+
1526
+ const deployUrl = result
1527
+ ? (result.kind === 'pages' ? (result.deployment && result.deployment.url) : result.url)
1528
+ : '';
1529
+
1530
+ const resultBlock = result
1531
+ ? h('div', { className: 'dsh-push-group' },
1532
+ h('div', { className: 'dsh-push-group-head' },
1533
+ h('span', null, result.kind === 'pages' ? t('cfDeployedPages') : t('cfDeployedWorker'))),
1534
+ deployUrl
1535
+ ? h('div', { className: 'dsh-push-cf-deploy-url' },
1536
+ h('a', {
1537
+ href: deployUrl,
1538
+ target: '_blank',
1539
+ rel: 'noopener',
1540
+ className: 'dsh-push-mono',
1541
+ title: deployUrl,
1542
+ }, deployUrl),
1543
+ h(Btn, { mini: true, onClick: () => copyUrl(deployUrl) }, t('copy')))
1544
+ : null,
1545
+ result.dashUrl
1546
+ ? h('div', { className: 'dsh-push-inline' },
1547
+ h(Btn, { mini: true, onClick: () => { try { window.open(result.dashUrl, '_blank', 'noopener'); } catch { /* ignore */ } } }, t('cfDeployOpenDash')))
1548
+ : null)
1549
+ : null;
1550
+
1551
+ return h('div', null,
1552
+ h('div', { className: 'dsh-push-group' },
1553
+ h('div', { className: 'dsh-push-group-head' },
1554
+ h('span', null, t('cfDeployTitle')),
1555
+ h(Btn, { mini: true, disabled: detecting, onClick: () => { detect(); loadProjects(); } },
1556
+ detecting ? t('cfDetecting') : t('refresh'))),
1557
+ kindHint,
1558
+ initBlock,
1559
+ h('div', { className: 'dsh-push-hint dsh-push-cf-path', title: cwd }, cwd)),
1560
+ deployForm,
1561
+ resultBlock,
1562
+ notice ? h('div', { className: 'dsh-push-hint' }, notice) : null,
1563
+ error ? h('div', { className: 'dsh-push-error' }, error) : null,
1564
+ h(CloudflareReviewDialog, {
1565
+ open: reviewOpen,
1566
+ ctx,
1567
+ cwd,
1568
+ kind,
1569
+ onClose: () => setReviewOpen(false),
1570
+ onReviewed: () => {},
1571
+ }));
1572
+ }
1573
+
1574
+ /**
1575
+ * 部署前审查弹窗(Cloudflare 版)。
1576
+ * @param {{ctx: object, open: boolean, cwd: string, kind: string|null,
1577
+ * onClose: () => void, onReviewed?: (data: object) => void}} props
1578
+ */
1579
+ function CloudflareReviewDialog(props) {
1580
+ const ctx = props.ctx;
1581
+ const [running, setRunning] = useState(false);
1582
+ const [result, setResult] = useState(null);
1583
+ const [error, setError] = useState('');
1584
+ const aliveRef = useRef(true);
1585
+
1586
+ useEffect(() => {
1587
+ aliveRef.current = true;
1588
+ return () => { aliveRef.current = false; };
1589
+ }, []);
1590
+
1591
+ useEffect(() => {
1592
+ if (props.open) { setResult(null); setError(''); }
1593
+ }, [props.open]);
1594
+
1595
+ if (!props.open) return null;
1596
+
1597
+ const run = async () => {
1598
+ setRunning(true);
1599
+ setError('');
1600
+ setResult(null);
1601
+ try {
1602
+ const data = await api(ctx, API + '/cf/review', {
1603
+ method: 'POST',
1604
+ body: { path: props.cwd, kind: props.kind || undefined },
1605
+ });
1606
+ if (aliveRef.current) {
1607
+ setResult(data);
1608
+ if (typeof props.onReviewed === 'function') props.onReviewed(data);
1609
+ }
1610
+ } catch (err) {
1611
+ if (aliveRef.current) setError(err.message);
1612
+ } finally {
1613
+ if (aliveRef.current) setRunning(false);
1614
+ }
1615
+ };
1616
+
1617
+ const findings = result ? result.findings || [] : [];
1618
+ const blockers = findings.filter((f) => f.severity === 'blocker').length;
1619
+
1620
+ const body = running
1621
+ ? h('div', { className: 'dsh-push-hint' }, t('rvRunning'))
1622
+ : result
1623
+ ? h('div', { className: 'dsh-push-cf-review' },
1624
+ blockers > 0 ? h('div', { className: 'dsh-push-error' }, t('cfReviewBlocker')) : null,
1625
+ findings.length === 0
1626
+ ? h('div', { className: 'dsh-push-hint' }, t('cfReviewNone'))
1627
+ : h('div', { className: 'dsh-push-rv-findings' },
1628
+ findings.map((f, i) => h('div', { key: i, className: 'dsh-push-rv-finding' },
1629
+ h('span', { className: 'dsh-push-rv-sev dsh-push-rv-sev--' + f.severity },
1630
+ h('span', { className: 'dsh-push-rv-dot' }),
1631
+ t(SEVERITY_LABEL[f.severity] || 'rvSeverityInfo')),
1632
+ h('span', { className: 'dsh-push-rv-finding-body' },
1633
+ h('span', { className: 'dsh-push-rv-finding-head' },
1634
+ h('span', { className: 'dsh-push-rv-finding-title' }, f.title)),
1635
+ f.detail ? h('span', { className: 'dsh-push-rv-finding-detail' }, f.detail) : null,
1636
+ f.file ? h('span', { className: 'dsh-push-rv-finding-file' }, f.file) : null)))),
1637
+ h('div', { className: 'dsh-push-hint' }, result.summary))
1638
+ : h('div', { className: 'dsh-push-hint' }, t('cfReviewHint'));
1639
+
1640
+ return h(Modal, {
1641
+ open: true,
1642
+ onClose: props.onClose,
1643
+ title: t('cfReviewOpen'),
1644
+ footer: [
1645
+ h(Btn, { key: 'run', kind: 'primary', disabled: running, onClick: run }, running ? t('rvRunning') : t('pjRun')),
1646
+ h(Btn, { key: 'close', onClick: props.onClose }, t('close')),
1647
+ ],
1648
+ },
1649
+ error ? h('div', { className: 'dsh-push-error' }, error) : null,
1650
+ body);
1651
+ }
1652
+
1653
+
1654
+
1655
+ /* ────────────────────────── 面板注册 ───────────────────────────────── */
1656
+
1657
+ /** 设置页那一块:账号卡片 + 概览。 */
1658
+ function settingsPanel(props) {
1659
+ return h(CloudflareSection, { ctx: props.ctx });
1660
+ }
1661
+
1662
+ /** 左侧栏:域名与资源的仪表盘。 */
1663
+ function sidebarPanel(props) {
1664
+ return h(CloudflarePanel, { ctx: props.ctx, reloadKey: props.reloadKey });
1665
+ }
1666
+
1667
+ /** 工作区标签页:目录探测、部署、新建 Worker、部署前审查。 */
1668
+ function workspacePanel(props) {
1669
+ return h(CloudflareWorkspaceTab, { ctx: props.ctx, scope: props.scope });
1670
+ }
1671
+
1672
+ function apply(ctx) {
1673
+ core.attachHostLocale(ctx);
1674
+ core.registerMessages('zh', ZH);
1675
+ core.registerMessages('en', EN);
1676
+
1677
+ // 面板属于这个 fiber:宿主卸载插件时随之消失,不会留一个点不开
1678
+ // 的入口。
1679
+ ctx.effect(() => core.registerPanel({
1680
+ id: 'cloudflare',
1681
+ label: 'Cloudflare',
1682
+ order: 30,
1683
+ mark: CloudflareMark,
1684
+ settings: settingsPanel,
1685
+ sidebar: sidebarPanel,
1686
+ workspace: workspacePanel,
1687
+ }), 'cloudflare: panel');
1688
+ }
1689
+
1690
+ exports.apply = apply;
1691
+ // 只有 slots 是必需的;locale 由内核用 ctx.get 探测。
1692
+ exports.inject = ['slots'];
1693
+
1694
+ return module.exports;
1695
+ },
1696
+ });