@oakzhong/dsh-tree-new-bee-api-client 0.0.0-stage → 1.0.1

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
+ # Tree New Bee 接口请求
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)中的类 Postman HTTP 接口调试插件。左侧栏提供统一入口,可在面板中构造请求、查看响应、管理集合/环境/历史,所有数据保存在浏览器本地。
4
+
5
+ ## 插件信息
6
+
7
+ - **包名**:`dsh-tree-new-bee-api-client`
8
+ - **版本**:1.0.0
9
+ - **入口**:左侧栏「Tree New Bee 接口请求」
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` 注册 `/api/dsh-tree-new-bee-api-client/request` 路由 |
18
+ | HTTP 请求 | Node.js 内置 `fetch` + `AbortController` 超时控制,零第三方依赖 |
19
+ | Client 半部 | `window.__ModuleLoader__` 注册的前端模块,React 无 JSX(`React.createElement`) |
20
+ | UI 样式 | 组件内联 `<style>`(data-plugin-css 标识),使用 DSH 主题 token,自动适配明暗主题 |
21
+ | 国际化 | `ctx.locale.register/ bind`,中英双语(zh / en) |
22
+ | 本地存储 | 浏览器 `localStorage`,集合、历史、环境、自定义头均持久化 |
23
+ | 数据解析 | URL 标准 `URL` / `searchParams`,JSON 格式化 `JSON.parse/stringify` |
24
+
25
+ ## 功能
26
+
27
+ ### 1. 请求构造与发送
28
+ - 支持 `GET / POST / PUT / PATCH / DELETE / HEAD / OPTIONS` 七种方法
29
+ - URL 输入、超时设置(秒)
30
+ - **Params**:键值对自动拼接到 URL(支持 `URL` 编码兜底)
31
+ - **Headers**:键值对编辑
32
+ - **Body**:原始文本,用于 POST/PUT/PATCH,支持 JSON
33
+ - 回车或点击「发送」执行,Host 侧返回状态码、状态文本、响应头、响应体、耗时、大小
34
+
35
+ ### 2. 响应查看
36
+ - 状态 / 耗时 / 大小指标卡,状态码按成功/失败着色
37
+ - 响应 Body:可切换「格式化 JSON」与原始文本
38
+ - 响应 Headers 标签页
39
+ - 超大响应截断保护(4MB)
40
+
41
+ ### 3. 集合管理(Postman 风格树形)
42
+ - 支持**文件夹嵌套层级**,文件夹可展开/折叠
43
+ - 保存请求到当前文件夹(面包屑展示路径:`根目录 / 父级 / 子级`,每段可点击跳转)
44
+ - 文件夹、请求**双击重命名**;删除均需用户确认(文件夹会连带内容)
45
+ - 集合**模糊搜索**:匹配文件夹名、请求名、方法、URL,自动展开命中节点
46
+ - 点击请求一键回填编辑器
47
+
48
+ ### 4. 环境管理(变量替换)
49
+ - 多环境管理,每个环境有专属 K-V 变量
50
+ - 用 `{{变量名}}` 引用,如 `{{baseUrl}}/users`
51
+ - 发送时自动替换 **URL / Params / Headers / Body** 中的变量;未定义变量保持原样
52
+ - 顶部环境选择器,显示当前环境的变量名
53
+
54
+ ### 5. 常用请求头
55
+ - 内置 14 个常用头(Accept、Content-Type、Authorization、User-Agent 等),带默认值
56
+ - **多选**:全选/取消全选、勾选多个后一次性插入,自动去重、填充空行
57
+ - **自定义请求头**:可新增自己的常用头(名称/默认值/说明),持久化保存,可删除
58
+
59
+ ### 6. 历史记录
60
+ - 最近 100 条请求(状态、时间、URL、错误),点击回填完整请求快照
61
+ - 一键清空历史
62
+
63
+ ## 数据存储
64
+
65
+ 全部保存在浏览器 `localStorage`,键名:
66
+
67
+ - `dsh-tree-new-bee-api-client.collection.v1` — 集合树
68
+ - `dsh-tree-new-bee-api-client.history.v1` — 请求历史
69
+ - `dsh-tree-new-bee-api-client.environments.v1` — 环境列表
70
+ - `dsh-tree-new-bee-api-client.activeEnv.v1` — 当前环境
71
+ - `dsh-tree-new-bee-api-client.customHeaders.v1` — 自定义请求头
72
+
73
+ ## 目录结构
74
+
75
+ ```
76
+ dsh-tree-new-bee-api-client/
77
+ ├── package.json # 清单、bundle 配置、client 注入声明
78
+ ├── cordis.patch.yml # Loader 插入行
79
+ ├── index.js # Host 半部:HTTP 请求路由
80
+ ├── client.js # Client 半部:完整 UI 与交互
81
+ ├── locale/
82
+ │ ├── zh.json # 中文显示元信息
83
+ │ └── en.json # 英文显示元信息
84
+ ├── icon.svg # 插件图标
85
+ └── README.md # 本文档
86
+ ```
87
+
88
+ ## 安装与使用
89
+
90
+ 1. 通过插件管理器安装该 bundle(`install_bundle` 指向本目录)
91
+ 2. 左侧栏点击「Tree New Bee 接口请求」
92
+ 3. 输入请求地址与方法,按需填写 Params / Headers / Body
93
+ 4. 点击「发送」查看响应
94
+ 5. 用集合保存常用请求、用环境管理不同服务器的变量
package/client.js ADDED
@@ -0,0 +1,811 @@
1
+ /**
2
+ * Client half of the API client bundle.
3
+ * Postman-style UI: request builder, collections, history and response viewer.
4
+ */
5
+ window.__ModuleLoader__.load({
6
+ id: 'dsh-tree-new-bee-api-client',
7
+ factory(require) {
8
+ const React = require('react')
9
+ const h = React.createElement
10
+ const { useState, useEffect, useRef, useCallback, useMemo } = React
11
+
12
+ const NS = 'dsh-tree-new-bee-api-client'
13
+ const PANEL_ID = 'api-client'
14
+ const STYLE_ID = 'dsh-tree-new-bee-api-client/css'
15
+ const API = '/api/dsh-tree-new-bee-api-client'
16
+ const COLLECTION_KEY = 'dsh-tree-new-bee-api-client.collection.v1'
17
+ const HISTORY_KEY = 'dsh-tree-new-bee-api-client.history.v1'
18
+ const ENV_KEY = 'dsh-tree-new-bee-api-client.environments.v1'
19
+ const ACTIVE_ENV_KEY = 'dsh-tree-new-bee-api-client.activeEnv.v1'
20
+ const CUSTOM_HEADERS_KEY = 'dsh-tree-new-bee-api-client.customHeaders.v1'
21
+ const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']
22
+ // Common request headers, modeled after Postman's header autocomplete.
23
+ const COMMON_HEADERS = [
24
+ { key: 'Accept', value: 'application/json', desc: '响应类型' },
25
+ { key: 'Content-Type', value: 'application/json', desc: '请求体类型' },
26
+ { key: 'Authorization', value: 'Bearer {{token}}', desc: 'Bearer 令牌' },
27
+ { key: 'User-Agent', value: 'dsh-tree-new-bee-api-client/1.0', desc: '客户端标识' },
28
+ { key: 'Host', value: '', desc: '主机' },
29
+ { key: 'Connection', value: 'keep-alive', desc: '连接模式' },
30
+ { key: 'Cache-Control', value: 'no-cache', desc: '缓存控制' },
31
+ { key: 'Accept-Language', value: 'zh-CN,zh;q=0.9', desc: '语言' },
32
+ { key: 'Accept-Encoding', value: 'gzip, deflate', desc: '压缩' },
33
+ { key: 'Origin', value: '', desc: '来源' },
34
+ { key: 'Referer', value: '', desc: '来源页' },
35
+ { key: 'Cookie', value: '', desc: 'Cookie' },
36
+ { key: 'X-Requested-With', value: 'XMLHttpRequest', desc: 'Ajax 标识' },
37
+ { key: 'X-API-Key', value: '', desc: 'API 密钥' },
38
+ ]
39
+
40
+ const zh = {
41
+ title: 'Tree New Bee 接口请求', subtitle: '类 Postman 的接口调试工具:请求构造、集合树、环境变量、常用头与历史记录。',
42
+ collection: '集合', history: '历史', save: '保存请求', saved: '已保存',
43
+ name: '请求名称', url: '请求地址', send: '发送', sending: '发送中…',
44
+ params: 'Params', headers: 'Headers', body: 'Body', authorize: '授权',
45
+ key: '键', value: '值', addRow: '添加一行', remove: '删除',
46
+ response: '响应', status: '状态', time: '耗时', size: '大小',
47
+ pretty: '格式化 JSON', raw: '原始', respHeaders: '响应头',
48
+ noResponse: '发送请求后在此查看响应。', noCollection: '暂无保存的请求。',
49
+ noHistory: '暂无历史记录。', confirmDel: '确定删除?',
50
+ tip: 'Params 会自动拼到 URL;Body 用于 POST/PUT/PATCH。支持 http/https。',
51
+ back: '返回', timeout: '超时(秒)', clearHistory: '清空历史',
52
+ environment: '环境', envs: '环境', newEnv: '新建环境', envName: '环境名称',
53
+ variables: '变量', variable: '变量名', noEnv: '暂无环境。新建环境后可设置专属变量。',
54
+ noEnvSelected: '未选择环境', useVariable: '用 {{变量名}} 引用,如 {{baseUrl}}',
55
+ confirmDelEnv: '确定删除该环境?', envSaved: '环境已保存', applyEnv: '变量将在发送时替换 {{key}}',
56
+ commonHeaders: '添加常用请求头', selectHeader: '选择请求头…',
57
+ addSelected: '添加选中', close: '收起', selectedN: '已选 {n} 项', clear: '清空选择',
58
+ selectAll: '全选', unselectAll: '取消全选', customHeader: '自定义请求头',
59
+ headerKeyName: '头名称', headerValue: '默认值', headerDesc: '说明(可选)', addCustom: '添加',
60
+ noCustomHeaders: '还没有自定义请求头。',
61
+ searchCollection: '搜索集合…', noMatches: '没有匹配的文件夹或请求。',
62
+ newFolder: '新建文件夹', folderName: '文件夹名称', confirmDelFolder: '确定删除该文件夹及其内容?',
63
+ moveTo: '移动到', root: '根目录', saveTo: '保存到', rename: '双击重命名',
64
+ }
65
+ const en = {
66
+ title: 'Tree New Bee API Client', subtitle: 'Postman-style API testing: request builder, collection tree, environments, common headers and history.',
67
+ collection: 'Collection', history: 'History', save: 'Save request', saved: 'Saved',
68
+ name: 'Request name', url: 'Request URL', send: 'Send', sending: 'Sending…',
69
+ params: 'Params', headers: 'Headers', body: 'Body', authorize: 'Auth',
70
+ key: 'Key', value: 'Value', addRow: 'Add row', remove: 'Remove',
71
+ response: 'Response', status: 'Status', time: 'Time', size: 'Size',
72
+ pretty: 'Pretty JSON', raw: 'Raw', respHeaders: 'Response headers',
73
+ noResponse: 'Send a request to see the response here.', noCollection: 'No saved requests.',
74
+ noHistory: 'No history yet.', confirmDel: 'Delete this?',
75
+ tip: 'Params are appended to the URL; Body is used for POST/PUT/PATCH. http/https supported.',
76
+ back: 'Back', timeout: 'Timeout (s)', clearHistory: 'Clear history',
77
+ environment: 'Environment', envs: 'Environments', newEnv: 'New environment', envName: 'Environment name',
78
+ variables: 'Variables', variable: 'Variable', noEnv: 'No environments. Create one to set scoped variables.',
79
+ noEnvSelected: 'No environment selected', useVariable: 'Use {{key}} to reference, e.g. {{baseUrl}}',
80
+ confirmDelEnv: 'Delete this environment?', envSaved: 'Environment saved', applyEnv: 'Variables replace {{key}} when sending',
81
+ commonHeaders: 'Add common header', selectHeader: 'Select a header…',
82
+ addSelected: 'Add selected', close: 'Close', selectedN: '{n} selected', clear: 'Clear selection',
83
+ selectAll: 'Select all', unselectAll: 'Deselect all', customHeader: 'Custom header',
84
+ headerKeyName: 'Header name', headerValue: 'Default value', headerDesc: 'Description (optional)', addCustom: 'Add',
85
+ noCustomHeaders: 'No custom headers yet.',
86
+ searchCollection: 'Search collection…', noMatches: 'No matching folders or requests.',
87
+ newFolder: 'New folder', folderName: 'Folder name', confirmDelFolder: 'Delete this folder and its contents?',
88
+ moveTo: 'Move to', root: 'Root', saveTo: 'Save to', rename: 'Double-click to rename',
89
+ }
90
+ let t = (k) => (zh[k] || k)
91
+ const fmt = (s, v) => String(s || '').replace(/\{(\w+)\}/g, (_, k) => (v && v[k] != null ? v[k] : ''))
92
+ function readJSON(key, fb) { try { const r = window.localStorage.getItem(key); return r ? JSON.parse(r) : fb } catch (_) { return fb } }
93
+ function writeJSON(key, v) { try { window.localStorage.setItem(key, JSON.stringify(v)) } catch (_) {} }
94
+ function makeId() { return 'r-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 7) }
95
+
96
+ async function api(path, body) {
97
+ const res = await fetch(API + path, {
98
+ method: 'POST', credentials: 'same-origin',
99
+ headers: { 'content-type': 'application/json' },
100
+ body: JSON.stringify(body),
101
+ })
102
+ let data = null
103
+ try { data = await res.json() } catch (_) {}
104
+ return data || { error: 'HTTP ' + res.status }
105
+ }
106
+
107
+ function SidebarIcon(props) {
108
+ const size = typeof props.size === 'number' ? props.size : 20
109
+ return h('svg', {
110
+ viewBox: '0 0 24 24', width: size, height: size, fill: 'none',
111
+ stroke: 'currentColor', strokeWidth: 1.6, 'aria-hidden': true,
112
+ style: { opacity: props.active ? 1 : 0.82 },
113
+ },
114
+ h('path', { d: 'M4 7h16M4 12h10M4 17h13' }),
115
+ h('circle', { cx: 19, cy: 12, r: 2.5 })
116
+ )
117
+ }
118
+
119
+ function ApiPanel({ ctx }) {
120
+ const [method, setMethod] = useState('GET')
121
+ const [url, setUrl] = useState('')
122
+ const [params, setParams] = useState([{ key: '', value: '' }])
123
+ const [headers, setHeaders] = useState([{ key: '', value: '' }])
124
+ const [body, setBody] = useState('')
125
+ const [timeout, setTimeoutV] = useState('20')
126
+ const [tab, setTab] = useState('params')
127
+ const [resp, setResp] = useState(null)
128
+ const [sending, setSending] = useState(false)
129
+ const [err, setErr] = useState('')
130
+ const [collection, setCollection] = useState(() => {
131
+ const raw = readJSON(COLLECTION_KEY, [])
132
+ // Migrate old flat request list into typed tree nodes.
133
+ return (raw || []).map((x) => x && x.type === 'folder' ? x : { ...x, type: x.type || 'request' })
134
+ })
135
+ const [currentFolder, setCurrentFolder] = useState('') // '' = root; folder id
136
+ const [folderName, setFolderName] = useState('')
137
+ const [expandedFolders, setExpandedFolders] = useState({})
138
+ const [editingNode, setEditingNode] = useState('')
139
+ const [editValue, setEditValue] = useState('')
140
+ const [collectionQuery, setCollectionQuery] = useState('')
141
+ const [history, setHistory] = useState(() => readJSON(HISTORY_KEY, []))
142
+ const [saveName, setSaveName] = useState('')
143
+ const [pretty, setPretty] = useState(true)
144
+ const [sideTab, setSideTab] = useState('collection')
145
+ const [respTab, setRespTab] = useState('body')
146
+ const [environments, setEnvironments] = useState(() => readJSON(ENV_KEY, []))
147
+ const [activeEnvId, setActiveEnvId] = useState(() => { try { return window.localStorage.getItem(ACTIVE_ENV_KEY) || '' } catch (_) { return '' } })
148
+ const [envName, setEnvName] = useState('')
149
+ const [showCommon, setShowCommon] = useState(false)
150
+ const [selectedHeaders, setSelectedHeaders] = useState([])
151
+ const [customHeaders, setCustomHeaders] = useState(() => readJSON(CUSTOM_HEADERS_KEY, []))
152
+ const [customForm, setCustomForm] = useState({ key: '', value: '', desc: '' })
153
+
154
+ useEffect(() => { writeJSON(COLLECTION_KEY, collection) }, [collection])
155
+ useEffect(() => { writeJSON(HISTORY_KEY, history) }, [history])
156
+ useEffect(() => { writeJSON(ENV_KEY, environments) }, [environments])
157
+ useEffect(() => { writeJSON(CUSTOM_HEADERS_KEY, customHeaders) }, [customHeaders])
158
+ useEffect(() => { try { window.localStorage.setItem(ACTIVE_ENV_KEY, activeEnvId) } catch (_) {} }, [activeEnvId])
159
+
160
+ const activeEnv = useMemo(() => environments.find((e) => e.id === activeEnvId) || null, [environments, activeEnvId])
161
+ const varMap = useMemo(() => {
162
+ const m = {}
163
+ if (activeEnv) for (const v of (activeEnv.variables || [])) if (v.key && v.key.trim()) m[v.key.trim()] = v.value || ''
164
+ return m
165
+ }, [activeEnv])
166
+ // Replace {{key}} with the active environment's value.
167
+ const resolveVars = useCallback((s) => {
168
+ if (!s || typeof s !== 'string' || !Object.keys(varMap).length) return s
169
+ return s.replace(/\{\{\s*([\w.\-]+)\s*\}\}/g, (match, k) => (k in varMap ? varMap[k] : match))
170
+ }, [varMap])
171
+
172
+ const buildUrl = useCallback(() => {
173
+ const active = params.filter((p) => p.key.trim())
174
+ const base = resolveVars(url)
175
+ if (!active.length) return base
176
+ try {
177
+ const u = new URL(base)
178
+ for (const p of active) u.searchParams.set(p.key.trim(), resolveVars(p.value || ''))
179
+ return u.toString()
180
+ } catch (_) {
181
+ const q = active.map((p) => encodeURIComponent(p.key.trim()) + '=' + encodeURIComponent(resolveVars(p.value || ''))).join('&')
182
+ return base + (base.includes('?') ? '&' : '?') + q
183
+ }
184
+ }, [url, params, resolveVars])
185
+
186
+ const send = useCallback(async () => {
187
+ if (!url.trim()) { setErr(t('url') + '?'); return }
188
+ setSending(true); setErr(''); setResp(null)
189
+ const headerObj = {}
190
+ for (const hh of headers) if (hh.key.trim()) headerObj[hh.key.trim()] = resolveVars(hh.value || '')
191
+ const finalUrl = buildUrl()
192
+ const result = await api('/request', {
193
+ method, url: finalUrl, headers: headerObj,
194
+ body: ['GET', 'HEAD'].includes(method) ? '' : resolveVars(body),
195
+ timeout: (Number(timeout) || 20),
196
+ })
197
+ if (result.error) { setErr(result.error); setResp({ timeMs: result.timeMs }) }
198
+ else setResp(result)
199
+ setHistory((prev) => [{
200
+ id: makeId(), method, url: finalUrl, time: new Date().toISOString(),
201
+ status: result.status, error: result.error || '',
202
+ snapshot: { method, url, params, headers, body, timeout },
203
+ }, ...prev].slice(0, 100))
204
+ setSending(false)
205
+ }, [url, method, headers, body, timeout, buildUrl, params, resolveVars])
206
+
207
+ // ---- collection tree helpers ----
208
+ const findFolder = useCallback((nodes, id) => {
209
+ if (!id) return null
210
+ for (const n of nodes) {
211
+ if (n.type === 'folder') {
212
+ if (n.id === id) return n
213
+ const found = findFolder(n.children || [], id)
214
+ if (found) return found
215
+ }
216
+ }
217
+ return null
218
+ }, [])
219
+ // Breadcrumb path from root to a folder: array of { id, name }.
220
+ const folderPath = useCallback((nodes, id, acc) => {
221
+ acc = acc || []
222
+ for (const n of nodes) {
223
+ if (n.type !== 'folder') continue
224
+ if (n.id === id) return [...acc, { id: n.id, name: n.name }]
225
+ const sub = folderPath(n.children || [], id, [...acc, { id: n.id, name: n.name }])
226
+ if (sub) return sub
227
+ }
228
+ return null
229
+ }, [])
230
+ // Fuzzy filter nodes by folder name / request name / method / URL.
231
+ const filterTree = useCallback((nodes, q) => {
232
+ if (!q) return nodes
233
+ const needle = q.toLowerCase()
234
+ const result = []
235
+ for (const n of nodes) {
236
+ if (n.type === 'folder') {
237
+ const kids = filterTree(n.children || [], q)
238
+ const selfMatch = (n.name || '').toLowerCase().indexOf(needle) >= 0
239
+ if (kids.length || selfMatch) result.push({ ...n, children: kids, _searchOpen: true })
240
+ } else {
241
+ const hay = [n.name, n.method, n.url].filter(Boolean).join(' ').toLowerCase()
242
+ if (hay.indexOf(needle) >= 0) result.push(n)
243
+ }
244
+ }
245
+ return result
246
+ }, [])
247
+ const insertNode = useCallback((nodes, parentId, node) => {
248
+ if (!parentId) return [...nodes, node]
249
+ return nodes.map((n) => {
250
+ if (n.type === 'folder') {
251
+ if (n.id === parentId) return { ...n, children: [...(n.children || []), node] }
252
+ return { ...n, children: insertNode(n.children || [], parentId, node) }
253
+ }
254
+ return n
255
+ })
256
+ }, [])
257
+ const removeNode = useCallback((nodes, id) =>
258
+ nodes.filter((n) => n.id !== id).map((n) =>
259
+ n.type === 'folder' ? { ...n, children: removeNode(n.children || [], id) } : n
260
+ ), [])
261
+ const countRequests = useCallback((n) => {
262
+ if (!n || n.type !== 'folder') return 0
263
+ return (n.children || []).reduce((s, c) => s + (c.type === 'folder' ? countRequests(c) : 1), 0)
264
+ }, [])
265
+
266
+ const addFolder = useCallback(() => {
267
+ const name = folderName.trim() || t('newFolder')
268
+ const node = { id: makeId(), type: 'folder', name, children: [] }
269
+ setCollection((prev) => insertNode(prev, currentFolder, node))
270
+ setExpandedFolders((prev) => ({ ...prev, [currentFolder || '__root']: true, [node.id]: true }))
271
+ setFolderName('')
272
+ }, [folderName, currentFolder, insertNode])
273
+
274
+ const findNode = useCallback((nodes, id) => {
275
+ for (const n of nodes) {
276
+ if (n.id === id) return n
277
+ if (n.type === 'folder') { const f = findNode(n.children || [], id); if (f) return f }
278
+ }
279
+ return null
280
+ }, [])
281
+ const renameNode = useCallback((nodes, id, name) => nodes.map((n) => {
282
+ if (n.id === id) return { ...n, name }
283
+ if (n.type === 'folder') return { ...n, children: renameNode(n.children || [], id, name) }
284
+ return n
285
+ }), [])
286
+ const delNode = useCallback((id) => {
287
+ const node = findNode(collection, id)
288
+ const isFolder = node && node.type === 'folder'
289
+ if (isFolder && !window.confirm(t('confirmDelFolder'))) return
290
+ if (!isFolder && !window.confirm(t('confirmDel'))) return
291
+ setCollection((prev) => removeNode(prev, id))
292
+ if (currentFolder === id) setCurrentFolder('')
293
+ }, [collection, findNode, currentFolder, removeNode])
294
+
295
+ const startRename = useCallback((n) => {
296
+ setEditingNode(n.id)
297
+ setEditValue(n.name || n.url || '')
298
+ }, [])
299
+ const commitRename = useCallback(() => {
300
+ const value = editValue.trim()
301
+ if (editingNode && value) setCollection((prev) => renameNode(prev, editingNode, value))
302
+ setEditingNode(''); setEditValue('')
303
+ }, [editingNode, editValue, renameNode])
304
+
305
+ const saveRequest = useCallback(() => {
306
+ const name = saveName.trim() || (method + ' ' + url)
307
+ if (!url.trim()) return
308
+ const node = { id: makeId(), type: 'request', name, method, url, params, headers, body, timeout }
309
+ setCollection((prev) => insertNode(prev, currentFolder, node))
310
+ if (currentFolder) setExpandedFolders((prev) => ({ ...prev, [currentFolder]: true }))
311
+ setSaveName('')
312
+ }, [saveName, method, url, params, headers, body, timeout, currentFolder, insertNode])
313
+
314
+
315
+ const loadSaved = useCallback((s) => {
316
+ setMethod(s.method || 'GET'); setUrl(s.url || '')
317
+ setParams(s.params && s.params.length ? s.params : [{ key: '', value: '' }])
318
+ setHeaders(s.headers && s.headers.length ? s.headers : [{ key: '', value: '' }])
319
+ setBody(s.body || ''); setTimeoutV(s.timeout || '20'); setResp(null)
320
+ }, [])
321
+
322
+ // ---- environment management ----
323
+ const addEnv = useCallback(() => {
324
+ const name = envName.trim() || ('Environment ' + (environments.length + 1))
325
+ const id = makeId()
326
+ setEnvironments((prev) => [...prev, { id, name, variables: [{ key: 'baseUrl', value: '' }] }])
327
+ setActiveEnvId(id)
328
+ setEnvName('')
329
+ setSideTab('envs')
330
+ }, [envName, environments.length])
331
+
332
+ const delEnv = useCallback((id) => {
333
+ if (!window.confirm(t('confirmDelEnv'))) return
334
+ setEnvironments((prev) => prev.filter((e) => e.id !== id))
335
+ if (activeEnvId === id) setActiveEnvId('')
336
+ }, [activeEnvId])
337
+
338
+ const updateEnv = useCallback((id, patch) => {
339
+ setEnvironments((prev) => prev.map((e) => e.id === id ? { ...e, ...patch } : e))
340
+ }, [])
341
+
342
+ const updateEnvVar = useCallback((envId, idx, field, val) => {
343
+ setEnvironments((prev) => prev.map((e) => {
344
+ if (e.id !== envId) return e
345
+ const vars = (e.variables || []).map((v, i) => i === idx ? { ...v, [field]: val } : v)
346
+ return { ...e, variables: vars }
347
+ }))
348
+ }, [])
349
+
350
+ const envAddRow = useCallback((envId) => {
351
+ setEnvironments((prev) => prev.map((e) => e.id === envId ? { ...e, variables: [...(e.variables || []), { key: '', value: '' }] } : e))
352
+ }, [])
353
+
354
+ const envDelRow = useCallback((envId, idx) => {
355
+ setEnvironments((prev) => prev.map((e) => e.id === envId ? { ...e, variables: (e.variables || []).filter((_, i) => i !== idx) } : e))
356
+ }, [])
357
+
358
+ const allCommonHeaders = useMemo(() => [...COMMON_HEADERS, ...customHeaders], [customHeaders])
359
+
360
+ const updateRow = (setter, idx, field, val) => setter((prev) => prev.map((r, i) => i === idx ? { ...r, [field]: val } : r))
361
+ const addRow = (setter) => setter((prev) => [...prev, { key: '', value: '' }])
362
+ const delRow = (setter, idx) => setter((prev) => prev.filter((_, i) => i !== idx))
363
+ const addCommonHeaders = useCallback((names) => {
364
+ const defs = names.map((n) => allCommonHeaders.find((x) => x.key === n)).filter(Boolean)
365
+ if (!defs.length) return
366
+ setHeaders((prev) => {
367
+ let next = prev.slice()
368
+ for (const hdef of defs) {
369
+ const idx = next.findIndex((r) => r.key.toLowerCase() === hdef.key.toLowerCase())
370
+ if (idx >= 0) { if (!next[idx].value) next[idx] = { ...next[idx], value: hdef.value }; continue }
371
+ const empty = next.findIndex((r) => !r.key.trim() && !r.value.trim())
372
+ if (empty >= 0) next[empty] = { key: hdef.key, value: hdef.value }
373
+ else next = [...next, { key: hdef.key, value: hdef.value }]
374
+ }
375
+ return next
376
+ })
377
+ setSelectedHeaders([])
378
+ setShowCommon(false)
379
+ }, [allCommonHeaders])
380
+
381
+ const selectAllCommon = useCallback(() => setSelectedHeaders(allCommonHeaders.map((x) => x.key)), [allCommonHeaders])
382
+ const addCustomHeader = useCallback(() => {
383
+ const key = customForm.key.trim()
384
+ if (!key) return
385
+ setCustomHeaders((prev) => {
386
+ const idx = prev.findIndex((x) => x.key.toLowerCase() === key.toLowerCase())
387
+ const item = { key, value: customForm.value || '', desc: customForm.desc || '自定义' }
388
+ if (idx >= 0) { const next = prev.slice(); next[idx] = item; return next }
389
+ return [...prev, item]
390
+ })
391
+ setCustomForm({ key: '', value: '', desc: '' })
392
+ }, [customForm])
393
+ const delCustomHeader = useCallback((key) => {
394
+ setCustomHeaders((prev) => prev.filter((x) => x.key !== key))
395
+ setSelectedHeaders((prev) => prev.filter((x) => x !== key))
396
+ }, [])
397
+ const toggleSelectedHeader = useCallback((name) => {
398
+ setSelectedHeaders((prev) => prev.indexOf(name) >= 0 ? prev.filter((x) => x !== name) : [...prev, name])
399
+ }, [])
400
+
401
+ const renderRows = (rows, setter) =>
402
+ h('div', { className: 'dshApi-rows' },
403
+ h('div', { className: 'dshApi-rowHead' },
404
+ h('span', null, t('key')), h('span', null, t('value')), h('span', null, '')),
405
+ rows.map((r, i) =>
406
+ h('div', { key: i, className: 'dshApi-row' },
407
+ h('input', { className: 'dshApi-input', value: r.key, placeholder: t('key'), onChange: (e) => updateRow(setter, i, 'key', e.target.value) }),
408
+ h('input', { className: 'dshApi-input', value: r.value, placeholder: t('value'), onChange: (e) => updateRow(setter, i, 'value', e.target.value) }),
409
+ h('button', { type: 'button', className: 'dshApi-mini', title: t('remove'), onClick: () => delRow(setter, i) }, '×')
410
+ )
411
+ ),
412
+ h('button', { type: 'button', className: 'dshApi-btn dshApi-btnSm', onClick: () => addRow(setter) }, '+ ' + t('addRow'))
413
+ )
414
+
415
+ // Recursive collection tree with inline rename (double-click a name).
416
+ const renderName = (n, suffix) => editingNode === n.id
417
+ ? h('input', {
418
+ className: 'dshApi-input dshApi-treeEdit', value: editValue, autoFocus: true,
419
+ onChange: (e) => setEditValue(e.target.value),
420
+ onBlur: commitRename,
421
+ onKeyDown: (e) => {
422
+ if (e.key === 'Enter') { e.preventDefault(); commitRename() }
423
+ else if (e.key === 'Escape') { setEditingNode(''); setEditValue('') }
424
+ },
425
+ })
426
+ : h('span', {
427
+ className: 'dshApi-treeName', title: t('rename'),
428
+ onDoubleClick: () => startRename(n),
429
+ }, (n.name || n.url || '') + (suffix || ''))
430
+ const renderTree = (nodes, depth) => nodes.map((n) => {
431
+ if (n.type === 'folder') {
432
+ const isOpen = n._searchOpen ? true : expandedFolders[n.id] !== false
433
+ const isCurrent = currentFolder === n.id
434
+ return h('div', { key: n.id, className: 'dshApi-treeFolder' },
435
+ h('div', {
436
+ className: 'dshApi-treeRow' + (isCurrent ? ' dshApi-treeRowOn' : ''),
437
+ style: { paddingLeft: (depth * 12) + 'px' },
438
+ },
439
+ h('span', {
440
+ className: 'dshApi-treeArrow',
441
+ onClick: () => setExpandedFolders((prev) => ({ ...prev, [n.id]: !isOpen })),
442
+ }, isOpen ? '▾' : '▸'),
443
+ h('span', { className: 'dshApi-folderIco' }, '📁'),
444
+ h('span', { className: 'dshApi-treePick', title: t('saveTo'), onClick: () => setCurrentFolder(n.id) },
445
+ renderName(n, ' (' + countRequests(n) + ')')
446
+ ),
447
+ h('button', { type: 'button', className: 'dshApi-mini', title: t('remove'), onClick: () => delNode(n.id) }, '×')
448
+ ),
449
+ isOpen ? renderTree(n.children || [], depth + 1) : null
450
+ )
451
+ }
452
+ return h('div', { key: n.id, className: 'dshApi-treeRequest' },
453
+ h('div', { className: 'dshApi-treeRow', style: { paddingLeft: (depth * 12) + 'px' } },
454
+ h('span', { className: 'dshApi-treeArrow' }, '·'),
455
+ h('span', { className: 'dshApi-method dshApi-' + n.method }, n.method),
456
+ h('span', { className: 'dshApi-treePick', onClick: () => { if (editingNode !== n.id) loadSaved(n) } }, renderName(n, '')),
457
+ h('button', { type: 'button', className: 'dshApi-mini', title: t('remove'), onClick: () => delNode(n.id) }, '×')
458
+ )
459
+ )
460
+ })
461
+
462
+ const prettyBody = useMemo(() => {
463
+ if (!resp || !resp.body) return ''
464
+ if (!pretty) return resp.body
465
+ try { return JSON.stringify(JSON.parse(resp.body), null, 2) } catch (_) { return resp.body }
466
+ }, [resp, pretty])
467
+
468
+ const statusColor = resp && resp.status >= 200 && resp.status < 300 ? 'dshApi-ok' : (resp && resp.status >= 400 ? 'dshApi-bad' : '')
469
+
470
+ const goBack = useCallback(() => {
471
+ const layout = ctx && ctx.layout
472
+ if (!layout || typeof layout.selectPanel !== 'function') return
473
+ try { layout.selectPanel(null) } catch (_) {
474
+ try { layout.selectPanel('conversation') } catch (_) {}
475
+ }
476
+ }, [ctx])
477
+
478
+ const currentPath = currentFolder ? (folderPath(collection, currentFolder) || []) : []
479
+
480
+ return h('div', { className: 'dshApi-root' },
481
+ h('div', { className: 'dshApi-head' },
482
+ h('div', null,
483
+ h('div', { className: 'dshApi-title' }, t('title')),
484
+ h('div', { className: 'dshApi-sub' }, t('subtitle'))
485
+ ),
486
+ h('button', { type: 'button', className: 'dshApi-back', onClick: goBack }, '‹ ' + t('back'))
487
+ ),
488
+ h('div', { className: 'dshApi-envBar' },
489
+ h('span', { className: 'dshApi-envIcon' }, '◈'),
490
+ h('span', null, t('environment') + ':'),
491
+ h('select', {
492
+ className: 'dshApi-select', value: activeEnvId,
493
+ onChange: (e) => setActiveEnvId(e.target.value),
494
+ },
495
+ h('option', { value: '' }, t('noEnvSelected')),
496
+ environments.map((e) => h('option', { key: e.id, value: e.id }, e.name))
497
+ ),
498
+ activeEnv
499
+ ? h('span', { className: 'dshApi-envVars' }, (activeEnv.variables || []).filter((v) => v.key).map((v) => v.key).join(', ') || t('noEnv'))
500
+ : null
501
+ ),
502
+ h('div', { className: 'dshApi-cols' },
503
+ // left: collection + history
504
+ h('div', { className: 'dshApi-col dshApi-side' },
505
+ h('div', { className: 'dshApi-tabs' },
506
+ h('button', { type: 'button', className: 'dshApi-tab' + (sideTab === 'collection' ? ' dshApi-tabOn' : ''), onClick: () => setSideTab('collection') }, t('collection')),
507
+ h('button', { type: 'button', className: 'dshApi-tab' + (sideTab === 'envs' ? ' dshApi-tabOn' : ''), onClick: () => setSideTab('envs') }, t('envs')),
508
+ h('button', { type: 'button', className: 'dshApi-tab' + (sideTab === 'history' ? ' dshApi-tabOn' : ''), onClick: () => setSideTab('history') }, t('history'))
509
+ ),
510
+ sideTab === 'collection'
511
+ ? h('div', { className: 'dshApi-sideList' },
512
+ h('div', { className: 'dshApi-saveTarget' },
513
+ h('span', null, t('saveTo') + ': '),
514
+ h('button', { type: 'button', className: 'dshApi-crumb', onClick: () => setCurrentFolder('') }, t('root')),
515
+ currentPath.map((seg, i) =>
516
+ h('span', { key: seg.id },
517
+ h('span', { className: 'dshApi-crumbSep' }, ' / '),
518
+ h('button', {
519
+ type: 'button',
520
+ className: 'dshApi-crumb' + (i === currentPath.length - 1 ? ' dshApi-crumbOn' : ''),
521
+ onClick: () => setCurrentFolder(seg.id),
522
+ }, seg.name)
523
+ )
524
+ )
525
+ ),
526
+ h('input', { className: 'dshApi-input', value: saveName, placeholder: t('name'), onChange: (e) => setSaveName(e.target.value) }),
527
+ h('button', { type: 'button', className: 'dshApi-btn dshApi-btnPrimary', onClick: saveRequest }, '+ ' + t('save')),
528
+ h('div', { className: 'dshApi-folderBar' },
529
+ h('input', { className: 'dshApi-input', value: folderName, placeholder: t('folderName'), onChange: (e) => setFolderName(e.target.value) }),
530
+ h('button', { type: 'button', className: 'dshApi-btn dshApi-btnSm', onClick: addFolder }, '+ ' + t('newFolder'))
531
+ ),
532
+ h('input', {
533
+ className: 'dshApi-input dshApi-search', type: 'search', value: collectionQuery,
534
+ placeholder: t('searchCollection'),
535
+ onChange: (e) => setCollectionQuery(e.target.value),
536
+ }),
537
+ h('div', { className: 'dshApi-tree' },
538
+ (collectionQuery ? filterTree(collection, collectionQuery) : collection).length === 0
539
+ ? h('div', { className: 'dshApi-note' }, collectionQuery ? t('noMatches') : t('noCollection'))
540
+ : renderTree(collectionQuery ? filterTree(collection, collectionQuery) : collection, 0)
541
+ )
542
+ )
543
+ : sideTab === 'envs'
544
+ ? h('div', { className: 'dshApi-sideList' },
545
+ h('input', { className: 'dshApi-input', value: envName, placeholder: t('envName'), onChange: (e) => setEnvName(e.target.value) }),
546
+ h('button', { type: 'button', className: 'dshApi-btn dshApi-btnPrimary', onClick: addEnv }, '+ ' + t('newEnv')),
547
+ h('div', { className: 'dshApi-note' }, t('useVariable')),
548
+ environments.length === 0
549
+ ? h('div', { className: 'dshApi-note' }, t('noEnv'))
550
+ : environments.map((env) =>
551
+ h('div', { key: env.id, className: 'dshApi-envCard' + (activeEnvId === env.id ? ' dshApi-envCardOn' : '') },
552
+ h('div', { className: 'dshApi-envCardHead', onClick: () => setActiveEnvId(env.id) },
553
+ h('span', { className: 'dshApi-envDot' }),
554
+ h('input', { className: 'dshApi-input dshApi-envName', value: env.name, onChange: (e) => updateEnv(env.id, { name: e.target.value }) }),
555
+ h('button', { type: 'button', className: 'dshApi-mini', title: t('remove'), onClick: () => delEnv(env.id) }, '×')
556
+ ),
557
+ (env.variables || []).map((v, i) =>
558
+ h('div', { key: i, className: 'dshApi-row' },
559
+ h('input', { className: 'dshApi-input', value: v.key, placeholder: t('variable'), onChange: (e) => updateEnvVar(env.id, i, 'key', e.target.value) }),
560
+ h('input', { className: 'dshApi-input', value: v.value, placeholder: t('value'), onChange: (e) => updateEnvVar(env.id, i, 'value', e.target.value) }),
561
+ h('button', { type: 'button', className: 'dshApi-mini', onClick: () => envDelRow(env.id, i) }, '×')
562
+ )
563
+ ),
564
+ h('button', { type: 'button', className: 'dshApi-btn dshApi-btnSm', onClick: () => envAddRow(env.id) }, '+ ' + t('addRow'))
565
+ )
566
+ )
567
+ )
568
+ : h('div', { className: 'dshApi-sideList' },
569
+ h('button', { type: 'button', className: 'dshApi-btn dshApi-btnSm', onClick: () => setHistory([]) }, t('clearHistory')),
570
+ history.length === 0
571
+ ? h('div', { className: 'dshApi-note' }, t('noHistory'))
572
+ : history.map((it) =>
573
+ h('div', { key: it.id, className: 'dshApi-sideItem', onClick: () => { if (it.snapshot) loadSaved(it.snapshot) } },
574
+ h('span', { className: 'dshApi-method dshApi-' + it.method }, it.method),
575
+ h('span', { className: 'dshApi-sideName' }, (it.error ? '✗ ' : (it.status || '') + ' ') + it.url),
576
+ h('span', { className: 'dshApi-timeSmall' }, new Date(it.time).toLocaleTimeString())
577
+ )
578
+ )
579
+ )
580
+ ),
581
+ // right: request + response
582
+ h('div', { className: 'dshApi-col dshApi-main' },
583
+ h('div', { className: 'dshApi-card' },
584
+ h('div', { className: 'dshApi-urlRow' },
585
+ h('select', { className: 'dshApi-select', value: method, onChange: (e) => setMethod(e.target.value) },
586
+ METHODS.map((m) => h('option', { key: m, value: m }, m))
587
+ ),
588
+ h('input', {
589
+ className: 'dshApi-input dshApi-url', value: url, spellCheck: false,
590
+ placeholder: '{{baseUrl}}/v1/resource',
591
+ onChange: (e) => setUrl(e.target.value),
592
+ onKeyDown: (e) => { if (e.key === 'Enter') send() },
593
+ }),
594
+ h('input', { className: 'dshApi-input dshApi-timeout', type: 'number', value: timeout, title: t('timeout'), onChange: (e) => setTimeoutV(e.target.value) }),
595
+ h('button', { type: 'button', className: 'dshApi-btn dshApi-btnPrimary', disabled: sending, onClick: send }, sending ? t('sending') : t('send'))
596
+ ),
597
+ h('div', { className: 'dshApi-tabs' },
598
+ h('button', { type: 'button', className: 'dshApi-tab' + (tab === 'params' ? ' dshApi-tabOn' : ''), onClick: () => setTab('params') }, t('params')),
599
+ h('button', { type: 'button', className: 'dshApi-tab' + (tab === 'headers' ? ' dshApi-tabOn' : ''), onClick: () => setTab('headers') }, t('headers')),
600
+ h('button', { type: 'button', className: 'dshApi-tab' + (tab === 'body' ? ' dshApi-tabOn' : ''), onClick: () => setTab('body') }, t('body'))
601
+ ),
602
+ tab === 'params' ? renderRows(params, setParams) : null,
603
+ tab === 'headers'
604
+ ? h('div', null,
605
+ h('div', { className: 'dshApi-commonBar' },
606
+ h('button', { type: 'button', className: 'dshApi-btn dshApi-btnSm', onClick: () => setShowCommon((v) => !v) },
607
+ (showCommon ? '▴ ' : '▾ ') + t('commonHeaders')),
608
+ selectedHeaders.length ? h('span', { className: 'dshApi-commonLabel' }, fmt(t('selectedN'), { n: selectedHeaders.length })) : null
609
+ ),
610
+ showCommon
611
+ ? h('div', { className: 'dshApi-commonPanel' },
612
+ h('div', { className: 'dshApi-commonGrid' },
613
+ allCommonHeaders.map((x) =>
614
+ h('div', { key: x.key, className: 'dshApi-commonItem' },
615
+ h('label', { className: 'dshApi-commonItemLabel' },
616
+ h('input', {
617
+ type: 'checkbox', checked: selectedHeaders.indexOf(x.key) >= 0,
618
+ onChange: () => toggleSelectedHeader(x.key),
619
+ }),
620
+ h('span', { className: 'dshApi-commonName' }, x.key),
621
+ h('span', { className: 'dshApi-commonDesc' }, x.desc + (x.value ? ' · ' + x.value : ''))
622
+ ),
623
+ customHeaders.some((c) => c.key === x.key)
624
+ ? h('button', { type: 'button', className: 'dshApi-mini', title: t('remove'), onClick: () => delCustomHeader(x.key) }, '×')
625
+ : null
626
+ )
627
+ )
628
+ ),
629
+ h('div', { className: 'dshApi-commonActions' },
630
+ h('button', { type: 'button', className: 'dshApi-btn dshApi-btnSm', onClick: selectAllCommon }, t('selectAll')),
631
+ h('button', { type: 'button', className: 'dshApi-btn dshApi-btnSm', onClick: () => setSelectedHeaders([]) }, t('unselectAll')),
632
+ h('button', { type: 'button', className: 'dshApi-btn dshApi-btnPrimary dshApi-btnSm', disabled: !selectedHeaders.length, onClick: () => addCommonHeaders(selectedHeaders) }, t('addSelected'))
633
+ ),
634
+ h('div', { className: 'dshApi-customBar' },
635
+ h('span', { className: 'dshApi-commonLabel' }, t('customHeader') + ':'),
636
+ h('input', { className: 'dshApi-input', value: customForm.key, placeholder: t('headerKeyName'), onChange: (e) => setCustomForm((f) => ({ ...f, key: e.target.value })) }),
637
+ h('input', { className: 'dshApi-input', value: customForm.value, placeholder: t('headerValue'), onChange: (e) => setCustomForm((f) => ({ ...f, value: e.target.value })) }),
638
+ h('input', { className: 'dshApi-input', value: customForm.desc, placeholder: t('headerDesc'), onChange: (e) => setCustomForm((f) => ({ ...f, desc: e.target.value })) }),
639
+ h('button', { type: 'button', className: 'dshApi-btn dshApi-btnSm', disabled: !customForm.key.trim(), onClick: addCustomHeader }, '+ ' + t('addCustom'))
640
+ )
641
+ )
642
+ : null,
643
+ renderRows(headers, setHeaders)
644
+ )
645
+ : null,
646
+ tab === 'body'
647
+ ? h('textarea', {
648
+ className: 'dshApi-body', value: body, spellCheck: false,
649
+ placeholder: '{ "key": "value" }',
650
+ onChange: (e) => setBody(e.target.value),
651
+ })
652
+ : null
653
+ ),
654
+ h('div', { className: 'dshApi-card dshApi-grow' },
655
+ h('div', { className: 'dshApi-toolbar' },
656
+ h('span', { className: 'dshApi-cardTitle' }, t('response')),
657
+ resp && !resp.error
658
+ ? h('div', { className: 'dshApi-metrics' },
659
+ h('span', { className: 'dshApi-metric ' + statusColor }, t('status') + ' ' + resp.status + (resp.statusText ? ' ' + resp.statusText : '')),
660
+ h('span', { className: 'dshApi-metric' }, t('time') + ' ' + (resp.timeMs || 0) + 'ms'),
661
+ h('span', { className: 'dshApi-metric' }, t('size') + ' ' + (resp.size || 0) + 'B')
662
+ )
663
+ : null
664
+ ),
665
+ err ? h('div', { className: 'dshApi-err' }, err) : null,
666
+ resp && !resp.error
667
+ ? h('div', null,
668
+ h('div', { className: 'dshApi-tabs' },
669
+ h('button', { type: 'button', className: 'dshApi-tab' + (respTab === 'body' ? ' dshApi-tabOn' : ''), onClick: () => setRespTab('body') }, t('body')),
670
+ h('button', { type: 'button', className: 'dshApi-tab' + (respTab === 'headers' ? ' dshApi-tabOn' : ''), onClick: () => setRespTab('headers') }, t('respHeaders'))
671
+ ),
672
+ respTab === 'body'
673
+ ? h('div', null,
674
+ h('label', { className: 'dshApi-cb' }, h('input', { type: 'checkbox', checked: pretty, onChange: (e) => setPretty(e.target.checked) }), t('pretty')),
675
+ h('pre', { className: 'dshApi-response' }, prettyBody || '(empty)')
676
+ )
677
+ : h('div', { className: 'dshApi-headers' },
678
+ Object.entries(resp.headers || {}).map(([k, v]) => h('div', { key: k, className: 'dshApi-hrow' }, h('b', null, k + ': '), v))
679
+ )
680
+ )
681
+ : h('div', { className: 'dshApi-note dshApi-center' }, t('noResponse'))
682
+ )
683
+ )
684
+ ),
685
+ h('div', { className: 'dshApi-foot' }, t('tip'))
686
+ )
687
+ }
688
+
689
+ function apply(ctx) {
690
+ ctx.effect(() => installStyles(), 'dsh-tree-new-bee-api-client: styles')
691
+ if (ctx.locale !== undefined) {
692
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-tree-new-bee-api-client: dictionaries')
693
+ t = ctx.locale.bind(NS)
694
+ }
695
+ ctx.effect(() => ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
696
+ name: 'sidebar.panellist', id: PANEL_ID, order: 31, label: () => t('title'), locale: NS,
697
+ }, SidebarIcon)), 'dsh-tree-new-bee-api-client: sidebar entry')
698
+ ctx.effect(() => ctx.slots.inject('main', () => ctx.slots.register({
699
+ name: 'main', key: PANEL_ID, locale: NS,
700
+ }, (props) => h(ApiPanel, { ctx }))), 'dsh-tree-new-bee-api-client: panel')
701
+ }
702
+
703
+ function installStyles() {
704
+ if (typeof document === 'undefined') return () => {}
705
+ const existing = document.querySelector('style[data-plugin-css="' + STYLE_ID + '"]')
706
+ if (existing) return () => {}
707
+ const style = document.createElement('style')
708
+ style.dataset.plugin = NS
709
+ style.dataset.pluginCss = STYLE_ID
710
+ style.textContent = `
711
+ .dshApi-root{display:flex;flex-direction:column;height:100%;box-sizing:border-box;padding:14px 18px 18px;gap:10px;overflow:hidden;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base)}
712
+ .dshApi-head{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;flex:0 0 auto}
713
+ .dshApi-title{font-size:20px;font-weight:700;line-height:1.3}
714
+ .dshApi-sub{font-size:12px;color:var(--dsw-alias-label-secondary);margin-top:3px}
715
+ .dshApi-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}
716
+ .dshApi-cols{display:grid;grid-template-columns:minmax(220px,300px) minmax(0,1fr);gap:12px;flex:1 1 auto;min-height:0}
717
+ .dshApi-col{display:flex;flex-direction:column;gap:10px;min-height:0;overflow:hidden}
718
+ .dshApi-side{border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1);padding:10px}
719
+ .dshApi-tabs{display:flex;gap:4px;flex-wrap:wrap;flex:0 0 auto}
720
+ .dshApi-tab{padding:6px 12px;border-radius:8px;border:1px solid var(--dsw-alias-border-l1);background:transparent;color:var(--dsw-alias-label-secondary);font-size:12px;cursor:pointer;font-family:inherit}
721
+ .dshApi-tabOn{background:var(--dsw-alias-brand-primary);color:var(--dsw-alias-bg-base);border-color:transparent;font-weight:600}
722
+ .dshApi-sideList{display:flex;flex-direction:column;gap:5px;overflow-y:auto;flex:1 1 auto}
723
+ .dshApi-sideItem{display:flex;align-items:center;gap:6px;padding:7px 8px;border-radius:7px;border:1px solid var(--dsw-alias-border-l1);font-size:11.5px;cursor:pointer;flex-wrap:wrap}
724
+ .dshApi-sideItem:hover{background:var(--dsw-alias-bg-layer-2)}
725
+ .dshApi-sideItemMain{display:flex;align-items:center;gap:6px;flex:1 1 auto;min-width:0;cursor:pointer}
726
+ .dshApi-method{font-size:10px;font-weight:700;padding:2px 5px;border-radius:5px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-secondary);flex:0 0 auto}
727
+ .dshApi-GET{color:#2e7d32}.dshApi-POST{color:#e65100}.dshApi-PUT{color:#1565c0}.dshApi-PATCH{color:#6a1b9a}.dshApi-DELETE{color:#c62828}
728
+ .dshApi-sideName{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
729
+ .dshApi-timeSmall{font-size:9px;color:var(--dsw-alias-label-secondary)}
730
+ .dshApi-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}
731
+ .dshApi-grow{flex:1 1 auto;min-height:0}
732
+ .dshApi-urlRow{display:flex;gap:6px;align-items:center;flex-wrap:wrap}
733
+ .dshApi-input,.dshApi-select{padding:7px 9px;border-radius:8px;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}
734
+ .dshApi-input:focus,.dshApi-select:focus{border-color:var(--dsw-alias-brand-primary)}
735
+ .dshApi-url{flex:1 1 260px}
736
+ .dshApi-timeout{width:66px}
737
+ .dshApi-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}
738
+ .dshApi-btn:hover{border-color:var(--dsw-alias-brand-primary)}
739
+ .dshApi-btn:disabled{opacity:.45;cursor:not-allowed}
740
+ .dshApi-btnPrimary{background:#2ecc71;color:#0b0e13;border-color:transparent;font-weight:700}
741
+ .dshApi-btnSm{padding:4px 8px;font-size:11px}
742
+ .dshApi-mini{border:0;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer;font-size:13px;padding:0 4px;font-family:inherit}
743
+ .dshApi-rows{display:flex;flex-direction:column;gap:4px}
744
+ .dshApi-rowHead,.dshApi-row{display:grid;grid-template-columns:1fr 1fr 24px;gap:6px;align-items:center}
745
+ .dshApi-rowHead{font-size:10px;color:var(--dsw-alias-label-secondary)}
746
+ .dshApi-body{width:100%;box-sizing:border-box;min-height:120px;resize:vertical;padding:10px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);font-family:ui-monospace,monospace;font-size:12px;outline:none}
747
+ .dshApi-toolbar{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap}
748
+ .dshApi-cardTitle{font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary)}
749
+ .dshApi-metrics{display:flex;gap:8px;flex-wrap:wrap}
750
+ .dshApi-metric{font-size:11px;padding:3px 8px;border-radius:7px;background:var(--dsw-alias-bg-layer-2);font-variant-numeric:tabular-nums}
751
+ .dshApi-ok{color:var(--dsw-alias-state-success-primary)}.dshApi-bad{color:var(--dsw-alias-state-error-primary)}
752
+ .dshApi-err{font-size:11px;color:var(--dsw-alias-state-error-primary);padding:6px 8px;border-radius:7px;background:var(--dsw-alias-bg-layer-2)}
753
+ .dshApi-cb{display:flex;align-items:center;gap:5px;font-size:11px;color:var(--dsw-alias-label-secondary)}
754
+ .dshApi-cb input{accent-color:var(--dsw-alias-brand-primary)}
755
+ .dshApi-response{flex:1 1 auto;min-height:120px;max-height:100%;overflow:auto;margin:4px 0 0;padding:12px;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.6;white-space:pre-wrap;word-break:break-all}
756
+ .dshApi-headers{display:flex;flex-direction:column;gap:4px;font-size:11px;max-height:240px;overflow:auto}
757
+ .dshApi-hrow{padding:4px 6px;border-radius:6px;background:var(--dsw-alias-bg-base);word-break:break-all}
758
+ .dshApi-note{font-size:12px;color:var(--dsw-alias-label-secondary);padding:8px}
759
+ .dshApi-center{flex:1 1 auto;display:flex;align-items:center;justify-content:center;text-align:center}
760
+ .dshApi-foot{font-size:11px;color:var(--dsw-alias-label-secondary);flex:0 0 auto}
761
+ .dshApi-envBar{display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:12px;flex:0 0 auto;padding:7px 11px;border-radius:8px;background:var(--dsw-alias-bg-layer-2)}
762
+ .dshApi-envIcon{color:#9b59b6;font-size:14px}
763
+ .dshApi-envVars{color:var(--dsw-alias-label-secondary);font-size:10.5px;flex:1 1 auto;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
764
+ .dshApi-envCard{display:flex;flex-direction:column;gap:5px;padding:8px;border-radius:8px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-2)}
765
+ .dshApi-envCardOn{border-color:#9b59b6;box-shadow:inset 3px 0 0 #9b59b6}
766
+ .dshApi-envCardHead{display:flex;align-items:center;gap:6px;cursor:pointer}
767
+ .dshApi-envDot{width:8px;height:8px;border-radius:50%;background:var(--dsw-alias-border-l2);flex:0 0 auto}
768
+ .dshApi-envCardOn .dshApi-envDot{background:#9b59b6}
769
+ .dshApi-envName{flex:1 1 auto;font-weight:600}
770
+ .dshApi-commonBar{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:6px 0}
771
+ .dshApi-commonLabel{font-size:11px;color:var(--dsw-alias-label-secondary)}
772
+ .dshApi-commonBar .dshApi-select{flex:1 1 240px}
773
+ .dshApi-commonPanel{border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-base);padding:8px;margin-bottom:6px}
774
+ .dshApi-commonGrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:4px;max-height:180px;overflow:auto}
775
+ .dshApi-commonItem{display:flex;align-items:center;justify-content:space-between;gap:4px;font-size:11.5px;padding:4px 6px;border-radius:6px;cursor:pointer}
776
+ .dshApi-commonItem:hover{background:var(--dsw-alias-bg-layer-2)}
777
+ .dshApi-commonItemLabel{display:flex;align-items:center;gap:6px;flex:1 1 auto;min-width:0;cursor:pointer}
778
+ .dshApi-commonItem input{accent-color:var(--dsw-alias-brand-primary);flex:0 0 auto}
779
+ .dshApi-commonName{font-weight:600;color:var(--dsw-alias-label-primary);white-space:nowrap}
780
+ .dshApi-commonDesc{color:var(--dsw-alias-label-secondary);font-size:10px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
781
+ .dshApi-commonActions{display:flex;gap:8px;padding-top:8px;margin-top:6px;border-top:1px solid var(--dsw-alias-border-l1)}
782
+ .dshApi-customBar{display:flex;gap:6px;align-items:center;flex-wrap:wrap;padding-top:8px;margin-top:6px;border-top:1px dashed var(--dsw-alias-border-l1)}
783
+ .dshApi-customBar .dshApi-input{flex:1 1 120px}
784
+ .dshApi-saveTarget{display:flex;align-items:center;gap:5px;font-size:11px;padding:4px 7px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-secondary);flex-wrap:wrap}
785
+ .dshApi-saveTargetName{font-weight:600;color:var(--dsw-alias-brand-primary)}
786
+ .dshApi-crumb{border:0;background:transparent;color:var(--dsw-alias-label-secondary);font-size:11px;cursor:pointer;padding:1px 3px;border-radius:4px;font-family:inherit}
787
+ .dshApi-crumb:hover{color:var(--dsw-alias-brand-primary);background:var(--dsw-alias-bg-layer-2)}
788
+ .dshApi-crumbOn{color:var(--dsw-alias-brand-primary);font-weight:600}
789
+ .dshApi-crumbSep{color:var(--dsw-alias-label-secondary);font-size:11px}
790
+ .dshApi-folderBar{display:flex;gap:5px;align-items:center}
791
+ .dshApi-folderBar .dshApi-input{flex:1 1 auto}
792
+ .dshApi-tree{flex:1 1 auto;overflow:auto;min-height:80px}
793
+ .dshApi-search{flex:0 0 auto}
794
+ .dshApi-treeFolder,.dshApi-treeRequest{font-size:12px}
795
+ .dshApi-treeRow{display:flex;align-items:center;gap:5px;padding:4px 6px;border-radius:6px;min-width:0}
796
+ .dshApi-treeRow:hover{background:var(--dsw-alias-bg-layer-2)}
797
+ .dshApi-treeRowOn{outline:1px solid var(--dsw-alias-brand-primary)}
798
+ .dshApi-treeArrow{width:12px;flex:0 0 auto;color:var(--dsw-alias-label-secondary);cursor:pointer;text-align:center}
799
+ .dshApi-folderIco{flex:0 0 auto;font-size:12px}
800
+ .dshApi-treeName{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;cursor:pointer}
801
+ .dshApi-treePick{display:flex;align-items:center;flex:1 1 auto;min-width:0;cursor:pointer}
802
+ .dshApi-treeEdit{flex:1 1 auto;min-width:0;padding:2px 6px;font-size:11.5px}
803
+ @media(max-width:900px){.dshApi-cols{grid-template-columns:1fr;overflow-y:auto}.dshApi-col{overflow:visible}}
804
+ `
805
+ document.head.appendChild(style)
806
+ return () => { style.remove() }
807
+ }
808
+
809
+ return { inject: ['slots', 'locale', 'layout'], apply }
810
+ },
811
+ })
@@ -0,0 +1,4 @@
1
+ # API client bundle: Host half performs HTTP requests; dsh.client renders the UI.
2
+ - insert:
3
+ - id: dsh-tree-new-bee-api-client
4
+ name: dsh-tree-new-bee-api-client
package/icon.svg ADDED
@@ -0,0 +1,24 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
2
+ <!-- 背景圆 -->
3
+ <circle cx="32" cy="32" r="30" fill="#fff3c4"/>
4
+ <!-- 翅膀 -->
5
+ <ellipse cx="20" cy="20" rx="12" ry="7" fill="#dbeafe" stroke="#93c5fd" stroke-width="1.5" transform="rotate(-35 20 20)"/>
6
+ <ellipse cx="44" cy="20" rx="12" ry="7" fill="#dbeafe" stroke="#93c5fd" stroke-width="1.5" transform="rotate(35 44 20)"/>
7
+ <!-- 触角 -->
8
+ <path d="M28 20 Q24 12 20 14 M36 20 Q40 12 44 14" stroke="#3b2f1c" stroke-width="2" fill="none" stroke-linecap="round"/>
9
+ <circle cx="20" cy="14" r="2" fill="#3b2f1c"/>
10
+ <circle cx="44" cy="14" r="2" fill="#3b2f1c"/>
11
+ <!-- 身体(黄黑条纹) -->
12
+ <ellipse cx="32" cy="38" rx="15" ry="18" fill="#ffcc00"/>
13
+ <path d="M20 30 Q32 34 44 30 L44 36 Q32 40 20 36 Z" fill="#2b2b2b"/>
14
+ <path d="M21 43 Q32 47 43 43 L42 49 Q32 52 22 49 Z" fill="#2b2b2b"/>
15
+ <!-- 头部 -->
16
+ <circle cx="32" cy="24" r="9" fill="#2b2b2b"/>
17
+ <!-- 眼睛 -->
18
+ <ellipse cx="28" cy="23" rx="2.5" ry="3" fill="#fff"/>
19
+ <ellipse cx="36" cy="23" rx="2.5" ry="3" fill="#fff"/>
20
+ <circle cx="28" cy="24" r="1.2" fill="#2b2b2b"/>
21
+ <circle cx="36" cy="24" r="1.2" fill="#2b2b2b"/>
22
+ <!-- 尾针 -->
23
+ <path d="M32 55 l0 5" stroke="#2b2b2b" stroke-width="2.5" stroke-linecap="round"/>
24
+ </svg>
package/index.js ADDED
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Host half of the API client bundle.
3
+ * Performs HTTP requests with Node's built-in fetch. No third-party deps.
4
+ */
5
+ export const name = 'dsh-tree-new-bee-api-client'
6
+ export const inject = ['connection']
7
+
8
+ const API = '/api/dsh-tree-new-bee-api-client'
9
+ const DEFAULT_TIMEOUT = 20000
10
+ const MAX_TIMEOUT = 120000
11
+ const MAX_BODY = 4 * 1024 * 1024
12
+
13
+ class ApiError extends Error {
14
+ constructor(message, status = 400) { super(message); this.status = status }
15
+ }
16
+ function json(value, status = 200) {
17
+ return Response.json(value, { status, headers: { 'cache-control': 'no-store' } })
18
+ }
19
+ function failure(error, fallback) {
20
+ const message = error instanceof ApiError ? error.message : fallback
21
+ const status = error instanceof ApiError ? error.status : 500
22
+ return json({ error: message }, status)
23
+ }
24
+ function route(path, methods, fetch) {
25
+ return { path: `${API}/${path}`, methods, requestBody: 'buffered', fetch }
26
+ }
27
+ async function readBody(request) {
28
+ try { return JSON.parse((await request.text()) || '{}') }
29
+ catch (_) { throw new ApiError('请求内容不是合法的 JSON。') }
30
+ }
31
+
32
+ export function apply(ctx) {
33
+ ctx.effect(() => {
34
+ const disposers = []
35
+ const register = (entry) => {
36
+ try {
37
+ const dispose = ctx.connection.fetch.register(entry)
38
+ if (typeof dispose === 'function') disposers.push(dispose)
39
+ } catch (error) {
40
+ console.warn(`[dsh-tree-new-bee-api-client] route ${entry.path} rejected: ${(error && error.message) || error}`)
41
+ }
42
+ }
43
+
44
+ register(route('request', ['POST'], async (request) => {
45
+ const started = Date.now()
46
+ try {
47
+ const body = await readBody(request)
48
+ const method = String(body.method || 'GET').toUpperCase()
49
+ const url = typeof body.url === 'string' ? body.url.trim() : ''
50
+ if (!url) throw new ApiError('请输入请求地址。')
51
+ if (!/^https?:\/\//i.test(url)) throw new ApiError('地址必须以 http:// 或 https:// 开头。')
52
+ const timeout = Math.min(MAX_TIMEOUT, Math.max(1000, Number(body.timeout) || DEFAULT_TIMEOUT))
53
+ const controller = new AbortController()
54
+ const timer = setTimeout(() => controller.abort(), timeout)
55
+ const headers = {}
56
+ if (body.headers && typeof body.headers === 'object') {
57
+ for (const [k, v] of Object.entries(body.headers)) {
58
+ if (k && v !== undefined && v !== null && String(v).trim()) headers[String(k)] = String(v)
59
+ }
60
+ }
61
+ const init = { method, headers, signal: controller.signal, redirect: 'follow' }
62
+ if (!['GET', 'HEAD'].includes(method) && body.body && String(body.body).length) {
63
+ init.body = String(body.body)
64
+ }
65
+ let res
66
+ try { res = await fetch(url, init) }
67
+ finally { clearTimeout(timer) }
68
+ const text = await res.text()
69
+ const truncated = text.length > MAX_BODY
70
+ const responseHeaders = {}
71
+ try { res.headers.forEach((v, k) => { responseHeaders[k] = v }) } catch (_) {}
72
+ return json({
73
+ ok: res.ok,
74
+ status: res.status,
75
+ statusText: res.statusText || '',
76
+ headers: responseHeaders,
77
+ body: truncated ? text.slice(0, MAX_BODY) : text,
78
+ truncated,
79
+ timeMs: Date.now() - started,
80
+ size: text.length,
81
+ url: res.url || url,
82
+ })
83
+ } catch (error) {
84
+ let message = error && error.message ? error.message : String(error)
85
+ if (/abort/i.test(message)) message = '请求超时。'
86
+ return json({ error: message, timeMs: Date.now() - started }, 502)
87
+ }
88
+ }))
89
+
90
+ return () => {
91
+ for (const dispose of disposers) {
92
+ try {
93
+ const result = dispose()
94
+ if (result && typeof result.then === 'function') result.catch(() => {})
95
+ } catch (_) {}
96
+ }
97
+ }
98
+ }, 'dsh-tree-new-bee-api-client: routes')
99
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Tree New Bee API Client",
4
+ "description": "Postman-style HTTP client with collections, environments and history."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Tree New Bee 接口请求",
4
+ "description": "在左侧栏打开 Tree New Bee 接口请求,支持请求构造、集合、环境与历史。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "@oakzhong/dsh-tree-new-bee-api-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "private": false,
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "type": "module",
9
+ "description": "A Postman-style API request client with collections and history.",
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
+ }