dsh-nikoapi 0.0.0-stage → 0.1.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/client.js ADDED
@@ -0,0 +1,398 @@
1
+ /** NikoAPI settings: group descriptions, multiple keys, per-key model selection. */
2
+ window.__ModuleLoader__.load({
3
+ id: 'dsh-nikoapi',
4
+ factory(require) {
5
+ const React = require('react')
6
+ const h = React.createElement
7
+ const NS = 'nikoapi'
8
+ const ENDPOINT = '/nikoapi/api'
9
+ const zh = {
10
+ nav: 'NikoAPI', title: 'NikoAPI', subtitle: '连接账号,按 Key 分组接入模型',
11
+ tabKeys: 'Key 与分组', tabModels: '模型', tabCost: '费用联动', connected: '已连接', notConnected: '未连接',
12
+ connection: '连接设置', reconnect: '更新凭据', tokenLabel: '管理访问令牌', tokenPlaceholder: '粘贴 NikoAPI 管理访问令牌',
13
+ tokenHint: '需要 api_key:read 与 api_key:reveal;修改远端分组另需 api_key:write。凭据单向保存,不回显。',
14
+ save: '保存', cancel: '取消', searchKeys: '搜索 Key 名称', refresh: '刷新', myKeys: '我的 Key', keyCount: '{count} 个 Key',
15
+ hidden: '凭据已隐藏', unlimited: '不限 Key 额度', keyQuota: 'Key 剩余 {value} quota',
16
+ keyCacheAt: '上次同步:{time}', keyCacheEmpty: '尚无 Key 缓存,点击刷新读取。',
17
+ costAutomatic: '检测到 cost-meter 后自动联动;仅注册已确认且路由有效的模型。',
18
+ costConflicts: '保留手工价格或其他计算器:{count}', costUnavailable: '等待有效费率或模型路由:{count}',
19
+ waiting: '等待 cost-meter 或已确认模型', pending: '等待有效模型路由或费率', stale: '使用上次有效费率,刷新未完成',
20
+ group: '分组', groupAuto: '自动分组', autoHint: '由服务端自动路由', inherit: '继承账号分组',
21
+ searchGroups: '搜索分组…', noGroups: '没有匹配的分组', groupUnknown: '倍率未知', groupSelected: '当前分组',
22
+ ratio: '{value}x', writeDenied: '缺少 api_key:write 权限,分组暂为只读。', groupSaved: '分组已保存,已自动刷新已确认模型费率。',
23
+ groupHint: '选择分组会修改 NikoAPI 远端 Key;保存失败时保留原值。',
24
+ selectedKeys: '已选 {count} 个 Key', preview: '确认', needKeys: '先到“Key 与分组”勾选 Key 并确认。',
25
+ noKeys: '没有匹配的 Key', selectAll: '全选', clearAll: '取消全选',
26
+ selectVisible: '全选当前结果', clearVisible: '取消当前结果', selectKey: '选择 Key:{name}',
27
+ partialKeys: '{count} 个 Key 读取失败,请查看提示。', keyLimit: '最多选择 {count} 个 Key。',
28
+ searchModels: '搜索模型或 Key 名称', modelCount: '{count} 个模型项', selectedModels: '已选 {count} 个模型项',
29
+ noModels: '没有匹配的模型', loading: '加载中…', addModels: '配置模型列表', saveModels: '配置模型列表',
30
+ confirmHint: '同名模型按 Key 分别接入;每个渠道使用对应 Key 与分组,不改变当前会话的默认模型。',
31
+ priceTokens: '{currency} {input} / 百万输入 · {output} / 百万输出', priceCall: '{currency} {value} / 次',
32
+ unknownPrice: '价格未知', dynamicPrice: 'NikoAPI 动态计价 · 按请求用量', zeroPrice: '按本地策略计价 · ¥0', reference: '参考价', priceUnknownReason: '缺少可准确转换的费率',
33
+ registered: '已接入 {count} 个模型项', registrationFailed: '模型接入失败:{message}', saved: '已保存',
34
+ unregistered: '尚未接入模型', registerAgain: '重新接入已保存模型', removeRegistration: '移除已接入模型',
35
+ selected: '已选择', enabled: '已启用', disabled: '已禁用', expired: '已过期', exhausted: '已耗尽', unknown: '未知',
36
+ failed: '操作失败:{message}', failureDiagnostic: '诊断:{method} · {type} · {code}',
37
+ unavailable: 'NikoAPI 服务暂不可用,请刷新或重启 DSH 后重试。',
38
+ costPlugin: '费用插件', costReady: '已安装 · 服务可用', costMissing: '未启用或服务不可用',
39
+ costMissingHint: 'dsh-cost-meter 尚不可用,无法建立联动。', costUnsupported: '费用插件缺少所需接口。',
40
+ interval: '费率刷新间隔(分钟)', intervalHint: '自动刷新已确认模型的费率;Key 列表由刷新按钮更新。',
41
+ costScope: '计算器只接管已确认且路由有效的精确模型;同步时保留手工价格,配置变更最迟在下次费率同步时识别。', costStatus: '当前状态',
42
+ unbound: '未绑定', bound: '已绑定', boundPartial: '已绑定(部分模型费率未知)', paused: '联动已暂停', syncError: '同步失败',
43
+ refreshCost: '手动刷新', saveSettings: '保存设置',
44
+ versionMismatch: '插件正在更新,请重启 DSH 并刷新页面后重试。',
45
+ }
46
+ const en = {
47
+ nav: 'NikoAPI', title: 'NikoAPI', subtitle: 'Connect an account and add models by key group',
48
+ tabKeys: 'Keys and groups', tabModels: 'Models', tabCost: 'Cost link', connected: 'Connected', notConnected: 'Not connected',
49
+ connection: 'Connection', reconnect: 'Update credential', tokenLabel: 'Management token', tokenPlaceholder: 'Paste a NikoAPI management token',
50
+ tokenHint: 'Requires api_key:read and api_key:reveal. Changing a remote group also requires api_key:write. Credentials are write-only.',
51
+ save: 'Save', cancel: 'Cancel', searchKeys: 'Search key names', refresh: 'Refresh', myKeys: 'My keys', keyCount: '{count} keys',
52
+ hidden: 'Credential hidden', unlimited: 'Unlimited key quota', keyQuota: 'Key remaining: {value} quota',
53
+ keyCacheAt: 'Last synchronized: {time}', keyCacheEmpty: 'No Key cache yet. Refresh to load it.',
54
+ costAutomatic: 'Automatically linked when cost-meter is detected; only confirmed models with verified routes are registered.',
55
+ costConflicts: 'Manual prices or other calculators preserved: {count}', costUnavailable: 'Waiting for a valid rate or model route: {count}',
56
+ waiting: 'Waiting for cost-meter or confirmed models', pending: 'Waiting for a valid model route or rate', stale: 'Using last valid rates; refresh incomplete',
57
+ group: 'Group', groupAuto: 'Auto group', autoHint: 'Routed automatically by the server', inherit: 'Inherit account group',
58
+ searchGroups: 'Search groups…', noGroups: 'No matching groups', groupUnknown: 'Ratio unknown', groupSelected: 'Current group',
59
+ ratio: '{value}x', writeDenied: 'api_key:write is missing; groups are read-only.', groupSaved: 'Group saved. Confirmed model rates were refreshed automatically.',
60
+ groupHint: 'Choosing a group changes the remote NikoAPI key. Failure keeps the previous value.',
61
+ selectedKeys: '{count} keys selected', preview: 'Confirm', needKeys: 'Select keys in Keys and groups, then confirm.',
62
+ noKeys: 'No matching keys', selectAll: 'Select all', clearAll: 'Clear all',
63
+ selectVisible: 'Select visible results', clearVisible: 'Clear visible results', selectKey: 'Select key: {name}',
64
+ partialKeys: '{count} keys could not be read. See the details.', keyLimit: 'Select up to {count} keys.',
65
+ searchModels: 'Search models or key names', modelCount: '{count} model entries', selectedModels: '{count} model entries selected',
66
+ noModels: 'No matching models', loading: 'Loading…', addModels: 'Configure model list', saveModels: 'Configure model list',
67
+ confirmHint: 'Matching model names stay separate per key. Each route uses that key and group; the current session default stays unchanged.',
68
+ priceTokens: '{currency} {input} / M input · {output} / M output', priceCall: '{currency} {value} / call',
69
+ unknownPrice: 'Price unknown', dynamicPrice: 'NikoAPI dynamic billing · per-request usage', zeroPrice: 'Local policy rate · ¥0', reference: 'Reference', priceUnknownReason: 'No accurately convertible rate',
70
+ registered: '{count} model entries connected', registrationFailed: 'Model connection failed: {message}', saved: 'Saved',
71
+ unregistered: 'No models connected yet', registerAgain: 'Reconnect saved models', removeRegistration: 'Remove connected models',
72
+ selected: 'Selected', enabled: 'Enabled', disabled: 'Disabled', expired: 'Expired', exhausted: 'Exhausted', unknown: 'Unknown',
73
+ failed: 'Failed: {message}', failureDiagnostic: 'Diagnostic: {method} · {type} · {code}',
74
+ unavailable: 'NikoAPI is unavailable. Refresh or restart DSH and try again.',
75
+ costPlugin: 'Cost plugin', costReady: 'Installed · service available', costMissing: 'Not enabled or service unavailable',
76
+ costMissingHint: 'dsh-cost-meter is unavailable; a link cannot be established.', costUnsupported: 'The cost plugin lacks the required API.',
77
+ interval: 'Rate refresh interval (minutes)', intervalHint: 'Refreshes rates for confirmed models automatically. Use Refresh to update the Key directory.',
78
+ costScope: 'Calculators cover confirmed models on exact routes; manual prices are preserved at sync checks and detected no later than the next rate sync.', costStatus: 'Current status',
79
+ unbound: 'Not linked', bound: 'Linked', boundPartial: 'Linked (some rates are unknown)', paused: 'Link paused', syncError: 'Sync failed',
80
+ refreshCost: 'Refresh now', saveSettings: 'Save settings',
81
+ versionMismatch: 'Plugin update in progress. Restart DSH and refresh this page.',
82
+ }
83
+ let translate = (key, values = {}) => {
84
+ const dictionary = document.documentElement.lang.toLowerCase().startsWith('zh') ? zh : en
85
+ return (dictionary[key] ?? key).replace(/\{(\w+)\}/g, (_, field) => String(values[field] ?? ''))
86
+ }
87
+ const t = (key, values) => translate(key, values)
88
+ const CSS = `
89
+ .nk-root{container-type:inline-size;display:flex;flex-direction:column;gap:14px;min-width:0;max-width:100%;font-size:14px;color:var(--dsw-alias-label-primary)}
90
+ .nk-root *{box-sizing:border-box}.nk-root button,.nk-root input{font:inherit}.nk-root button{cursor:pointer}.nk-root button:disabled{cursor:not-allowed;opacity:.55}
91
+ .nk-root button:focus-visible,.nk-root input:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:2px}
92
+ .nk-title{font-size:20px;font-weight:600;line-height:28px}.nk-muted{font-size:13px;line-height:1.55;color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere}.nk-note{font-size:12px;line-height:1.6;color:var(--dsw-alias-label-tertiary);overflow-wrap:anywhere}.nk-strong{font-weight:600;overflow-wrap:anywhere;min-width:0}
93
+ .nk-tabs{display:flex;border-bottom:1px solid var(--dsw-alias-border-l1);gap:4px}.nk-tab{flex:1;min-width:0;min-height:44px;border:0;border-bottom:2px solid transparent;background:transparent;color:var(--dsw-alias-label-secondary);padding:8px 4px;overflow-wrap:anywhere}.nk-tab[aria-selected=true]{border-bottom-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-brand-primary)}
94
+ .nk-stack{display:flex;flex-direction:column;gap:12px;min-width:0}.nk-row{display:flex;align-items:center;gap:10px;min-width:0;flex-wrap:wrap}.nk-grow{flex:1 1 160px;min-width:0}.nk-card{display:flex;flex-direction:column;gap:10px;padding:12px;border:1px solid var(--dsw-alias-border-l1);border-radius:12px;background:var(--dsw-alias-bg-layer-2);min-width:0}
95
+ .nk-input{min-width:0;width:100%;min-height:44px;padding:8px 10px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-layer-1);color:inherit}.nk-search{flex:1 1 160px}
96
+ .nk-btn{min-width:0;min-height:44px;padding:8px 14px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-layer-2);color:inherit;overflow-wrap:anywhere}.nk-btn:hover:not(:disabled),.nk-tab:hover{background:var(--dsw-alias-interactive-bg-hover)}.nk-btn[data-primary=true]{background:var(--dsw-alias-brand-primary);color:var(--dsw-alias-label-on-color);border-color:transparent}
97
+ .nk-foot{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;border-top:1px solid var(--dsw-alias-border-l1);padding-top:12px;min-width:0}.nk-foot .nk-btn{max-width:100%}
98
+ .nk-list{display:flex;flex-direction:column;gap:8px;min-width:0;max-height:440px;overflow:auto;padding:2px}.nk-key{display:flex;flex:0 0 auto;align-items:flex-start;gap:8px;border:1px solid var(--dsw-alias-border-l2);border-radius:10px;padding:12px;min-width:0}.nk-key[data-selected=true]{border-color:var(--dsw-alias-brand-primary)}.nk-key-body{flex:1;min-width:0;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.2fr);gap:8px 12px}.nk-key-body>.nk-row{grid-column:1/-1}.nk-key-body>.nk-note{align-self:center}.nk-key-body>.nk-picker{grid-column:2}
99
+ .nk-check{display:inline-flex;align-items:center;gap:6px;min-height:44px;min-width:44px;flex:none;cursor:pointer}.nk-check input{width:18px;height:18px;margin:0;accent-color:var(--dsw-alias-brand-primary)}.nk-key>.nk-check{justify-content:center;min-width:32px}.nk-check-text{overflow-wrap:anywhere;min-width:0}.nk-model{display:flex;align-items:flex-start;gap:8px;padding:8px 0;border-top:1px solid var(--dsw-alias-border-l1);min-width:0}.nk-model .nk-check{align-items:flex-start;width:100%}.nk-model .nk-check input{margin-top:3px;flex:none}.nk-model-body{display:flex;flex-direction:column;gap:4px;min-width:0;flex:1}
100
+ .nk-badge{flex:none;border-radius:6px;padding:2px 7px;font-size:12px;line-height:20px;color:var(--dsw-alias-label-secondary);background:var(--dsw-alias-interactive-bg-hover)}.nk-ok{color:var(--dsw-alias-state-success-primary)}.nk-warn{color:var(--dsw-alias-state-warning-primary)}.nk-error{color:var(--dsw-alias-state-error-primary);overflow-wrap:anywhere;font-size:13px;line-height:1.6}.nk-success{color:var(--dsw-alias-label-primary);overflow-wrap:anywhere;font-size:13px}
101
+ .nk-picker{display:flex;flex-direction:column;gap:6px;min-width:0;width:100%}.nk-group-trigger{display:flex;align-items:center;gap:8px;justify-content:space-between;text-align:left;width:100%;border:1px solid var(--dsw-alias-border-l2)}.nk-group-label{min-width:0;overflow-wrap:anywhere;flex:1}.nk-group-panel{border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:6px;background:var(--dsw-alias-bg-layer-2);box-shadow:var(--dsw-elevation-prominent);min-width:0}.nk-group-options{display:flex;flex-direction:column;max-height:250px;overflow-y:auto;min-width:0;overscroll-behavior:contain}.nk-group-option{display:flex;gap:10px;align-items:flex-start;width:100%;min-height:64px;padding:12px 10px;border:0;border-radius:7px;text-align:left;background:transparent;color:inherit}.nk-group-option:hover,.nk-group-option[aria-selected=true]{background:var(--dsw-alias-interactive-bg-hover)}.nk-group-copy{flex:1;min-width:0}.nk-group-name{display:block;font-weight:500;overflow-wrap:anywhere;line-height:22px}.nk-group-desc{display:block;font-size:13px;color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere;white-space:pre-wrap;line-height:20px}.nk-ratio{display:inline-flex;align-items:center;justify-content:center;flex:none;align-self:flex-start;padding:0 7px;line-height:20px;border:1px solid var(--dsw-alias-brand-primary);color:var(--dsw-alias-brand-primary);border-radius:999px;font-size:12px;white-space:nowrap}.nk-group-options .nk-ratio{margin-top:2px}
102
+ @container (max-width:480px){.nk-list{gap:10px}.nk-key{gap:8px;padding:10px}.nk-key-body{display:flex;flex-direction:column;gap:10px}.nk-group-trigger{min-height:44px}}
103
+ @container (max-width:360px){.nk-foot{align-items:stretch}.nk-foot>.nk-btn{width:100%}.nk-key{padding:8px;gap:8px}.nk-card{padding:10px}.nk-key .nk-grow{flex-basis:130px}.nk-key-body{gap:10px}}
104
+ `
105
+ async function call(method, params = {}, signal) {
106
+ let result
107
+ try {
108
+ const response = await fetch(ENDPOINT, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ method, params }), credentials: 'same-origin', signal })
109
+ result = await response.json()
110
+ } catch (error) { if (error?.name === 'AbortError') throw error; throw new Error(t('unavailable')) }
111
+ if (result?.ok === true) return result.data
112
+ const error = new Error(result?.error?.message ?? t('unavailable'))
113
+ error.code = result?.error?.code
114
+ const diagnostic = result?.error?.diagnostic
115
+ if (typeof diagnostic?.method === 'string' && /^[a-z][A-Za-z0-9]{0,39}$/.test(diagnostic.method)
116
+ && typeof diagnostic.errorType === 'string' && /^[A-Za-z][A-Za-z0-9_.-]{0,39}$/.test(diagnostic.errorType)
117
+ && typeof diagnostic.errorCode === 'string' && /^[A-Za-z0-9_.-]{1,40}$/.test(diagnostic.errorCode)) {
118
+ error.diagnostic = { method: diagnostic.method, type: diagnostic.errorType, code: diagnostic.errorCode }
119
+ }
120
+ throw error
121
+ }
122
+ const badge = text => h('span', { className: 'nk-badge' }, text)
123
+ const btn = (text, props = {}) => h('button', { type: 'button', className: 'nk-btn', ...props }, text)
124
+ const pairId = (keyId, modelId) => JSON.stringify([keyId, modelId])
125
+ const isSelectable = key => key.status === 'enabled'
126
+ const groupTitle = (id, groups) => id === 'auto' ? t('groupAuto') : groups.find(group => group.id === id)?.id ?? (id || t('inherit'))
127
+ const priceText = price => price?.kind === 'perMillion'
128
+ ? `${price.reference ? `${t('reference')} · ` : ''}${t('priceTokens', { currency: price.currency, input: price.input, output: price.output })}`
129
+ : price?.kind === 'perCall' ? `${price.reference ? `${t('reference')} · ` : ''}${t('priceCall', { currency: price.currency, value: price.perCall })}`
130
+ : price?.kind === 'nikoExpression' ? `${price.reference ? `${t('reference')} · ` : ''}${t('dynamicPrice')}`
131
+ : price?.kind === 'nikoZero' ? t('zeroPrice') : t('unknownPrice')
132
+
133
+ function SelectCheckbox({ checked, mixed = false, children, ...props }) {
134
+ const ref = React.useRef(null)
135
+ React.useEffect(() => { if (ref.current) ref.current.indeterminate = mixed }, [mixed])
136
+ return h('label', { className: 'nk-check' }, h('input', { ...props, ref, type: 'checkbox', checked, 'aria-checked': mixed ? 'mixed' : checked }), children ? h('span', { className: 'nk-check-text' }, children) : null)
137
+ }
138
+ function GroupPicker({ value, groups, disabled, onChange, keyName }) {
139
+ const [open, setOpen] = React.useState(false)
140
+ const [query, setQuery] = React.useState('')
141
+ const root = React.useRef(null)
142
+ const search = React.useRef(null)
143
+ const trigger = React.useRef(null)
144
+ const listId = React.useId()
145
+ const options = [
146
+ { id: 'auto', name: t('groupAuto'), desc: '', ratio: null, title: t('groupAuto') },
147
+ ...groups.filter(group => group.id !== 'auto').map(group => ({ ...group, title: group.id, auto: false })),
148
+ ]
149
+ const visible = options.filter(group => `${group.title ?? group.name}\n${group.name}\n${group.desc}`.toLocaleLowerCase().includes(query.toLocaleLowerCase()))
150
+ const current = options.find(group => group.id === value)
151
+ React.useEffect(() => {
152
+ if (!open) return
153
+ search.current?.focus()
154
+ const outside = event => { if (!root.current?.contains(event.target)) setOpen(false) }
155
+ document.addEventListener('pointerdown', outside)
156
+ return () => document.removeEventListener('pointerdown', outside)
157
+ }, [open])
158
+ const close = () => { setOpen(false); trigger.current?.focus() }
159
+ const choose = group => { close(); if (group.id !== value) void onChange(group.id) }
160
+ return h('div', { className: 'nk-picker', ref: root, onBlur: event => { if (event.relatedTarget && !event.currentTarget.contains(event.relatedTarget)) setOpen(false) }, onKeyDown: event => {
161
+ if (event.key === 'Escape' && open) { event.preventDefault(); event.stopPropagation(); close() }
162
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
163
+ event.preventDefault()
164
+ if (!open) { setOpen(true); return }
165
+ const options = [...root.current.querySelectorAll('[role="option"]')]
166
+ const index = options.indexOf(document.activeElement)
167
+ const next = index < 0 ? (event.key === 'ArrowDown' ? 0 : options.length - 1) : (index + (event.key === 'ArrowDown' ? 1 : -1) + options.length) % options.length
168
+ options[next]?.focus()
169
+ }
170
+ } },
171
+ h('button', {
172
+ type: 'button', ref: trigger, className: 'nk-btn nk-group-trigger', disabled,
173
+ 'aria-label': `${t('group')} · ${keyName}`, 'aria-haspopup': 'listbox', 'aria-expanded': open, 'aria-controls': listId,
174
+ onClick: () => { setOpen(previous => !previous); setQuery('') },
175
+ },
176
+ h('span', { className: 'nk-group-label' }, `${t('group')}:${current?.title ?? (value === 'auto' ? t('groupAuto') : value || t('inherit'))}`),
177
+ current?.ratio !== null && current?.ratio !== undefined ? h('span', { className: 'nk-ratio' }, t('ratio', { value: current.ratio })) : null,
178
+ h('span', { 'aria-hidden': true }, open ? '⌃' : '⌄')),
179
+ open ? h('div', { className: 'nk-group-panel' },
180
+ h('input', { ref: search, className: 'nk-input', type: 'search', value: query, placeholder: t('searchGroups'), 'aria-label': t('searchGroups'), onChange: event => setQuery(event.target.value) }),
181
+ h('div', { id: listId, role: 'listbox', 'aria-label': t('group'), className: 'nk-group-options' },
182
+ visible.length === 0
183
+ ? h('div', { className: 'nk-muted', role: 'status' }, t('noGroups'))
184
+ : visible.map(group => h('button', {
185
+ key: group.id, type: 'button', role: 'option', 'aria-selected': group.id === value,
186
+ className: 'nk-group-option', onClick: () => choose(group),
187
+ },
188
+ h('span', { className: 'nk-group-copy' },
189
+ h('span', { className: 'nk-group-name' }, group.title),
190
+ group.desc ? h('span', { className: 'nk-group-desc' }, group.desc) : null),
191
+ h('span', { className: 'nk-ratio' }, group.auto ? t('autoHint') : group.ratio === null ? t('groupUnknown') : t('ratio', { value: group.ratio })),
192
+ )),
193
+ ),
194
+ ) : null,
195
+ )
196
+ }
197
+
198
+ function Section() {
199
+ const [tab, setTab] = React.useState('keys')
200
+ const [info, setInfo] = React.useState(null)
201
+ const [busy, setBusy] = React.useState(false)
202
+ const [error, setError] = React.useState('')
203
+ const [notice, setNotice] = React.useState('')
204
+ const [modelSnapshot, setModelSnapshot] = React.useState(null)
205
+ const mounted = React.useRef(true)
206
+ const pending = React.useRef(false)
207
+ React.useEffect(() => { mounted.current = true; return () => { mounted.current = false } }, [])
208
+ const run = React.useCallback(async work => {
209
+ if (pending.current) return undefined
210
+ pending.current = true; setBusy(true); setError(''); setNotice('')
211
+ try { return await work() }
212
+ catch (failure) {
213
+ if (mounted.current && failure?.name !== 'AbortError') {
214
+ const message = t('failed', { message: failure.message })
215
+ const details = failure.diagnostic ? t('failureDiagnostic', failure.diagnostic) : ''
216
+ setError(details ? `${message}(${details})` : message)
217
+ }
218
+ return undefined
219
+ }
220
+ finally { pending.current = false; if (mounted.current) setBusy(false) }
221
+ }, [])
222
+ const reload = React.useCallback(async () => { const next = await call('describe'); if (mounted.current) setInfo(next); return next }, [])
223
+ React.useEffect(() => { void run(reload) }, [reload, run])
224
+ const preview = async keys => {
225
+ const result = await run(async () => {
226
+ const selected = await call('selectKeys', { keys })
227
+ if (selected.failed?.length) throw new Error(selected.failed.map(row => `${row.name}: ${row.message}`).join(';'))
228
+ setInfo(selected)
229
+ if (keys.length === 0) { setModelSnapshot(null); return { cleared: true } }
230
+ return call('previewModels', { force: true })
231
+ })
232
+ if (!result) return
233
+ if (result.cleared) { setNotice(t('saved')); return }
234
+ setModelSnapshot(result); setTab('models')
235
+ }
236
+ const tabs = [['keys', 'tabKeys'], ['models', 'tabModels'], ['cost', 'tabCost']]
237
+ return h('div', { className: 'nk-root', 'data-nikoapi-ui': 'multi-key-groups' }, h('style', null, CSS),
238
+ h('div', null, h('div', { className: 'nk-title' }, t('title')), h('div', { className: 'nk-muted' }, t('subtitle'))),
239
+ h('div', { className: 'nk-tabs', role: 'tablist' }, tabs.map(([id, label]) => h('button', { key: id, type: 'button', role: 'tab', className: 'nk-tab', 'aria-selected': tab === id, disabled: busy, onClick: () => setTab(id) }, t(label)))),
240
+ error ? h('div', { className: 'nk-error', role: 'alert' }, error) : null,
241
+ notice ? h('div', { className: 'nk-success', role: 'status' }, notice) : null,
242
+ !info ? h('div', { className: 'nk-muted' }, busy ? t('loading') : t('unavailable'))
243
+ : h('div', { role: 'tabpanel', className: 'nk-stack' }, tab === 'keys'
244
+ ? h(KeysTab, { info, busy, run, setInfo, setNotice, onPreview: preview, invalidate: () => setModelSnapshot(null) })
245
+ : tab === 'models' ? h(ModelsTab, { info, busy, run, setInfo, setNotice, snapshot: modelSnapshot, setSnapshot: setModelSnapshot })
246
+ : h(CostTab, { info, busy, run, setInfo, setNotice })),
247
+ )
248
+ }
249
+ function keysFromCache(info) {
250
+ const rows = new Map((info.keyDirectory?.keys ?? []).map(key => [key.id, key]))
251
+ for (const key of info.connection.keys ?? []) rows.set(key.id, { ...rows.get(key.id), ...key })
252
+ return [...rows.values()]
253
+ }
254
+ function KeysTab({ info, busy, run, setInfo, setNotice, onPreview, invalidate }) {
255
+ const [keys, setKeys] = React.useState(() => keysFromCache(info))
256
+ const [groups, setGroups] = React.useState(() => info.keyDirectory?.groups ?? [])
257
+ const [query, setQuery] = React.useState('')
258
+ const [selected, setSelected] = React.useState(() => new Set((info.connection.keys ?? []).map(key => key.id)))
259
+ const [editing, setEditing] = React.useState(false)
260
+ const [token, setToken] = React.useState('')
261
+ const [writeBlocked, setWriteBlocked] = React.useState(false)
262
+ const [loaded, setLoaded] = React.useState(() => info.keyDirectory?.complete === true)
263
+ const accept = data => {
264
+ if (!Array.isArray(data.selectedKeys)) throw new Error(t('versionMismatch'))
265
+ setKeys(data.keys ?? []); setGroups(data.groups ?? []); setLoaded(data.complete === true)
266
+ setSelected(new Set(data.selectedKeys.map(key => key.id)))
267
+ }
268
+ const load = React.useCallback(async () => {
269
+ const data = await call('listKeys'); accept(data); setInfo(await call('describe')); return data
270
+ }, [setInfo])
271
+ React.useEffect(() => {
272
+ const directory = info.keyDirectory
273
+ setKeys(keysFromCache(info))
274
+ setGroups(directory?.groups ?? [])
275
+ setLoaded(directory?.complete === true)
276
+ }, [info.keyDirectory, info.connection.keys])
277
+ const connect = async () => {
278
+ const result = await run(async () => {
279
+ const credential = token; setToken('')
280
+ const data = await call('connect', { managementToken: credential }); accept(data); setWriteBlocked(false)
281
+ const fresh = await call('describe'); setInfo(fresh); invalidate(); return fresh
282
+ })
283
+ if (result) { setEditing(false); setNotice(t('saved')) }
284
+ }
285
+ const visible = keys.filter(key => key.name.toLocaleLowerCase().includes(query.toLocaleLowerCase()))
286
+ const eligible = visible.filter(isSelectable)
287
+ const all = eligible.length > 0 && eligible.every(key => selected.has(key.id))
288
+ const chosen = keys.filter(key => selected.has(key.id)).map(({ id }) => ({ id }))
289
+ const toggle = id => setSelected(previous => { const next = new Set(previous); if (next.has(id)) next.delete(id); else next.add(id); return next })
290
+ const toggleVisible = () => setSelected(previous => { const next = new Set(previous); eligible.forEach(key => { if (all) next.delete(key.id); else next.add(key.id) }); return next })
291
+ const changeGroup = async (key, group) => {
292
+ const result = await run(async () => {
293
+ try {
294
+ const data = await call('setGroup', { keyId: key.id, group })
295
+ setKeys(current => current.map(row => row.id === key.id ? data.key : row)); invalidate()
296
+ setInfo(await call('describe')); return data
297
+ } catch (error) { if (error.code === 'scope_missing') setWriteBlocked(true); throw error }
298
+ })
299
+ if (result) setNotice(t('groupSaved'))
300
+ }
301
+ return h(React.Fragment, null,
302
+ h('div', { className: 'nk-card' }, h('div', { className: 'nk-row' }, h('div', { className: 'nk-grow' },
303
+ h('div', { className: 'nk-strong' }, t(info.connection.managementToken.configured ? 'connected' : 'notConnected')),
304
+ h('div', { className: 'nk-note' }, info.site.origin)), btn(t(info.connection.managementToken.configured ? 'reconnect' : 'connection'), { disabled: busy, onClick: () => setEditing(value => !value) })),
305
+ editing ? h('div', { className: 'nk-stack' }, h('label', null, t('tokenLabel'), h('input', { className: 'nk-input', type: 'password', autoComplete: 'off', placeholder: t('tokenPlaceholder'), value: token, onChange: event => setToken(event.target.value) })), h('div', { className: 'nk-note' }, t('tokenHint')),
306
+ h('div', { className: 'nk-row' }, btn(t('save'), { disabled: busy || !token.trim(), onClick: connect }), btn(t('cancel'), { disabled: busy, onClick: () => { setEditing(false); setToken('') } }))) : null),
307
+ h('div', { className: 'nk-row' }, h('input', { className: 'nk-input nk-search', type: 'search', placeholder: t('searchKeys'), 'aria-label': t('searchKeys'), value: query, onChange: event => setQuery(event.target.value) }), btn(t('refresh'), { disabled: busy || !info.connection.managementToken.configured, onClick: () => void run(load) })),
308
+ h('div', { className: 'nk-row' }, h('div', { className: 'nk-strong nk-grow' }, t('myKeys')), h('span', { className: 'nk-note' }, t('keyCount', { count: info.keyDirectory?.total ?? visible.length }))),
309
+ h(SelectCheckbox, { checked: all, mixed: !all && eligible.some(key => selected.has(key.id)), disabled: busy || eligible.length === 0, onChange: toggleVisible }, t(query ? all ? 'clearVisible' : 'selectVisible' : all ? 'clearAll' : 'selectAll')),
310
+ h('div', { className: 'nk-note' }, info.keyDirectory?.at ? t('keyCacheAt', { time: new Date(info.keyDirectory.at).toLocaleString() }) : t('keyCacheEmpty')),
311
+ writeBlocked ? h('div', { className: 'nk-warn' }, t('writeDenied')) : null,
312
+ !loaded && busy ? h('div', { className: 'nk-muted' }, t('loading')) : null,
313
+ h('div', { className: 'nk-list' }, visible.length ? visible.map(key => h('div', { key: key.id, className: 'nk-key', 'data-selected': selected.has(key.id), 'data-key-id': key.id },
314
+ h(SelectCheckbox, { checked: selected.has(key.id), disabled: busy || !isSelectable(key) && !selected.has(key.id), 'aria-label': t('selectKey', { name: key.name }), onChange: () => toggle(key.id) }),
315
+ h('div', { className: 'nk-key-body' }, h('div', { className: 'nk-row' }, h('div', { className: 'nk-strong nk-grow' }, key.name), badge(t(key.status in zh ? key.status : 'unknown'))),
316
+ h('div', { className: 'nk-note' }, `${t('hidden')} · ${key.unlimitedQuota ? t('unlimited') : t('keyQuota', { value: key.remainQuota ?? '—' })}`),
317
+ h(GroupPicker, { value: key.group, groups, disabled: busy || writeBlocked, keyName: key.name, onChange: group => changeGroup(key, group) })))) : h('div', { className: 'nk-muted' }, t('noKeys'))),
318
+ h('div', { className: 'nk-note' }, t('groupHint')),
319
+ h('div', { className: 'nk-foot' }, h('span', { className: 'nk-note' }, t('selectedKeys', { count: selected.size })), btn(t('preview'), { 'data-primary': true, disabled: busy || chosen.length === 0 && (info.connection.keys ?? []).length === 0, onClick: () => onPreview(chosen) })),
320
+ )
321
+ }
322
+ function ModelsTab({ info, busy, run, setInfo, setNotice, snapshot, setSnapshot }) {
323
+ const [query, setQuery] = React.useState('')
324
+ const [checked, setChecked] = React.useState(() => new Set((snapshot?.confirmed ?? info.confirmed ?? []).map(row => pairId(row.keyId, row.modelId))))
325
+ const [registration, setRegistration] = React.useState(info.modelRegistration)
326
+ const load = React.useCallback(async (force = false) => {
327
+ const data = await call('previewModels', { force })
328
+ if (!Array.isArray(data.keys)) throw new Error(t('versionMismatch'))
329
+ setSnapshot(data)
330
+ setChecked(new Set(data.confirmed.map(row => pairId(row.keyId, row.modelId))))
331
+ setInfo(await call('describe'))
332
+ }, [setSnapshot, setInfo])
333
+ React.useEffect(() => { if (!snapshot && info.connection.keys?.length) void run(() => load(false)) }, [snapshot, info.connection.keys?.length, load, run])
334
+ if (!info.connection.keys?.length) return h('div', { className: 'nk-muted' }, t('needKeys'))
335
+ if (!snapshot) return h('div', { className: 'nk-muted' }, t('loading'))
336
+ const needle = query.toLocaleLowerCase()
337
+ const keys = snapshot.keys.map(key => ({ ...key, visible: key.models.filter(model => `${model.modelId}\n${model.name}\n${key.name}`.toLocaleLowerCase().includes(needle)) }))
338
+ const visiblePairs = keys.flatMap(key => key.visible.map(model => pairId(key.id, model.modelId)))
339
+ const all = visiblePairs.length > 0 && visiblePairs.every(id => checked.has(id))
340
+ const anyChecked = checked.size > 0
341
+ const togglePairs = (pairs, select) => setChecked(previous => { const next = new Set(previous); pairs.forEach(id => { if (select) next.add(id); else next.delete(id) }); return next })
342
+ const toggleOne = id => setChecked(previous => { const next = new Set(previous); if (next.has(id)) next.delete(id); else next.add(id); return next })
343
+ const confirm = async () => {
344
+ const selections = snapshot.keys.map(key => ({ keyId: key.id, modelIds: key.models.filter(model => checked.has(pairId(key.id, model.modelId))).map(model => model.modelId) }))
345
+ const data = await run(async () => { const next = await call('confirmModels', { selections }); setInfo(await call('describe')); return next })
346
+ if (!data) return
347
+ setSnapshot({ ...snapshot, confirmed: data.confirmed }); setRegistration(data.registration)
348
+ if (data.registration.registered) setNotice(t('registered', { count: data.registration.count }))
349
+ }
350
+ return h(React.Fragment, null,
351
+ h('div', { className: 'nk-row' }, h('div', { className: 'nk-strong nk-grow' }, t('selectedKeys', { count: snapshot.keys.length })), badge(t('modelCount', { count: snapshot.keys.reduce((sum, key) => sum + key.models.length, 0) }))),
352
+ h('div', { className: 'nk-row' }, h('input', { className: 'nk-input nk-search', type: 'search', placeholder: t('searchModels'), 'aria-label': t('searchModels'), value: query, onChange: event => setQuery(event.target.value) }), btn(t('refresh'), { disabled: busy, onClick: () => void run(() => load(true)) })),
353
+ h(SelectCheckbox, { checked: all, mixed: !all && visiblePairs.some(id => checked.has(id)), disabled: busy || visiblePairs.length === 0, onChange: () => togglePairs(visiblePairs, !all) }, t(query ? all ? 'clearVisible' : 'selectVisible' : all ? 'clearAll' : 'selectAll')),
354
+ h('div', { className: 'nk-stack', 'data-niko-model-list': true }, keys.filter(key => key.visible.length || key.error || !query).map(key => {
355
+ const pairs = key.visible.map(model => pairId(key.id, model.modelId))
356
+ const keyAll = pairs.length > 0 && pairs.every(id => checked.has(id))
357
+ return h('div', { key: key.id, className: 'nk-card', 'data-model-key': key.id },
358
+ h('div', { className: 'nk-row' }, h('div', { className: 'nk-grow' }, h('div', { className: 'nk-strong' }, key.name), h('div', { className: 'nk-note' }, `${t('group')}:${groupTitle(key.group, snapshot.groups ?? [])}`)),
359
+ h(SelectCheckbox, { checked: keyAll, mixed: !keyAll && pairs.some(id => checked.has(id)), disabled: busy || !pairs.length, onChange: () => togglePairs(pairs, !keyAll) }, t(keyAll ? 'clearAll' : 'selectAll'))),
360
+ key.error ? h('div', { className: 'nk-error' }, key.error) : null,
361
+ ...key.visible.map(model => h('div', { className: 'nk-model', key: model.modelId }, h(SelectCheckbox, { checked: checked.has(pairId(key.id, model.modelId)), disabled: busy, onChange: () => toggleOne(pairId(key.id, model.modelId)) },
362
+ h('span', { className: 'nk-model-body' }, h('span', { className: 'nk-strong' }, model.modelId), h('span', { className: 'nk-muted' }, priceText(model.price)), model.price?.reference ? h('span', { className: 'nk-note' }, t('reference')) : null)))),
363
+ !key.visible.length && !key.error ? h('div', { className: 'nk-muted' }, t('noModels')) : null)
364
+ })),
365
+ h('div', { className: 'nk-note' }, t('confirmHint')),
366
+ h('div', { className: 'nk-foot' }, h('span', { className: 'nk-note' }, t('selectedModels', { count: checked.size })), btn(checked.size === 0 && (info.confirmed ?? []).length ? t('saveModels') : t('addModels'), { 'data-primary': true, disabled: busy || (!anyChecked && !(info.confirmed ?? []).length), onClick: confirm })),
367
+ registration?.lastStatus === 'error' ? h('div', { className: 'nk-error', role: 'alert' }, t('registrationFailed', { message: registration.lastMessage })) : h('div', { className: 'nk-note' }, registration?.registered ? t('registered', { count: registration.count }) : t('unregistered')),
368
+ )
369
+ }
370
+ function CostTab({ info, busy, run, setInfo, setNotice }) {
371
+ const [minutes, setMinutes] = React.useState(String(info.cost.refreshMinutes))
372
+ const available = info.cost.available === true
373
+ const save = async () => {
374
+ const result = await run(async () => { const data = await call('saveCostBinding', { refreshMinutes: Number(minutes) }); setInfo(await call('describe')); return data })
375
+ if (result) setNotice(t('saved'))
376
+ }
377
+ const status = { bound: 'bound', 'bound-partial': 'boundPartial', 'bound-stale': 'stale', waiting: 'waiting', pending: 'pending', error: 'syncError' }[info.cost.status] ?? 'unbound'
378
+ return h(React.Fragment, null,
379
+ h('div', { className: 'nk-card' }, h('div', { className: 'nk-strong' }, t('costPlugin')), h('div', null, 'dsh-cost-meter'), h('div', { className: 'nk-muted' }, t(available ? 'costReady' : 'costMissing')), !available ? h('div', { className: 'nk-note' }, t(info.cost.reason === 'unsupported' ? 'costUnsupported' : 'costMissingHint')) : null),
380
+ h('div', { className: 'nk-note' }, t('costAutomatic')),
381
+ h('div', { className: 'nk-note' }, t('costConflicts', { count: info.cost.conflicts?.length ?? 0 })),
382
+ h('label', { className: 'nk-stack' }, t('interval'), h('input', { className: 'nk-input', type: 'number', min: 1, max: 1440, disabled: busy || !available, value: minutes, onChange: event => setMinutes(event.target.value) })),
383
+ h('div', { className: 'nk-note' }, t('intervalHint')),
384
+ h('div', { className: 'nk-note' }, t('costScope')), h('div', { className: 'nk-note' }, t('costUnavailable', { count: info.cost.unavailable?.length ?? 0 })),
385
+ h('div', { className: 'nk-card' }, h('div', { className: 'nk-strong' }, t('costStatus')), h('div', null, t(status)), info.cost.message ? h('div', { className: 'nk-note' }, info.cost.message) : null),
386
+ h('div', { className: 'nk-foot' }, btn(t('refreshCost'), { disabled: busy || !available, onClick: () => void run(async () => { await call('refresh'); setInfo(await call('describe')); setNotice(t('saved')) }) }), btn(t('saveSettings'), { 'data-primary': true, disabled: busy, onClick: save })),
387
+ )
388
+ }
389
+ return {
390
+ inject: ['slots', 'locale'],
391
+ apply(ctx) {
392
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'nikoapi: dictionaries')
393
+ translate = ctx.locale.bind(NS)
394
+ ctx.slots.inject('settings.section', () => ctx.slots.register({ name: 'settings.section', id: 'nikoapi', order: 60, label: () => t('nav') }, Section))
395
+ },
396
+ }
397
+ },
398
+ })
@@ -0,0 +1,6 @@
1
+ - insert:
2
+ - id: nikoapi
3
+ name: dsh-nikoapi
4
+ config:
5
+ baseUrl: https://nikoapi.xyz
6
+ refreshMinutes: 15
package/icon.svg ADDED
@@ -0,0 +1,7 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36">
2
+ <path d="M6 9.5a11 11 0 0 1 0 17" fill="none" stroke="#6ea8d8" stroke-width="2" stroke-linecap="round"/>
3
+ <path fill="#247bbf" fill-rule="evenodd" d="M13 12a6 6 0 1 0 0 12 6 6 0 0 0 0-12zm0 3.6a2.4 2.4 0 1 1 0 4.8 2.4 2.4 0 0 1 0-4.8z"/>
4
+ <rect x="18.2" y="16.4" width="11.4" height="3.2" rx="1.6" fill="#247bbf"/>
5
+ <rect x="23.6" y="19.6" width="2.6" height="4.2" rx="1.3" fill="#247bbf"/>
6
+ <rect x="27.8" y="19.6" width="2.6" height="3" rx="1.3" fill="#247bbf"/>
7
+ </svg>
Binary file
Binary file
Binary file