dsh-mo-image 0.0.0-stage → 0.4.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.
@@ -0,0 +1,310 @@
1
+ /**
2
+ * 生图提示词「方言」描述层。
3
+ *
4
+ * 同一个提示词写给不同模型,效果差别很大:
5
+ * GPT-Image / DALL·E 3 / FLUX / Nano Banana 更吃自然语言;
6
+ * Seedream / Qwen-Image / 通义万相 / Kolors 更吃中文叙事;
7
+ * Stable Diffusion 仍常用短语标签 + negative prompt。
8
+ *
9
+ * 这里只放「怎么写」的知识,不发请求。插件在系统提示词里按当前模型
10
+ * 注入对应规则,完整模板放在 skills/ 里按需加载。
11
+ */
12
+
13
+ export const GENERATION_FORMULA = '主体 + 动作 + 环境 + 艺术风格 + 光影 + 构图 + 限制条件';
14
+ export const EDITING_FORMULA = '动作动词 + 目标元素 + 期望变化 + 风格细节';
15
+
16
+ function languageLabel(language) {
17
+ if (language === 'en') return '英文优先';
18
+ if (language === 'zh') return '中文优先';
19
+ return '中英皆可,默认跟随用户';
20
+ }
21
+
22
+ /**
23
+ * 模型族 → 提示词写法。match 只看模型 ID,adapter 是模型 ID 认不出时的兜底。
24
+ * 顺序有意义:越具体的族越靠前。
25
+ */
26
+ const PROFILES = [
27
+ {
28
+ id: 'gpt-image',
29
+ label: 'OpenAI GPT-Image',
30
+ match: /gpt-?image|chatgpt-?image/i,
31
+ adapter: 'gpt-image',
32
+ language: 'en',
33
+ supportsNegative: false,
34
+ supportsEdit: true,
35
+ textRendering: 'strong',
36
+ rules: [
37
+ '结构:场景/背景 → 主体 → 关键细节 → 明确约束;复杂需求用短标签或换行分段,不要只堆关键词。',
38
+ '先写用途与画幅(电商主图/海报/UI/信息图/摄影),用位置词安排布局和留白(居中/左上/右侧留白)。',
39
+ '图中文字用引号原样写出,并指定字体、颜色、大小、位置;小字或密集排版用高质量挡位。',
40
+ '编辑:只改 X,其余保持不变;每轮重复身份、构图、文字、光线的保留清单,避免漂移。',
41
+ '具体到材质、镜头、光线;避免空泛质量词(masterpiece/8k/best quality)。'
42
+ ],
43
+ editRule: '只改指定元素,保持身份、构图、文字、光线和背景不变。'
44
+ },
45
+ {
46
+ id: 'dall-e-3',
47
+ label: 'OpenAI DALL·E 3',
48
+ match: /dall-?e-?3/i,
49
+ adapter: 'dall-e-3',
50
+ language: 'en',
51
+ supportsNegative: false,
52
+ supportsEdit: false,
53
+ textRendering: 'weak',
54
+ rules: [
55
+ '用完整自然语言段落(2–5 句)描述画面,不要用关键词列表或标签堆叠。',
56
+ '写清主体、动作、场景、媒介/风格、光线和氛围;模型会自动改写扩展,细节要明确。',
57
+ '文字渲染弱:避免长文字和 logo;文字需求改用 GPT-Image 等模型。',
58
+ '不支持透明背景:需要纯色背景时直接写“纯白背景”等,不要写 transparent。',
59
+ '不要用 no/without 否定句;把不要的东西改写成正面描述。'
60
+ ],
61
+ editRule: '不适合参考图编辑;需要编辑时换用 GPT-Image、Seedream、Nano Banana 等。'
62
+ },
63
+ {
64
+ id: 'nano-banana',
65
+ label: 'Google Nano Banana / Gemini Image',
66
+ match: /nano-?banana|gemini.*(?:image|flash)|imagen/i,
67
+ language: 'any',
68
+ supportsNegative: false,
69
+ supportsEdit: true,
70
+ textRendering: 'strong',
71
+ rules: [
72
+ '自然语言叙事,先写主体/动作/场景,再写构图、风格、镜头;不要只列关键词。',
73
+ '正向描述:说“空荡的街道”而不是“没有车”;不要用否定句。',
74
+ '参考图公式:参考图 + 关系指令 + 新场景;按图1/图2说明用途。',
75
+ '文字放引号中并指定字体/位置;支持多语言文字和 1K/2K/4K。',
76
+ '编辑:用强动词开头(添加/移除/替换/改成),明确保留项;可用文字描述蒙版区域。'
77
+ ],
78
+ editRule: '强动词开头,只改指定区域,明确保持主体、构图和风格。'
79
+ },
80
+ {
81
+ id: 'seedream',
82
+ label: '字节 Seedream',
83
+ match: /seedream|doubao.*(?:image|t2i)/i,
84
+ adapter: 'volcengine-ark',
85
+ language: 'zh',
86
+ supportsNegative: false,
87
+ supportsEdit: true,
88
+ textRendering: 'strong',
89
+ rules: [
90
+ '简洁连贯的中文自然语言:主体 + 行为 + 环境,再补风格、色彩、光影、构图。',
91
+ '不要关键词堆砌;说明用途/类型(海报/电商/角色设定/分镜)和画幅。',
92
+ '文字放双引号中;需要多张时写“一组/四张/分镜”等,可生成统一风格的组图。',
93
+ '编辑:用“增加/删除/替换/修改”明确对象和变化,避免代词;强调其余保持不变。',
94
+ '支持图1/图2参考和多图输入;按顺序说明每张图的作用。'
95
+ ],
96
+ editRule: '只说清改哪个对象、怎么改、其余保持不变;不要用“它/那个”指代。'
97
+ },
98
+ {
99
+ id: 'qwen-image',
100
+ label: '阿里 Qwen-Image',
101
+ match: /qwen.*image|qwen-?image/i,
102
+ language: 'zh',
103
+ supportsNegative: true,
104
+ supportsEdit: true,
105
+ textRendering: 'strong',
106
+ rules: [
107
+ '中文或英文自然语言,主体、场景、风格、构图写具体;支持长提示词和复杂版面。',
108
+ '文字渲染强:把文字放引号中,指定字体、颜色、位置和层级。',
109
+ '支持 negative prompt:把畸变、水印、多余文字、低质量等放进 negative_prompt。',
110
+ '编辑:按图1/图2说明参考关系,只改指定元素,保持其余不变。',
111
+ '需要精确控制时,把“必须出现/必须保留”的内容写成清单。'
112
+ ],
113
+ editRule: '只改指定区域,保持文字、版式和主体不变。'
114
+ },
115
+ {
116
+ id: 'flux',
117
+ label: 'Black Forest Labs FLUX',
118
+ match: /flux|kontext/i,
119
+ language: 'en',
120
+ supportsNegative: false,
121
+ supportsEdit: true,
122
+ textRendering: 'weak',
123
+ rules: [
124
+ '自然语言散文,前置主体和动作;30–80 词最佳,最多约 512 tokens。',
125
+ '按 主体 + 动作 + 风格/媒介 + 环境 + 光线 + 镜头/技术细节 的顺序写。',
126
+ '只写你想要的:FLUX 不支持 negative prompt,用正面描述替代排除项。',
127
+ '文字渲染弱:不要依赖长文字;需要文字用 GPT-Image/Qwen/Seedream。',
128
+ 'Kontext 编辑:明确“改什么 + 保持什么”,参考图按图1/图2指代。'
129
+ ],
130
+ editRule: 'Kontext 编辑只改目标元素,保持主体、构图、背景和风格一致。'
131
+ },
132
+ {
133
+ id: 'stable-diffusion',
134
+ label: 'Stable Diffusion / Stability',
135
+ match: /stable-?diffusion|sdxl|sd-?3|sd3|stable-image/i,
136
+ adapter: 'stability',
137
+ language: 'en',
138
+ supportsNegative: true,
139
+ supportsEdit: true,
140
+ textRendering: 'weak',
141
+ rules: [
142
+ 'SD3.5 用自然语言段落;SDXL/1.5 用逗号分隔的短语标签(媒介、主体、构图、光线、细节)。',
143
+ '支持 negative prompt:把低质量、畸变、多余肢体、水印等放进 negative_prompt。',
144
+ '写清风格/媒介、主体、构图、光线、色彩;避免互相冲突的风格词。',
145
+ '文字渲染弱:不要依赖长文字;需要文字用 GPT-Image/Qwen/Seedream。',
146
+ '编辑:说明保留区域和修改区域;参考图按图1/图2指代。'
147
+ ],
148
+ editRule: '说明保留区域和修改区域;需要局部重绘时优先用支持蒙版的模型。'
149
+ },
150
+ {
151
+ id: 'wanx',
152
+ label: '阿里通义万相',
153
+ match: /wanx|wan-?xiang|tongyi.*wan/i,
154
+ adapter: 'dashscope-wanx',
155
+ language: 'zh',
156
+ supportsNegative: true,
157
+ supportsEdit: false,
158
+ textRendering: 'fair',
159
+ rules: [
160
+ '中文自然语言:主体 + 场景 + 风格 + 光影 + 构图,简洁具体。',
161
+ '支持 negative prompt:把低质量、畸变、水印、多余文字放入 negative_prompt。',
162
+ '写清画幅和用途;避免长文字渲染。',
163
+ '编辑能力有限:需要局部修改时优先换支持编辑的模型。',
164
+ '不要堆砌抽象形容词;用可画的细节替代。'
165
+ ],
166
+ editRule: '编辑能力有限;需要局部修改时换支持编辑的模型。'
167
+ },
168
+ {
169
+ id: 'kolors',
170
+ label: '快手 Kolors',
171
+ match: /kolors/i,
172
+ language: 'zh',
173
+ supportsNegative: true,
174
+ supportsEdit: true,
175
+ textRendering: 'fair',
176
+ rules: [
177
+ '中文自然语言,主体、场景、风格、光线、构图写具体;写实/插画均可。',
178
+ '支持 negative prompt:低质量、畸变、多余肢体、水印等。',
179
+ '文字渲染一般:避免长文字;需要文字用 GPT-Image/Qwen/Seedream。',
180
+ '编辑:明确对象和变化,保持其余不变。',
181
+ '写清人物年龄、发型、服装、材质等可画细节。'
182
+ ],
183
+ editRule: '只改指定对象,保持人物身份、构图和光线不变。'
184
+ }
185
+ ];
186
+
187
+ const GENERIC_PROFILE = {
188
+ id: 'generic',
189
+ label: '通用 OpenAI Images 兼容模型',
190
+ match: null,
191
+ adapter: '',
192
+ language: 'any',
193
+ supportsNegative: false,
194
+ supportsEdit: true,
195
+ textRendering: 'fair',
196
+ rules: [
197
+ '自然语言写清主体、动作、环境、风格、光影、构图和限制条件。',
198
+ '具体到材质、颜色、镜头和光线;避免关键词堆砌和空泛质量词。',
199
+ '图中文字用引号;不确定模型是否支持 negative prompt 时省略。',
200
+ '编辑:只改 X,其余保持不变;按图1/图2指代参考图。',
201
+ '先用最少的模型专属指令,再逐步加细节;一次只改一个变量。'
202
+ ],
203
+ editRule: '只改 X,其余保持不变。'
204
+ };
205
+
206
+ export function listPromptProfiles() {
207
+ return PROFILES.map((profile) => ({ id: profile.id, label: profile.label }))
208
+ .concat([{ id: GENERIC_PROFILE.id, label: GENERIC_PROFILE.label }]);
209
+ }
210
+
211
+ /**
212
+ * 按模型 ID 选提示词写法;模型 ID 认不出时退回适配器族。
213
+ * @param {string} modelId
214
+ * @param {{id?: string}|string|null} adapter
215
+ */
216
+ export function resolvePromptProfile(modelId, adapter) {
217
+ const model = String(modelId || '');
218
+ for (const profile of PROFILES) {
219
+ if (profile.match && profile.match.test(model)) return profile;
220
+ }
221
+ const adapterId = typeof adapter === 'string' ? adapter : String((adapter && adapter.id) || '');
222
+ if (adapterId) {
223
+ const hit = PROFILES.find((profile) => profile.adapter === adapterId);
224
+ if (hit) return hit;
225
+ }
226
+ return GENERIC_PROFILE;
227
+ }
228
+
229
+ export function describePromptProfile(profile) {
230
+ return profile ? profile.id + ' (' + profile.label + ')' : '';
231
+ }
232
+
233
+ /**
234
+ * 生成注入系统提示词的那一节。没有当前模型时返回空串,整节省略。
235
+ * @param {{model?: string, adapter?: {id?: string}|null, editModel?: string, editAdapter?: {id?: string}|null, promptOptimization?: boolean}} state
236
+ */
237
+ /** 交付与选择权的硬约束:对话模型只负责把提示词交出去,不评判、不换模型。 */
238
+ const DELIVERY_RULES = [
239
+ '- 交付即止:工具返回图片链接后,最终回复只输出那一行;不评价画质、不描述画面。除非用户明确要求看图,否则不要打开或读取生成的图片。',
240
+ '- 提供商由用户在设置里固定:不要自行切换提供商,也不要用其他工具(本地生图、建模/Blender、脚本绘图)替代生图模型。',
241
+ '- 调用失败时:把错误原样告诉用户;可以问用户是否要更换模型或服务商,但不要自己更换,也不要换别的模型重试。'
242
+ ];
243
+
244
+ /** Auto 行:用户把选择器设为 Auto 时,模型选择权才下放给对话模型。 */
245
+ function autoSectionText(state) {
246
+ const models = Array.isArray(state && state.models) ? state.models.filter(Boolean) : [];
247
+ return [
248
+ '<mo-image-prompt>',
249
+ '仅在用户需要生成/编辑图片时使用;其他任务忽略本节。',
250
+ '当前生图模型:Auto —— 由你按任务从下面的列表里选,并在调用工具时通过 model 传入。',
251
+ '可选模型:' + (models.length ? models.join(' / ') : '(列表为空,请让用户先在设置里添加模型)'),
252
+ '- 不传 model 会被拒绝;也只能从上面列表里选,不能换提供商。',
253
+ '- 提示词优化:' + (state && state.promptOptimization === false
254
+ ? 'Off,直接用用户原话,不要扩写;生图/改图时仍加载 skill mo-image-generation / mo-image-editing,使用其中的调用与输出规则,但不要套用提示词公式。'
255
+ : 'On,按所选模型的方言写(可加载 skill mo-image-generation / mo-image-editing)。'),
256
+ ...DELIVERY_RULES,
257
+ '</mo-image-prompt>'
258
+ ].join('\n');
259
+ }
260
+
261
+ export function promptSectionText(state) {
262
+ const model = String((state && state.model) || '').trim();
263
+ if (!model) return '';
264
+ if (model === 'auto') return autoSectionText(state);
265
+ if (state && state.promptOptimization === false) {
266
+ return [
267
+ '<mo-image-prompt>',
268
+ '仅在用户需要生成/编辑图片时使用;其他任务忽略本节。',
269
+ '当前生图模型:' + model + '。提示词优化:Off。',
270
+ '- 调用生图工具时必须传 model:' + model + '(工具会核对;不传或传错都会被拒绝)。',
271
+ '- 直接使用用户原话作为 prompt;不要扩写、改写、补充风格/光线/构图,不要替用户做提示词工程。',
272
+ '- 只做最低限度的文本整理:保留用户原话中的主体、动作、文字、语言和限制;如果用户分多段描述,可以原样拼接,不添加用户没说的内容。',
273
+ '- 不要自动补 negative_prompt;用户原话里没有的排除项不要加。',
274
+ '- 生图/改图时仍加载 skill mo-image-generation / mo-image-editing,使用其中的工具调用、参考图顺序和输出规则;但不要套用提示词公式、模板和自检清单。',
275
+ '- 尺寸、质量、提供商、模型由用户选择器控制;工具不接受这些参数,不要传。',
276
+ '- 只有用户明确要求“优化/改写提示词”时,才按当前模型方言优化,并说明这是应要求改写。',
277
+ '- 编辑时,prompt 也只写用户原话或最小必要修改说明;images 按用户指定的参考图传。',
278
+ ...DELIVERY_RULES,
279
+ '</mo-image-prompt>'
280
+ ].join('\n');
281
+ }
282
+ const profile = resolvePromptProfile(model, (state && state.adapter) || null);
283
+ const editModel = String((state && state.editModel) || '').trim();
284
+ const editProfile = editModel && editModel !== model
285
+ ? resolvePromptProfile(editModel, (state && state.editAdapter) || (state && state.adapter) || null)
286
+ : null;
287
+
288
+ const lines = [];
289
+ lines.push('<mo-image-prompt>');
290
+ lines.push('仅在用户需要生成/编辑图片时使用;其他任务忽略本节。');
291
+ lines.push('当前生图模型:' + model + '(' + profile.label + ')。按该模型的提示词方言写。');
292
+ lines.push('- 调用生图工具时必须传 model:' + model + '(工具会核对;不传或传错都会被拒绝)。');
293
+ for (const rule of DELIVERY_RULES) lines.push(rule);
294
+ lines.push('生成公式:' + GENERATION_FORMULA + '。');
295
+ for (const rule of profile.rules) lines.push('- ' + rule);
296
+ lines.push('- ' + (profile.supportsNegative
297
+ ? '支持 negative prompt:把畸变、水印、多余文字等放进 negative_prompt。'
298
+ : '无 negative prompt:用正面描述和硬约束表达排除项。'));
299
+ lines.push('- 提示词语言:' + languageLabel(profile.language) + ';用户明确指定时从用户。');
300
+ lines.push('- 尺寸、质量、提供商、模型由用户选择器控制;工具不接受这些参数,不要传。');
301
+ lines.push('编辑公式:' + EDITING_FORMULA + '。');
302
+ if (editProfile) {
303
+ lines.push('编辑模型:' + editModel + '(' + editProfile.label + ')——' + editProfile.editRule);
304
+ } else {
305
+ lines.push('编辑:' + profile.editRule);
306
+ }
307
+ lines.push('完整模板与示例:按需加载 skill mo-image-generation / mo-image-editing。');
308
+ lines.push('</mo-image-prompt>');
309
+ return lines.join('\n');
310
+ }
@@ -0,0 +1,212 @@
1
+ /**
2
+ * 一个最小的 undici dispatcher:把 fetch() 的请求塞进 HTTP 代理。
3
+ *
4
+ * 为什么不用 undici 包:插件是零依赖的,而且跨副本的 FormData/Blob 会被
5
+ * undici 的 brand check 静默绕过(multipart 会变成字符串 "[object FormData]")。
6
+ * 这里只接管传输层,请求体序列化仍然由宿主自带的 fetch 完成。
7
+ *
8
+ * 协议:https 目标走 CONNECT 隧道 + TLS;http 目标走 absolute-form。
9
+ */
10
+ import http from 'node:http';
11
+ import net from 'node:net';
12
+ import tls from 'node:tls';
13
+
14
+ const NO_BODY = Symbol('no-body');
15
+
16
+ function parseProxyUrl(proxyUrl) {
17
+ let url;
18
+ try { url = new URL(String(proxyUrl || '')); } catch (_error) { throw new Error('网络连接配置无效:' + proxyUrl); }
19
+ if (url.protocol !== 'http:') throw new Error('只支持 http:// 形式的连接配置:' + proxyUrl);
20
+ const auth = url.username
21
+ ? 'Basic ' + Buffer.from(decodeURIComponent(url.username) + ':' + decodeURIComponent(url.password || '')).toString('base64')
22
+ : '';
23
+ return {
24
+ host: url.hostname.replace(/^\[|\]$/g, ''),
25
+ port: Number(url.port) || 80,
26
+ auth: auth
27
+ };
28
+ }
29
+
30
+ function rawHeaderPairs(response) {
31
+ const out = [];
32
+ for (let index = 0; index < response.rawHeaders.length; index += 2) {
33
+ out.push(response.rawHeaders[index], response.rawHeaders[index + 1]);
34
+ }
35
+ return out;
36
+ }
37
+
38
+ function abortError() {
39
+ if (typeof DOMException === 'function') return new DOMException('This operation was aborted', 'AbortError');
40
+ const error = new Error('This operation was aborted');
41
+ error.name = 'AbortError';
42
+ return error;
43
+ }
44
+
45
+ function connectThroughProxy(proxy, host, port) {
46
+ return new Promise((resolve, reject) => {
47
+ const headers = { host: host + ':' + port };
48
+ if (proxy.auth) headers['proxy-authorization'] = proxy.auth;
49
+ const request = http.request({
50
+ host: proxy.host, port: proxy.port, method: 'CONNECT',
51
+ path: host + ':' + port, headers: headers, agent: false, setHost: false
52
+ });
53
+ request.once('connect', (response, socket, head) => {
54
+ if (response.statusCode !== 200) {
55
+ socket.destroy();
56
+ const error = new Error('连接失败:HTTP ' + response.statusCode);
57
+ error.code = 'ERR_PROXY_CONNECT';
58
+ reject(error);
59
+ return;
60
+ }
61
+ resolve({ socket, head });
62
+ });
63
+ request.once('error', reject);
64
+ request.end();
65
+ });
66
+ }
67
+
68
+ function upgradeToTls(socket, host, tlsOptions) {
69
+ const servername = net.isIP(host) ? undefined : host;
70
+ const options = Object.assign({ socket: socket, ALPNProtocols: ['http/1.1'] }, tlsOptions || {});
71
+ if (servername) options.servername = servername;
72
+ const secure = tls.connect(options);
73
+ return new Promise((resolve, reject) => {
74
+ secure.once('secureConnect', () => resolve(secure));
75
+ secure.once('error', reject);
76
+ });
77
+ }
78
+
79
+ /**
80
+ * 已经拿到连接(隧道或代理直连)后,用一次性 Agent 把连接塞给 http.request。
81
+ * 直接给 http.request 传 createConnection 会被默认 Agent 忽略,反而去连 host:80。
82
+ */
83
+ function requestOverSocket(socket, options, onResponse) {
84
+ const agent = new http.Agent({ keepAlive: false, maxSockets: 1 });
85
+ agent.createConnection = () => socket;
86
+ return http.request(Object.assign({}, options, { agent: agent }), onResponse);
87
+ }
88
+
89
+ function openTunnel(proxy, host, port) {
90
+ return new Promise((resolve, reject) => {
91
+ const socket = net.connect({ host: proxy.host, port: proxy.port });
92
+ socket.once('connect', () => resolve(socket));
93
+ socket.once('error', reject);
94
+ });
95
+ }
96
+
97
+ /**
98
+ * @param {{ proxyUrl: string, tlsOptions?: import('node:tls').ConnectionOptions, log?: (message: string) => void }} options
99
+ */
100
+ export function createProxyDispatcher(options = {}) {
101
+ const proxy = parseProxyUrl(options.proxyUrl);
102
+ const log = typeof options.log === 'function' ? options.log : () => {};
103
+
104
+ return {
105
+ dispatch(opts, handler) {
106
+ const target = new URL(opts.origin);
107
+ const isTls = target.protocol === 'https:' || target.protocol === 'wss:';
108
+ const host = target.hostname.replace(/^\[|\]$/g, '');
109
+ const port = Number(target.port) || (isTls ? 443 : 80);
110
+
111
+ let settled = false;
112
+ let socket = null;
113
+ let rawSocket = null;
114
+ let currentRequest = null;
115
+
116
+ // TLS socket 被 destroy 时不保证把底层 TCP 也关掉,代理那侧会一直挂着,
117
+ // 所以两个都显式销毁。
118
+ const closeTunnel = () => {
119
+ try { if (currentRequest) currentRequest.destroy(); } catch (_error) { /* ignore */ }
120
+ try { if (socket) socket.destroy(); } catch (_error) { /* ignore */ }
121
+ try { if (rawSocket && rawSocket !== socket) rawSocket.destroy(); } catch (_error) { /* ignore */ }
122
+ };
123
+
124
+ const finish = (error) => {
125
+ if (settled) return;
126
+ settled = true;
127
+ closeTunnel();
128
+ if (error) handler.onError(error);
129
+ };
130
+
131
+ if (typeof handler.onConnect === 'function') {
132
+ handler.onConnect(() => finish(abortError()));
133
+ }
134
+
135
+ if (opts.signal) {
136
+ if (opts.signal.aborted) { finish(abortError()); return; }
137
+ opts.signal.addEventListener('abort', () => finish(abortError()), { once: true });
138
+ }
139
+
140
+ const headers = Object.assign({}, opts.headers);
141
+ // 让上游别压缩:压缩是 fetch 那一层的事,这里透传会把 zlib 流打乱。
142
+ headers['accept-encoding'] = 'identity';
143
+ headers.connection = 'close';
144
+ headers.host = host + (port === (isTls ? 443 : 80) ? '' : ':' + port);
145
+
146
+ const sendPath = isTls ? opts.path : target.origin + opts.path;
147
+
148
+ (async () => {
149
+ if (isTls) {
150
+ const tunnel = await connectThroughProxy(proxy, host, port);
151
+ rawSocket = tunnel.socket;
152
+ if (settled) { closeTunnel(); return; }
153
+ if (tunnel.head && tunnel.head.length) rawSocket.unshift(tunnel.head);
154
+ socket = await upgradeToTls(rawSocket, host, options.tlsOptions);
155
+ } else {
156
+ rawSocket = await openTunnel(proxy, host, port);
157
+ socket = rawSocket;
158
+ if (proxy.auth) headers['proxy-authorization'] = proxy.auth;
159
+ }
160
+ // 连接建立期间可能已经被 abort:别把刚拿到的 socket 漏掉。
161
+ if (settled) { closeTunnel(); return; }
162
+
163
+ currentRequest = requestOverSocket(socket, {
164
+ host: host,
165
+ port: port,
166
+ method: opts.method,
167
+ path: sendPath,
168
+ headers: headers,
169
+ setHost: false
170
+ }, (response) => {
171
+ let resumed = false;
172
+ const resume = () => {
173
+ if (resumed) return;
174
+ resumed = true;
175
+ response.resume();
176
+ };
177
+ handler.onHeaders(response.statusCode, rawHeaderPairs(response), resume, response.statusMessage);
178
+ response.pause();
179
+ setImmediate(() => { if (!settled) resume(); });
180
+
181
+ response.on('data', (chunk) => {
182
+ if (settled) return;
183
+ handler.onData(chunk);
184
+ });
185
+ response.on('end', () => {
186
+ if (settled) return;
187
+ settled = true;
188
+ handler.onComplete([]);
189
+ closeTunnel();
190
+ log('tunnel closed after response: ' + host + ':' + port);
191
+ });
192
+ response.on('error', finish);
193
+ response.on('aborted', () => finish(new Error('响应被上游中断')));
194
+ });
195
+
196
+ currentRequest.on('error', finish);
197
+
198
+ if (opts.body && opts.body !== NO_BODY) {
199
+ for await (const chunk of opts.body) {
200
+ if (settled) return;
201
+ if (!currentRequest.write(chunk)) {
202
+ await new Promise((resolve) => currentRequest.once('drain', resolve));
203
+ }
204
+ }
205
+ }
206
+ currentRequest.end();
207
+ })().catch(finish);
208
+ },
209
+ close() { return Promise.resolve(); },
210
+ destroy() { return Promise.resolve(); }
211
+ };
212
+ }