@lucky_zone/net-proxy 0.0.0-stage → 1.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,773 @@
1
+ /**
2
+ * Browser half of the network-proxy plugin: the left sidebar entry and the panel
3
+ * it opens, plus the row configuration page the Plugins manager renders.
4
+ *
5
+ * Both surfaces edit the Host entry `net-proxy` through the shared configuration
6
+ * forms service, so the sidebar, the Plugins page, and the Host policy always read
7
+ * one document.
8
+ */
9
+
10
+ window.__ModuleLoader__.load({
11
+ id: '@lucky_zone/net-proxy',
12
+ factory(require) {
13
+ const React = require('react')
14
+ const h = React.createElement
15
+
16
+ /** Locale namespace owned by this plugin. */
17
+ const NS = 'net-proxy'
18
+ /** Loader entry id of the Host row; the configuration form is keyed by it. */
19
+ const ENTRY_ID = 'net-proxy'
20
+ /** Panel id shared by the sidebar entry and the main-column panel it opens. */
21
+ const PANEL_ID = 'net-proxy'
22
+ /** `plugins.row.config` key of the row this bundle inserts. */
23
+ const ROW_KEY = '@lucky_zone/net-proxy#net-proxy'
24
+
25
+ const EN = {
26
+ panel: 'Network proxy',
27
+ title: 'Network proxy',
28
+ lead: 'Send the listed domains through your own proxy server; everything else connects directly.',
29
+ statusOn: 'Proxied',
30
+ statusOff: 'Direct',
31
+ statusIdleHint: 'Requests connect directly. Turn on \u201cUse proxy\u201d to route the listed domains.',
32
+ statusOnHint: 'Only the listed domains go through {proxy}; everything else connects directly.',
33
+ invalidEnabled: 'The proxy address is not usable, so requests still connect directly.',
34
+ emptyDomains: 'No usable domain is listed, so every request connects directly.',
35
+ covers: 'What it covers',
36
+ coversHost: 'Host requests: model calls, web fetch, HTTP MCP',
37
+ coversChild: 'Commands and terminals started after the change',
38
+ coversFallback: 'Unlisted hosts retry through the proxy when a direct connection fails',
39
+ directAlways: 'localhost and 127.0.0.1 always connect directly',
40
+ enabledLabel: 'Use proxy',
41
+ enabledHint: 'Applies to the Host\u2019s own requests and to commands and terminals started afterwards.',
42
+ proxyLabel: 'Proxy server',
43
+ proxyHint: 'http:// or https:// only, for example http://127.0.0.1:7890.',
44
+ proxyInvalid: 'Enter an http:// or https:// proxy address.',
45
+ domainsLabel: 'Proxied domains',
46
+ domainsHint: 'One per line or comma-separated. Each entry also matches its subdomains; every other host connects directly.',
47
+ domainsInvalid: 'Write host names only, without a scheme or path, for example github.com.',
48
+ domainsPlaceholder: 'github.com',
49
+ fallbackLabel: 'Retry direct failures through the proxy',
50
+ fallbackHint: 'A host outside the list that cannot be reached directly is tried once more through the proxy server.',
51
+ save: 'Save',
52
+ saving: 'Saving\u2026',
53
+ saved: 'Saved',
54
+ unsaved: 'Unsaved changes',
55
+ failed: 'The Host refused the change. Check the fields and try again.',
56
+ reset: 'Reset to defaults',
57
+ loading: 'Reading configuration\u2026',
58
+ unavailable: 'Configuration is unavailable. Check that this plugin is enabled.',
59
+ summaryOn: 'Enabled',
60
+ summaryOff: 'Disabled',
61
+ summaryNone: 'no domains',
62
+ summaryInvalidProxy: 'proxy unusable',
63
+ summaryDomainOne: '1 domain',
64
+ summaryDomains: '{count} domains',
65
+ managerHint: 'The same settings are on this plugin\u2019s page in Plugins; click its row title to open them.',
66
+ openManager: 'Open in Plugins',
67
+ }
68
+
69
+ const ZH = {
70
+ panel: '网络代理',
71
+ title: '网络代理',
72
+ lead: '只把列表内的域名交给你的代理服务器,其余站点直连。',
73
+ statusOn: '走代理',
74
+ statusOff: '直连',
75
+ statusIdleHint: '请求当前直连。打开「使用代理」后,列表内的域名改为走代理。',
76
+ statusOnHint: '只有列表内的域名经由 {proxy},其余站点一律直连。',
77
+ invalidEnabled: '代理地址不可用,请求仍然直连。',
78
+ emptyDomains: '列表中没有可用的域名,所有请求直连。',
79
+ covers: '生效范围',
80
+ coversHost: '宿主请求:模型调用、网页抓取、HTTP MCP',
81
+ coversChild: '改动之后新启动的命令与终端',
82
+ coversFallback: '列表外站点直连失败时改用代理重试一次',
83
+ directAlways: 'localhost 与 127.0.0.1 始终直连',
84
+ enabledLabel: '使用代理',
85
+ enabledHint: '作用于宿主自身的请求,以及之后新启动的命令与终端。',
86
+ proxyLabel: '代理服务器',
87
+ proxyHint: '仅支持 http:// 与 https://,例如 http://127.0.0.1:7890。',
88
+ proxyInvalid: '请填写 http:// 或 https:// 代理地址。',
89
+ domainsLabel: '走代理的域名',
90
+ domainsHint: '每行一个或用逗号分隔;条目同时匹配其子域名,其余主机一律直连。',
91
+ domainsInvalid: '只填主机名,不要带协议或路径,例如 github.com。',
92
+ domainsPlaceholder: 'github.com',
93
+ fallbackLabel: '直连失败时改用代理重试',
94
+ fallbackHint: '列表外的站点如果无法直连,会再通过代理服务器尝试一次。',
95
+ save: '保存',
96
+ saving: '保存中…',
97
+ saved: '已保存',
98
+ unsaved: '有未保存的改动',
99
+ failed: '宿主拒绝了这次改动,请检查字段后重试。',
100
+ reset: '恢复默认',
101
+ loading: '正在读取配置…',
102
+ unavailable: '配置不可用,请确认插件已启用。',
103
+ summaryOn: '已启用',
104
+ summaryOff: '未启用',
105
+ summaryNone: '未指定域名',
106
+ summaryInvalidProxy: '代理不可用',
107
+ summaryDomainOne: '1 个域名',
108
+ summaryDomains: '{count} 个域名',
109
+ managerHint: '同样的设置也在「插件管理」中本插件的配置页:点击这一行的标题打开。',
110
+ openManager: '在插件管理中打开',
111
+ }
112
+
113
+ const CSS = `
114
+ .dsh-np-page {
115
+ display: flex;
116
+ flex-direction: column;
117
+ height: 100%;
118
+ overflow-y: auto;
119
+ box-sizing: border-box;
120
+ padding: 32px clamp(20px, 4vw, 48px) 48px;
121
+ color: var(--dsw-alias-label-primary);
122
+ font-size: 14px;
123
+ }
124
+ .dsh-np-inner {
125
+ display: flex;
126
+ flex-direction: column;
127
+ gap: 16px;
128
+ width: 100%;
129
+ max-width: 720px;
130
+ margin: 0 auto;
131
+ }
132
+ .dsh-np-head { display: flex; flex-direction: column; gap: 6px; }
133
+ .dsh-np-title { margin: 0; font-size: 20px; font-weight: 600; letter-spacing: -0.01em; }
134
+ .dsh-np-lead { margin: 0; font-size: 13px; line-height: 1.6; color: var(--dsw-alias-label-secondary); }
135
+ .dsh-np-card {
136
+ display: flex;
137
+ flex-direction: column;
138
+ gap: 18px;
139
+ padding: 18px 20px;
140
+ border: 1px solid var(--dsw-alias-border-l1);
141
+ border-radius: 12px;
142
+ background: var(--dsw-alias-bg-layer-1);
143
+ }
144
+ .dsh-np-status { display: flex; flex-direction: column; gap: 8px; }
145
+ .dsh-np-statusRow { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
146
+ .dsh-np-pill {
147
+ display: inline-flex;
148
+ align-items: center;
149
+ gap: 6px;
150
+ flex: none;
151
+ padding: 3px 10px;
152
+ border: 1px solid var(--dsw-alias-border-l1);
153
+ border-radius: 999px;
154
+ font-size: 12px;
155
+ font-weight: 600;
156
+ color: var(--dsw-alias-label-secondary);
157
+ }
158
+ .dsh-np-pill::before {
159
+ content: '';
160
+ width: 6px;
161
+ height: 6px;
162
+ border-radius: 50%;
163
+ background: currentColor;
164
+ }
165
+ .dsh-np-pill[data-tone="on"] { color: var(--dsw-alias-state-success-primary); }
166
+ .dsh-np-pill[data-tone="warn"] { color: var(--dsw-alias-state-warn-primary); }
167
+ .dsh-np-statusText { font-size: 13px; line-height: 1.55; color: var(--dsw-alias-label-secondary); }
168
+ .dsh-np-covers { display: flex; flex-direction: column; gap: 6px; }
169
+ .dsh-np-coversTitle {
170
+ font-size: 11px;
171
+ font-weight: 600;
172
+ letter-spacing: 0.04em;
173
+ text-transform: uppercase;
174
+ color: var(--dsw-alias-label-secondary);
175
+ }
176
+ .dsh-np-list { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 4px; }
177
+ .dsh-np-list li {
178
+ position: relative;
179
+ padding-left: 16px;
180
+ font-size: 13px;
181
+ line-height: 1.55;
182
+ color: var(--dsw-alias-label-secondary);
183
+ }
184
+ .dsh-np-list li::before {
185
+ content: '';
186
+ position: absolute;
187
+ left: 3px;
188
+ top: 8px;
189
+ width: 5px;
190
+ height: 5px;
191
+ border-radius: 50%;
192
+ background: var(--dsw-alias-border-l2);
193
+ }
194
+ .dsh-np-row { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }
195
+ .dsh-np-rowText { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
196
+ .dsh-np-label { font-size: 13px; font-weight: 500; line-height: 1.5; }
197
+ .dsh-np-hint { font-size: 12px; line-height: 1.55; color: var(--dsw-alias-label-secondary); }
198
+ .dsh-np-hint[data-invalid="true"] { color: var(--dsw-alias-state-error-primary); }
199
+ .dsh-np-hint[data-warn="true"] { color: var(--dsw-alias-state-warn-primary); }
200
+ .dsh-np-switch {
201
+ position: relative;
202
+ flex: none;
203
+ width: 38px;
204
+ height: 22px;
205
+ margin-top: 2px;
206
+ padding: 0;
207
+ border: 1px solid var(--dsw-alias-border-l2);
208
+ border-radius: 999px;
209
+ background: var(--dsw-alias-bg-layer-2);
210
+ cursor: pointer;
211
+ }
212
+ .dsh-np-switch::after {
213
+ content: '';
214
+ position: absolute;
215
+ top: 2px;
216
+ left: 2px;
217
+ width: 16px;
218
+ height: 16px;
219
+ border-radius: 50%;
220
+ background: #ffffff;
221
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);
222
+ transition: transform 120ms ease;
223
+ }
224
+ .dsh-np-switch[aria-checked="true"] {
225
+ border-color: var(--dsw-alias-brand-primary);
226
+ background: var(--dsw-alias-brand-primary);
227
+ }
228
+ .dsh-np-switch[aria-checked="true"]::after { transform: translateX(16px); }
229
+ .dsh-np-switch:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 2px; }
230
+ .dsh-np-switch:disabled { opacity: 0.5; cursor: default; }
231
+ .dsh-np-field { display: flex; flex-direction: column; gap: 6px; }
232
+ .dsh-np-input {
233
+ box-sizing: border-box;
234
+ width: 100%;
235
+ padding: 8px 10px;
236
+ border: 1px solid var(--dsw-alias-border-l1);
237
+ border-radius: 8px;
238
+ background: var(--dsw-alias-bg-base);
239
+ color: var(--dsw-alias-label-primary);
240
+ font: inherit;
241
+ font-size: 13px;
242
+ line-height: 1.5;
243
+ }
244
+ .dsh-np-input::placeholder { color: var(--dsw-alias-label-secondary); opacity: 0.7; }
245
+ .dsh-np-input:focus-visible {
246
+ outline: none;
247
+ border-color: var(--dsw-alias-brand-primary);
248
+ box-shadow: 0 0 0 1px var(--dsw-alias-brand-primary);
249
+ }
250
+ .dsh-np-input[aria-invalid="true"] { border-color: var(--dsw-alias-state-error-primary); }
251
+ .dsh-np-textarea {
252
+ min-height: 88px;
253
+ resize: vertical;
254
+ }
255
+ .dsh-np-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
256
+ .dsh-np-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
257
+ .dsh-np-button {
258
+ padding: 7px 14px;
259
+ border: 1px solid var(--dsw-alias-border-l1);
260
+ border-radius: 8px;
261
+ background: transparent;
262
+ color: var(--dsw-alias-label-primary);
263
+ font: inherit;
264
+ font-size: 13px;
265
+ line-height: 1.4;
266
+ cursor: pointer;
267
+ }
268
+ .dsh-np-button:hover:not(:disabled) { background: var(--dsw-alias-bg-layer-2); }
269
+ .dsh-np-button:disabled { opacity: 0.5; cursor: default; }
270
+ .dsh-np-button:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 2px; }
271
+ .dsh-np-button[data-variant="primary"] {
272
+ border-color: var(--dsw-alias-brand-primary);
273
+ background: var(--dsw-alias-brand-primary);
274
+ color: #ffffff;
275
+ }
276
+ .dsh-np-button[data-variant="primary"]:hover:not(:disabled) {
277
+ background: var(--dsw-alias-brand-primary);
278
+ filter: brightness(1.06);
279
+ }
280
+ .dsh-np-button[data-variant="ghost"] { border-color: transparent; color: var(--dsw-alias-label-secondary); }
281
+ .dsh-np-feedback {
282
+ min-height: 18px;
283
+ font-size: 12px;
284
+ line-height: 1.5;
285
+ color: var(--dsw-alias-label-secondary);
286
+ }
287
+ .dsh-np-feedback[data-tone="ok"] { color: var(--dsw-alias-state-success-primary); }
288
+ .dsh-np-feedback[data-tone="error"] { color: var(--dsw-alias-state-error-primary); }
289
+ .dsh-np-note { margin: 0; font-size: 12px; line-height: 1.6; color: var(--dsw-alias-label-secondary); }
290
+ .dsh-np-placeholder {
291
+ padding: 18px 20px;
292
+ border: 1px dashed var(--dsw-alias-border-l1);
293
+ border-radius: 12px;
294
+ font-size: 13px;
295
+ line-height: 1.6;
296
+ color: var(--dsw-alias-label-secondary);
297
+ }
298
+ @media (max-width: 640px) {
299
+ .dsh-np-page { padding: 24px 16px 40px; }
300
+ .dsh-np-card { padding: 16px; }
301
+ }
302
+ `
303
+
304
+ /**
305
+ * Read the three fields from a form value.
306
+ * @param value - accepted configuration values, possibly incomplete.
307
+ * @returns the fields this plugin owns.
308
+ */
309
+ function pick(value) {
310
+ return {
311
+ enabled: value !== undefined && value !== null && value.enabled === true,
312
+ proxyUrl: value !== undefined && value !== null && typeof value.proxyUrl === 'string' ? value.proxyUrl : '',
313
+ domains: value !== undefined && value !== null && typeof value.domains === 'string' ? value.domains : '',
314
+ fallback: value !== undefined && value !== null && value.fallback === true,
315
+ }
316
+ }
317
+
318
+ /**
319
+ * Split configured text into domains, dropping blanks and repeats.
320
+ * @param text - the field's text, separated by newlines, commas, or spaces.
321
+ * @returns domain entries in the order written.
322
+ */
323
+ function splitDomains(text) {
324
+ const seen = new Set()
325
+ const entries = []
326
+ for (const raw of String(text).split(/[\s,]+/)) {
327
+ const entry = raw.trim()
328
+ if (entry === '') continue
329
+ const key = entry.toLowerCase()
330
+ if (seen.has(key)) continue
331
+ seen.add(key)
332
+ entries.push(entry)
333
+ }
334
+ return entries
335
+ }
336
+
337
+ /**
338
+ * Canonical field text: one domain per line, without blanks or repeats.
339
+ * @param text - the field's text.
340
+ * @returns the stored form of the allowlist.
341
+ */
342
+ function normalizeDomains(text) {
343
+ return splitDomains(text).join('\n')
344
+ }
345
+
346
+ /**
347
+ * Whether one entry can match a host: a host name, optionally with a port,
348
+ * a leading `*.`, or `*` alone.
349
+ * @param entry - one already-trimmed entry.
350
+ * @returns true for an entry the router can use.
351
+ */
352
+ function isValidDomainEntry(entry) {
353
+ if (entry === '*') return true
354
+ if (entry.length > 255 || /[\s/?#@]/.test(entry)) return false
355
+ if (entry.startsWith('[')) return /^\[[0-9A-Fa-f:.]+\](:\d{1,5})?$/.test(entry)
356
+ const colon = entry.indexOf(':')
357
+ const host = colon === -1 ? entry : entry.slice(0, colon)
358
+ const port = colon === -1 ? undefined : entry.slice(colon + 1)
359
+ if (port !== undefined && !/^\d{1,5}$/.test(port)) return false
360
+ if (host === '' || host === '.' || host.includes('..')) return false
361
+ return /^[A-Za-z0-9.*_-]+$/.test(host)
362
+ }
363
+
364
+ /**
365
+ * Whether the harness can route through this address.
366
+ * @param value - proxy address as typed.
367
+ * @returns true for a parseable http: or https: URL.
368
+ */
369
+ function supportedProxyUrl(value) {
370
+ try {
371
+ const url = new URL(value)
372
+ return url.protocol === 'http:' || url.protocol === 'https:'
373
+ } catch {
374
+ return false
375
+ }
376
+ }
377
+
378
+ /**
379
+ * The proxy address without credentials, for display.
380
+ * @param value - proxy address as typed.
381
+ * @returns scheme and authority only.
382
+ */
383
+ function displayProxy(value) {
384
+ try {
385
+ const url = new URL(value)
386
+ return `${url.protocol}//${url.host}`
387
+ } catch {
388
+ return value
389
+ }
390
+ }
391
+
392
+ /**
393
+ * Follow a snapshot source's replacements.
394
+ * @param source - observable with getSnapshot and subscribe.
395
+ * @returns the current snapshot.
396
+ */
397
+ function useSnapshot(source) {
398
+ const [snapshot, setSnapshot] = React.useState(() => (source === undefined ? undefined : source.getSnapshot()))
399
+ React.useEffect(() => {
400
+ if (source === undefined) {
401
+ setSnapshot(undefined)
402
+ return undefined
403
+ }
404
+ setSnapshot(source.getSnapshot())
405
+ return source.subscribe(() => { setSnapshot(source.getSnapshot()) })
406
+ }, [source])
407
+ return snapshot
408
+ }
409
+
410
+ /**
411
+ * Render the policy status summary from accepted values.
412
+ * @param props - translations and the current snapshot.
413
+ * @returns the status card.
414
+ */
415
+ function StatusCard({ t, snapshot }) {
416
+ const ready = snapshot !== undefined && snapshot.status === 'ready'
417
+ const loading = snapshot === undefined || snapshot.status === 'loading'
418
+ const value = pick(ready ? snapshot.value : undefined)
419
+ const listed = splitDomains(value.domains).filter(isValidDomainEntry).length
420
+ const usable = supportedProxyUrl(value.proxyUrl)
421
+ const on = ready && value.enabled && usable && listed > 0
422
+ const broken = ready && value.enabled && !usable
423
+ const empty = ready && value.enabled && usable && listed === 0
424
+ const tone = on ? 'on' : broken || empty ? 'warn' : 'off'
425
+ return h('div', { className: 'dsh-np-card dsh-np-status' },
426
+ h('div', { className: 'dsh-np-statusRow' },
427
+ h('span', { className: 'dsh-np-pill', 'data-tone': tone }, t(on ? 'statusOn' : 'statusOff')),
428
+ h('span', { className: 'dsh-np-statusText' },
429
+ loading
430
+ ? t('loading')
431
+ : !ready
432
+ ? t('unavailable')
433
+ : on
434
+ ? t('statusOnHint', { proxy: displayProxy(value.proxyUrl) })
435
+ : broken
436
+ ? t('invalidEnabled')
437
+ : empty
438
+ ? t('emptyDomains')
439
+ : t('statusIdleHint')),
440
+ ),
441
+ h('div', { className: 'dsh-np-covers' },
442
+ h('span', { className: 'dsh-np-coversTitle' }, t('covers')),
443
+ h('ul', { className: 'dsh-np-list' },
444
+ h('li', null, t('coversHost')),
445
+ h('li', null, t('coversChild')),
446
+ value.fallback ? h('li', null, t('coversFallback')) : null,
447
+ h('li', null, t('directAlways')),
448
+ ),
449
+ ),
450
+ )
451
+ }
452
+
453
+ /**
454
+ * The editable settings card shared by the sidebar panel and the row page.
455
+ * @param props - translations, the current snapshot, and the write action.
456
+ * @returns the settings card.
457
+ */
458
+ function SettingsCard({ t, snapshot, mutate }) {
459
+ const available = snapshot !== undefined && snapshot.status === 'ready' && typeof mutate === 'function'
460
+ const value = pick(available ? snapshot.value : undefined)
461
+ const revision = available ? snapshot.revision : undefined
462
+ const [draft, setDraft] = React.useState(() => value)
463
+ const [phase, setPhase] = React.useState('idle')
464
+ const [failure, setFailure] = React.useState(false)
465
+ const applied = React.useRef(revision)
466
+ const fieldId = React.useId()
467
+ const proxyHintId = `${fieldId}-proxy`
468
+ const domainsHintId = `${fieldId}-domains`
469
+
470
+ React.useEffect(() => {
471
+ if (revision === applied.current) return
472
+ applied.current = revision
473
+ const next = pick(snapshot !== undefined && snapshot.status === 'ready' ? snapshot.value : undefined)
474
+ setDraft(next)
475
+ }, [revision, snapshot])
476
+
477
+ if (snapshot === undefined || snapshot.status === 'loading') {
478
+ return h('div', { className: 'dsh-np-placeholder' }, t('loading'))
479
+ }
480
+ if (snapshot.status !== 'ready' || typeof mutate !== 'function') {
481
+ return h('div', { className: 'dsh-np-placeholder' }, t('unavailable'))
482
+ }
483
+
484
+ const proxyText = draft.proxyUrl.trim()
485
+ const proxyInvalid = proxyText !== '' && !supportedProxyUrl(proxyText)
486
+ const proxyMissing = draft.enabled && proxyText === ''
487
+ const domainEntries = splitDomains(draft.domains)
488
+ const domainsInvalid = domainEntries.some(entry => !isValidDomainEntry(entry))
489
+ const domainListEmpty = domainEntries.length === 0
490
+ const dirty = draft.enabled !== value.enabled
491
+ || proxyText !== value.proxyUrl
492
+ || normalizeDomains(draft.domains) !== value.domains
493
+ || draft.fallback !== value.fallback
494
+ const blocked = proxyInvalid || proxyMissing || domainsInvalid
495
+ const saving = phase === 'saving'
496
+
497
+ const edit = (patch) => {
498
+ setDraft((current) => ({ ...current, ...patch }))
499
+ setPhase('idle')
500
+ setFailure(false)
501
+ }
502
+
503
+ const write = async (ops, guarded) => {
504
+ if (saving) return
505
+ if (guarded === true && blocked) {
506
+ setPhase('failed')
507
+ setFailure(true)
508
+ return
509
+ }
510
+ setPhase('saving')
511
+ setFailure(false)
512
+ let accepted = false
513
+ try {
514
+ accepted = await mutate(ops, revision)
515
+ } catch (error) {
516
+ accepted = false
517
+ }
518
+ setPhase(accepted ? 'saved' : 'failed')
519
+ setFailure(!accepted)
520
+ }
521
+
522
+ const save = () => write([
523
+ { op: 'set', path: ['enabled'], value: draft.enabled },
524
+ { op: 'set', path: ['proxyUrl'], value: proxyText },
525
+ { op: 'set', path: ['domains'], value: normalizeDomains(draft.domains) },
526
+ { op: 'set', path: ['fallback'], value: draft.fallback },
527
+ ], true)
528
+
529
+ const reset = () => write([
530
+ { op: 'unset', path: ['enabled'] },
531
+ { op: 'unset', path: ['proxyUrl'] },
532
+ { op: 'unset', path: ['domains'] },
533
+ { op: 'unset', path: ['fallback'] },
534
+ ], false)
535
+
536
+ const feedback = failure
537
+ ? { tone: 'error', text: proxyInvalid || proxyMissing ? t('proxyInvalid') : domainsInvalid ? t('domainsInvalid') : t('failed') }
538
+ : saving
539
+ ? { tone: 'muted', text: t('saving') }
540
+ : phase === 'saved' && !dirty
541
+ ? { tone: 'ok', text: t('saved') }
542
+ : dirty
543
+ ? { tone: 'muted', text: t('unsaved') }
544
+ : null
545
+
546
+ return h('div', { className: 'dsh-np-card' },
547
+ h('div', { className: 'dsh-np-row' },
548
+ h('div', { className: 'dsh-np-rowText' },
549
+ h('span', { className: 'dsh-np-label' }, t('enabledLabel')),
550
+ h('span', { className: 'dsh-np-hint' }, t('enabledHint')),
551
+ ),
552
+ h('button', {
553
+ type: 'button',
554
+ className: 'dsh-np-switch',
555
+ role: 'switch',
556
+ 'aria-checked': draft.enabled,
557
+ 'aria-label': t('enabledLabel'),
558
+ disabled: saving,
559
+ onClick: () => { edit({ enabled: !draft.enabled }) },
560
+ }),
561
+ ),
562
+ h('label', { className: 'dsh-np-field' },
563
+ h('span', { className: 'dsh-np-label' }, t('proxyLabel')),
564
+ h('input', {
565
+ className: 'dsh-np-input dsh-np-mono',
566
+ type: 'text',
567
+ inputMode: 'url',
568
+ spellCheck: false,
569
+ autoComplete: 'off',
570
+ placeholder: 'http://127.0.0.1:7890',
571
+ value: draft.proxyUrl,
572
+ 'aria-invalid': proxyInvalid,
573
+ 'aria-describedby': proxyHintId,
574
+ disabled: saving,
575
+ onChange: (event) => { edit({ proxyUrl: event.target.value }) },
576
+ }),
577
+ h('span', { className: 'dsh-np-hint', id: proxyHintId, 'data-invalid': proxyInvalid }, proxyInvalid ? t('proxyInvalid') : t('proxyHint')),
578
+ ),
579
+ h('label', { className: 'dsh-np-field' },
580
+ h('span', { className: 'dsh-np-label' }, t('domainsLabel')),
581
+ h('textarea', {
582
+ className: 'dsh-np-input dsh-np-textarea dsh-np-mono',
583
+ rows: 4,
584
+ spellCheck: false,
585
+ autoComplete: 'off',
586
+ placeholder: t('domainsPlaceholder'),
587
+ value: draft.domains,
588
+ 'aria-invalid': domainsInvalid,
589
+ 'aria-describedby': domainsHintId,
590
+ disabled: saving,
591
+ onChange: (event) => { edit({ domains: event.target.value }) },
592
+ }),
593
+ h('span', {
594
+ className: 'dsh-np-hint',
595
+ id: domainsHintId,
596
+ 'data-invalid': domainsInvalid,
597
+ 'data-warn': !domainsInvalid && domainListEmpty && draft.enabled,
598
+ }, domainsInvalid
599
+ ? t('domainsInvalid')
600
+ : domainListEmpty && draft.enabled
601
+ ? t('emptyDomains')
602
+ : t('domainsHint')),
603
+ ),
604
+ h('div', { className: 'dsh-np-row' },
605
+ h('div', { className: 'dsh-np-rowText' },
606
+ h('span', { className: 'dsh-np-label' }, t('fallbackLabel')),
607
+ h('span', { className: 'dsh-np-hint' }, t('fallbackHint')),
608
+ ),
609
+ h('button', {
610
+ type: 'button',
611
+ className: 'dsh-np-switch',
612
+ role: 'switch',
613
+ 'aria-checked': draft.fallback,
614
+ 'aria-label': t('fallbackLabel'),
615
+ disabled: saving,
616
+ onClick: () => { edit({ fallback: !draft.fallback }) },
617
+ }),
618
+ ),
619
+ h('div', { className: 'dsh-np-actions' },
620
+ h('button', {
621
+ type: 'button',
622
+ className: 'dsh-np-button',
623
+ 'data-variant': 'primary',
624
+ disabled: saving || !dirty,
625
+ onClick: save,
626
+ }, saving ? t('saving') : t('save')),
627
+ h('button', {
628
+ type: 'button',
629
+ className: 'dsh-np-button',
630
+ 'data-variant': 'ghost',
631
+ disabled: saving,
632
+ onClick: reset,
633
+ }, t('reset')),
634
+ ),
635
+ feedback === null
636
+ ? null
637
+ : h('span', {
638
+ className: 'dsh-np-feedback',
639
+ 'data-tone': feedback.tone,
640
+ role: feedback.tone === 'error' ? 'alert' : 'status',
641
+ }, feedback.text),
642
+ )
643
+ }
644
+
645
+ /**
646
+ * The main-column panel the sidebar entry opens.
647
+ * @param props - the slot's translate seat plus this plugin's injection.
648
+ * @returns the panel.
649
+ */
650
+ function ProxyPanel(props) {
651
+ const t = typeof props.t === 'function' ? props.t : props.translate
652
+ const source = props.proxyForm
653
+ const snapshot = useSnapshot(source)
654
+ const openManager = props.openPluginManager
655
+ return h('div', { className: 'dsh-np-page' },
656
+ h('style', null, CSS),
657
+ h('div', { className: 'dsh-np-inner' },
658
+ h('header', { className: 'dsh-np-head' },
659
+ h('h2', { className: 'dsh-np-title' }, t('title')),
660
+ h('p', { className: 'dsh-np-lead' }, t('lead')),
661
+ ),
662
+ h(StatusCard, { t, snapshot }),
663
+ h(SettingsCard, {
664
+ t,
665
+ snapshot,
666
+ mutate: (ops, revision) => source.mutate(ops, revision),
667
+ }),
668
+ h('div', { className: 'dsh-np-actions' },
669
+ h('p', { className: 'dsh-np-note' }, t('managerHint')),
670
+ openManager === undefined
671
+ ? null
672
+ : h('button', {
673
+ type: 'button',
674
+ className: 'dsh-np-button',
675
+ 'data-variant': 'ghost',
676
+ onClick: openManager,
677
+ }, t('openManager')),
678
+ ),
679
+ ),
680
+ )
681
+ }
682
+
683
+ /**
684
+ * The row configuration page the Plugins manager renders for this bundle.
685
+ * @param props - the page's view, the configuration form, and the translate seat.
686
+ * @returns the summary line or the settings card.
687
+ */
688
+ function ProxyRowConfig(props) {
689
+ const t = typeof props.t === 'function' ? props.t : props.translate
690
+ const form = props.form
691
+ const snapshot = form === undefined ? undefined : form.state
692
+ if (props.view === 'summary') {
693
+ const value = pick(snapshot !== undefined && snapshot.status === 'ready' ? snapshot.value : undefined)
694
+ if (!value.enabled) return h('span', null, t('summaryOff'))
695
+ if (!supportedProxyUrl(value.proxyUrl)) return h('span', null, `${t('summaryOn')} · ${t('summaryInvalidProxy')}`)
696
+ const count = splitDomains(value.domains).filter(isValidDomainEntry).length
697
+ if (count === 0) return h('span', null, `${t('summaryOn')} · ${t('summaryNone')}`)
698
+ return h('span', null, `${t('summaryOn')} · ${count === 1 ? t('summaryDomainOne') : t('summaryDomains', { count })}`)
699
+ }
700
+ return h(React.Fragment, null,
701
+ h('style', null, CSS),
702
+ h('div', { className: 'dsh-np-inner' },
703
+ h(SettingsCard, {
704
+ t,
705
+ snapshot,
706
+ mutate: form === undefined ? undefined : form.mutate,
707
+ }),
708
+ ),
709
+ )
710
+ }
711
+
712
+ /**
713
+ * Decorative glyph for the sidebar's panel row.
714
+ * @param props - the sidebar's requested edge.
715
+ * @returns the globe glyph element.
716
+ */
717
+ function ProxyIcon(props) {
718
+ const size = typeof props.size === 'number' ? props.size : 20
719
+ return h('svg', {
720
+ width: size,
721
+ height: size,
722
+ viewBox: '0 0 24 24',
723
+ fill: 'none',
724
+ 'aria-hidden': true,
725
+ focusable: false,
726
+ style: { display: 'block' },
727
+ },
728
+ h('circle', { cx: 12, cy: 12, r: 8.2, stroke: 'currentColor', strokeWidth: 1.6 }),
729
+ h('ellipse', { cx: 12, cy: 12, rx: 4, ry: 8.2, stroke: 'currentColor', strokeWidth: 1.6 }),
730
+ h('path', { d: 'M4.37 9h15.26M4.37 15h15.26', stroke: 'currentColor', strokeWidth: 1.6, strokeLinecap: 'round' }),
731
+ )
732
+ }
733
+
734
+ return {
735
+ inject: ['slots', 'locale', 'configForms'],
736
+ apply(ctx) {
737
+ ctx.effect(() => ctx.locale.register(NS, { en: EN, zh: ZH }), 'net-proxy: dictionaries')
738
+ const t = ctx.locale.bind(NS)
739
+ const form = ctx.configForms.get(ENTRY_ID)
740
+
741
+ ctx.slots.inject('main', () => ctx.slots.register({
742
+ name: 'main',
743
+ key: PANEL_ID,
744
+ locale: NS,
745
+ inject: () => ({
746
+ proxyForm: form,
747
+ translate: t,
748
+ openPluginManager: () => {
749
+ const navigation = ctx.get('pluginNavigation')
750
+ if (navigation === undefined || navigation === null || typeof navigation.openBundle !== 'function') return
751
+ navigation.openBundle('@lucky_zone/net-proxy')
752
+ },
753
+ }),
754
+ }, ProxyPanel))
755
+
756
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
757
+ name: 'sidebar.panellist',
758
+ id: PANEL_ID,
759
+ order: 5,
760
+ locale: NS,
761
+ label: () => t('panel'),
762
+ }, ProxyIcon))
763
+
764
+ ctx.slots.inject('plugins.row.config', () => ctx.slots.register({
765
+ name: 'plugins.row.config',
766
+ key: ROW_KEY,
767
+ locale: NS,
768
+ inject: () => ({ translate: t }),
769
+ }, ProxyRowConfig))
770
+ },
771
+ }
772
+ },
773
+ })