dsh-postapi 0.0.0-stage → 0.0.2

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.
Files changed (75) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +139 -2
  3. package/cordis.patch.yml +3 -0
  4. package/dist/client.js +5651 -0
  5. package/docs/DETAIL.md +27 -0
  6. package/docs/apifox-design-spec.md +101 -0
  7. package/docs/apifox-research/analysis.md +254 -0
  8. package/docs/apifox-ui-delivery.md +150 -0
  9. package/docs/apifox-visual-parity-spec.md +353 -0
  10. package/docs/feature-matrix.md +112 -0
  11. package/docs/flow-reference/sequence-reference.html +163 -0
  12. package/docs/interface-contract-v2.md +175 -0
  13. package/docs/interface-contract.md +105 -0
  14. package/docs/nav-layout-v2-spec.md +107 -0
  15. package/docs/preview.svg +9 -0
  16. package/docs/probe-client.legacy.js +31 -0
  17. package/docs/rootcause-sidebar-vanish.md +95 -0
  18. package/docs/rootcause.md +86 -0
  19. package/docs/sidebar-notes.md +153 -0
  20. package/docs/ui-audit.md +197 -0
  21. package/docs/ui-notes.md +98 -0
  22. package/docs/v2-delivery.md +99 -0
  23. package/icon.svg +4 -0
  24. package/index.js +5 -0
  25. package/locale/en.json +7 -0
  26. package/locale/zh.json +7 -0
  27. package/package.json +73 -4
  28. package/src/client/index.js +132 -0
  29. package/src/client/jsx-shim.js +9 -0
  30. package/src/client/pages/__tests__/heights.test.js +135 -0
  31. package/src/client/pages/components/AssertTable.jsx +122 -0
  32. package/src/client/pages/components/BodyEditor.jsx +91 -0
  33. package/src/client/pages/components/EmptyState.jsx +52 -0
  34. package/src/client/pages/components/FolderTree.jsx +109 -0
  35. package/src/client/pages/components/JsonEditor.jsx +45 -0
  36. package/src/client/pages/components/ParamTable.jsx +226 -0
  37. package/src/client/pages/components/ResponsePanel.jsx +278 -0
  38. package/src/client/pages/components/ScriptPanel.jsx +99 -0
  39. package/src/client/pages/components/StatusPill.jsx +35 -0
  40. package/src/client/pages/components/__tests__/apifox-ui.test.js +291 -0
  41. package/src/client/pages/components/__tests__/pages-a.test.js +392 -0
  42. package/src/client/pages/components/__tests__/tree.test.js +379 -0
  43. package/src/client/pages/components/headerPresets.js +63 -0
  44. package/src/client/pages/debug.jsx +576 -0
  45. package/src/client/pages/design-tokens.css +2604 -0
  46. package/src/client/pages/doc.jsx +552 -0
  47. package/src/client/pages/env.jsx +378 -0
  48. package/src/client/pages/flow.jsx +349 -0
  49. package/src/client/pages/history.jsx +238 -0
  50. package/src/client/pages/import.jsx +396 -0
  51. package/src/client/pages/mock.jsx +316 -0
  52. package/src/client/pages/overview.jsx +348 -0
  53. package/src/client/pages/schema.jsx +317 -0
  54. package/src/client/pages/search.jsx +216 -0
  55. package/src/client/pages/sequence.jsx +344 -0
  56. package/src/client/pages/settings.jsx +205 -0
  57. package/src/client/pages/test.jsx +470 -0
  58. package/src/client/pages/theme.js +27 -0
  59. package/src/client/pages-entry.js +20 -0
  60. package/src/client/shell/ApiTitle.js +19 -0
  61. package/src/client/shell/Body.js +492 -0
  62. package/src/client/shell/definition.js +57 -0
  63. package/src/client/shell/locales.js +185 -0
  64. package/src/client/shell/menu.js +174 -0
  65. package/src/client/shell/registry.js +530 -0
  66. package/src/host/bridge.js +407 -0
  67. package/src/host/codegen.js +356 -0
  68. package/src/host/import-export.js +1044 -0
  69. package/src/host/index.js +102 -0
  70. package/src/host/mock-server.js +303 -0
  71. package/src/host/request.js +336 -0
  72. package/src/host/script-sandbox.js +272 -0
  73. package/src/host/storage.js +803 -0
  74. package/src/host/test-runner.js +126 -0
  75. package/src/host/variables.js +108 -0
@@ -0,0 +1,109 @@
1
+ // FolderTree — 多级分组树(递归渲染 project.folders 的 parentId 层级)
2
+ // 观感对齐 Apifox 左侧目录树(spec §12.3),供 doc / debug / schema 页共用。
3
+ // 纪律:类名只用 design-tokens.css 既有 .pp-tree / .pp-tree-row / .pp-tree-group / .pp-tree-row-count /
4
+ // .pp-tree-switcher / .pp-tree-icon / .pp-method / .pp-ellipsis / .pp-empty;
5
+ // 颜色/字号/高度全部由 CSS 承载,内联样式只放缩进(layout)。
6
+ // 不引图标库:展开箭头用 ▸ / ▾ 文本,目录图标用 ▦ 文本。
7
+ // 行内顺序(Apifox 实测,docs/apifox-visual-parity-spec.md §4 §12.3):
8
+ // 目录行 switcher → icon → 名称 → 计数;接口行 方法徽标 → 名称(无 switcher / icon,靠 paddingLeft 负补偿对齐)。
9
+ // 数据契约(契约 §2):folders[{ id, name, parentId, order }],endpoints[{ id, name, method, folderId, order }]。
10
+ import { EmptyState } from './EmptyState.jsx'
11
+
12
+ /** 缩进步长:0 层沿用 .pp-tree-row 自带内边距,深层按 calc(var(--sp-1) * depth) 累加(纯 layout)。 */
13
+ const INDENT_STEP = 'var(--sp-1)'
14
+
15
+ /** 目录行缩进:depth 级目录各占一个步长。 */
16
+ function indentStyle(depth) {
17
+ if (!depth) return undefined
18
+ return { paddingLeft: 'calc(' + INDENT_STEP + ' * ' + depth + ')' }
19
+ }
20
+
21
+ /**
22
+ * 接口行缩进:接口行没有 switcher + icon(那两格共 20px + 两个 4px gap = 28px 占位带),
23
+ * 方法徽标 .pp-method 的 min-width 44px 恰好顶住这格占位带,所以接口行比同层目录行少一个步长,
24
+ * 否则接口名会随层级累积右移、与目录名错位。depth 参数仍是「所在层级」(≥1),
25
+ * 用 calc(... - var(--sp-1)) 表达负补偿,不额外引入 state。
26
+ */
27
+ function endpointIndentStyle(depth) {
28
+ if (!depth) return undefined
29
+ return { paddingLeft: 'calc(' + INDENT_STEP + ' * ' + depth + ' - ' + INDENT_STEP + ')' }
30
+ }
31
+
32
+ /** order 升序;缺省按 0(sort 稳定,同序保持入参顺序)。 */
33
+ function byOrder(a, b) {
34
+ return (Number(a && a.order) || 0) - (Number(b && b.order) || 0)
35
+ }
36
+
37
+ export function FolderTree({ project, activeEndpointId, onPick, onToggle, collapsed, readOnly = false }) {
38
+ const folders = (Array.isArray(project && project.folders) ? project.folders : []).filter(Boolean)
39
+ const endpoints = (Array.isArray(project && project.endpoints) ? project.endpoints : []).filter(Boolean)
40
+ const collapsedMap = collapsed && typeof collapsed === 'object' ? collapsed : {}
41
+ // 悬挂 folderId(目录已删/导入残留)同样收进「未归类」,避免接口凭空消失。
42
+ const folderIds = new Set(folders.map((f) => f.id))
43
+
44
+ const pick = (endpointId) => {
45
+ if (readOnly || typeof onPick !== 'function') return
46
+ onPick(endpointId)
47
+ }
48
+ const toggle = (folderId) => {
49
+ if (typeof onToggle !== 'function') return
50
+ onToggle(folderId)
51
+ }
52
+
53
+ const renderEndpoint = (ep, depth) => (
54
+ <div
55
+ key={ep.id}
56
+ className="pp-tree-row"
57
+ data-active={Boolean(activeEndpointId) && ep.id === activeEndpointId}
58
+ onClick={() => pick(ep.id)}
59
+ style={endpointIndentStyle(depth)}
60
+ >
61
+ <span className="pp-method" data-method={ep.method}>{ep.method}</span>
62
+ <span className="pp-ellipsis">{ep.name || '未命名接口'}</span>
63
+ </div>
64
+ )
65
+
66
+ /**
67
+ * 递归渲染一个目录:目录行 → (未折叠时)子目录 → 属于本目录的接口行。
68
+ * 规模假设:单项目目录/接口数百级,直接 filter 比预建索引更短;上万级再改 Map。
69
+ */
70
+ const renderFolder = (folder, depth) => {
71
+ const children = folders.filter((f) => f.parentId === folder.id).sort(byOrder)
72
+ const own = endpoints.filter((e) => e.folderId === folder.id).sort(byOrder)
73
+ const isCollapsed = Boolean(collapsedMap[folder.id])
74
+ return (
75
+ <div key={folder.id}>
76
+ <div className="pp-tree-row" style={indentStyle(depth)} onClick={() => toggle(folder.id)}>
77
+ <span className="pp-tree-switcher">{isCollapsed ? '▸' : '▾'}</span>
78
+ <span className="pp-tree-icon">▦</span>
79
+ <span className="pp-ellipsis">{folder.name || '未命名目录'}</span>
80
+ <span className="pp-tree-row-count">{own.length}</span>
81
+ </div>
82
+ {isCollapsed ? null : (
83
+ <>
84
+ {children.map((child) => renderFolder(child, depth + 1))}
85
+ {own.map((ep) => renderEndpoint(ep, depth + 1))}
86
+ </>
87
+ )}
88
+ </div>
89
+ )
90
+ }
91
+
92
+ const topFolders = folders.filter((f) => f.parentId == null || f.parentId === '').sort(byOrder)
93
+ const loose = endpoints.filter((e) => e.folderId == null || e.folderId === '' || !folderIds.has(e.folderId)).sort(byOrder)
94
+ const isEmpty = folders.length === 0 && endpoints.length === 0
95
+
96
+ return (
97
+ <div className="pp-tree">
98
+ <div className="pp-tree-group">{(project && project.name) || '未命名项目'}</div>
99
+ {topFolders.map((folder) => renderFolder(folder, 0))}
100
+ {loose.length > 0 ? (
101
+ <div>
102
+ <div className="pp-tree-group">未归类</div>
103
+ {loose.map((ep) => renderEndpoint(ep, 0))}
104
+ </div>
105
+ ) : null}
106
+ {isEmpty ? <EmptyState icon={null} text="暂无目录与接口" /> : null}
107
+ </div>
108
+ )
109
+ }
@@ -0,0 +1,45 @@
1
+ // JsonEditor — 轻量 JSON 文本编辑(.pp-json-editor 文本域 + 格式化/压缩 + 行内校验提示,不引 Monaco)
2
+ // 只读态用于 doc 页展示请求体/响应示例;可编辑态用于 debug 页 Body 页签。
3
+ // 尺寸与配色全部来自 .pp-json-editor(token 承载),内联样式只放 layout。
4
+ import { useState } from 'react'
5
+
6
+ export function JsonEditor({ value = '', onChange, readOnly = false, rows = 8, placeholder = '{}' }) {
7
+ const [error, setError] = useState('')
8
+ const text = value == null ? '' : String(value)
9
+
10
+ const transform = (fn, label) => {
11
+ try {
12
+ const next = fn(JSON.parse(text))
13
+ setError('')
14
+ if (typeof onChange === 'function') onChange(next)
15
+ } catch (err) {
16
+ setError(label + '失败:' + (err && err.message ? err.message : String(err)))
17
+ }
18
+ }
19
+
20
+ return (
21
+ <div>
22
+ {readOnly ? null : (
23
+ <div className="pp-toolbar-inline" style={{ marginBottom: 'var(--sp-2)' }}>
24
+ <button className="pp-btn pp-btn-sm" onClick={() => transform((v) => JSON.stringify(v, null, 2), '格式化')}>
25
+ 格式化
26
+ </button>
27
+ <button className="pp-btn pp-btn-sm" onClick={() => transform((v) => JSON.stringify(v), '压缩')}>
28
+ 压缩
29
+ </button>
30
+ </div>
31
+ )}
32
+ <textarea
33
+ className="pp-json-editor"
34
+ rows={rows}
35
+ readOnly={readOnly}
36
+ placeholder={placeholder}
37
+ value={text}
38
+ onChange={(e) => {
39
+ if (typeof onChange === 'function') onChange(e.target.value)
40
+ }}
41
+ />
42
+ {error ? <p className="pp-error-text">{error}</p> : null}
43
+ </div>
44
+ )
45
+ }
@@ -0,0 +1,226 @@
1
+ // ParamTable — 参数表(doc 页只读展示 / debug 页可编辑,四组参数共用一套列定义)
2
+ // Apifox 规格:固定列宽 + table-layout:fixed,横向滚动由调用方的 .pp-table-wrap 承担,
3
+ // 窄容器里是整体滚动而不是列被压塌;单元格内编辑用无边框 .pp-cell-input,聚焦才显边框。
4
+ // 可选 suggest(query => [{ key, value, description }]):key 列挂 <datalist> 常用建议,
5
+ // 选中建议时把该条的 value / description 回填到本行空字段;suggest 缺省时渲染与原行为完全一致。
6
+ import { useState } from 'react'
7
+ import { EmptyState } from './EmptyState.jsx'
8
+
9
+ /** 列定义:width 写死(description 吃剩余宽度,最小 160px 由 design-tokens.css 表格段兜住)。 */
10
+ export const COLUMN_META = {
11
+ enabled: { title: '启用', width: '44px' },
12
+ key: { title: '参数', width: '150px', mono: true },
13
+ type: { title: '类型', width: '96px' },
14
+ required: { title: '必填', width: '52px' },
15
+ value: { title: '示例值', width: '140px', mono: true },
16
+ description: { title: '描述', width: 'auto' },
17
+ }
18
+
19
+ /** 参数类型选项(Apifox 同一套)。 */
20
+ export const PARAM_TYPES = ['string', 'integer', 'number', 'boolean', 'array', 'object']
21
+
22
+ /** 参数表默认列:debug 页与 doc 页共用;操作列由组件按可编辑态追加,不计入 columns。 */
23
+ export const DEFAULT_COLUMNS = ['enabled', 'key', 'type', 'required', 'value', 'description']
24
+
25
+ /** 新增行模板(契约 §2 endpoint.params 行结构)。 */
26
+ export function blankParamRow() {
27
+ return { key: '', value: '', enabled: true, type: 'string', required: false, description: '' }
28
+ }
29
+
30
+ /** description 列吃剩余宽度,最小 160px(fixed 布局下由 min-width 兜住)。 */
31
+ const DESC_MIN_WIDTH = 120
32
+ const OP_WIDTH = 52
33
+
34
+ /* ---------------- 常用建议(suggest)辅助 ---------------- */
35
+
36
+ /** datalist id 自增序号:每张表一个稳定唯一 id。用模块级计数器而不是随机数——
37
+ * 随机数会让每次渲染 id 变化,input 的 list 关联随之失效。 */
38
+ let suggestSeq = 0
39
+
40
+ function nextSuggestId() {
41
+ suggestSeq += 1
42
+ return 'pp-param-suggest-' + suggestSeq
43
+ }
44
+
45
+ /** 空值判定:null / undefined / 空串都算「用户还没填」。 */
46
+ function isBlank(v) {
47
+ return v == null || v === ''
48
+ }
49
+
50
+ /** 取建议清单:suggest 缺省、返回非数组或抛错一律按「无建议」处理,
51
+ * 建议源有问题也不能把表格本身带崩。 */
52
+ function collectSuggestions(suggest, query) {
53
+ if (typeof suggest !== 'function') return []
54
+ try {
55
+ const items = suggest(query)
56
+ if (!Array.isArray(items)) return []
57
+ return items.filter((it) => it && !isBlank(it.key))
58
+ } catch {
59
+ return []
60
+ }
61
+ }
62
+
63
+ function headStyle(col) {
64
+ const meta = COLUMN_META[col]
65
+ return meta && meta.width && meta.width !== 'auto' ? { width: meta.width } : undefined
66
+ }
67
+
68
+ /** 列宽合计 = 表格最小宽度:窄容器里整表横向滚动,列不被压缩。 */
69
+ export function tableMinWidth(columns, editable) {
70
+ let total = editable ? OP_WIDTH : 0
71
+ for (const col of columns) {
72
+ const meta = COLUMN_META[col]
73
+ total += meta && meta.width && meta.width !== 'auto' ? parseInt(meta.width, 10) : DESC_MIN_WIDTH
74
+ }
75
+ return total
76
+ }
77
+
78
+ function renderCell(col, row, index, editable, patch, ctx) {
79
+ const meta = COLUMN_META[col] || {}
80
+ const value = row ? row[col] : undefined
81
+
82
+ if (col === 'enabled' || col === 'required') {
83
+ if (!editable) return value ? '是' : '否'
84
+ return (
85
+ <input
86
+ type="checkbox"
87
+ checked={Boolean(value)}
88
+ onChange={(e) => patch(index, col, e.target.checked)}
89
+ />
90
+ )
91
+ }
92
+ if (!editable) {
93
+ // 只读态与可编辑态口径一致:type 空值按 string 展示(Apifox 从不显示裸 '-'),其它列仍用 '-'。
94
+ const blank = value == null || value === ''
95
+ const text = blank ? (col === 'type' ? 'string' : '-') : String(value)
96
+ return <span className={meta.mono ? 'pp-table-mono' : undefined}>{text}</span>
97
+ }
98
+ if (col === 'key' && ctx) {
99
+ // key 列挂 datalist:浏览器原生下拉列出常用建议,选中后由 ctx.onKeyChange 回填。
100
+ return (
101
+ <input
102
+ className={'pp-cell-input pp-input-sm' + (meta.mono ? ' pp-input-mono' : '')}
103
+ list={ctx.suggestId}
104
+ value={value == null ? '' : String(value)}
105
+ onChange={(e) => ctx.onKeyChange(index, e.target.value)}
106
+ />
107
+ )
108
+ }
109
+ if (col === 'type') {
110
+ return (
111
+ <select
112
+ className="pp-cell-input pp-input-sm"
113
+ value={value || 'string'}
114
+ onChange={(e) => patch(index, col, e.target.value)}
115
+ >
116
+ {PARAM_TYPES.map((t) => <option key={t} value={t}>{t}</option>)}
117
+ </select>
118
+ )
119
+ }
120
+ return (
121
+ <input
122
+ className={'pp-cell-input pp-input-sm' + (meta.mono ? ' pp-input-mono' : '')}
123
+ value={value == null ? '' : String(value)}
124
+ onChange={(e) => patch(index, col, e.target.value)}
125
+ />
126
+ )
127
+ }
128
+
129
+ export function ParamTable({
130
+ rows,
131
+ onChange,
132
+ readOnly = false,
133
+ columns = DEFAULT_COLUMNS,
134
+ emptyText = '无',
135
+ emptyHint = '',
136
+ addLabel = '+ 添加参数',
137
+ suggest,
138
+ }) {
139
+ const list = Array.isArray(rows) ? rows : []
140
+ const editable = !readOnly && typeof onChange === 'function'
141
+ const hasSuggest = editable && typeof suggest === 'function'
142
+ // 每张表一个稳定 datalist id:首次渲染定下来,后续渲染不变(useState 惰性初始化)。
143
+ const [suggestId] = useState(nextSuggestId)
144
+
145
+ /** 单字段或整行补丁:value 传对象时按多字段合并。 */
146
+ const patch = (index, field, value) => {
147
+ const next = list.slice()
148
+ const fields = field && typeof field === 'object' ? field : { [field]: value }
149
+ next[index] = { ...next[index], ...fields }
150
+ onChange(next)
151
+ }
152
+
153
+ /**
154
+ * key 列输入:先写 key;若输入值恰好等于某条建议的 key,则把该条的 value / description
155
+ * 一并回填——只填空字段,用户已经填过的内容一律保留。
156
+ */
157
+ const onKeyChange = (index, value) => {
158
+ const row = list[index] || {}
159
+ const hit = collectSuggestions(suggest, value).find((it) => it.key === value)
160
+ if (!hit) {
161
+ patch(index, 'key', value)
162
+ return
163
+ }
164
+ const fill = { key: value }
165
+ if (isBlank(row.value) && !isBlank(hit.value)) fill.value = hit.value
166
+ if (isBlank(row.description) && !isBlank(hit.description)) fill.description = hit.description
167
+ patch(index, fill)
168
+ }
169
+
170
+ const cellCtx = hasSuggest ? { suggestId, onKeyChange } : undefined
171
+ const remove = (index) => {
172
+ const next = list.slice()
173
+ next.splice(index, 1)
174
+ onChange(next)
175
+ }
176
+
177
+ if (list.length === 0 && !editable) return <EmptyState text={emptyText} hint={emptyHint} />
178
+
179
+ // datalist:option 的 value 是建议 key,label 用 description(浏览器下拉里显示为副标题)。
180
+ const datalist = hasSuggest
181
+ ? <datalist id={suggestId}>
182
+ {collectSuggestions(suggest, '').map((it, i) => (
183
+ <option key={it.key + '-' + i} value={it.key} label={it.description || undefined} />
184
+ ))}
185
+ </datalist>
186
+ : null
187
+
188
+ return (
189
+ <table className="pp-table pp-table-params" data-param-table style={{ minWidth: tableMinWidth(columns, editable) }}>
190
+ <thead>
191
+ <tr>
192
+ {columns.map((col) => (
193
+ <th key={col} data-col={col} style={headStyle(col)}>
194
+ {COLUMN_META[col] ? COLUMN_META[col].title : col}
195
+ </th>
196
+ ))}
197
+ {editable ? <th data-col="op" style={{ width: OP_WIDTH }}>操作</th> : null}
198
+ </tr>
199
+ </thead>
200
+ <tbody>
201
+ {list.map((row, index) => (
202
+ <tr key={index}>
203
+ {columns.map((col) => (
204
+ <td key={col} data-col={col}>{renderCell(col, row, index, editable, patch, cellCtx)}</td>
205
+ ))}
206
+ {editable ? (
207
+ <td data-col="op">
208
+ <button className="pp-btn pp-btn-sm pp-btn-ghost pp-btn-danger" onClick={() => remove(index)}>删除</button>
209
+ </td>
210
+ ) : null}
211
+ </tr>
212
+ ))}
213
+ {editable ? (
214
+ <tr>
215
+ <td colSpan={columns.length + 1}>
216
+ <button className="pp-btn pp-btn-sm pp-btn-ghost pp-table-add" onClick={() => onChange(list.concat([blankParamRow()]))}>
217
+ {addLabel}
218
+ </button>
219
+ </td>
220
+ </tr>
221
+ ) : null}
222
+ </tbody>
223
+ {datalist}
224
+ </table>
225
+ )
226
+ }
@@ -0,0 +1,278 @@
1
+ // ResponsePanel — 响应面板(Apifox 六页签:Body / Headers / Cookies / 实际请求 / 测试结果 / 控制台)
2
+ // resp 结构严格对齐 host request.send 返回值:
3
+ // { status, statusText, headers, body, bodySize, timeMs, truncated?, error?,
4
+ // request?: { method, url, headers, body }, tests?: [{ name, passed, error? }],
5
+ // variables?, logs? }
6
+ // 纪律:类名只用 design-tokens.css 已定义的 .pp-*;颜色/字号/间距一律走 var(--*);
7
+ // 复制失败只在页面内 .pp-note-bad 提示,不弹窗。
8
+ import { useState } from 'react'
9
+ import { EmptyState } from './EmptyState.jsx'
10
+ import { ParamTable } from './ParamTable.jsx'
11
+ import { StatusPill } from './StatusPill.jsx'
12
+
13
+ /** 六个页签,顺序即 Apifox 顺序。 */
14
+ export const RESPONSE_TABS = [
15
+ { id: 'body', label: 'Body' },
16
+ { id: 'headers', label: 'Headers' },
17
+ { id: 'cookies', label: 'Cookies' },
18
+ { id: 'request', label: '实际请求' },
19
+ { id: 'tests', label: '测试结果' },
20
+ { id: 'logs', label: '控制台' },
21
+ ]
22
+
23
+ /** 只有这两个页签的标题后面挂数量徽标(Apifox 同款)。 */
24
+ export const COUNTED_TABS = ['headers', 'tests']
25
+
26
+ /** 页签标题:Headers / 测试结果 带计数,如「Headers (8)」。 */
27
+ export function tabTitle(tab, counts) {
28
+ const n = counts ? counts[tab.id] : undefined
29
+ const counted = COUNTED_TABS.indexOf(tab.id) > -1 && typeof n === 'number'
30
+ return counted ? tab.label + ' (' + n + ')' : tab.label
31
+ }
32
+
33
+ /** 任意值转展示文本:数组逐行(set-cookie 多值),对象 JSON,其余 String。 */
34
+ function textOf(v) {
35
+ if (v == null) return ''
36
+ if (Array.isArray(v)) return v.map(textOf).filter((s) => s !== '').join('\n')
37
+ if (typeof v === 'object') {
38
+ try {
39
+ return JSON.stringify(v)
40
+ } catch {
41
+ return String(v)
42
+ }
43
+ }
44
+ return String(v)
45
+ }
46
+
47
+ /** 响应体原文。 */
48
+ export function bodyText(body) {
49
+ return body == null ? '' : textOf(body)
50
+ }
51
+
52
+ /** 美化:JSON 解析成功则缩进两格,失败(或空体)回落原文。 */
53
+ export function prettyBody(body) {
54
+ const text = bodyText(body)
55
+ if (!text) return ''
56
+ try {
57
+ return JSON.stringify(JSON.parse(text), null, 2)
58
+ } catch {
59
+ return text
60
+ }
61
+ }
62
+
63
+ /** 响应头/请求头对象 → ParamTable 行(值可能是数组,逐行展示)。 */
64
+ export function headersToRows(headers) {
65
+ if (!headers || typeof headers !== 'object') return []
66
+ const keys = Array.isArray(headers) ? headers.map((_, i) => String(i)) : Object.keys(headers)
67
+ return keys.map((key) => ({ key, value: textOf(headers[key]) }))
68
+ }
69
+
70
+ /**
71
+ * 从响应头里拆 set-cookie:键名大小写不敏感,值支持字符串或数组,
72
+ * 每条按 ';' 拆成 name=value 与属性串。
73
+ */
74
+ export function parseSetCookies(headers) {
75
+ const raw = []
76
+ if (headers && typeof headers === 'object') {
77
+ for (const key of Object.keys(headers)) {
78
+ if (key.toLowerCase() !== 'set-cookie') continue
79
+ const value = headers[key]
80
+ if (Array.isArray(value)) raw.push(...value.map(textOf))
81
+ else if (value != null) raw.push(textOf(value))
82
+ }
83
+ }
84
+ const rows = []
85
+ for (const item of raw) {
86
+ // 数组值可能已被 join 成多行,逐行再拆
87
+ for (const line of String(item).split('\n')) {
88
+ const seg = line.trim()
89
+ if (!seg) continue
90
+ const pieces = seg.split(';').map((s) => s.trim()).filter((s) => s !== '')
91
+ const head = pieces.shift() || ''
92
+ const eq = head.indexOf('=')
93
+ rows.push({
94
+ name: eq >= 0 ? head.slice(0, eq).trim() : head,
95
+ value: eq >= 0 ? head.slice(eq + 1).trim() : '',
96
+ attrs: pieces.join('; '),
97
+ })
98
+ }
99
+ }
100
+ return rows
101
+ }
102
+
103
+ /** 控制台日志:数组逐行,空行丢弃。 */
104
+ export function logsText(logs) {
105
+ if (Array.isArray(logs)) return logs.map(textOf).filter((s) => s !== '').join('\n')
106
+ return logs == null ? '' : textOf(logs)
107
+ }
108
+
109
+ function errText(err) {
110
+ if (err == null) return ''
111
+ if (typeof err === 'object' && err.message) return String(err.message)
112
+ return String(err)
113
+ }
114
+
115
+ /** Cookies 三列表头(列宽写死,值/属性吃剩余宽度)。 */
116
+ const COOKIE_COLS = [
117
+ { title: '名称', width: '180px' },
118
+ { title: '值', width: '' },
119
+ { title: '属性', width: '' },
120
+ ]
121
+
122
+ export function ResponsePanel({ resp, sending = false, onCancel }) {
123
+ const [tab, setTab] = useState('body')
124
+ const [bodyView, setBodyView] = useState('pretty')
125
+ const [copyError, setCopyError] = useState('')
126
+
127
+ /** 复制响应体:只走 navigator.clipboard,失败写页面内提示(不弹窗)。 */
128
+ const copyBody = () => {
129
+ const clip = typeof navigator === 'undefined' || !navigator ? null : navigator.clipboard
130
+ if (!clip || typeof clip.writeText !== 'function') {
131
+ setCopyError('复制失败:当前环境不支持剪贴板')
132
+ return
133
+ }
134
+ try {
135
+ const result = clip.writeText(bodyText(resp ? resp.body : ''))
136
+ if (result && typeof result.then === 'function') {
137
+ result.then(() => setCopyError('')).catch((err) => setCopyError('复制失败:' + errText(err)))
138
+ } else {
139
+ setCopyError('')
140
+ }
141
+ } catch (err) {
142
+ setCopyError('复制失败:' + errText(err))
143
+ }
144
+ }
145
+
146
+ const sendingBar = sending ? (
147
+ <div className="pp-resp-bar">
148
+ <span className="pp-pill pp-pill-accent">发送中…</span>
149
+ <button className="pp-btn pp-btn-sm" onClick={() => { if (typeof onCancel === 'function') onCancel() }}>取消</button>
150
+ </div>
151
+ ) : null
152
+
153
+ if (!resp) {
154
+ return (
155
+ <div data-response-panel="">
156
+ {sendingBar}
157
+ {sending ? null : <EmptyState text="尚未发送请求" hint="填写 URL 后点「发送」" />}
158
+ </div>
159
+ )
160
+ }
161
+
162
+ const headerRows = headersToRows(resp.headers)
163
+ const cookieRows = parseSetCookies(resp.headers)
164
+ const testItems = Array.isArray(resp.tests) ? resp.tests : []
165
+ const logText = logsText(resp.logs)
166
+ const req = resp.request && typeof resp.request === 'object' ? resp.request : null
167
+ const counts = { headers: headerRows.length, tests: testItems.length }
168
+ const errorMsg = resp.error ? errText(resp.error) : ''
169
+
170
+ const statusBar = (
171
+ <div className="pp-resp-bar">
172
+ <StatusPill status={resp.status} text={resp.statusText || ''} />
173
+ <span className="pp-meta">{resp.timeMs == null ? '-' : resp.timeMs} ms</span>
174
+ <span className="pp-meta">{resp.bodySize == null ? '-' : resp.bodySize} B</span>
175
+ {resp.truncated ? <span className="pp-pill pp-pill-warn">已截断</span> : null}
176
+ <button className="pp-btn pp-btn-sm" onClick={copyBody}>复制</button>
177
+ </div>
178
+ )
179
+
180
+ let tabBody = null
181
+ if (tab === 'body') {
182
+ tabBody = (
183
+ <div>
184
+ <div className="pp-tabs">
185
+ <button className="pp-tab" data-active={bodyView === 'pretty'} onClick={() => setBodyView('pretty')}>美化</button>
186
+ <button className="pp-tab" data-active={bodyView === 'raw'} onClick={() => setBodyView('raw')}>原文</button>
187
+ </div>
188
+ <pre className="pp-pre pp-pre-scroll" style={{ marginTop: 'var(--sp-2)' }}>
189
+ {bodyView === 'pretty' ? prettyBody(resp.body) : bodyText(resp.body)}
190
+ </pre>
191
+ </div>
192
+ )
193
+ } else if (tab === 'headers') {
194
+ tabBody = (
195
+ <div className="pp-table-wrap">
196
+ <ParamTable rows={headerRows} readOnly columns={['key', 'value']} emptyText="无响应头" />
197
+ </div>
198
+ )
199
+ } else if (tab === 'cookies') {
200
+ tabBody = cookieRows.length === 0 ? <EmptyState text="无 Cookies" /> : (
201
+ <div className="pp-table-wrap">
202
+ <table className="pp-table">
203
+ <thead>
204
+ <tr>
205
+ {COOKIE_COLS.map((col) => (
206
+ <th key={col.title} style={col.width ? { width: col.width } : undefined}>{col.title}</th>
207
+ ))}
208
+ </tr>
209
+ </thead>
210
+ <tbody>
211
+ {cookieRows.map((row, i) => (
212
+ <tr key={i}>
213
+ <td className="pp-table-mono">{row.name || '-'}</td>
214
+ <td className="pp-table-mono">{row.value || '-'}</td>
215
+ <td className="pp-muted">{row.attrs || '-'}</td>
216
+ </tr>
217
+ ))}
218
+ </tbody>
219
+ </table>
220
+ </div>
221
+ )
222
+ } else if (tab === 'request') {
223
+ tabBody = req ? (
224
+ <div>
225
+ <div className="pp-toolbar-inline">
226
+ <span className="pp-method" data-method={String(req.method || 'GET').toUpperCase()}>
227
+ {String(req.method || 'GET').toUpperCase()}
228
+ </span>
229
+ <span className="pp-mono pp-ellipsis" title={req.url || ''}>{req.url || '-'}</span>
230
+ </div>
231
+ <div className="pp-table-wrap" style={{ marginTop: 'var(--sp-2)' }}>
232
+ <ParamTable rows={headersToRows(req.headers)} readOnly columns={['key', 'value']} emptyText="无请求头" />
233
+ </div>
234
+ {bodyText(req.body) ? (
235
+ <pre className="pp-pre pp-pre-scroll" style={{ marginTop: 'var(--sp-2)' }}>{bodyText(req.body)}</pre>
236
+ ) : null}
237
+ </div>
238
+ ) : <EmptyState text="无请求快照" />
239
+ } else if (tab === 'tests') {
240
+ tabBody = testItems.length === 0 ? <EmptyState text="无断言" /> : (
241
+ <div className="pp-list">
242
+ {testItems.map((item, i) => (
243
+ <div className="pp-result-row" key={i}>
244
+ <span className={item && item.passed ? 'pp-pill pp-pill-ok' : 'pp-pill pp-pill-bad'}>
245
+ {item && item.passed ? '通过' : '失败'}
246
+ </span>
247
+ <span className="pp-ellipsis">{item && item.name ? String(item.name) : '-'}</span>
248
+ {item && item.error ? <span className="pp-meta">{errText(item.error)}</span> : null}
249
+ </div>
250
+ ))}
251
+ </div>
252
+ )
253
+ } else {
254
+ tabBody = logText ? (
255
+ <pre className="pp-pre pp-pre-scroll">{logText}</pre>
256
+ ) : <EmptyState text="无日志" />
257
+ }
258
+
259
+ return (
260
+ <div data-response-panel="">
261
+ {sendingBar}
262
+ {statusBar}
263
+ {copyError ? <p className="pp-note pp-note-bad">{copyError}</p> : null}
264
+ {errorMsg ? <p className="pp-note pp-note-bad">{errorMsg}</p> : (
265
+ <div>
266
+ <div className="pp-resp-tabs">
267
+ {RESPONSE_TABS.map((t) => (
268
+ <button key={t.id} className="pp-tab" data-active={tab === t.id} onClick={() => setTab(t.id)}>
269
+ {tabTitle(t, counts)}
270
+ </button>
271
+ ))}
272
+ </div>
273
+ <div className="pp-debug-tabbody">{tabBody}</div>
274
+ </div>
275
+ )}
276
+ </div>
277
+ )
278
+ }