@oakzhong/dsh-redis-client 0.0.0-stage → 1.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/README.md CHANGED
@@ -1,3 +1,94 @@
1
- # Temporary Holding Version
1
+ # Redis 客户端(dsh-redis-client)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 一款运行在 DSH(DeepSeek Harness)中的 Redis 管理插件。左侧栏提供入口,可管理多个 Redis 连接、浏览键值、执行命令。基于系统 `redis-cli`,无需额外 npm 依赖。
4
+
5
+ ## 插件信息
6
+
7
+ - **包名**:`@oakzhong/dsh-redis-client`
8
+ - **版本**:1.0.0
9
+ - **入口**:左侧栏「Redis 客户端」
10
+ - **类型**:Host + Client 双半部插件(bundle)
11
+
12
+ ## 使用技术
13
+
14
+ | 层面 | 技术 |
15
+ |---|---|
16
+ | 插件框架 | DSH Cordis bundle(`cordis.patch.yml` 插入 Loader 行) |
17
+ | Host 半部 | ESM `apply(ctx)`,通过 `ctx.connection.fetch.register` 注册 7 条 API 路由 |
18
+ | Redis 交互 | 调用系统 `redis-cli`(本机 `/usr/local/bin/redis-cli`,v6.0.8),零 npm 依赖 |
19
+ | 命令执行 | Node `child_process.execFile`,参数数组传递避免注入 |
20
+ | 连接配置 | Client 保存在 `localStorage`(`dsh-redis-client.connections.v1` / `.active.v1`) |
21
+ | Client 半部 | `window.__ModuleLoader__` 注册,React 无 JSX(`React.createElement`) |
22
+ | UI 样式 | 组件内注入 `<style>`,使用 DSH 主题 token |
23
+ | 国际化 | `ctx.locale.register / bind`,中英双语(zh / en) |
24
+
25
+ ## 功能
26
+
27
+ ### 1. 连接管理
28
+ - 新建 / 编辑 / 删除多个 Redis 连接
29
+ - 配置项:名称、主机、端口、密码、数据库索引
30
+ - 测试连接(PING),显示已连接/断开状态
31
+ - 连接配置保存在本机 localStorage,刷新不丢失
32
+
33
+ ### 2. 数据库与键浏览
34
+ - 查看数据库列表(DBSIZE / 库切换)
35
+ - 按模式扫描键(`--scan --pattern`,兼容 redis-cli 6.x,不用 `--count`)
36
+ - 显示每个键的类型、TTL、值
37
+ - 支持不同数据类型读取(string / hash / list / set / zset)
38
+
39
+ ### 3. 键值操作
40
+ - 读取键值(GET / HGETALL / LRANGE 等按类型)
41
+ - 删除键
42
+ - 设置过期时间(TTL 秒数,-1 表示永久)
43
+
44
+ ### 4. 命令行
45
+ - 直接输入 Redis 命令执行,显示原始输出
46
+ - 常用命令提示:GET / SET / DBSIZE / INFO 等
47
+
48
+ ## Host API 路由
49
+
50
+ 所有路由前缀 `/api/dsh-redis-client/`:
51
+
52
+ | 路由 | 方法 | 说明 |
53
+ |---|---|---|
54
+ | `ping` | POST | 测试连接(PING) |
55
+ | `dbs` | POST | 查询数据库信息 |
56
+ | `keys` | POST | 扫描键(支持 pattern) |
57
+ | `get` | POST | 读取键值(按类型) |
58
+ | `delete` | POST | 删除键 |
59
+ | `expire` | POST | 设置过期时间 |
60
+ | `command` | POST | 执行任意 Redis 命令 |
61
+
62
+ ## 依赖与环境
63
+
64
+ - 需要本机安装 `redis-cli`(默认路径 `/usr/local/bin/redis-cli`)
65
+ - 目标 Redis 服务网络可达
66
+ - 连接密码等敏感信息仅保存在本机 localStorage,不上传
67
+
68
+ ## 注意事项
69
+
70
+ - redis-cli 6.0.8 的 `--scan` 支持 `--pattern`,**不支持 `--count`**(旧版写法会报 "Unrecognized option")
71
+ - 命令通过参数数组传递,避免 shell 注入
72
+ - Host 侧修改后需通过插件管理器 disable→enable 重新加载路由,`unlag_refresh` 只刷新前端
73
+
74
+ ## 目录结构
75
+
76
+ ```
77
+ dsh-redis-client/
78
+ ├── package.json # 清单(命名空间包)、bundle 配置、client 注入声明
79
+ ├── cordis.patch.yml # Loader 插入行
80
+ ├── index.js # Host 半部:7 条 Redis 路由(redis-cli 封装)
81
+ ├── client.js # Client 半部:连接管理、键浏览、命令行、样式
82
+ ├── locale/
83
+ │ ├── zh.json # 中文显示元信息
84
+ │ └── en.json # 英文显示元信息
85
+ ├── icon.svg # 插件图标
86
+ └── README.md # 本文档
87
+ ```
88
+
89
+ ## 安装与使用
90
+
91
+ 1. 确认本机有 `redis-cli`
92
+ 2. 通过插件管理器安装该 bundle(`install_bundle` 指向本目录)
93
+ 3. 左侧栏点击「Redis 客户端」
94
+ 4. 新建连接并测试,成功后即可浏览键、执行命令
package/client.js ADDED
@@ -0,0 +1,405 @@
1
+ /**
2
+ * Client half of the Redis client bundle.
3
+ *
4
+ * Registers a left sidebar entry + panel. Connections are kept in localStorage
5
+ * and each operation calls the Host's /api/dsh-redis-client routes.
6
+ */
7
+ window.__ModuleLoader__.load({
8
+ id: 'dsh-redis-client',
9
+ factory(require) {
10
+ const React = require('react')
11
+ const h = React.createElement
12
+ const { useState, useEffect, useRef, useCallback, useMemo } = React
13
+
14
+ const NS = 'dsh-redis-client'
15
+ const PANEL_ID = 'redis-client'
16
+ const STYLE_ID = 'dsh-redis-client/css'
17
+ const API = '/api/dsh-redis-client'
18
+ const CONN_KEY = 'dsh-redis-client.connections.v1'
19
+ const ACTIVE_KEY = 'dsh-redis-client.active.v1'
20
+
21
+ const zh = {
22
+ title: 'Redis 客户端', subtitle: '管理 Redis 连接,浏览键与值。',
23
+ connections: '连接', newConn: '新建连接', edit: '编辑', delete: '删除', save: '保存', cancel: '取消',
24
+ name: '名称', host: '地址', port: '端口', password: '密码', username: '用户名(可选)', db: '数据库',
25
+ test: '测试连接', connected: '已连接', disconnected: '未连接', pingOk: '连接成功', pingFail: '连接失败',
26
+ keys: '键', refresh: '刷新', filter: '筛选键 (*)', count: '共 {n} 个键',
27
+ type: '类型', ttl: '过期(秒)', value: '值', field: '字段', noKeys: '暂无匹配键,点刷新扫描。',
28
+ selectKey: '选择一个键查看内容', permanent: '永久', expire: '设置过期', deleteKey: '删除键',
29
+ command: '命令行', run: '执行', output: '输出', noConn: '请先新建并选择一个连接。',
30
+ noWorkspace: '', listFailed: '操作失败', confirmDelete: '确定删除该连接?', confirmDelKey: '确定删除这个键?',
31
+ expireHint: '秒数,-1 表示永久', quickCmd: '常用:GET key / SET key val / DBSIZE / INFO',
32
+ }
33
+ const en = {
34
+ title: 'Redis client', subtitle: 'Manage Redis connections and browse keys and values.',
35
+ connections: 'Connections', newConn: 'New connection', edit: 'Edit', delete: 'Delete', save: 'Save', cancel: 'Cancel',
36
+ name: 'Name', host: 'Host', port: 'Port', password: 'Password', username: 'Username (optional)', db: 'Database',
37
+ test: 'Test connection', connected: 'Connected', disconnected: 'Disconnected', pingOk: 'Connected', pingFail: 'Connection failed',
38
+ keys: 'Keys', refresh: 'Refresh', filter: 'Filter keys (*)', count: '{n} keys',
39
+ type: 'Type', ttl: 'TTL (s)', value: 'Value', field: 'Field', noKeys: 'No matching keys. Click Refresh to scan.',
40
+ selectKey: 'Select a key to view its value', permanent: 'Permanent', expire: 'Set TTL', deleteKey: 'Delete key',
41
+ command: 'Command', run: 'Run', output: 'Output', noConn: 'Create and select a connection first.',
42
+ noWorkspace: '', listFailed: 'Operation failed', confirmDelete: 'Delete this connection?', confirmDelKey: 'Delete this key?',
43
+ expireHint: 'Seconds, -1 for permanent', quickCmd: 'Try: GET key / SET key val / DBSIZE / INFO',
44
+ }
45
+ let t = (key) => (zh[key] || key)
46
+ const fmt = (s, v) => String(s || '').replace(/\{(\w+)\}/g, (_, k) => (v && v[k] != null ? v[k] : ''))
47
+
48
+ function readConns() {
49
+ try {
50
+ const raw = window.localStorage.getItem(CONN_KEY)
51
+ const p = raw ? JSON.parse(raw) : []
52
+ return Array.isArray(p) ? p : []
53
+ } catch (_) { return [] }
54
+ }
55
+ function writeConns(c) { try { window.localStorage.setItem(CONN_KEY, JSON.stringify(c)) } catch (_) {} }
56
+ function readActive() { try { return window.localStorage.getItem(ACTIVE_KEY) || '' } catch (_) { return '' } }
57
+ function writeActive(id) { try { window.localStorage.setItem(ACTIVE_KEY, id) } catch (_) {} }
58
+ function makeId() { return 'c-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 7) }
59
+
60
+ async function api(path, body) {
61
+ const res = await fetch(API + path, {
62
+ method: body === undefined ? 'GET' : 'POST',
63
+ credentials: 'same-origin',
64
+ headers: { 'content-type': 'application/json' },
65
+ body: body === undefined ? undefined : JSON.stringify(body),
66
+ })
67
+ let data = null
68
+ try { data = await res.json() } catch (_) {}
69
+ if (!res.ok) throw new Error((data && data.error) || ('HTTP ' + res.status))
70
+ return data
71
+ }
72
+
73
+ function SidebarIcon(props) {
74
+ const size = typeof props.size === 'number' ? props.size : 20
75
+ return h('svg', {
76
+ viewBox: '0 0 24 24', width: size, height: size, fill: 'none',
77
+ stroke: 'currentColor', strokeWidth: 1.6, 'aria-hidden': true,
78
+ style: { opacity: props.active ? 1 : 0.82 },
79
+ },
80
+ h('ellipse', { cx: 12, cy: 6, rx: 8, ry: 3 }),
81
+ h('path', { d: 'M4 6v6c0 1.7 3.6 3 8 3s8-1.3 8-3V6' }),
82
+ h('path', { d: 'M4 12v6c0 1.7 3.6 3 8 3s8-1.3 8-3v-6' })
83
+ )
84
+ }
85
+
86
+ function RedisPanel({ ctx }) {
87
+ const [conns, setConns] = useState(readConns)
88
+ const [activeId, setActiveId] = useState(readActive)
89
+ const [editing, setEditing] = useState(null)
90
+ const [form, setForm] = useState({ name: '', host: '127.0.0.1', port: 6379, password: '', username: '', db: 0 })
91
+ const [ping, setPing] = useState('')
92
+ const [keys, setKeys] = useState([])
93
+ const [pattern, setPattern] = useState('*')
94
+ const [selected, setSelected] = useState('')
95
+ const [detail, setDetail] = useState(null)
96
+ const [cmd, setCmd] = useState('')
97
+ const [output, setOutput] = useState('')
98
+ const [busy, setBusy] = useState(false)
99
+ const [err, setErr] = useState('')
100
+ const [expireVal, setExpireVal] = useState('-1')
101
+
102
+ const active = useMemo(() => conns.find((c) => c.id === activeId) || null, [conns, activeId])
103
+ const connCfg = active ? { host: active.host, port: active.port, password: active.password, username: active.username, db: active.db } : null
104
+
105
+ useEffect(() => { writeConns(conns) }, [conns])
106
+ useEffect(() => { writeActive(activeId) }, [activeId])
107
+
108
+ const saveConn = useCallback(() => {
109
+ const c = {
110
+ id: editing || makeId(),
111
+ name: form.name.trim() || (form.host + ':' + form.port),
112
+ host: form.host.trim() || '127.0.0.1',
113
+ port: Number(form.port) || 6379,
114
+ password: form.password || '', username: form.username || '',
115
+ db: Number(form.db) || 0,
116
+ }
117
+ setConns((prev) => editing ? prev.map((x) => x.id === editing ? c : x) : [...prev, c])
118
+ setActiveId(c.id)
119
+ setEditing(null)
120
+ setPing('')
121
+ setErr('')
122
+ }, [form, editing])
123
+
124
+ const editConn = useCallback((c) => {
125
+ setEditing(c.id)
126
+ setForm({ name: c.name, host: c.host, port: c.port, password: c.password || '', username: c.username || '', db: c.db || 0 })
127
+ }, [])
128
+
129
+ const removeConn = useCallback((id) => {
130
+ if (!window.confirm(t('confirmDelete'))) return
131
+ setConns((prev) => prev.filter((c) => c.id !== id))
132
+ if (activeId === id) { setActiveId(''); setKeys([]); setSelected(''); setDetail(null) }
133
+ }, [activeId])
134
+
135
+ const testConn = useCallback(async () => {
136
+ if (!connCfg) return
137
+ setBusy(true); setErr(''); setPing('')
138
+ try {
139
+ const d = await api('/ping', { connection: connCfg })
140
+ setPing(d.ok ? t('pingOk') : (t('pingFail') + ': ' + d.raw))
141
+ } catch (e) { setPing(t('pingFail')); setErr(e.message) }
142
+ finally { setBusy(false) }
143
+ }, [connCfg])
144
+
145
+ const scanKeys = useCallback(async () => {
146
+ if (!connCfg) return
147
+ setBusy(true); setErr('')
148
+ try {
149
+ const d = await api('/keys', { connection: connCfg, pattern: pattern || '*' })
150
+ setKeys(d.keys || [])
151
+ } catch (e) { setErr(e.message) }
152
+ finally { setBusy(false) }
153
+ }, [connCfg, pattern])
154
+
155
+ const openKey = useCallback(async (key) => {
156
+ if (!connCfg) return
157
+ setSelected(key); setErr(''); setExpireVal('-1')
158
+ try {
159
+ const d = await api('/get', { connection: connCfg, key })
160
+ setDetail(d)
161
+ setExpireVal(d.ttl >= 0 ? String(d.ttl) : '-1')
162
+ } catch (e) { setErr(e.message); setDetail(null) }
163
+ }, [connCfg])
164
+
165
+ const delKey = useCallback(async () => {
166
+ if (!connCfg || !selected) return
167
+ if (!window.confirm(t('confirmDelKey'))) return
168
+ setBusy(true)
169
+ try {
170
+ await api('/delete', { connection: connCfg, keys: [selected] })
171
+ setSelected(''); setDetail(null); await scanKeys()
172
+ } catch (e) { setErr(e.message) }
173
+ finally { setBusy(false) }
174
+ }, [connCfg, selected, scanKeys])
175
+
176
+ const setExpire = useCallback(async () => {
177
+ if (!connCfg || !selected) return
178
+ setBusy(true)
179
+ try {
180
+ const n = Number(expireVal)
181
+ if (n < 0) await api('/command', { connection: connCfg, command: 'PERSIST ' + JSON.stringify(selected) })
182
+ else await api('/expire', { connection: connCfg, key: selected, seconds: n })
183
+ await openKey(selected)
184
+ } catch (e) { setErr(e.message) }
185
+ finally { setBusy(false) }
186
+ }, [connCfg, selected, expireVal, openKey])
187
+
188
+ const runCmd = useCallback(async () => {
189
+ if (!connCfg || !cmd.trim()) return
190
+ setBusy(true); setErr('')
191
+ try {
192
+ const d = await api('/command', { connection: connCfg, command: cmd })
193
+ setOutput(d.output || '')
194
+ } catch (e) { setErr(e.message); setOutput('') }
195
+ finally { setBusy(false) }
196
+ }, [connCfg, cmd])
197
+
198
+ const goBack = useCallback(() => {
199
+ try { if (ctx && ctx.layout) ctx.layout.selectPanel('conversation') } catch (_) {}
200
+ }, [ctx])
201
+
202
+ const formRow = (label, key, type) =>
203
+ h('label', { className: 'dshRds-field' },
204
+ h('span', null, t(label)),
205
+ h('input', {
206
+ className: 'dshRds-input', type: type || 'text',
207
+ value: form[key],
208
+ onChange: (e) => setForm((f) => ({ ...f, [key]: e.target.value })),
209
+ })
210
+ )
211
+
212
+ const valueNode = detail && detail.value != null
213
+ ? (Array.isArray(detail.value)
214
+ ? (detail.type === 'hash' || detail.type === 'zset'
215
+ ? h('div', { className: 'dshRds-pairs' }, detail.value.map((p, i) =>
216
+ h('div', { key: i, className: 'dshRds-pair' },
217
+ h('span', { className: 'dshRds-badge' }, p.field),
218
+ h('span', null, p.value))))
219
+ : h('div', { className: 'dshRds-list' }, detail.value.map((v, i) => h('div', { key: i }, v))))
220
+ : h('pre', { className: 'dshRds-value' }, String(detail.value)))
221
+ : null
222
+
223
+ return h('div', { className: 'dshRds-root' },
224
+ h('div', { className: 'dshRds-head' },
225
+ h('div', null,
226
+ h('div', { className: 'dshRds-title' }, t('title')),
227
+ h('div', { className: 'dshRds-sub' }, t('subtitle'))
228
+ ),
229
+ h('button', { type: 'button', className: 'dshRds-back', onClick: goBack }, t('back'))
230
+ ),
231
+ err ? h('div', { className: 'dshRds-err' }, err) : null,
232
+ h('div', { className: 'dshRds-cols' },
233
+ // left: connections
234
+ h('div', { className: 'dshRds-col' },
235
+ h('div', { className: 'dshRds-card' },
236
+ h('div', { className: 'dshRds-cardTitle' }, t('connections')),
237
+ h('div', { className: 'dshRds-connList' },
238
+ conns.length === 0
239
+ ? h('div', { className: 'dshRds-note' }, t('noConn'))
240
+ : conns.map((c) =>
241
+ h('div', {
242
+ key: c.id,
243
+ className: 'dshRds-conn' + (activeId === c.id ? ' dshRds-connOn' : ''),
244
+ onClick: () => { setActiveId(c.id); setKeys([]); setSelected(''); setDetail(null); setPing('') },
245
+ },
246
+ h('span', { className: 'dshRds-name' }, c.name),
247
+ h('span', { className: 'dshRds-addr' }, `${c.host}:${c.port}`),
248
+ h('button', { type: 'button', className: 'dshRds-mini', onClick: (e) => { e.stopPropagation(); editConn(c) } }, t('edit')),
249
+ h('button', { type: 'button', className: 'dshRds-mini dshRds-del', onClick: (e) => { e.stopPropagation(); removeConn(c.id) } }, '×')
250
+ )
251
+ )
252
+ ),
253
+ h('button', { type: 'button', className: 'dshRds-btn dshRds-btnPrimary', onClick: () => { setEditing(null); setForm({ name: '', host: '127.0.0.1', port: 6379, password: '', username: '', db: 0 }) } }, '+ ' + t('newConn')),
254
+ active
255
+ ? h('button', { type: 'button', className: 'dshRds-btn', disabled: busy, onClick: testConn }, t('test'))
256
+ : null,
257
+ ping ? h('div', { className: 'dshRds-note' }, ping) : null
258
+ ),
259
+ // connection form
260
+ h('div', { className: 'dshRds-card' },
261
+ h('div', { className: 'dshRds-cardTitle' }, editing ? t('edit') : t('newConn')),
262
+ h('div', { className: 'dshRds-form' },
263
+ formRow('name', 'name'), formRow('host', 'host'),
264
+ formRow('port', 'port', 'number'), formRow('password', 'password', 'password'),
265
+ formRow('username', 'username'), formRow('db', 'db', 'number'),
266
+ h('button', { type: 'button', className: 'dshRds-btn dshRds-btnPrimary', onClick: saveConn }, t('save'))
267
+ )
268
+ )
269
+ ),
270
+ // middle: keys
271
+ h('div', { className: 'dshRds-col' },
272
+ h('div', { className: 'dshRds-card dshRds-fill' },
273
+ h('div', { className: 'dshRds-cardTitle' }, t('keys')),
274
+ h('div', { className: 'dshRds-searchRow' },
275
+ h('input', {
276
+ className: 'dshRds-input', value: pattern, placeholder: t('filter'),
277
+ onChange: (e) => setPattern(e.target.value),
278
+ onKeyDown: (e) => { if (e.key === 'Enter') scanKeys() },
279
+ }),
280
+ h('button', { type: 'button', className: 'dshRds-btn', disabled: busy || !connCfg, onClick: scanKeys }, t('refresh'))
281
+ ),
282
+ h('div', { className: 'dshRds-note' }, fmt(t('count'), { n: keys.length })),
283
+ h('div', { className: 'dshRds-keyList' },
284
+ keys.length === 0
285
+ ? h('div', { className: 'dshRds-note' }, t('noKeys'))
286
+ : keys.map((k) =>
287
+ h('div', {
288
+ key: k, className: 'dshRds-key' + (selected === k ? ' dshRds-keyOn' : ''),
289
+ onClick: () => openKey(k), title: k,
290
+ }, k)
291
+ )
292
+ )
293
+ )
294
+ ),
295
+ // right: value + command
296
+ h('div', { className: 'dshRds-col' },
297
+ h('div', { className: 'dshRds-card' },
298
+ h('div', { className: 'dshRds-cardTitle' }, selected || t('selectKey')),
299
+ detail && detail.type !== 'none'
300
+ ? h('div', { className: 'dshRds-detail' },
301
+ h('div', { className: 'dshRds-meta' },
302
+ h('span', null, t('type') + ': ' + detail.type),
303
+ h('span', null, t('ttl') + ': ' + (detail.ttl >= 0 ? detail.ttl : t('permanent')))
304
+ ),
305
+ valueNode,
306
+ h('div', { className: 'dshRds-actions' },
307
+ h('input', {
308
+ className: 'dshRds-input', type: 'number', value: expireVal,
309
+ onChange: (e) => setExpireVal(e.target.value), title: t('expireHint'),
310
+ }),
311
+ h('button', { type: 'button', className: 'dshRds-btn', disabled: busy, onClick: setExpire }, t('expire')),
312
+ h('button', { type: 'button', className: 'dshRds-btn dshRds-del', disabled: busy, onClick: delKey }, t('deleteKey'))
313
+ )
314
+ )
315
+ : h('div', { className: 'dshRds-note' }, t('selectKey'))
316
+ ),
317
+ h('div', { className: 'dshRds-card' },
318
+ h('div', { className: 'dshRds-cardTitle' }, t('command')),
319
+ h('div', { className: 'dshRds-searchRow' },
320
+ h('input', {
321
+ className: 'dshRds-input', value: cmd, placeholder: t('quickCmd'),
322
+ onChange: (e) => setCmd(e.target.value),
323
+ onKeyDown: (e) => { if (e.key === 'Enter') runCmd() },
324
+ }),
325
+ h('button', { type: 'button', className: 'dshRds-btn', disabled: busy || !connCfg, onClick: runCmd }, t('run'))
326
+ ),
327
+ output ? h('pre', { className: 'dshRds-value' }, output) : null
328
+ )
329
+ )
330
+ )
331
+ )
332
+ }
333
+
334
+ function apply(ctx) {
335
+ ctx.effect(() => installStyles(), 'dsh-redis-client: styles')
336
+ if (ctx.locale !== undefined) {
337
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-redis-client: dictionaries')
338
+ t = ctx.locale.bind(NS)
339
+ }
340
+ ctx.effect(() => ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
341
+ name: 'sidebar.panellist', id: PANEL_ID, order: 26, label: () => t('title'), locale: NS,
342
+ }, SidebarIcon)), 'dsh-redis-client: sidebar entry')
343
+ ctx.effect(() => ctx.slots.inject('main', () => ctx.slots.register({
344
+ name: 'main', key: PANEL_ID, locale: NS,
345
+ }, (props) => h(RedisPanel, { ctx }))), 'dsh-redis-client: panel')
346
+ }
347
+
348
+ function installStyles() {
349
+ if (typeof document === 'undefined') return () => {}
350
+ const existing = document.querySelector('style[data-plugin-css="' + STYLE_ID + '"]')
351
+ if (existing) return () => {}
352
+ const style = document.createElement('style')
353
+ style.dataset.plugin = NS
354
+ style.dataset.pluginCss = STYLE_ID
355
+ style.textContent = `
356
+ .dshRds-root{display:flex;flex-direction:column;height:100%;box-sizing:border-box;padding:16px 18px 18px;gap:12px;overflow:hidden;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base)}
357
+ .dshRds-head{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;flex:0 0 auto}
358
+ .dshRds-title{font-size:20px;font-weight:700;line-height:1.3}
359
+ .dshRds-sub{font-size:12px;color:var(--dsw-alias-label-secondary);margin-top:3px}
360
+ .dshRds-back{display:inline-flex;align-items:center;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font-size:12px;padding:5px 11px;border-radius:8px;cursor:pointer;font-family:inherit;white-space:nowrap}
361
+ .dshRds-err{font-size:11px;color:var(--dsw-alias-state-error-primary);flex:0 0 auto}
362
+ .dshRds-cols{display:grid;grid-template-columns:minmax(220px,1.1fr) minmax(200px,1fr) minmax(220px,1.2fr);gap:12px;flex:1 1 auto;min-height:0}
363
+ .dshRds-col{display:flex;flex-direction:column;gap:10px;min-height:0;overflow-y:auto}
364
+ .dshRds-card{padding:12px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1);display:flex;flex-direction:column;gap:8px}
365
+ .dshRds-fill{flex:1 1 auto;min-height:0}
366
+ .dshRds-cardTitle{font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary)}
367
+ .dshRds-note{font-size:11px;color:var(--dsw-alias-label-secondary);line-height:1.5}
368
+ .dshRds-btn{padding:7px 11px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font-size:12px;cursor:pointer;font-family:inherit;white-space:nowrap}
369
+ .dshRds-btn:hover{border-color:var(--dsw-alias-brand-primary)}
370
+ .dshRds-btn:disabled{opacity:.45;cursor:not-allowed}
371
+ .dshRds-btnPrimary{background:#d82c20;color:#fff;border-color:transparent;font-weight:600}
372
+ .dshRds-del{color:var(--dsw-alias-state-error-primary)}
373
+ .dshRds-connList{display:flex;flex-direction:column;gap:4px}
374
+ .dshRds-conn{display:flex;align-items:center;gap:6px;padding:7px 8px;border-radius:7px;border:1px solid var(--dsw-alias-border-l1);cursor:pointer;font-size:12px;flex-wrap:wrap}
375
+ .dshRds-connOn{border-color:#d82c20;background:var(--dsw-alias-bg-layer-2)}
376
+ .dshRds-name{font-weight:600;flex:1 1 auto}
377
+ .dshRds-addr{font-size:10px;color:var(--dsw-alias-label-secondary)}
378
+ .dshRds-mini{border:0;background:transparent;color:var(--dsw-alias-label-secondary);font-size:11px;cursor:pointer;padding:0 3px;font-family:inherit}
379
+ .dshRds-form{display:flex;flex-direction:column;gap:7px}
380
+ .dshRds-field{display:flex;flex-direction:column;gap:3px;font-size:11px;color:var(--dsw-alias-label-secondary)}
381
+ .dshRds-input{padding:6px 9px;border-radius:7px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);font-size:12px;outline:none;font-family:inherit;min-width:0}
382
+ .dshRds-input:focus{border-color:var(--dsw-alias-brand-primary)}
383
+ .dshRds-searchRow{display:flex;gap:6px}
384
+ .dshRds-searchRow .dshRds-input{flex:1 1 auto}
385
+ .dshRds-keyList{flex:1 1 auto;min-height:120px;overflow-y:auto;display:flex;flex-direction:column;gap:2px}
386
+ .dshRds-key{padding:6px 8px;border-radius:6px;font-size:12px;cursor:pointer;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
387
+ .dshRds-key:hover{background:var(--dsw-alias-bg-layer-2)}
388
+ .dshRds-keyOn{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-brand-primary);font-weight:600}
389
+ .dshRds-detail{display:flex;flex-direction:column;gap:8px}
390
+ .dshRds-meta{display:flex;gap:14px;font-size:11px;color:var(--dsw-alias-label-secondary);flex-wrap:wrap}
391
+ .dshRds-value{margin:0;padding:10px;border-radius:8px;background:var(--dsw-alias-bg-base);border:1px solid var(--dsw-alias-border-l1);font-family:ui-monospace,monospace;font-size:12px;line-height:1.5;white-space:pre-wrap;word-break:break-all;max-height:280px;overflow:auto}
392
+ .dshRds-pairs,.dshRds-list{display:flex;flex-direction:column;gap:4px;max-height:280px;overflow:auto;font-size:12px}
393
+ .dshRds-pair{display:flex;gap:8px;padding:4px 6px;border-radius:6px;background:var(--dsw-alias-bg-base)}
394
+ .dshRds-badge{font-weight:600;color:var(--dsw-alias-brand-primary);min-width:60px}
395
+ .dshRds-actions{display:flex;gap:6px;align-items:center;flex-wrap:wrap}
396
+ .dshRds-actions .dshRds-input{width:80px}
397
+ @media(max-width:1000px){.dshRds-cols{grid-template-columns:1fr;overflow-y:auto}.dshRds-col{overflow:visible}}
398
+ `
399
+ document.head.appendChild(style)
400
+ return () => { style.remove() }
401
+ }
402
+
403
+ return { inject: ['slots', 'locale'], apply }
404
+ },
405
+ })
@@ -0,0 +1,4 @@
1
+ # Redis client bundle: the Host half runs redis-cli; `dsh.client` renders the UI.
2
+ - insert:
3
+ - id: dsh-redis-client
4
+ name: dsh-redis-client
package/icon.svg ADDED
@@ -0,0 +1,7 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
2
+ <path d="M8 20c0-6 11-10 24-10s24 4 24 10-11 10-24 10S8 26 8 20z" fill="#d82c20"/>
3
+ <path d="M8 20v12c0 6 11 10 24 10s24-4 24-10V20" fill="#b01c14"/>
4
+ <path d="M8 32v12c0 6 11 10 24 10s24-4 24-10V32" fill="#8e1610"/>
5
+ <ellipse cx="32" cy="20" rx="24" ry="10" fill="none" stroke="#7a120c" stroke-width="2"/>
6
+ <text x="32" y="25" text-anchor="middle" font-family="sans-serif" font-size="11" font-weight="700" fill="#fff">Redis</text>
7
+ </svg>
package/index.js ADDED
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Host half of the Redis client bundle.
3
+ *
4
+ * Runs redis-cli via a child process for each operation. Connection details
5
+ * are supplied per request by the Client (stored locally there); nothing is
6
+ * persisted on the Host. Args are passed as an argv array so values are never
7
+ * interpreted by a shell.
8
+ */
9
+ import { execFile } from 'node:child_process'
10
+ import { promisify } from 'node:util'
11
+
12
+ export const name = 'dsh-redis-client'
13
+ export const inject = ['connection']
14
+
15
+ const execFileAsync = promisify(execFile)
16
+ const API = '/api/dsh-redis-client'
17
+ const CLI = process.env.REDIS_CLI_PATH || 'redis-cli'
18
+ const TIMEOUT = 8000
19
+
20
+ class RedisError extends Error {
21
+ constructor(message, status = 400) { super(message); this.status = status }
22
+ }
23
+ function json(value, status = 200) {
24
+ return Response.json(value, { status, headers: { 'cache-control': 'no-store' } })
25
+ }
26
+ function failure(error, fallback) {
27
+ const message = error instanceof RedisError ? error.message : fallback
28
+ const status = error instanceof RedisError ? error.status : 500
29
+ return json({ error: message }, status)
30
+ }
31
+ function route(path, methods, fetch) {
32
+ return { path: `${API}/${path}`, methods, requestBody: 'buffered', fetch }
33
+ }
34
+
35
+ // Build the argv prefix for a connection.
36
+ function connArgs(cfg) {
37
+ const args = []
38
+ if (cfg.host) args.push('-h', String(cfg.host))
39
+ if (cfg.port) args.push('-p', String(cfg.port))
40
+ if (cfg.password) args.push('-a', String(cfg.password))
41
+ if (cfg.username) args.push('--user', String(cfg.username))
42
+ if (cfg.db !== undefined && cfg.db !== null && cfg.db !== '') args.push('-n', String(cfg.db))
43
+ if (cfg.timeout) args.push('-t', String(cfg.timeout))
44
+ return args
45
+ }
46
+ async function readBody(request) {
47
+ try {
48
+ const text = await request.text()
49
+ return JSON.parse(text || '{}')
50
+ } catch (_) { throw new RedisError('请求内容不是合法的 JSON。') }
51
+ }
52
+ // Run redis-cli with command args and return raw stdout.
53
+ async function run(cfg, commandArgs) {
54
+ const argv = [...connArgs(cfg), ...commandArgs]
55
+ try {
56
+ const { stdout, stderr } = await execFileAsync(CLI, argv, { timeout: TIMEOUT, maxBuffer: 8 * 1024 * 1024 })
57
+ // redis-cli may print warnings to stderr (e.g. AUTH warning) alongside valid stdout.
58
+ return { out: stdout, err: stderr }
59
+ } catch (error) {
60
+ const msg = (error && error.message) || String(error)
61
+ if (msg.includes('ENOENT')) throw new RedisError('找不到 redis-cli,请确认已安装。', 500)
62
+ if (msg.includes('timed out') || msg.includes('ETIMEDOUT')) throw new RedisError('连接超时,请检查地址与端口。', 504)
63
+ // redis-cli often exits non-zero with a useful stderr message.
64
+ const detail = (error && error.stderr) ? String(error.stderr).trim() : msg
65
+ throw new RedisError(detail || '命令执行失败。')
66
+ }
67
+ }
68
+ function clean(s) { return String(s == null ? '' : s).replace(/\r/g, '') }
69
+
70
+ export function apply(ctx) {
71
+ ctx.effect(() => {
72
+ const disposers = []
73
+ const register = (entry) => {
74
+ try {
75
+ const dispose = ctx.connection.fetch.register(entry)
76
+ if (typeof dispose === 'function') disposers.push(dispose)
77
+ } catch (error) {
78
+ console.warn(`[dsh-redis-client] route ${entry.path} rejected: ${(error && error.message) || error}`)
79
+ }
80
+ }
81
+
82
+ // Test connection: PING.
83
+ register(route('ping', ['POST'], async (request) => {
84
+ try {
85
+ const body = await readBody(request)
86
+ const { out } = await run(body.connection || {}, ['PING'])
87
+ const text = clean(out).trim()
88
+ return json({ ok: /PONG/i.test(text), raw: text })
89
+ } catch (error) { return failure(error, '连接测试失败。') }
90
+ }))
91
+
92
+ // List all 16 databases via INFO keyspace (best effort).
93
+ register(route('dbs', ['POST'], async (request) => {
94
+ try {
95
+ const body = await readBody(request)
96
+ const cfg = body.connection || {}
97
+ const base = { ...cfg, db: 0 }
98
+ const { out } = await run(base, ['INFO', 'keyspace'])
99
+ const keyspace = {}
100
+ for (const line of clean(out).split('\n')) {
101
+ const m = line.match(/^db(\d+):(.*)$/)
102
+ if (m) keyspace[m[1]] = m[2].trim()
103
+ }
104
+ const dbs = Array.from({ length: 16 }, (_, i) => ({ index: i, info: keyspace[String(i)] || '' }))
105
+ return json({ dbs })
106
+ } catch (error) { return failure(error, '无法读取数据库信息。') }
107
+ }))
108
+
109
+ // Scan keys with MATCH using redis-cli --scan (iterator mode).
110
+ // Note: redis-cli 6.x supports --pattern but NOT --count; omit it.
111
+ register(route('keys', ['POST'], async (request) => {
112
+ try {
113
+ const body = await readBody(request)
114
+ const cfg = body.connection || {}
115
+ const pattern = typeof body.pattern === 'string' && body.pattern ? body.pattern : '*'
116
+ const args = [...connArgs(cfg), '--scan', '--pattern', pattern]
117
+ let stdout
118
+ try {
119
+ const r = await execFileAsync(CLI, args, { timeout: TIMEOUT, maxBuffer: 16 * 1024 * 1024 })
120
+ stdout = r.stdout
121
+ } catch (error) {
122
+ const detail = (error && error.stderr) ? String(error.stderr).trim() : ''
123
+ if (detail) throw new RedisError(detail)
124
+ throw error
125
+ }
126
+ const keys = clean(stdout).split('\n').map((k) => k.trim()).filter(Boolean).sort()
127
+ return json({ keys, total: keys.length, pattern })
128
+ } catch (error) { return failure(error, '无法扫描键。') }
129
+ }))
130
+
131
+ // Read a key: TYPE + value by type + TTL.
132
+ register(route('get', ['POST'], async (request) => {
133
+ try {
134
+ const body = await readBody(request)
135
+ const cfg = body.connection || {}
136
+ const key = body.key
137
+ if (typeof key !== 'string' || !key) throw new RedisError('缺少键名。')
138
+ const { out: typeOut } = await run(cfg, ['TYPE', key])
139
+ const type = clean(typeOut).trim().replace(/^"|"$/g, '') || 'none'
140
+ if (type === 'none') return json({ key, type: 'none', value: null, ttl: -2 })
141
+ const { out: ttlOut } = await run(cfg, ['TTL', key])
142
+ const ttl = parseInt(clean(ttlOut).trim(), 10)
143
+ let value = null
144
+ if (type === 'string') {
145
+ const r = await run(cfg, ['GET', key]); value = clean(r.out).replace(/\n$/, '')
146
+ } else if (type === 'hash') {
147
+ const r = await run(cfg, ['HGETALL', key]); value = parsePairs(r.out)
148
+ } else if (type === 'list') {
149
+ const r = await run(cfg, ['LRANGE', key, '0', '199']); value = parseLines(r.out)
150
+ } else if (type === 'set') {
151
+ const r = await run(cfg, ['SMEMBERS', key]); value = parseLines(r.out)
152
+ } else if (type === 'zset') {
153
+ const r = await run(cfg, ['ZRANGE', key, '0', '199', 'WITHSCORES']); value = parsePairs(r.out)
154
+ } else {
155
+ value = '(unsupported type)'
156
+ }
157
+ return json({ key, type, ttl, value })
158
+ } catch (error) { return failure(error, '无法读取键。') }
159
+ }))
160
+
161
+ // Delete keys.
162
+ register(route('delete', ['POST'], async (request) => {
163
+ try {
164
+ const body = await readBody(request)
165
+ const cfg = body.connection || {}
166
+ const keys = Array.isArray(body.keys) ? body.keys.filter((k) => typeof k === 'string' && k) : []
167
+ if (!keys.length) throw new RedisError('缺少键名。')
168
+ const { out } = await run(cfg, ['DEL', ...keys])
169
+ return json({ ok: true, deleted: parseInt(clean(out).trim(), 10) || 0 })
170
+ } catch (error) { return failure(error, '删除失败。') }
171
+ }))
172
+
173
+ // Set TTL on a key.
174
+ register(route('expire', ['POST'], async (request) => {
175
+ try {
176
+ const body = await readBody(request)
177
+ const cfg = body.connection || {}
178
+ const key = body.key
179
+ const seconds = Number(body.seconds)
180
+ if (typeof key !== 'string' || !key) throw new RedisError('缺少键名。')
181
+ if (!Number.isFinite(seconds)) throw new RedisError('缺少有效期。')
182
+ const { out } = await run(cfg, ['EXPIRE', key, String(Math.round(seconds))])
183
+ return json({ ok: clean(out).trim() === '1' })
184
+ } catch (error) { return failure(error, '设置过期时间失败。') }
185
+ }))
186
+
187
+ // Run an arbitrary read-only-ish command (user typed).
188
+ register(route('command', ['POST'], async (request) => {
189
+ try {
190
+ const body = await readBody(request)
191
+ const cfg = body.connection || {}
192
+ const line = typeof body.command === 'string' ? body.command.trim() : ''
193
+ if (!line) throw new RedisError('请输入命令。')
194
+ const parts = splitCommand(line)
195
+ const { out, err } = await run(cfg, parts)
196
+ return json({ output: clean(out), warning: clean(err).trim() })
197
+ } catch (error) { return failure(error, '命令执行失败。') }
198
+ }))
199
+
200
+ return () => {
201
+ for (const dispose of disposers) {
202
+ try {
203
+ const result = dispose()
204
+ if (result && typeof result.then === 'function') result.catch(() => {})
205
+ } catch (_) {}
206
+ }
207
+ }
208
+ }, 'dsh-redis-client: routes')
209
+ }
210
+
211
+ function parseLines(text) {
212
+ return clean(text).split('\n').map((l) => l.trim()).filter((l) => l.length > 0)
213
+ }
214
+ function parsePairs(text) {
215
+ const lines = parseLines(text)
216
+ const out = []
217
+ for (let i = 0; i < lines.length; i += 2) out.push({ field: lines[i], value: lines[i + 1] === undefined ? '' : lines[i + 1] })
218
+ return out
219
+ }
220
+ function splitCommand(line) {
221
+ // Simple quote-aware tokenizer for typed redis commands.
222
+ const out = []
223
+ let cur = ''
224
+ let quote = null
225
+ for (let i = 0; i < line.length; i++) {
226
+ const ch = line[i]
227
+ if (quote) {
228
+ if (ch === quote && line[i - 1] !== '\\') { quote = null }
229
+ else cur += ch
230
+ } else if (ch === '"' || ch === "'") quote = ch
231
+ else if (/\s/.test(ch)) { if (cur) { out.push(cur); cur = '' } }
232
+ else cur += ch
233
+ }
234
+ if (cur) out.push(cur)
235
+ return out
236
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Redis client",
4
+ "description": "Manage Redis connections and browse keys, values and TTLs from the left sidebar."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Redis 客户端",
4
+ "description": "在左侧栏管理 Redis 连接,浏览键值、类型与过期时间。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "@oakzhong/dsh-redis-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "private":false,
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "type": "module",
9
+ "description": "A Redis client with connection management and data browsing, using redis-cli.",
10
+ "exports": {
11
+ ".": "./index.js",
12
+ "./client": "./client.js",
13
+ "./locale/*.json": "./locale/*.json",
14
+ "./icon": "./icon.svg"
15
+ },
16
+ "files": ["index.js", "client.js", "cordis.patch.yml", "locale/*.json", "icon.svg", "README.md"],
17
+ "dsh": {
18
+ "bundle": { "patch": "./cordis.patch.yml" },
19
+ "client": {
20
+ "platform": "web",
21
+ "immediately": true,
22
+ "inject": ["@deepseek-ai/dsh-client-locale"]
23
+ }
24
+ }
25
+ }