dsh-mo-image 0.6.0 → 0.7.0
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/CHANGELOG.md +11 -0
- package/README.md +57 -17
- package/icon.png +0 -0
- package/lib/adapter-kit.js +363 -11
- package/lib/adapters/async.js +258 -31
- package/lib/adapters/cn.js +13 -0
- package/lib/adapters/openai.js +21 -2
- package/lib/adapters.js +880 -139
- package/lib/client.js +459 -131
- package/lib/comfy-workflow.js +7 -3
- package/lib/config-store.js +692 -0
- package/lib/image-execution.js +835 -0
- package/lib/image-jobs.js +333 -0
- package/lib/image-queue.js +195 -0
- package/lib/image-service.js +226 -0
- package/lib/image-worker.js +195 -0
- package/lib/index.js +439 -858
- package/lib/png-scale.js +103 -28
- package/lib/prompt-profiles.js +139 -68
- package/lib/request-auth.js +143 -0
- package/lib/retry.js +162 -0
- package/lib/settings-memory.js +33 -0
- package/lib/status.js +187 -0
- package/locale/messages.csv +226 -214
- package/package.json +3 -1
- package/skills/mo-image-editing/SKILL.md +34 -72
- package/skills/mo-image-generation/SKILL.md +59 -152
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 成图管道:收尾尺寸、严格模式缩放、Worker 卸载与成品保存。
|
|
3
|
+
*
|
|
4
|
+
* 这些逻辑原来长在 lib/index.js 里,和执行器/配置/路由混在一起。拆出来以后
|
|
5
|
+
* index.js 只负责装配与工具入口;这里只依赖适配器层的纯函数和 Worker 客户端,
|
|
6
|
+
* 不读配置、不发请求,测试也就能直接针对成图行为。
|
|
7
|
+
*/
|
|
8
|
+
import { mkdirSync } from 'node:fs';
|
|
9
|
+
import { writeFile } from 'node:fs/promises';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { randomUUID } from 'node:crypto';
|
|
12
|
+
|
|
13
|
+
import { aspectLabel, comfySizeWritable, imageSizeOf, resizeTo } from './adapters.js';
|
|
14
|
+
import { resizeInWorker } from './image-worker.js';
|
|
15
|
+
|
|
16
|
+
/** 从 content-type 猜扩展名;只有成品文件名用它,认不出按 png。 */
|
|
17
|
+
export function safeExt(contentType) {
|
|
18
|
+
const type = String(contentType || '').toLowerCase();
|
|
19
|
+
if (type.includes('jpeg') || type.includes('jpg')) return 'jpg';
|
|
20
|
+
if (type.includes('webp')) return 'webp';
|
|
21
|
+
if (type.includes('gif')) return 'gif';
|
|
22
|
+
return 'png';
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 工具结果/日志里给人看的尺寸标签。 */
|
|
26
|
+
export function sizeLabel(fitted) {
|
|
27
|
+
if (!fitted) return '';
|
|
28
|
+
if (fitted.omit || fitted.size === 'none') return 'auto';
|
|
29
|
+
if (fitted.size === 'auto') return fitted.width && fitted.height ? fitted.width + 'x' + fitted.height : 'auto';
|
|
30
|
+
return fitted.size;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 模型不接收尺寸参数时的降级:把尺寸写进提示词。
|
|
35
|
+
* 生图模型对英文尺寸句最稳,所以这句固定英文。
|
|
36
|
+
*/
|
|
37
|
+
export function stitchSizePrompt(prompt, fitted) {
|
|
38
|
+
const text = String(prompt || '');
|
|
39
|
+
if (!fitted || fitted.omit || !fitted.width || !fitted.height) return text;
|
|
40
|
+
return text + '\n\nOutput size: ' + fitted.width + 'x' + fitted.height
|
|
41
|
+
+ ' (' + aspectLabel(fitted.width, fitted.height) + ').';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 描述符声明了 stitch,或 ComfyUI 自定义工作流根本写不进尺寸时,把尺寸补进提示词。 */
|
|
45
|
+
export function applySizeStitch(prompt, fitted, adapter, provider, model) {
|
|
46
|
+
const declared = fitted && fitted.stitch === true;
|
|
47
|
+
// ComfyUI 自定义工作流:宽高既没有占位符也没有映射时,尺寸根本进不了图。
|
|
48
|
+
let blind = false;
|
|
49
|
+
if (adapter && adapter.id === 'comfyui' && provider) {
|
|
50
|
+
try { blind = !comfySizeWritable(provider, model); } catch (_error) { blind = false; }
|
|
51
|
+
}
|
|
52
|
+
if (!declared && !blind) return { prompt: prompt, note: '' };
|
|
53
|
+
const next = stitchSizePrompt(prompt, fitted);
|
|
54
|
+
if (next === prompt) return { prompt: prompt, note: '' };
|
|
55
|
+
return {
|
|
56
|
+
prompt: next,
|
|
57
|
+
note: '该模型不接收尺寸参数,尺寸 ' + fitted.width + 'x' + fitted.height + ' 已写进提示词'
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 收尾:读出回图真实尺寸,按严格模式决定要不要缩放,并把原始尺寸一并回报。
|
|
63
|
+
*
|
|
64
|
+
* 目标值只来自「请求里实际带的那个尺寸」(`fitted.requested`):
|
|
65
|
+
* 固定尺寸下是选择器的值,自动尺寸下是对话模型填进 size 的值。
|
|
66
|
+
* 档位名(`2K`)没有像素含义,官方连 2048×2048 都不保证,所以不拿它当目标。
|
|
67
|
+
*/
|
|
68
|
+
export function finalizeImage(result, options, log = () => {}) {
|
|
69
|
+
const strict = Boolean(options && options.strict === true);
|
|
70
|
+
let bytes = result.bytes;
|
|
71
|
+
let contentType = result.contentType;
|
|
72
|
+
let fitted = result.fitted;
|
|
73
|
+
let note = result && result.note ? String(result.note) : '';
|
|
74
|
+
const actual = imageSizeOf(bytes);
|
|
75
|
+
const generated = actual && actual.width && actual.height ? actual.width + 'x' + actual.height : '';
|
|
76
|
+
const omit = !fitted || fitted.omit || fitted.size === 'none';
|
|
77
|
+
const wanted = fitted && fitted.requested ? fitted.requested : null;
|
|
78
|
+
const wantedPixels = wanted ? wanted.width * wanted.height : 0;
|
|
79
|
+
const fittedPixels = fitted ? (fitted.width || 0) * (fitted.height || 0) : 0;
|
|
80
|
+
const appendNote = (text) => { note = note ? note + ';' + text : text; };
|
|
81
|
+
|
|
82
|
+
if (strict) {
|
|
83
|
+
if (!wanted || !wanted.width || !wanted.height) {
|
|
84
|
+
appendNote(omit
|
|
85
|
+
? '自动尺寸且请求未带尺寸,严格模式未生效'
|
|
86
|
+
: '该模型按档位出图,没有固定像素目标,严格模式未生效');
|
|
87
|
+
} else if (actual && (actual.width !== wanted.width || actual.height !== wanted.height)) {
|
|
88
|
+
const upscale = actual.width * actual.height < wanted.width * wanted.height;
|
|
89
|
+
// 缩之前留一份:严格模式改了像素,上游原图反而是没法再拿到的。
|
|
90
|
+
const originalBytes = bytes;
|
|
91
|
+
const resized = resizeTo(bytes, wanted.width, wanted.height, 'cover');
|
|
92
|
+
if (resized) {
|
|
93
|
+
bytes = resized.bytes;
|
|
94
|
+
contentType = resized.contentType;
|
|
95
|
+
fitted = Object.assign({}, fitted, {
|
|
96
|
+
size: wanted.text || (wanted.width + 'x' + wanted.height),
|
|
97
|
+
width: wanted.width,
|
|
98
|
+
height: wanted.height,
|
|
99
|
+
adjusted: false
|
|
100
|
+
});
|
|
101
|
+
appendNote('严格模式:上游出图 ' + generated + ',已' + (resized.cropped ? '裁切并' : '')
|
|
102
|
+
+ '缩放到 ' + fitted.size + (upscale ? '(已放大,画质有损)' : ''));
|
|
103
|
+
return {
|
|
104
|
+
bytes: bytes, contentType: contentType, fitted: fitted, note: note,
|
|
105
|
+
generated: generated, original: originalBytes
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
appendNote('严格模式:上游出图 ' + generated + ',未能缩放到 '
|
|
109
|
+
+ (wanted.text || wanted.width + 'x' + wanted.height) + ',成图保持原尺寸');
|
|
110
|
+
}
|
|
111
|
+
return { bytes: bytes, contentType: contentType, fitted: fitted, note: note, generated: generated };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// 非严格模式:只有我们自己把尺寸落大过,才缩回用户要的尺寸。
|
|
115
|
+
if (fitted && fitted.adjusted && wanted && wanted.width && wanted.height
|
|
116
|
+
&& wanted.text !== fitted.size && fittedPixels > wantedPixels) {
|
|
117
|
+
const resized = resizeTo(bytes, wanted.width, wanted.height);
|
|
118
|
+
if (resized) {
|
|
119
|
+
bytes = resized.bytes;
|
|
120
|
+
contentType = resized.contentType;
|
|
121
|
+
log('resize ' + fitted.size + ' → ' + wanted.text);
|
|
122
|
+
fitted = Object.assign({}, fitted, { size: wanted.text, width: wanted.width, height: wanted.height, adjusted: false });
|
|
123
|
+
} else {
|
|
124
|
+
log('resize unavailable, keep ' + fitted.size + '(用户要 ' + wanted.text + ')');
|
|
125
|
+
}
|
|
126
|
+
} else if (fitted && fitted.adjusted && wanted && fittedPixels < wantedPixels) {
|
|
127
|
+
const sizeNote = '该模型上限为 ' + fitted.size + ',已按上限生成(请求 ' + wanted.text + ',未放大)。';
|
|
128
|
+
appendNote(sizeNote);
|
|
129
|
+
log('keep model max ' + fitted.size + '(用户要 ' + wanted.text + ',不放大)');
|
|
130
|
+
}
|
|
131
|
+
return { bytes: bytes, contentType: contentType, fitted: fitted, note: note, generated: generated };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* 只有大图、且确实需要缩放时才进 Worker;小图/非 PNG 继续走同步的
|
|
136
|
+
* `finalizeImage`,省掉 Worker 的启动与消息开销。
|
|
137
|
+
*/
|
|
138
|
+
const WORKER_MIN_PIXELS = 512 * 1024;
|
|
139
|
+
|
|
140
|
+
function workerResizePlan(result, options) {
|
|
141
|
+
const strict = Boolean(options && options.strict === true);
|
|
142
|
+
const fitted = result && result.fitted;
|
|
143
|
+
const wanted = fitted && fitted.requested ? fitted.requested : null;
|
|
144
|
+
if (!wanted || !wanted.width || !wanted.height) return null;
|
|
145
|
+
const actual = imageSizeOf(result && result.bytes);
|
|
146
|
+
if (!actual || !actual.width || !actual.height) return null;
|
|
147
|
+
const same = actual.width === wanted.width && actual.height === wanted.height;
|
|
148
|
+
if (strict) return same ? null : { strict: true, mode: 'cover', actual: actual, wanted: wanted };
|
|
149
|
+
const fittedPixels = (fitted.width || 0) * (fitted.height || 0);
|
|
150
|
+
const wantedPixels = wanted.width * wanted.height;
|
|
151
|
+
if (fitted.adjusted && wanted.text !== fitted.size && fittedPixels > wantedPixels) {
|
|
152
|
+
return { strict: false, mode: undefined, actual: actual, wanted: wanted };
|
|
153
|
+
}
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* 异步版收尾:把大图的解码/裁切/缩放/编码放到 Worker;Worker 不可用、
|
|
159
|
+
* 超时或遇到非 PNG 时自动退回同步 `finalizeImage`,行为与原来完全一致。
|
|
160
|
+
*/
|
|
161
|
+
export async function finalizeImageAsync(result, options, log = () => {}) {
|
|
162
|
+
const plan = workerResizePlan(result, options);
|
|
163
|
+
if (!plan) return finalizeImage(result, options, log);
|
|
164
|
+
const sourcePixels = plan.actual.width * plan.actual.height;
|
|
165
|
+
const targetPixels = plan.wanted.width * plan.wanted.height;
|
|
166
|
+
if (Math.max(sourcePixels, targetPixels) < WORKER_MIN_PIXELS) return finalizeImage(result, options, log);
|
|
167
|
+
|
|
168
|
+
let resized = null;
|
|
169
|
+
try {
|
|
170
|
+
resized = await resizeInWorker(result.bytes, plan.wanted.width, plan.wanted.height, plan.mode);
|
|
171
|
+
} catch (_error) {
|
|
172
|
+
resized = null;
|
|
173
|
+
}
|
|
174
|
+
if (!resized) return finalizeImage(result, options, log);
|
|
175
|
+
|
|
176
|
+
// 已经缩好了,再让 finalizeImage 只负责 generate/note 等元数据;不能让它在
|
|
177
|
+
// 主线程把同一张图再解一遍。
|
|
178
|
+
const merged = Object.assign({}, result, {
|
|
179
|
+
bytes: resized.bytes,
|
|
180
|
+
contentType: resized.contentType,
|
|
181
|
+
fitted: Object.assign({}, result.fitted, { adjusted: false })
|
|
182
|
+
});
|
|
183
|
+
const final = finalizeImage(merged, options, log);
|
|
184
|
+
const wanted = plan.wanted;
|
|
185
|
+
const fitted = Object.assign({}, final.fitted, {
|
|
186
|
+
size: wanted.text || (wanted.width + 'x' + wanted.height),
|
|
187
|
+
width: wanted.width, height: wanted.height, adjusted: false
|
|
188
|
+
});
|
|
189
|
+
const generated = plan.actual.width + 'x' + plan.actual.height;
|
|
190
|
+
let note = final.note || '';
|
|
191
|
+
const append = (text) => { note = note ? note + ';' + text : text; };
|
|
192
|
+
if (plan.strict) {
|
|
193
|
+
const upscale = sourcePixels < targetPixels;
|
|
194
|
+
append('严格模式:上游出图 ' + generated + ',已' + (resized.cropped ? '裁切并' : '')
|
|
195
|
+
+ '缩放到 ' + fitted.size + (upscale ? '(已放大,画质有损)' : ''));
|
|
196
|
+
}
|
|
197
|
+
return Object.assign({}, final, {
|
|
198
|
+
bytes: resized.bytes, contentType: resized.contentType, fitted: fitted,
|
|
199
|
+
note: note, generated: generated,
|
|
200
|
+
original: plan.strict ? result.bytes : final.original
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** 生成图旁边留一份上游原图(严格模式缩过图时用)。 */
|
|
205
|
+
export async function saveSidecar(bytes, contentType, file, log = () => {}) {
|
|
206
|
+
try {
|
|
207
|
+
const ext = safeExt(contentType);
|
|
208
|
+
const base = path.basename(file, path.extname(file));
|
|
209
|
+
const target = path.join(path.dirname(file), base + '-original.' + ext);
|
|
210
|
+
await writeFile(target, bytes);
|
|
211
|
+
return target;
|
|
212
|
+
} catch (error) {
|
|
213
|
+
log('save original failed: ' + String(error && error.message ? error.message : error));
|
|
214
|
+
return '';
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** 把成品写进调用方选定的目录(当前项目 generated-images 或 DSH 状态目录)。 */
|
|
219
|
+
export async function saveImage(bytes, contentType, provider, model, size, dir) {
|
|
220
|
+
mkdirSync(dir, { recursive: true });
|
|
221
|
+
const ext = safeExt(contentType);
|
|
222
|
+
const filename = 'mo-' + Date.now() + '-' + randomUUID().slice(0, 8) + '.' + ext;
|
|
223
|
+
const file = path.join(dir, filename);
|
|
224
|
+
await writeFile(file, bytes);
|
|
225
|
+
return { file, filename, provider: provider.name || provider.id, model, size, bytes: bytes.length, contentType };
|
|
226
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 大图处理的受控 Worker(OPTIMIZATION_PLAN 阶段 D2)。
|
|
3
|
+
*
|
|
4
|
+
* 主线程只负责收图和落盘;解码、裁切、缩放、编码都在 Worker 里做。
|
|
5
|
+
* 一个 4K PNG 解码后是 33MB 的 RGBA,在主线程上做面积平均缩放会把事件循环
|
|
6
|
+
* 顶住几百毫秒,设置页和对话流都会卡;Worker 里做,主线程只等一条消息。
|
|
7
|
+
*
|
|
8
|
+
* 失败一律回 null,让调用方退回同步的 `resizeTo()`;Worker 起不来、超时、
|
|
9
|
+
* 图片格式不支持都不应该让一次生图失败。并发 1 个 Worker 是有意的:
|
|
10
|
+
* 上游本身已经有 2 并发的队列,这里再开多线程只会抢 CPU 和内存。
|
|
11
|
+
*/
|
|
12
|
+
import { isMainThread, parentPort, Worker } from 'node:worker_threads';
|
|
13
|
+
import { Buffer } from 'node:buffer';
|
|
14
|
+
|
|
15
|
+
import { decodePng, encodePng, resizeRgba } from './png-scale.js';
|
|
16
|
+
|
|
17
|
+
const MAX_SIDE = 16384;
|
|
18
|
+
const MAX_PIXELS = 32 * 1024 * 1024;
|
|
19
|
+
const DEFAULT_TIMEOUT_MS = 30000;
|
|
20
|
+
|
|
21
|
+
function targetOk(width, height) {
|
|
22
|
+
return Number.isSafeInteger(width) && Number.isSafeInteger(height)
|
|
23
|
+
&& width > 0 && height > 0
|
|
24
|
+
&& width <= MAX_SIDE && height <= MAX_SIDE
|
|
25
|
+
&& width * height <= MAX_PIXELS;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 居中裁切一段 RGBA;和 adapters.js 的 cover 语义保持一致。 */
|
|
29
|
+
function cropRgba(rgba, width, height, left, top, cropWidth, cropHeight) {
|
|
30
|
+
const out = new Uint8Array(cropWidth * cropHeight * 4);
|
|
31
|
+
for (let y = 0; y < cropHeight; y++) {
|
|
32
|
+
const from = ((top + y) * width + left) * 4;
|
|
33
|
+
out.set(rgba.subarray(from, from + cropWidth * 4), y * cropWidth * 4);
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function coverCrop(image, targetWidth, targetHeight) {
|
|
39
|
+
const targetRatio = targetWidth / targetHeight;
|
|
40
|
+
const ratio = image.width / image.height;
|
|
41
|
+
if (Math.abs(ratio - targetRatio) <= 0.01) return null;
|
|
42
|
+
let cropWidth = image.width;
|
|
43
|
+
let cropHeight = Math.round(image.width / targetRatio);
|
|
44
|
+
if (cropHeight > image.height) {
|
|
45
|
+
cropHeight = image.height;
|
|
46
|
+
cropWidth = Math.round(image.height * targetRatio);
|
|
47
|
+
}
|
|
48
|
+
if (cropWidth <= 0 || cropHeight <= 0) return null;
|
|
49
|
+
const left = Math.max(0, Math.floor((image.width - cropWidth) / 2));
|
|
50
|
+
const top = Math.max(0, Math.floor((image.height - cropHeight) / 2));
|
|
51
|
+
return {
|
|
52
|
+
width: cropWidth,
|
|
53
|
+
height: cropHeight,
|
|
54
|
+
rgba: cropRgba(image.rgba, image.width, image.height, left, top, cropWidth, cropHeight)
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/* --------------------------------------------------------------- worker 侧 */
|
|
59
|
+
|
|
60
|
+
if (!isMainThread && parentPort) {
|
|
61
|
+
parentPort.on('message', (message) => {
|
|
62
|
+
const id = message && message.id;
|
|
63
|
+
try {
|
|
64
|
+
const width = Number(message && message.width);
|
|
65
|
+
const height = Number(message && message.height);
|
|
66
|
+
if (!id || !targetOk(width, height)) {
|
|
67
|
+
parentPort.postMessage({ id: id, ok: false });
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
const bytes = Buffer.from(message.bytes);
|
|
71
|
+
const image = decodePng(bytes);
|
|
72
|
+
if (!image) {
|
|
73
|
+
parentPort.postMessage({ id: id, ok: false });
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
let source = image;
|
|
77
|
+
let cropped = false;
|
|
78
|
+
if (message.mode === 'cover') {
|
|
79
|
+
const next = coverCrop(image, width, height);
|
|
80
|
+
if (next) { source = next; cropped = true; }
|
|
81
|
+
}
|
|
82
|
+
const rgba = resizeRgba(source.rgba, source.width, source.height, width, height);
|
|
83
|
+
const encoded = encodePng(rgba, width, height);
|
|
84
|
+
// 复制到独立的 ArrayBuffer 再转移:Buffer.concat 返回的底层 buffer
|
|
85
|
+
// 可能来自共享池,直接写进 transfer list 会被 worker_threads 拒绝。
|
|
86
|
+
const out = new Uint8Array(encoded);
|
|
87
|
+
parentPort.postMessage({ id: id, ok: true, bytes: out.buffer, cropped: cropped }, [out.buffer]);
|
|
88
|
+
} catch (error) {
|
|
89
|
+
parentPort.postMessage({ id: id, ok: false, error: String(error && error.message ? error.message : error) });
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/* ----------------------------------------------------------------- 主线程 */
|
|
95
|
+
|
|
96
|
+
let worker = null;
|
|
97
|
+
let nextId = 1;
|
|
98
|
+
const pending = new Map();
|
|
99
|
+
|
|
100
|
+
function settleAll() {
|
|
101
|
+
for (const entry of pending.values()) {
|
|
102
|
+
clearTimeout(entry.timer);
|
|
103
|
+
entry.resolve(null);
|
|
104
|
+
}
|
|
105
|
+
pending.clear();
|
|
106
|
+
worker = null;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function ensureWorker() {
|
|
110
|
+
if (worker) return worker;
|
|
111
|
+
const created = new Worker(new URL('./image-worker.js', import.meta.url));
|
|
112
|
+
worker = created;
|
|
113
|
+
// 不因为这个 Worker 让宿主进程无法退出;每次请求仍有自己的超时。
|
|
114
|
+
if (typeof created.unref === 'function') created.unref();
|
|
115
|
+
created.on('message', (message) => {
|
|
116
|
+
const entry = pending.get(message && message.id);
|
|
117
|
+
if (!entry) return;
|
|
118
|
+
pending.delete(entry.id);
|
|
119
|
+
clearTimeout(entry.timer);
|
|
120
|
+
if (message.ok && message.bytes) {
|
|
121
|
+
entry.resolve({
|
|
122
|
+
bytes: Buffer.from(message.bytes),
|
|
123
|
+
contentType: 'image/png',
|
|
124
|
+
resized: true,
|
|
125
|
+
cropped: !!message.cropped
|
|
126
|
+
});
|
|
127
|
+
} else {
|
|
128
|
+
entry.resolve(null);
|
|
129
|
+
}
|
|
130
|
+
if (pending.size === 0 && typeof created.unref === 'function') created.unref();
|
|
131
|
+
});
|
|
132
|
+
// 旧 Worker 被 close/重启后,它的 exit 不能把新 Worker 的请求一起结算掉。
|
|
133
|
+
created.on('error', () => { if (worker === created) settleAll(); });
|
|
134
|
+
created.on('exit', () => { if (worker === created) settleAll(); });
|
|
135
|
+
return created;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function releaseWorkerIfIdle() {
|
|
139
|
+
if (pending.size === 0 && worker && typeof worker.unref === 'function') worker.unref();
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* 在 Worker 里把 PNG 缩放/裁切到目标尺寸。
|
|
144
|
+
*
|
|
145
|
+
* @param {Buffer} bytes 原始 PNG
|
|
146
|
+
* @param {number} width 目标宽
|
|
147
|
+
* @param {number} height 目标高
|
|
148
|
+
* @param {string} [mode] 'cover' 先居中裁切
|
|
149
|
+
* @param {{timeoutMs?:number}} [options]
|
|
150
|
+
* @returns {Promise<{bytes:Buffer,contentType:string,resized:boolean,cropped:boolean}|null>}
|
|
151
|
+
*/
|
|
152
|
+
export function resizeInWorker(bytes, width, height, mode, options = {}) {
|
|
153
|
+
if (!Buffer.isBuffer(bytes) || !targetOk(Number(width), Number(height))) return Promise.resolve(null);
|
|
154
|
+
let active;
|
|
155
|
+
try {
|
|
156
|
+
active = ensureWorker();
|
|
157
|
+
} catch (_error) {
|
|
158
|
+
return Promise.resolve(null);
|
|
159
|
+
}
|
|
160
|
+
const requestedTimeout = options && options.timeoutMs !== undefined ? Number(options.timeoutMs) : DEFAULT_TIMEOUT_MS;
|
|
161
|
+
if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) return Promise.resolve(null);
|
|
162
|
+
const timeoutMs = requestedTimeout;
|
|
163
|
+
return new Promise((resolve) => {
|
|
164
|
+
const id = nextId++;
|
|
165
|
+
if (typeof active.ref === 'function') active.ref();
|
|
166
|
+
const timer = setTimeout(() => {
|
|
167
|
+
if (!pending.has(id)) return;
|
|
168
|
+
pending.delete(id);
|
|
169
|
+
releaseWorkerIfIdle();
|
|
170
|
+
resolve(null);
|
|
171
|
+
}, timeoutMs);
|
|
172
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
173
|
+
pending.set(id, { id: id, resolve: resolve, timer: timer });
|
|
174
|
+
// 复制一份再转移:Buffer 可能来自共享的 Buffer 池,转移共享底层内存会破坏其他引用。
|
|
175
|
+
// 复制到独立的 ArrayBuffer 再转移:Buffer 可能来自 Node 的共享池,
|
|
176
|
+
// 池底层的 ArrayBuffer 带 byteOffset,直接放进 transfer list 会被拒绝。
|
|
177
|
+
const copy = new Uint8Array(bytes);
|
|
178
|
+
try {
|
|
179
|
+
active.postMessage({ id: id, bytes: copy.buffer, width: Number(width), height: Number(height), mode: mode }, [copy.buffer]);
|
|
180
|
+
} catch (_error) {
|
|
181
|
+
pending.delete(id);
|
|
182
|
+
clearTimeout(timer);
|
|
183
|
+
releaseWorkerIfIdle();
|
|
184
|
+
resolve(null);
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** 关闭 Worker;测试和插件卸载时调用。进行中的请求回 null,由调用方同步兜底。 */
|
|
190
|
+
export function closeImageWorker() {
|
|
191
|
+
if (!worker) return;
|
|
192
|
+
try { worker.terminate(); } catch (_error) { /* ignore */ }
|
|
193
|
+
if (typeof worker.unref === 'function') worker.unref();
|
|
194
|
+
settleAll();
|
|
195
|
+
}
|