dsh-hsr 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +166 -2
- package/config/config.json +272 -0
- package/config/safety.macro +0 -0
- package/dsh.bundle.patch.yml +10 -0
- package/experience/base.md +33 -0
- package/experience/team-base.md +41 -0
- package/lib/client.js +256 -0
- package/lib/experience.js +125 -0
- package/lib/http.js +323 -0
- package/lib/index.js +483 -0
- package/lib/knowledge.js +98 -0
- package/lib/match.js +113 -0
- package/lib/render.js +545 -0
- package/lib/settings.js +114 -0
- package/lib/source.js +119 -0
- package/lib/text.js +96 -0
- package/lib/tool.js +219 -0
- package/package.json +47 -4
- package/rules/game.md +286 -0
- package/rules/rules.md +34 -0
package/lib/client.js
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-hsr 的客户端半边:在「设置」里注册一栏「HSR 数据库」。
|
|
3
|
+
*
|
|
4
|
+
* 这个文件由宿主的模块加载器(window.__ModuleLoader__)执行,只向基座要 react:
|
|
5
|
+
* 设置区的 slot 渲染的是 React 树,所以面板本体用原生 DOM 搭好之后,
|
|
6
|
+
* 由一个极薄的 React 组件通过 ref 挂进去,省掉手写整棵 React 元素树。
|
|
7
|
+
* 宿主侧读写接口见 lib/index.js 的 registerRoutes()。
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
window.__ModuleLoader__.load({
|
|
11
|
+
id: 'dsh-hsr',
|
|
12
|
+
factory: (require) => {
|
|
13
|
+
var module = { exports: {} };
|
|
14
|
+
var exports = module.exports;
|
|
15
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
16
|
+
|
|
17
|
+
const React = require('react');
|
|
18
|
+
|
|
19
|
+
const BASE = '/dsh-hsr/api';
|
|
20
|
+
const SOURCE_TEXT = {
|
|
21
|
+
setting: '使用设置里填写的代理',
|
|
22
|
+
env: '使用环境变量里的代理',
|
|
23
|
+
system: '使用系统(浏览器)代理',
|
|
24
|
+
direct: '已强制直连',
|
|
25
|
+
none: '直连',
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
function el(tag, style, text) {
|
|
29
|
+
const node = document.createElement(tag);
|
|
30
|
+
if (style) node.setAttribute('style', style);
|
|
31
|
+
if (text !== undefined) node.textContent = text;
|
|
32
|
+
return node;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const HINT = 'font-size:12px;line-height:1.6;opacity:.72;margin:0;';
|
|
36
|
+
|
|
37
|
+
function field(title, hint) {
|
|
38
|
+
const box = el('div', 'display:flex;flex-direction:column;gap:6px;');
|
|
39
|
+
box.appendChild(el('div', 'font-size:13px;font-weight:600;', title));
|
|
40
|
+
if (hint) box.appendChild(el('p', HINT, hint));
|
|
41
|
+
return box;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function input(placeholder) {
|
|
45
|
+
const node = el(
|
|
46
|
+
'input',
|
|
47
|
+
'width:100%;box-sizing:border-box;padding:8px 10px;border-radius:8px;border:1px solid rgba(128,128,128,.35);background:transparent;color:inherit;font:inherit;',
|
|
48
|
+
);
|
|
49
|
+
node.type = 'text';
|
|
50
|
+
node.spellcheck = false;
|
|
51
|
+
node.placeholder = placeholder;
|
|
52
|
+
return node;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function textarea(placeholder, rows) {
|
|
56
|
+
const node = el(
|
|
57
|
+
'textarea',
|
|
58
|
+
'width:100%;box-sizing:border-box;padding:8px 10px;border-radius:8px;border:1px solid rgba(128,128,128,.35);background:transparent;color:inherit;font:inherit;resize:vertical;',
|
|
59
|
+
);
|
|
60
|
+
node.rows = rows;
|
|
61
|
+
node.spellcheck = false;
|
|
62
|
+
node.placeholder = placeholder;
|
|
63
|
+
return node;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function button(label, primary) {
|
|
67
|
+
const node = el('button', '', label);
|
|
68
|
+
node.type = 'button';
|
|
69
|
+
node.setAttribute(
|
|
70
|
+
'style',
|
|
71
|
+
[
|
|
72
|
+
'padding:7px 14px',
|
|
73
|
+
'border-radius:8px',
|
|
74
|
+
'font:inherit',
|
|
75
|
+
'cursor:pointer',
|
|
76
|
+
primary
|
|
77
|
+
? 'border:1px solid transparent;background:var(--dsh-accent,#3b82f6);color:#fff'
|
|
78
|
+
: 'border:1px solid rgba(128,128,128,.4);background:transparent;color:inherit',
|
|
79
|
+
].join(';'),
|
|
80
|
+
);
|
|
81
|
+
return node;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function request(path, options) {
|
|
85
|
+
const response = await fetch(BASE + path, {
|
|
86
|
+
cache: 'no-store',
|
|
87
|
+
headers: { 'content-type': 'application/json' },
|
|
88
|
+
...options,
|
|
89
|
+
});
|
|
90
|
+
const text = await response.text();
|
|
91
|
+
let data = {};
|
|
92
|
+
try {
|
|
93
|
+
data = text ? JSON.parse(text) : {};
|
|
94
|
+
} catch {
|
|
95
|
+
data = {};
|
|
96
|
+
}
|
|
97
|
+
if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`);
|
|
98
|
+
return data;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function createPanel() {
|
|
102
|
+
const root = el('div', 'display:flex;flex-direction:column;gap:18px;padding:2px 0 8px;max-width:760px;');
|
|
103
|
+
root.appendChild(el('h3', 'margin:0;font-size:16px;', 'HSR 数据库'));
|
|
104
|
+
root.appendChild(
|
|
105
|
+
el(
|
|
106
|
+
'p',
|
|
107
|
+
HINT,
|
|
108
|
+
'这里的设置只作用于《崩坏:星穹铁道》资料查询插件,改完点保存即可生效。',
|
|
109
|
+
),
|
|
110
|
+
);
|
|
111
|
+
|
|
112
|
+
const proxyField = field(
|
|
113
|
+
'代理',
|
|
114
|
+
'留空表示跟随系统(浏览器)代理;填 direct 表示强制直连;也可以填 127.0.0.1:7897 这样的地址。',
|
|
115
|
+
);
|
|
116
|
+
const proxyInput = input('例如 127.0.0.1:7897');
|
|
117
|
+
proxyField.appendChild(proxyInput);
|
|
118
|
+
const proxyState = el('p', HINT, '');
|
|
119
|
+
proxyField.appendChild(proxyState);
|
|
120
|
+
root.appendChild(proxyField);
|
|
121
|
+
|
|
122
|
+
const queryField = field(
|
|
123
|
+
'查询经验',
|
|
124
|
+
'在这里写你对角色的称呼与角色全称的对应关系,例如「板鸭 = 布洛妮娅」。模型查询时会先看这段。',
|
|
125
|
+
);
|
|
126
|
+
const queryInput = textarea('板鸭 = 布洛妮娅', 4);
|
|
127
|
+
queryField.appendChild(queryInput);
|
|
128
|
+
root.appendChild(queryField);
|
|
129
|
+
|
|
130
|
+
const teamField = field(
|
|
131
|
+
'配队经验',
|
|
132
|
+
'在这里写你的配队偏好与已有角色、光锥、遗器。模型给出配队建议时会参考这段。',
|
|
133
|
+
);
|
|
134
|
+
const teamInput = textarea('常用的角色有……;倾向的打法是……', 6);
|
|
135
|
+
teamField.appendChild(teamInput);
|
|
136
|
+
root.appendChild(teamField);
|
|
137
|
+
|
|
138
|
+
const status = el('p', `${HINT}min-height:18px;`, '');
|
|
139
|
+
|
|
140
|
+
const row = el('div', 'display:flex;gap:10px;flex-wrap:wrap;align-items:center;');
|
|
141
|
+
const save = button('保存', true);
|
|
142
|
+
const reset = button('删除本机自识别经验');
|
|
143
|
+
row.appendChild(save);
|
|
144
|
+
row.appendChild(reset);
|
|
145
|
+
row.appendChild(status);
|
|
146
|
+
root.appendChild(row);
|
|
147
|
+
|
|
148
|
+
const paths = el('p', HINT, '');
|
|
149
|
+
root.appendChild(paths);
|
|
150
|
+
|
|
151
|
+
let loaded = null;
|
|
152
|
+
|
|
153
|
+
const apply = (data) => {
|
|
154
|
+
loaded = data;
|
|
155
|
+
proxyInput.value = data.proxy || '';
|
|
156
|
+
queryInput.value = data.query || '';
|
|
157
|
+
teamInput.value = data.team || '';
|
|
158
|
+
const resolved = data.resolved || { proxy: '', source: 'none' };
|
|
159
|
+
proxyState.textContent = resolved.proxy
|
|
160
|
+
? `当前实际走:${resolved.proxy}(${SOURCE_TEXT[resolved.source] || resolved.source})`
|
|
161
|
+
: `当前实际走:直连(${SOURCE_TEXT[resolved.source] || resolved.source})`;
|
|
162
|
+
if (data.paths) paths.textContent = `查询经验文件:${data.paths.query} 配队经验文件:${data.paths.team}`;
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
const load = async () => {
|
|
166
|
+
status.textContent = '读取中…';
|
|
167
|
+
try {
|
|
168
|
+
apply(await request('/settings'));
|
|
169
|
+
status.textContent = '';
|
|
170
|
+
} catch (error) {
|
|
171
|
+
status.textContent = `读取失败:${error.message}`;
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
save.addEventListener('click', async () => {
|
|
176
|
+
status.textContent = '保存中…';
|
|
177
|
+
try {
|
|
178
|
+
apply(
|
|
179
|
+
await request('/settings', {
|
|
180
|
+
method: 'POST',
|
|
181
|
+
body: JSON.stringify({
|
|
182
|
+
proxy: proxyInput.value,
|
|
183
|
+
query: queryInput.value,
|
|
184
|
+
team: teamInput.value,
|
|
185
|
+
}),
|
|
186
|
+
}),
|
|
187
|
+
);
|
|
188
|
+
status.textContent = '已保存。';
|
|
189
|
+
} catch (error) {
|
|
190
|
+
status.textContent = `保存失败:${error.message}`;
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
reset.addEventListener('click', async () => {
|
|
195
|
+
const ok = window.confirm(
|
|
196
|
+
'确定要删除模型在本地写下的检验经验吗?删除后模型需要重新积累,这个操作不可撤销。',
|
|
197
|
+
);
|
|
198
|
+
if (!ok) return;
|
|
199
|
+
status.textContent = '删除中…';
|
|
200
|
+
try {
|
|
201
|
+
await request('/clear-model-notes', { method: 'POST' });
|
|
202
|
+
status.textContent = '已删除模型检验经验。';
|
|
203
|
+
} catch (error) {
|
|
204
|
+
status.textContent = `删除失败:${error.message}`;
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
void load();
|
|
209
|
+
return root;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const name = 'dsh-hsr';
|
|
213
|
+
const inject = ['slots'];
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* 设置区的一栏。slot 要的是 React 组件,面板本体是原生 DOM,
|
|
217
|
+
* 所以这里只放一个容器,等挂载完成后把 createPanel() 塞进去。
|
|
218
|
+
*/
|
|
219
|
+
function SettingsSection() {
|
|
220
|
+
const host = React.useRef(null);
|
|
221
|
+
React.useEffect(() => {
|
|
222
|
+
const node = host.current;
|
|
223
|
+
if (!node) return undefined;
|
|
224
|
+
const panel = createPanel();
|
|
225
|
+
node.appendChild(panel);
|
|
226
|
+
return () => {
|
|
227
|
+
if (panel.parentNode === node) node.removeChild(panel);
|
|
228
|
+
};
|
|
229
|
+
}, []);
|
|
230
|
+
return React.createElement('div', {
|
|
231
|
+
ref: host,
|
|
232
|
+
style: { display: 'flex', flexDirection: 'column', gap: '18px', padding: '4px 0' },
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function apply(ctx) {
|
|
237
|
+
ctx.slots.inject('settings.section', () =>
|
|
238
|
+
ctx.slots.register(
|
|
239
|
+
{
|
|
240
|
+
name: 'settings.section',
|
|
241
|
+
id: 'dsh-hsr',
|
|
242
|
+
order: 70,
|
|
243
|
+
label: () => 'HSR 数据库',
|
|
244
|
+
inject: () => ({}),
|
|
245
|
+
},
|
|
246
|
+
SettingsSection,
|
|
247
|
+
),
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
exports.name = name;
|
|
252
|
+
exports.inject = inject;
|
|
253
|
+
exports.apply = apply;
|
|
254
|
+
return module.exports;
|
|
255
|
+
},
|
|
256
|
+
});
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 经验层:查询经验与配队经验各成一套,每套三段。
|
|
3
|
+
*
|
|
4
|
+
* - 基础经验:随插件发布,只读。
|
|
5
|
+
* - 模型检验:模型可以直接用文件工具改写。
|
|
6
|
+
* - 用户经验:用户在设置页里填写,也可以直接改文件。
|
|
7
|
+
*
|
|
8
|
+
* 文件不存在时按空内容处理,并在首次读取时把目录与空文件建好,
|
|
9
|
+
* 这样负责写经验的模型知道该往哪里写。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import fs from 'node:fs/promises';
|
|
13
|
+
import os from 'node:os';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
|
|
16
|
+
/** 两类经验的文件名。 */
|
|
17
|
+
const KINDS = {
|
|
18
|
+
query: { model: 'model.md', user: 'user.md' },
|
|
19
|
+
team: { model: 'model-team.md', user: 'user-team.md' },
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/** 经验文件所在目录(用户主目录下)。 */
|
|
23
|
+
export function experienceDir() {
|
|
24
|
+
return path.join(os.homedir(), '.dsh', 'dsh-hsr', 'experience');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* 某一类经验的两个可写文件路径。
|
|
29
|
+
* @param {'query'|'team'} kind 经验类别。
|
|
30
|
+
* @returns {{dir: string, model: string, user: string}} 路径。
|
|
31
|
+
*/
|
|
32
|
+
export function notePaths(kind) {
|
|
33
|
+
const names = KINDS[kind] ?? KINDS.query;
|
|
34
|
+
const dir = experienceDir();
|
|
35
|
+
return {
|
|
36
|
+
dir,
|
|
37
|
+
model: path.join(dir, names.model),
|
|
38
|
+
user: path.join(dir, names.user),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function readIfExists(file) {
|
|
43
|
+
try {
|
|
44
|
+
return await fs.readFile(file, 'utf8');
|
|
45
|
+
} catch {
|
|
46
|
+
return '';
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function ensureFiles() {
|
|
51
|
+
try {
|
|
52
|
+
await fs.mkdir(experienceDir(), { recursive: true });
|
|
53
|
+
for (const kind of Object.keys(KINDS)) {
|
|
54
|
+
const paths = notePaths(kind);
|
|
55
|
+
for (const file of [paths.model, paths.user]) {
|
|
56
|
+
try {
|
|
57
|
+
await fs.access(file);
|
|
58
|
+
} catch {
|
|
59
|
+
await fs.writeFile(file, '', 'utf8');
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
} catch {
|
|
64
|
+
// 主目录不可写时退化成"只有基础经验",不影响查询。
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 读用户自己写的那一段。 */
|
|
69
|
+
export async function readUserNotes(kind) {
|
|
70
|
+
return readIfExists(notePaths(kind).user);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 写用户自己写的那一段(设置页保存时调用)。 */
|
|
74
|
+
export async function writeUserNotes(kind, text) {
|
|
75
|
+
const paths = notePaths(kind);
|
|
76
|
+
await fs.mkdir(paths.dir, { recursive: true });
|
|
77
|
+
await fs.writeFile(paths.user, String(text ?? ''), 'utf8');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 清空模型写下的检验经验,两类一起清。 */
|
|
81
|
+
export async function clearModelNotes() {
|
|
82
|
+
const cleared = [];
|
|
83
|
+
for (const kind of Object.keys(KINDS)) {
|
|
84
|
+
const paths = notePaths(kind);
|
|
85
|
+
try {
|
|
86
|
+
await fs.mkdir(paths.dir, { recursive: true });
|
|
87
|
+
await fs.writeFile(paths.model, '', 'utf8');
|
|
88
|
+
cleared.push(paths.model);
|
|
89
|
+
} catch {
|
|
90
|
+
// 清不掉的路径不报错,交给调用方提示。
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return cleared;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 读一套经验并拼成一段文本。
|
|
98
|
+
* @param {'query'|'team'} kind 经验类别。
|
|
99
|
+
* @param {string} baseFile 随插件发布的基础经验文件路径。
|
|
100
|
+
* @param {{lang?: string}} options 语言。
|
|
101
|
+
* @returns {Promise<string>} 拼好的文本。
|
|
102
|
+
*/
|
|
103
|
+
export async function loadNotes(kind, baseFile, options = {}) {
|
|
104
|
+
await ensureFiles();
|
|
105
|
+
const paths = notePaths(kind);
|
|
106
|
+
const [base, model, user] = await Promise.all([
|
|
107
|
+
readIfExists(baseFile),
|
|
108
|
+
readIfExists(paths.model),
|
|
109
|
+
readIfExists(paths.user),
|
|
110
|
+
]);
|
|
111
|
+
const zh = options.lang !== 'en';
|
|
112
|
+
const sections = [
|
|
113
|
+
[zh ? '基础经验(插件自带)' : 'Base notes (bundled)', base],
|
|
114
|
+
[zh ? `模型检验(可编辑:${paths.model})` : `Model notes (editable: ${paths.model})`, model],
|
|
115
|
+
[zh ? `用户经验(用户编辑:${paths.user})` : `User notes (user-edited: ${paths.user})`, user],
|
|
116
|
+
];
|
|
117
|
+
const lines = [];
|
|
118
|
+
for (const [title, body] of sections) {
|
|
119
|
+
lines.push(`### ${title}`);
|
|
120
|
+
const text = String(body || '').trim();
|
|
121
|
+
lines.push(text.length > 0 ? text : (zh ? '(暂无)' : '(empty)'));
|
|
122
|
+
lines.push('');
|
|
123
|
+
}
|
|
124
|
+
return lines.join('\n').trimEnd();
|
|
125
|
+
}
|
package/lib/http.js
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 网络层:直连或经 HTTP 代理取一个 JSON。
|
|
3
|
+
*
|
|
4
|
+
* 代理写法接受 `127.0.0.1:7897`、`http://127.0.0.1:7897` 两种;
|
|
5
|
+
* 走 CONNECT 隧道后再在隧道上发一个 HTTP/1.1 请求,因此不依赖任何第三方库。
|
|
6
|
+
*
|
|
7
|
+
* 所有失败都收敛成 `NetError`,消息里不出现主机名、路径以外的任何地址信息 ——
|
|
8
|
+
* 调用方只把它转成一句固定提示。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import http from 'node:http';
|
|
12
|
+
import tls from 'node:tls';
|
|
13
|
+
import zlib from 'node:zlib';
|
|
14
|
+
|
|
15
|
+
/** 网络取数失败。 */
|
|
16
|
+
export class NetError extends Error {
|
|
17
|
+
constructor(message) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.name = 'NetError';
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** 代理写法不合法时抛出,消息可直接展示。 */
|
|
24
|
+
export class ProxyError extends Error {
|
|
25
|
+
constructor(message) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = 'ProxyError';
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const HEADER_LIMIT = 32 * 1024;
|
|
32
|
+
const BODY_LIMIT = 24 * 1024 * 1024;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 解析代理写法。
|
|
36
|
+
* @param {string} raw 用户填的代理,空串表示直连。
|
|
37
|
+
* @returns {{host: string, port: number}|null} 代理地址;空串返回 null。
|
|
38
|
+
*/
|
|
39
|
+
export function parseProxy(raw) {
|
|
40
|
+
const text = String(raw ?? '').trim();
|
|
41
|
+
if (text.length === 0) return null;
|
|
42
|
+
let body = text;
|
|
43
|
+
const scheme = /^([a-zA-Z][a-zA-Z0-9+.-]*):\/\//.exec(body);
|
|
44
|
+
if (scheme) {
|
|
45
|
+
const name = scheme[1].toLowerCase();
|
|
46
|
+
if (name !== 'http' && name !== 'https') {
|
|
47
|
+
throw new ProxyError('代理只支持 http:// 形式,例如 127.0.0.1:7897。');
|
|
48
|
+
}
|
|
49
|
+
body = body.slice(scheme[0].length);
|
|
50
|
+
}
|
|
51
|
+
body = body.replace(/\/+$/, '');
|
|
52
|
+
if (body.includes('@')) body = body.slice(body.lastIndexOf('@') + 1);
|
|
53
|
+
const matched = /^\[([^\]]+)\](?::(\d+))?$/.exec(body) || /^([^:]+)(?::(\d+))?$/.exec(body);
|
|
54
|
+
if (!matched) throw new ProxyError('代理写法看不懂,请填 127.0.0.1:7897 这样的地址。');
|
|
55
|
+
const host = matched[1];
|
|
56
|
+
const port = matched[2] === undefined ? 8080 : Number(matched[2]);
|
|
57
|
+
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
|
58
|
+
throw new ProxyError('代理端口不对,请填 127.0.0.1:7897 这样的地址。');
|
|
59
|
+
}
|
|
60
|
+
return { host, port };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function openTunnel(proxy, targetHost, targetPort, timeoutMs) {
|
|
64
|
+
return new Promise((resolve, reject) => {
|
|
65
|
+
const request = http.request({
|
|
66
|
+
host: proxy.host,
|
|
67
|
+
port: proxy.port,
|
|
68
|
+
method: 'CONNECT',
|
|
69
|
+
path: `${targetHost}:${targetPort}`,
|
|
70
|
+
headers: { host: `${targetHost}:${targetPort}` },
|
|
71
|
+
timeout: timeoutMs,
|
|
72
|
+
});
|
|
73
|
+
request.once('connect', (response, socket) => {
|
|
74
|
+
if (response.statusCode !== 200) {
|
|
75
|
+
socket.destroy();
|
|
76
|
+
reject(new NetError('proxy refused'));
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
socket.setTimeout(timeoutMs);
|
|
80
|
+
resolve(socket);
|
|
81
|
+
});
|
|
82
|
+
request.once('timeout', () => {
|
|
83
|
+
request.destroy();
|
|
84
|
+
reject(new NetError('timeout'));
|
|
85
|
+
});
|
|
86
|
+
request.once('error', () => reject(new NetError('connect failed')));
|
|
87
|
+
request.end();
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function secure(socket, host, timeoutMs) {
|
|
92
|
+
return new Promise((resolve, reject) => {
|
|
93
|
+
const tlsSocket = tls.connect({ socket, servername: host, ALPNProtocols: ['http/1.1'] });
|
|
94
|
+
tlsSocket.setTimeout(timeoutMs);
|
|
95
|
+
tlsSocket.once('secureConnect', () => resolve(tlsSocket));
|
|
96
|
+
tlsSocket.once('timeout', () => {
|
|
97
|
+
tlsSocket.destroy();
|
|
98
|
+
reject(new NetError('tls timeout'));
|
|
99
|
+
});
|
|
100
|
+
tlsSocket.once('error', () => reject(new NetError('tls failed')));
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function splitHead(buffer) {
|
|
105
|
+
const end = buffer.indexOf('\r\n\r\n');
|
|
106
|
+
if (end < 0) return null;
|
|
107
|
+
const head = buffer.subarray(0, end).toString('latin1');
|
|
108
|
+
const rest = buffer.subarray(end + 4);
|
|
109
|
+
const lines = head.split('\r\n');
|
|
110
|
+
const status = Number(/^HTTP\/1\.[01] (\d{3})/.exec(lines[0] || '')?.[1] ?? 0);
|
|
111
|
+
const headers = {};
|
|
112
|
+
for (const line of lines.slice(1)) {
|
|
113
|
+
const colon = line.indexOf(':');
|
|
114
|
+
if (colon <= 0) continue;
|
|
115
|
+
headers[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim();
|
|
116
|
+
}
|
|
117
|
+
return { status, headers, rest };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function decodeChunked(buffer) {
|
|
121
|
+
const parts = [];
|
|
122
|
+
let offset = 0;
|
|
123
|
+
for (;;) {
|
|
124
|
+
const lineEnd = buffer.indexOf('\r\n', offset);
|
|
125
|
+
if (lineEnd < 0) return null;
|
|
126
|
+
const size = parseInt(buffer.subarray(offset, lineEnd).toString('latin1').trim(), 16);
|
|
127
|
+
if (!Number.isFinite(size)) return null;
|
|
128
|
+
if (size === 0) return Buffer.concat(parts);
|
|
129
|
+
const start = lineEnd + 2;
|
|
130
|
+
if (buffer.length < start + size + 2) return null;
|
|
131
|
+
parts.push(buffer.subarray(start, start + size));
|
|
132
|
+
offset = start + size + 2;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function readBody(socket, head, timeoutMs) {
|
|
137
|
+
return new Promise((resolve, reject) => {
|
|
138
|
+
const chunks = [head.rest];
|
|
139
|
+
let settled = false;
|
|
140
|
+
const finish = (buffer) => {
|
|
141
|
+
if (settled) return;
|
|
142
|
+
settled = true;
|
|
143
|
+
socket.destroy();
|
|
144
|
+
if (head.headers['transfer-encoding']?.toLowerCase().includes('chunked')) {
|
|
145
|
+
const decoded = decodeChunked(buffer);
|
|
146
|
+
if (decoded === null) reject(new NetError('bad chunked body'));
|
|
147
|
+
else resolve(decoded);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
const length = Number(head.headers['content-length']);
|
|
151
|
+
resolve(Number.isFinite(length) ? buffer.subarray(0, length) : buffer);
|
|
152
|
+
};
|
|
153
|
+
const attempt = () => {
|
|
154
|
+
const buffer = Buffer.concat(chunks);
|
|
155
|
+
if (head.headers['transfer-encoding']?.toLowerCase().includes('chunked')) {
|
|
156
|
+
const decoded = decodeChunked(buffer);
|
|
157
|
+
if (decoded !== null) finish(buffer);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
const length = Number(head.headers['content-length']);
|
|
161
|
+
if (Number.isFinite(length) && buffer.length >= length) finish(buffer);
|
|
162
|
+
};
|
|
163
|
+
socket.on('data', (chunk) => {
|
|
164
|
+
chunks.push(chunk);
|
|
165
|
+
const total = chunks.reduce((sum, part) => sum + part.length, 0);
|
|
166
|
+
if (total > BODY_LIMIT) {
|
|
167
|
+
if (!settled) {
|
|
168
|
+
settled = true;
|
|
169
|
+
socket.destroy();
|
|
170
|
+
reject(new NetError('body too large'));
|
|
171
|
+
}
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
attempt();
|
|
175
|
+
});
|
|
176
|
+
socket.on('end', () => {
|
|
177
|
+
if (settled) return;
|
|
178
|
+
settled = true;
|
|
179
|
+
const buffer = Buffer.concat(chunks);
|
|
180
|
+
if (head.headers['transfer-encoding']?.toLowerCase().includes('chunked')) {
|
|
181
|
+
const decoded = decodeChunked(buffer);
|
|
182
|
+
if (decoded === null) reject(new NetError('bad chunked body'));
|
|
183
|
+
else resolve(decoded);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
resolve(buffer);
|
|
187
|
+
});
|
|
188
|
+
socket.on('timeout', () => {
|
|
189
|
+
if (!settled) {
|
|
190
|
+
settled = true;
|
|
191
|
+
socket.destroy();
|
|
192
|
+
reject(new NetError('timeout'));
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
socket.on('error', () => {
|
|
196
|
+
if (!settled) {
|
|
197
|
+
settled = true;
|
|
198
|
+
reject(new NetError('socket error'));
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
attempt();
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function requestThroughProxy(target, proxy, timeoutMs) {
|
|
206
|
+
const socket = await openTunnel(proxy, target.hostname, Number(target.port || 443), timeoutMs);
|
|
207
|
+
let tlsSocket;
|
|
208
|
+
try {
|
|
209
|
+
tlsSocket = await secure(socket, target.hostname, timeoutMs);
|
|
210
|
+
} catch (error) {
|
|
211
|
+
socket.destroy();
|
|
212
|
+
throw error;
|
|
213
|
+
}
|
|
214
|
+
const requestText = [
|
|
215
|
+
`GET ${target.pathname}${target.search} HTTP/1.1`,
|
|
216
|
+
`Host: ${target.hostname}`,
|
|
217
|
+
'Accept: application/json',
|
|
218
|
+
'Accept-Encoding: identity',
|
|
219
|
+
'Cache-Control: no-cache',
|
|
220
|
+
'Connection: close',
|
|
221
|
+
'',
|
|
222
|
+
'',
|
|
223
|
+
].join('\r\n');
|
|
224
|
+
tlsSocket.write(requestText, 'latin1');
|
|
225
|
+
|
|
226
|
+
const buffer = await new Promise((resolve, reject) => {
|
|
227
|
+
const chunks = [];
|
|
228
|
+
let total = 0;
|
|
229
|
+
let settled = false;
|
|
230
|
+
const done = (finish) => {
|
|
231
|
+
if (settled) return;
|
|
232
|
+
settled = true;
|
|
233
|
+
finish();
|
|
234
|
+
};
|
|
235
|
+
tlsSocket.on('data', (chunk) => {
|
|
236
|
+
chunks.push(chunk);
|
|
237
|
+
total += chunk.length;
|
|
238
|
+
if (total > BODY_LIMIT) {
|
|
239
|
+
done(() => {
|
|
240
|
+
tlsSocket.destroy();
|
|
241
|
+
reject(new NetError('body too large'));
|
|
242
|
+
});
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
const all = Buffer.concat(chunks);
|
|
246
|
+
const end = all.indexOf('\r\n\r\n');
|
|
247
|
+
if (end < 0) {
|
|
248
|
+
if (all.length > HEADER_LIMIT) {
|
|
249
|
+
done(() => {
|
|
250
|
+
tlsSocket.destroy();
|
|
251
|
+
reject(new NetError('header too large'));
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
const head = splitHead(all);
|
|
257
|
+
if (head === null) return;
|
|
258
|
+
if (head.headers['transfer-encoding']?.toLowerCase().includes('chunked')) {
|
|
259
|
+
if (decodeChunked(head.rest) !== null) done(() => resolve(all));
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
const length = Number(head.headers['content-length']);
|
|
263
|
+
if (Number.isFinite(length) && head.rest.length >= length) done(() => resolve(all));
|
|
264
|
+
});
|
|
265
|
+
tlsSocket.on('end', () => done(() => resolve(Buffer.concat(chunks))));
|
|
266
|
+
tlsSocket.on('timeout', () => done(() => {
|
|
267
|
+
tlsSocket.destroy();
|
|
268
|
+
reject(new NetError('timeout'));
|
|
269
|
+
}));
|
|
270
|
+
tlsSocket.on('error', (error) => done(() => {
|
|
271
|
+
tlsSocket.destroy();
|
|
272
|
+
reject(error instanceof NetError ? error : new NetError('socket error'));
|
|
273
|
+
}));
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
const head = splitHead(buffer);
|
|
277
|
+
if (head === null) throw new NetError('bad response');
|
|
278
|
+
let body = head.rest;
|
|
279
|
+
if (head.headers['transfer-encoding']?.toLowerCase().includes('chunked')) {
|
|
280
|
+
const decoded = decodeChunked(body);
|
|
281
|
+
if (decoded === null) throw new NetError('bad chunked body');
|
|
282
|
+
body = decoded;
|
|
283
|
+
} else {
|
|
284
|
+
const length = Number(head.headers['content-length']);
|
|
285
|
+
if (Number.isFinite(length) && body.length > length) body = body.subarray(0, length);
|
|
286
|
+
}
|
|
287
|
+
if (head.headers['content-encoding']?.toLowerCase() === 'gzip') {
|
|
288
|
+
try {
|
|
289
|
+
body = zlib.gunzipSync(body);
|
|
290
|
+
} catch {
|
|
291
|
+
throw new NetError('bad gzip body');
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
return { status: head.status, text: body.toString('utf8') };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* 取回一个 JSON 文本。
|
|
299
|
+
* @param {string} url 完整地址。
|
|
300
|
+
* @param {{proxy?: string, timeoutMs?: number}} options 代理与超时。
|
|
301
|
+
* @returns {Promise<{status: number, text: string}>} 响应。
|
|
302
|
+
*/
|
|
303
|
+
export async function requestText(url, options = {}) {
|
|
304
|
+
const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : 20000;
|
|
305
|
+
const proxy = parseProxy(options.proxy);
|
|
306
|
+
const target = new URL(url);
|
|
307
|
+
if (proxy !== null) return requestThroughProxy(target, proxy, timeoutMs);
|
|
308
|
+
|
|
309
|
+
const controller = new AbortController();
|
|
310
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
311
|
+
try {
|
|
312
|
+
const response = await fetch(target, {
|
|
313
|
+
headers: { accept: 'application/json', 'cache-control': 'no-cache' },
|
|
314
|
+
signal: controller.signal,
|
|
315
|
+
});
|
|
316
|
+
const text = await response.text();
|
|
317
|
+
return { status: response.status, text };
|
|
318
|
+
} catch {
|
|
319
|
+
throw new NetError('request failed');
|
|
320
|
+
} finally {
|
|
321
|
+
clearTimeout(timer);
|
|
322
|
+
}
|
|
323
|
+
}
|