@kuanbandu/dsh-email 0.0.0-stage → 0.1.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,673 @@
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-email',
3
+ factory(require) {
4
+ const React = require('react')
5
+ const { useCallback, useEffect, useState } = React
6
+ const h = React.createElement
7
+
8
+ /** Same-origin endpoint served by index.js (absolute, like the HMR channel). */
9
+ const API_PATH = 'plugins/dsh-email/api'
10
+ const HEADER = { 'content-type': 'application/json', 'x-dsh-email': '1' }
11
+
12
+ const DICTS = {
13
+ zh: {
14
+ nav: '邮件',
15
+ title: '邮件账号',
16
+ subtitle: '在这里登录一次,harness 就能用 email_* 工具收发邮件。密码保存在本机凭据库,不会进入对话、报告或日志。',
17
+ addAccount: '添加邮箱账号',
18
+ cancel: '取消',
19
+ provider: '服务商',
20
+ email: '邮箱地址',
21
+ password: '密码 / 授权码',
22
+ passwordHint: 'Gmail/Outlook 用应用专用密码;163/QQ 用客户端授权码;Proton 用 Bridge 显示的密码。',
23
+ label: '显示名(可选)',
24
+ advanced: '高级:自定义服务器',
25
+ imapHost: 'IMAP 地址',
26
+ imapPort: '端口',
27
+ smtpHost: 'SMTP 地址',
28
+ smtpPort: '端口',
29
+ implicitTls: '隐式 TLS(465)',
30
+ starttls: 'STARTTLS(587/1143)',
31
+ skipVerify: '跳过 TLS 证书校验(仅本地桥接)',
32
+ proxy: '代理(可选)',
33
+ proxyHint: '用于这条邮箱的代理。留空 = 跟随全局设置;填 off = 强制直连。支持 host:port / http:// / socks5://。',
34
+ proxyOff: '直连',
35
+ proxyGlobal: '全局代理',
36
+ smtpProxy: 'SMTP 代理(可选)',
37
+ smtpProxyHint: '留空 = 与 IMAP 相同;填 off = SMTP 直连。很多代理节点会封 465/587,收信走代理、发信直连是常见组合。',
38
+ save: '登录并保存',
39
+ saving: '正在验证 IMAP/SMTP…',
40
+ testing: '测试中…',
41
+ test: '测试',
42
+ setDefault: '设为默认',
43
+ remove: '删除',
44
+ removeConfirm: '确认删除?',
45
+ noAccounts: '还没有登录任何邮箱。点下面的「添加邮箱账号」开始。',
46
+ defaultBadge: '默认',
47
+ missingPassword: '缺密码,请重新登录',
48
+ lastTestFailed: '上次测试失败',
49
+ lastTestOk: '上次测试通过',
50
+ note: '工具能力:email_accounts · email_mailboxes · email_search · email_read · email_send · email_reply · email_wait · email_attachment',
51
+ imap: 'IMAP',
52
+ smtp: 'SMTP',
53
+ loadFailed: '加载失败',
54
+ formError: '登录失败',
55
+ ok: '已保存',
56
+ deleteFailed: '删除失败',
57
+ testFailed: '测试失败',
58
+ defaultFailed: '设置默认失败',
59
+ mailboxes: '个文件夹',
60
+ security: '读取邮件使用 PEEK,不会把邮件标记为已读。',
61
+ loading: '加载中…',
62
+ },
63
+ en: {
64
+ nav: 'Email',
65
+ title: 'Email accounts',
66
+ subtitle: 'Log in once here and the agent can use the email_* tools. Passwords stay in the local credential store — never in the conversation, reports, or logs.',
67
+ addAccount: 'Add account',
68
+ cancel: 'Cancel',
69
+ provider: 'Provider',
70
+ email: 'Address',
71
+ password: 'Password / app password',
72
+ passwordHint: 'Gmail/Outlook need an app password, 163/QQ an authorization code, Proton the Bridge password.',
73
+ label: 'Display name (optional)',
74
+ advanced: 'Advanced: custom servers',
75
+ imapHost: 'IMAP host',
76
+ imapPort: 'Port',
77
+ smtpHost: 'SMTP host',
78
+ smtpPort: 'Port',
79
+ implicitTls: 'Implicit TLS (465)',
80
+ starttls: 'STARTTLS (587/1143)',
81
+ skipVerify: 'Skip TLS verification (local bridge only)',
82
+ proxy: 'Proxy (optional)',
83
+ proxyHint: 'Proxy for this mailbox. Empty = follow the global setting; "off" = always direct. Accepts host:port / http:// / socks5://.',
84
+ proxyOff: 'direct',
85
+ proxyGlobal: 'global proxy',
86
+ smtpProxy: 'SMTP proxy (optional)',
87
+ smtpProxyHint: 'Empty = same as IMAP; "off" = send directly. Many proxy nodes block 465/587, so proxied IMAP + direct SMTP is a common split.',
88
+ save: 'Log in and save',
89
+ saving: 'Verifying IMAP/SMTP…',
90
+ testing: 'Testing…',
91
+ test: 'Test',
92
+ setDefault: 'Make default',
93
+ remove: 'Remove',
94
+ removeConfirm: 'Confirm remove?',
95
+ noAccounts: 'No account yet. Use “Add account” below.',
96
+ defaultBadge: 'default',
97
+ missingPassword: 'password missing — log in again',
98
+ lastTestFailed: 'last test failed',
99
+ lastTestOk: 'last test passed',
100
+ note: 'Tools: email_accounts · email_mailboxes · email_search · email_read · email_send · email_reply · email_wait · email_attachment',
101
+ imap: 'IMAP',
102
+ smtp: 'SMTP',
103
+ loadFailed: 'Failed to load',
104
+ formError: 'Login failed',
105
+ ok: 'Saved',
106
+ deleteFailed: 'Remove failed',
107
+ testFailed: 'Test failed',
108
+ defaultFailed: 'Could not set default',
109
+ mailboxes: 'folders',
110
+ security: 'Reading uses PEEK, so messages are not marked as read.',
111
+ loading: 'Loading…',
112
+ },
113
+ }
114
+
115
+ const STYLES = `
116
+ .dsh-email-section { display:flex; flex-direction:column; gap:16px; padding:8px 0; font-size:13px; line-height:22px; color:var(--dsw-alias-label-primary); }
117
+ .dsh-email-head { display:flex; flex-direction:column; gap:4px; }
118
+ .dsh-email-title { font-size:16px; font-weight:600; line-height:24px; }
119
+ .dsh-email-sub { color:var(--dsw-alias-label-secondary); }
120
+ .dsh-email-list { display:flex; flex-direction:column; gap:8px; }
121
+ .dsh-email-card { display:flex; align-items:center; justify-content:space-between; gap:16px; padding:12px 16px; border:0.5px solid var(--dsw-alias-border-l1); border-radius:12px; background:var(--dsw-alias-bg-layer-1); }
122
+ .dsh-email-ident { display:flex; align-items:center; gap:10px; min-width:0; }
123
+ .dsh-email-avatar { flex:none; display:flex; align-items:center; justify-content:center; width:32px; height:32px; border-radius:50%; font-weight:600; text-transform:uppercase; color:var(--dsw-alias-label-secondary); background:var(--dsw-alias-bg-layer-2); }
124
+ .dsh-email-copy { display:flex; flex-direction:column; min-width:0; }
125
+ .dsh-email-address { font-size:14px; font-weight:500; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
126
+ .dsh-email-meta { color:var(--dsw-alias-label-secondary); font-size:12px; line-height:18px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
127
+ .dsh-email-actions { display:flex; align-items:center; gap:8px; flex:none; flex-wrap:wrap; }
128
+ .dsh-email-badges { display:flex; gap:6px; flex-wrap:wrap; margin-top:2px; }
129
+ .dsh-email-badge { font-size:11px; line-height:16px; padding:1px 6px; border-radius:6px; border:0.5px solid var(--dsw-alias-border-l1); color:var(--dsw-alias-label-secondary); }
130
+ .dsh-email-badge.is-default { color:var(--dsw-alias-brand-primary); border-color:var(--dsw-alias-brand-primary); }
131
+ .dsh-email-badge.is-warn { color:var(--dsw-alias-state-warn-primary); border-color:var(--dsw-alias-state-warn-primary); }
132
+ .dsh-email-badge.is-error { color:var(--dsw-alias-state-error-primary); border-color:var(--dsw-alias-state-error-primary); }
133
+ .dsh-email-badge.is-ok { color:var(--dsw-alias-state-success-primary); border-color:var(--dsw-alias-state-success-primary); }
134
+ .dsh-email-btn { display:inline-flex; align-items:center; gap:6px; height:28px; padding:0 10px; border-radius:8px; border:0.5px solid var(--dsw-alias-border-l2); background:transparent; color:var(--dsw-alias-label-primary); font-size:12px; font-family:inherit; cursor:pointer; }
135
+ .dsh-email-btn:hover:not(:disabled) { background:var(--dsw-alias-bg-layer-2); }
136
+ .dsh-email-btn:disabled { opacity:.55; cursor:default; }
137
+ .dsh-email-btn:focus-visible { outline:2px solid var(--dsw-alias-brand-primary); outline-offset:1px; }
138
+ .dsh-email-btn.is-primary { background:var(--dsw-alias-brand-primary); border-color:var(--dsw-alias-brand-primary); color:var(--dsw-alias-bg-base); }
139
+ .dsh-email-btn.is-danger { color:var(--dsw-alias-state-error-primary); border-color:var(--dsw-alias-state-error-primary); }
140
+ .dsh-email-form { display:flex; flex-direction:column; gap:12px; padding:16px; border:0.5px solid var(--dsw-alias-border-l1); border-radius:12px; background:var(--dsw-alias-bg-layer-1); }
141
+ .dsh-email-row { display:flex; gap:12px; flex-wrap:wrap; }
142
+ .dsh-email-field { display:flex; flex-direction:column; gap:4px; flex:1 1 200px; min-width:0; }
143
+ .dsh-email-caption { font-size:12px; color:var(--dsw-alias-label-secondary); }
144
+ .dsh-email-input, .dsh-email-select { height:32px; padding:0 10px; border-radius:8px; border:0.5px solid var(--dsw-alias-border-l2); background:var(--dsw-alias-bg-base); color:inherit; font-size:13px; font-family:inherit; }
145
+ .dsh-email-input:focus-visible, .dsh-email-select:focus-visible { outline:2px solid var(--dsw-alias-brand-primary); outline-offset:1px; }
146
+ .dsh-email-check { display:flex; align-items:center; gap:8px; font-size:12px; color:var(--dsw-alias-label-secondary); min-height:32px; }
147
+ .dsh-email-hint { font-size:12px; line-height:18px; color:var(--dsw-alias-label-secondary); white-space:pre-wrap; }
148
+ .dsh-email-error { font-size:12px; line-height:18px; color:var(--dsw-alias-state-error-primary); white-space:pre-wrap; }
149
+ .dsh-email-report { display:flex; gap:8px; flex-wrap:wrap; }
150
+ .dsh-email-empty { padding:16px; border:0.5px dashed var(--dsw-alias-border-l2); border-radius:12px; color:var(--dsw-alias-label-secondary); text-align:center; }
151
+ .dsh-email-foot { font-size:12px; color:var(--dsw-alias-label-secondary); }
152
+ .dsh-email-details { border-top:0.5px solid var(--dsw-alias-border-l1); padding-top:12px; display:flex; flex-direction:column; gap:12px; }
153
+ .dsh-email-details > summary { cursor:pointer; font-size:12px; color:var(--dsw-alias-label-secondary); }
154
+ `
155
+
156
+ /** One same-origin POST to the plugin API. */
157
+ async function call(op, payload, signal) {
158
+ const response = await fetch(`${location.origin}/${API_PATH}`, {
159
+ method: 'POST',
160
+ headers: HEADER,
161
+ body: JSON.stringify({ op, ...(payload ?? {}) }),
162
+ signal,
163
+ })
164
+ if (response.ok === false) throw new Error(`HTTP ${response.status}`)
165
+ const json = await response.json()
166
+ if (json.ok === false) {
167
+ const error = new Error(json.error ?? 'operation failed')
168
+ error.code = json.code
169
+ throw error
170
+ }
171
+ return json
172
+ }
173
+
174
+ /** Current UI language id, 'zh' or 'en'. */
175
+ function readLang(ctx) {
176
+ try {
177
+ const locale = serviceOf(ctx, 'locale')
178
+ const snapshot = locale?.getSnapshot?.() ?? locale?.getLocale?.() ?? {}
179
+ const id = String(snapshot.active ?? snapshot.id ?? snapshot.locale ?? 'zh').toLowerCase()
180
+ return id.startsWith('zh') ? 'zh' : 'en'
181
+ } catch {
182
+ return 'zh'
183
+ }
184
+ }
185
+
186
+ /** Read one service defensively: an undeclared service throws on access. */
187
+ function serviceOf(ctx, name) {
188
+ try {
189
+ return ctx?.[name] ?? undefined
190
+ } catch {
191
+ return undefined
192
+ }
193
+ }
194
+
195
+ /** Translate + re-render on locale change; degrades to Chinese without a locale service. */
196
+ function useTranslate(ctx) {
197
+ const [tick, setTick] = useState(0)
198
+ useEffect(() => {
199
+ try {
200
+ const locale = serviceOf(ctx, 'locale')
201
+ if (typeof locale?.subscribe !== 'function') return undefined
202
+ const dispose = locale.subscribe(() => setTick(value => value + 1))
203
+ return typeof dispose === 'function' ? dispose : undefined
204
+ } catch {
205
+ return undefined
206
+ }
207
+ }, [ctx])
208
+ return useCallback(key => DICTS[readLang(ctx)][key] ?? DICTS.en[key] ?? key, [ctx, tick])
209
+ }
210
+
211
+ /** Badge chip. */
212
+ function Badge({ text, kind }) {
213
+ return h('span', { className: kind === undefined ? 'dsh-email-badge' : `dsh-email-badge is-${kind}` }, text)
214
+ }
215
+
216
+ /** Labelled field wrapper. */
217
+ function Field({ label, children }) {
218
+ return h('div', { className: 'dsh-email-field' },
219
+ h('div', { className: 'dsh-email-caption' }, label),
220
+ children)
221
+ }
222
+
223
+ /** One account row. */
224
+ function AccountCard({ account, t, busy, confirming, onTest, onDefault, onRemove }) {
225
+ const endpointLine = `${account.providerLabel ?? account.provider} · IMAP ${account.imap.host}:${account.imap.port} · SMTP ${account.smtp.host}:${account.smtp.port}`
226
+ const badges = []
227
+ if (account.default === true) badges.push(h(Badge, { key: 'default', text: t('defaultBadge'), kind: 'default' }))
228
+ if (account.hasPassword === false) badges.push(h(Badge, { key: 'nopass', text: t('missingPassword'), kind: 'warn' }))
229
+ if (account.lastTest?.ok === true) badges.push(h(Badge, { key: 'ok', text: t('lastTestOk'), kind: 'ok' }))
230
+ if (account.lastTest?.ok === false) badges.push(h(Badge, { key: 'fail', text: t('lastTestFailed'), kind: 'error' }))
231
+ const imapRoute = account.route === undefined || account.route === 'direct' ? t('proxyOff') : account.route
232
+ const smtpRoute = account.smtpRoute === undefined || account.smtpRoute === 'direct' ? t('proxyOff') : account.smtpRoute
233
+ badges.push(h(Badge, {
234
+ key: 'route',
235
+ text: imapRoute === smtpRoute ? `IMAP/SMTP ${imapRoute === t('proxyOff') ? imapRoute : `via ${imapRoute}`}` : `IMAP ${imapRoute === t('proxyOff') ? imapRoute : `via ${imapRoute}`} · SMTP ${smtpRoute === t('proxyOff') ? smtpRoute : `via ${smtpRoute}`}`,
236
+ }))
237
+
238
+ return h('div', { className: 'dsh-email-card' },
239
+ h('div', { className: 'dsh-email-ident' },
240
+ h('div', { className: 'dsh-email-avatar', 'aria-hidden': 'true' }, account.email.slice(0, 1)),
241
+ h('div', { className: 'dsh-email-copy' },
242
+ h('div', { className: 'dsh-email-address' }, account.label === '' ? account.email : `${account.label} · ${account.email}`),
243
+ h('div', { className: 'dsh-email-meta', title: endpointLine }, endpointLine),
244
+ badges.length === 0 ? null : h('div', { className: 'dsh-email-badges' }, ...badges))),
245
+ h('div', { className: 'dsh-email-actions' },
246
+ h('button', {
247
+ type: 'button',
248
+ className: 'dsh-email-btn',
249
+ disabled: busy,
250
+ onClick: () => onTest(account),
251
+ }, busy ? t('testing') : t('test')),
252
+ account.default === true ? null : h('button', {
253
+ type: 'button',
254
+ className: 'dsh-email-btn',
255
+ disabled: busy,
256
+ onClick: () => onDefault(account),
257
+ }, t('setDefault')),
258
+ h('button', {
259
+ type: 'button',
260
+ className: 'dsh-email-btn is-danger',
261
+ disabled: busy,
262
+ onClick: () => onRemove(account),
263
+ }, confirming ? t('removeConfirm') : t('remove'))))
264
+ }
265
+
266
+ /** The add-account form. */
267
+ function AddAccountForm({ form, providers, t, lang, defaults, busy, onChange, onProvider, onSubmit, onCancel }) {
268
+ const provider = providers.find(item => item.id === form.provider)
269
+ const hint = provider === undefined ? '' : (lang === 'zh' ? provider.hint.zh : provider.hint.en)
270
+ const set = (patch) => onChange({ ...form, ...patch })
271
+
272
+ const providerField = h(Field, { key: 'provider', label: t('provider') },
273
+ h('select', {
274
+ className: 'dsh-email-select',
275
+ 'aria-label': t('provider'),
276
+ value: form.provider,
277
+ onChange: event => onProvider(event.target.value),
278
+ }, ...providers.map(item => h('option', { key: item.id, value: item.id }, item.label))))
279
+
280
+ const emailField = h(Field, { key: 'email', label: t('email') },
281
+ h('input', {
282
+ className: 'dsh-email-input',
283
+ 'aria-label': t('email'),
284
+ type: 'email',
285
+ required: true,
286
+ autoComplete: 'username',
287
+ value: form.email,
288
+ onChange: event => set({ email: event.target.value }),
289
+ }))
290
+
291
+ const labelField = h(Field, { key: 'label', label: t('label') },
292
+ h('input', {
293
+ className: 'dsh-email-input',
294
+ 'aria-label': t('label'),
295
+ type: 'text',
296
+ placeholder: 'Kali',
297
+ value: form.label,
298
+ onChange: event => set({ label: event.target.value }),
299
+ }))
300
+
301
+ const passwordField = h(Field, { key: 'password', label: t('password') },
302
+ h('input', {
303
+ className: 'dsh-email-input',
304
+ 'aria-label': t('password'),
305
+ type: 'password',
306
+ required: true,
307
+ autoComplete: 'current-password',
308
+ value: form.password,
309
+ onChange: event => set({ password: event.target.value }),
310
+ }))
311
+
312
+ const advanced = h('details', {
313
+ key: 'advanced',
314
+ className: 'dsh-email-details',
315
+ open: form.advanced,
316
+ onToggle: event => set({ advanced: event.target.open }),
317
+ },
318
+ h('summary', null, t('advanced')),
319
+ h('div', { className: 'dsh-email-row' },
320
+ h(Field, { label: t('imapHost') },
321
+ h('input', {
322
+ className: 'dsh-email-input',
323
+ 'aria-label': t('imapHost'),
324
+ value: form.imap.host,
325
+ onChange: event => set({ imap: { ...form.imap, host: event.target.value } }),
326
+ })),
327
+ h(Field, { label: t('imapPort') },
328
+ h('input', {
329
+ className: 'dsh-email-input',
330
+ 'aria-label': t('imapPort'),
331
+ type: 'number',
332
+ value: form.imap.port,
333
+ onChange: event => set({ imap: { ...form.imap, port: event.target.value } }),
334
+ })),
335
+ h('label', { className: 'dsh-email-check' },
336
+ h('input', {
337
+ type: 'checkbox',
338
+ 'aria-label': `IMAP ${t('implicitTls')}`,
339
+ checked: form.imap.secure === true,
340
+ onChange: event => set({ imap: { ...form.imap, secure: event.target.checked, starttls: event.target.checked ? false : form.imap.starttls } }),
341
+ }),
342
+ t('implicitTls')),
343
+ h('label', { className: 'dsh-email-check' },
344
+ h('input', {
345
+ type: 'checkbox',
346
+ 'aria-label': `IMAP ${t('starttls')}`,
347
+ checked: form.imap.starttls === true,
348
+ onChange: event => set({ imap: { ...form.imap, starttls: event.target.checked, secure: event.target.checked ? false : form.imap.secure } }),
349
+ }),
350
+ t('starttls'))),
351
+ h('div', { className: 'dsh-email-row' },
352
+ h(Field, { label: t('smtpHost') },
353
+ h('input', {
354
+ className: 'dsh-email-input',
355
+ 'aria-label': t('smtpHost'),
356
+ value: form.smtp.host,
357
+ onChange: event => set({ smtp: { ...form.smtp, host: event.target.value } }),
358
+ })),
359
+ h(Field, { label: t('smtpPort') },
360
+ h('input', {
361
+ className: 'dsh-email-input',
362
+ 'aria-label': t('smtpPort'),
363
+ type: 'number',
364
+ value: form.smtp.port,
365
+ onChange: event => set({ smtp: { ...form.smtp, port: event.target.value } }),
366
+ })),
367
+ h('label', { className: 'dsh-email-check' },
368
+ h('input', {
369
+ type: 'checkbox',
370
+ 'aria-label': `SMTP ${t('implicitTls')}`,
371
+ checked: form.smtp.secure === true,
372
+ onChange: event => set({ smtp: { ...form.smtp, secure: event.target.checked, starttls: event.target.checked ? false : form.smtp.starttls } }),
373
+ }),
374
+ t('implicitTls')),
375
+ h('label', { className: 'dsh-email-check' },
376
+ h('input', {
377
+ type: 'checkbox',
378
+ 'aria-label': `SMTP ${t('starttls')}`,
379
+ checked: form.smtp.starttls === true,
380
+ onChange: event => set({ smtp: { ...form.smtp, starttls: event.target.checked, secure: event.target.checked ? false : form.smtp.secure } }),
381
+ }),
382
+ t('starttls'))),
383
+ h('label', { className: 'dsh-email-check' },
384
+ h('input', {
385
+ type: 'checkbox',
386
+ checked: form.rejectUnauthorized === false,
387
+ onChange: event => set({ rejectUnauthorized: event.target.checked === false }),
388
+ }),
389
+ t('skipVerify')),
390
+ h('div', { className: 'dsh-email-row' },
391
+ h(Field, { label: t('proxy') },
392
+ h('input', {
393
+ className: 'dsh-email-input',
394
+ 'aria-label': t('proxy'),
395
+ type: 'text',
396
+ placeholder: defaults?.proxy === undefined || defaults.proxy === '' ? 'off' : defaults.proxy,
397
+ value: form.proxy,
398
+ onChange: event => set({ proxy: event.target.value }),
399
+ }))),
400
+ h('div', { className: 'dsh-email-row' },
401
+ h(Field, { label: t('smtpProxy') },
402
+ h('input', {
403
+ className: 'dsh-email-input',
404
+ 'aria-label': t('smtpProxy'),
405
+ type: 'text',
406
+ placeholder: '-',
407
+ value: form.smtpProxy,
408
+ onChange: event => set({ smtpProxy: event.target.value }),
409
+ }))),
410
+ h('div', { className: 'dsh-email-hint' },
411
+ `${t('proxyHint')}${defaults?.proxy === undefined || defaults.proxy === '' ? '' : `(${t('proxyGlobal')}: ${defaults.proxy})`}`),
412
+ h('div', { className: 'dsh-email-hint' }, t('smtpProxyHint')))
413
+
414
+ const actions = h('div', { key: 'actions', className: 'dsh-email-actions' },
415
+ h('button', { type: 'submit', className: 'dsh-email-btn is-primary', disabled: busy },
416
+ busy ? t('saving') : t('save')),
417
+ h('button', { type: 'button', className: 'dsh-email-btn', disabled: busy, onClick: onCancel }, t('cancel')))
418
+
419
+ return h('form', { className: 'dsh-email-form', onSubmit },
420
+ h('div', { className: 'dsh-email-row' }, providerField, emailField, labelField),
421
+ passwordField,
422
+ hint === '' ? null : h('div', { className: 'dsh-email-hint' }, hint),
423
+ h('div', { className: 'dsh-email-hint' }, t('passwordHint')),
424
+ advanced,
425
+ actions)
426
+ }
427
+
428
+ /** The settings page. */
429
+ function EmailSettings(props) {
430
+ const ctx = props.ctx
431
+ const t = useTranslate(ctx)
432
+ const lang = readLang(ctx)
433
+ const [accounts, setAccounts] = useState(undefined)
434
+ const [providers, setProviders] = useState([])
435
+ const [defaults, setDefaults] = useState(undefined)
436
+ const [error, setError] = useState('')
437
+ const [notice, setNotice] = useState('')
438
+ const [busyId, setBusyId] = useState('')
439
+ const [confirmId, setConfirmId] = useState('')
440
+ const [form, setForm] = useState(undefined)
441
+ const [report, setReport] = useState(undefined)
442
+
443
+ useEffect(() => {
444
+ let alive = true
445
+ void (async () => {
446
+ try {
447
+ const [catalog, list] = await Promise.all([call('catalog'), call('list')])
448
+ if (alive === false) return
449
+ setProviders(catalog.providers ?? [])
450
+ setDefaults(catalog.defaults)
451
+ setAccounts(list.accounts ?? [])
452
+ } catch (failure) {
453
+ if (alive === false) return
454
+ setError(`${t('loadFailed')}: ${failure.message}`)
455
+ setAccounts([])
456
+ }
457
+ })()
458
+ return () => { alive = false }
459
+ }, [t])
460
+
461
+ const reload = useCallback(async () => {
462
+ try {
463
+ const list = await call('list')
464
+ setAccounts(list.accounts ?? [])
465
+ } catch { /* the next user action surfaces the failure */ }
466
+ }, [])
467
+
468
+ const openForm = useCallback(() => {
469
+ const first = providers[0]
470
+ setError('')
471
+ setNotice('')
472
+ setReport(undefined)
473
+ setConfirmId('')
474
+ setForm({
475
+ provider: first?.id ?? 'gmail',
476
+ email: '',
477
+ password: '',
478
+ label: '',
479
+ imap: {
480
+ host: first?.imap?.host ?? '',
481
+ port: first?.imap?.port ?? 993,
482
+ secure: first?.imap?.secure !== false,
483
+ starttls: first?.imap?.starttls === true,
484
+ },
485
+ smtp: {
486
+ host: first?.smtp?.host ?? '',
487
+ port: first?.smtp?.port ?? 465,
488
+ secure: first?.smtp?.secure !== false,
489
+ starttls: first?.smtp?.starttls === true,
490
+ },
491
+ advanced: false,
492
+ rejectUnauthorized: true,
493
+ proxy: '',
494
+ smtpProxy: '',
495
+ })
496
+ }, [providers])
497
+
498
+ const pickProvider = useCallback((id) => {
499
+ const preset = providers.find(item => item.id === id)
500
+ setForm(current => current === undefined ? current : {
501
+ ...current,
502
+ provider: id,
503
+ imap: {
504
+ host: preset?.imap?.host ?? '',
505
+ port: preset?.imap?.port ?? 993,
506
+ secure: preset?.imap?.secure !== false,
507
+ starttls: preset?.imap?.starttls === true,
508
+ },
509
+ smtp: {
510
+ host: preset?.smtp?.host ?? '',
511
+ port: preset?.smtp?.port ?? 465,
512
+ secure: preset?.smtp?.secure !== false,
513
+ starttls: preset?.smtp?.starttls === true,
514
+ },
515
+ rejectUnauthorized: preset?.imap?.rejectUnauthorized !== false,
516
+ })
517
+ }, [providers])
518
+
519
+ const submit = useCallback(async (event) => {
520
+ event.preventDefault()
521
+ if (form === undefined) return
522
+ setBusyId('form')
523
+ setError('')
524
+ setNotice('')
525
+ setReport(undefined)
526
+ try {
527
+ const result = await call('add', {
528
+ email: form.email.trim(),
529
+ password: form.password,
530
+ provider: form.provider,
531
+ label: form.label,
532
+ proxy: form.proxy.trim(),
533
+ smtpProxy: form.smtpProxy.trim(),
534
+ imap: {
535
+ host: form.imap.host.trim(),
536
+ port: Number(form.imap.port),
537
+ secure: form.imap.secure === true,
538
+ starttls: form.imap.starttls === true,
539
+ rejectUnauthorized: form.rejectUnauthorized !== false,
540
+ },
541
+ smtp: {
542
+ host: form.smtp.host.trim(),
543
+ port: Number(form.smtp.port),
544
+ secure: form.smtp.secure === true,
545
+ starttls: form.smtp.starttls === true,
546
+ rejectUnauthorized: form.rejectUnauthorized !== false,
547
+ },
548
+ })
549
+ setAccounts(result.accounts ?? [])
550
+ setReport(result.report)
551
+ const warnings = result.warnings ?? []
552
+ setNotice(warnings.length > 0 ? warnings.join('\n') : t('ok'))
553
+ if (warnings.length === 0) setForm(undefined)
554
+ } catch (failure) {
555
+ setError(`${t('formError')}: ${failure.message}`)
556
+ } finally {
557
+ setBusyId('')
558
+ }
559
+ }, [form, t])
560
+
561
+ const runOp = useCallback(async (op, account, failureLabel) => {
562
+ setBusyId(account.id)
563
+ setError('')
564
+ setNotice('')
565
+ try {
566
+ const result = await call(op, { account: account.id })
567
+ if (result.accounts !== undefined) setAccounts(result.accounts)
568
+ if (result.report !== undefined) setReport(result.report)
569
+ if (op === 'test') setNotice(`${account.email} — ${result.ok === true ? t('lastTestOk') : t('lastTestFailed')}`)
570
+ else setNotice(t('ok'))
571
+ } catch (failure) {
572
+ setError(`${failureLabel}: ${failure.message}`)
573
+ } finally {
574
+ setBusyId('')
575
+ }
576
+ }, [t])
577
+
578
+ const remove = useCallback(async (account) => {
579
+ if (confirmId !== account.id) {
580
+ setConfirmId(account.id)
581
+ return
582
+ }
583
+ setConfirmId('')
584
+ setBusyId(account.id)
585
+ try {
586
+ const result = await call('remove', { account: account.id })
587
+ setAccounts(result.accounts ?? [])
588
+ setNotice(t('ok'))
589
+ } catch (failure) {
590
+ setError(`${t('deleteFailed')}: ${failure.message}`)
591
+ await reload()
592
+ } finally {
593
+ setBusyId('')
594
+ }
595
+ }, [confirmId, reload, t])
596
+
597
+ const reportNode = report === undefined ? null : h('div', { className: 'dsh-email-report' },
598
+ h(Badge, {
599
+ text: report.imap?.ok === true
600
+ ? `IMAP OK · ${report.imap.ms}ms · ${report.imap.mailboxes} ${t('mailboxes')}`
601
+ : `IMAP ✗ ${report.imap?.error ?? ''}`,
602
+ kind: report.imap?.ok === true ? 'ok' : 'error',
603
+ }),
604
+ h(Badge, {
605
+ text: report.smtp?.ok === true ? `SMTP OK · ${report.smtp.ms}ms` : `SMTP ✗ ${report.smtp?.error ?? ''}`,
606
+ kind: report.smtp?.ok === true ? 'ok' : 'error',
607
+ }))
608
+
609
+ let body
610
+ if (accounts === undefined) body = h('div', { className: 'dsh-email-empty' }, t('loading'))
611
+ else if (accounts.length === 0) body = h('div', { className: 'dsh-email-empty' }, t('noAccounts'))
612
+ else {
613
+ body = h('div', { className: 'dsh-email-list' }, ...accounts.map(account => h(AccountCard, {
614
+ key: account.id,
615
+ account,
616
+ t,
617
+ busy: busyId === account.id,
618
+ confirming: confirmId === account.id,
619
+ onTest: item => runOp('test', item, t('testFailed')),
620
+ onDefault: item => runOp('default', item, t('defaultFailed')),
621
+ onRemove: item => remove(item),
622
+ })))
623
+ }
624
+
625
+ const formNode = form === undefined
626
+ ? h('div', null, h('button', { type: 'button', className: 'dsh-email-btn is-primary', onClick: openForm }, t('addAccount')))
627
+ : h(AddAccountForm, {
628
+ form,
629
+ providers,
630
+ t,
631
+ lang,
632
+ defaults,
633
+ busy: busyId === 'form',
634
+ onChange: setForm,
635
+ onProvider: pickProvider,
636
+ onSubmit: submit,
637
+ onCancel: () => { setForm(undefined); setError('') },
638
+ })
639
+
640
+ return h('div', { className: 'dsh-email-section' },
641
+ h('style', null, STYLES),
642
+ h('div', { className: 'dsh-email-head' },
643
+ h('div', { className: 'dsh-email-title' }, t('title')),
644
+ h('div', { className: 'dsh-email-sub' }, t('subtitle'))),
645
+ error === '' ? null : h('div', { className: 'dsh-email-error', role: 'alert' }, error),
646
+ notice === '' ? null : h('div', { className: 'dsh-email-hint', role: 'status' }, notice),
647
+ body,
648
+ reportNode,
649
+ formNode,
650
+ h('div', { className: 'dsh-email-foot' }, t('note')),
651
+ h('div', { className: 'dsh-email-foot' }, t('security')))
652
+ }
653
+
654
+ /** Nav label, localized at render time by the settings shell. */
655
+ function makeLabel(ctx) {
656
+ return () => DICTS[readLang(ctx)].nav
657
+ }
658
+
659
+ return {
660
+ // `locale` must be declared: a Cordis client context throws when a
661
+ // plugin reads a service it did not inject.
662
+ inject: ['slots', 'locale'],
663
+ apply(ctx) {
664
+ ctx.effect(() => ctx.slots.inject('settings.section', () => ctx.slots.register({
665
+ name: 'settings.section',
666
+ id: 'dsh-email',
667
+ order: 30,
668
+ label: makeLabel(ctx),
669
+ }, props => h(EmailSettings, { ...props, ctx }))), 'dsh-email: settings section')
670
+ },
671
+ }
672
+ },
673
+ })