dsh-game-material-master 0.1.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/lib/minimax.js ADDED
@@ -0,0 +1,390 @@
1
+ /**
2
+ * MiniMax 视频生成客户端(图生视频)。
3
+ *
4
+ * 两套协议并存,按模型名自动选择:
5
+ *
6
+ * **v2(MiniMax-H3 / H3-Max)** —— 平台新的统一入口,多模态 content 数组:
7
+ * 1. `POST {root}/v2/video_generation` → task_id
8
+ * 2. `GET {root}/v2/query/video_generation/{id}` → status + content.url
9
+ * 查询接口**直接返回视频地址**,不需要再走一次取件。
10
+ *
11
+ * **v1(Hailuo / I2V 系列)** —— 老的三步走:
12
+ * 1. `POST {root}/v1/video_generation` → task_id
13
+ * 2. `GET {root}/v1/query/video_generation` → status / file_id
14
+ * 3. `GET {root}/v1/files/retrieve` → download_url
15
+ *
16
+ * **优云智算版 H3(`MiniMax-H3(优云智算)`)** —— H3 的第三方网关,请求体与官方 v2
17
+ * 完全一致,只是路径多一层 `/minimax` 前缀(`{root}/minimax/v2/...`),模型名仍是
18
+ * `MiniMax-H3`;分辨率多支持 1080P/4K 后置超分,时长放宽到 4~30 秒。它由用户在设置里
19
+ * **显式选择**,本模块不从 Base URL 或 Key 前缀去猜。
20
+ *
21
+ * 提交与轮询分开,是因为 8 个视频要并发提交、统一轮询;一次生成通常需要
22
+ * 1~6 分钟,绝不能同步阻塞一次远程调用。
23
+ */
24
+ /**
25
+ * 优云智算(Compshare)版 H3:与官方 H3 是**同一个模型**,只是走第三方网关。
26
+ * 因此把它做成一个独立的可选项,由用户在设置里显式选择——不从 Base URL 或
27
+ * Key 前缀去猜。请求体里的 `model` 仍然是 `MiniMax-H3`,只有路径多一层 `/minimax`。
28
+ */
29
+ export const COMP_SHARE_MODEL_ID = "MiniMax-H3 优云智算";
30
+ export const COMP_SHARE_BASE_URL = "https://cp.compshare.cn";
31
+ export const COMP_SHARE_PATH_PREFIX = "/minimax";
32
+ export const MODEL_CAPABILITIES = {
33
+ "MiniMax-H3": {
34
+ protocol: "v2",
35
+ resolutions: ["2K", "768P"],
36
+ durationMin: 4,
37
+ durationMax: 15,
38
+ note: "v2 · 768P/2K · 4~15 秒"
39
+ },
40
+ [COMP_SHARE_MODEL_ID]: {
41
+ protocol: "v2",
42
+ resolutions: ["2K", "1080P", "768P"],
43
+ durationMin: 4,
44
+ durationMax: 30,
45
+ note: "v2 优云智算 · 768P/1080P/2K · 4~30 秒"
46
+ },
47
+ "MiniMax-H3-Max": {
48
+ protocol: "v2",
49
+ resolutions: ["768P", "480P"],
50
+ durationMin: 5,
51
+ durationMax: 15,
52
+ note: "v2 极速 · 480P/768P · 5~15 秒"
53
+ },
54
+ "MiniMax-Hailuo-02": {
55
+ protocol: "v1",
56
+ resolutions: ["768P", "1080P"],
57
+ durations: [6, 10],
58
+ durationMin: 6,
59
+ durationMax: 10,
60
+ note: "v1 · 6/10 秒"
61
+ },
62
+ "I2V-01-Director": {
63
+ protocol: "v1",
64
+ resolutions: ["720P"],
65
+ durations: [6],
66
+ durationMin: 6,
67
+ durationMax: 6,
68
+ note: "v1 · 支持运镜指令"
69
+ },
70
+ "I2V-01": { protocol: "v1", resolutions: ["720P"], durations: [6], durationMin: 6, durationMax: 6, note: "v1" },
71
+ "I2V-01-live": { protocol: "v1", resolutions: ["720P"], durations: [6], durationMin: 6, durationMax: 6, note: "v1" }
72
+ };
73
+ export class MiniMaxError extends Error {
74
+ status;
75
+ code;
76
+ constructor(message, status, code) {
77
+ super(message);
78
+ this.name = "MiniMaxError";
79
+ this.status = status;
80
+ this.code = code;
81
+ }
82
+ }
83
+ /** 从模型名判断走哪套协议。 */
84
+ export function protocolOf(model) {
85
+ return /^MiniMax-H3/i.test(model.trim()) ? "v2" : "v1";
86
+ }
87
+ /** 这个模型选择是不是「优云智算版 H3」。 */
88
+ export function isCompshareModel(model) {
89
+ return model.trim() === COMP_SHARE_MODEL_ID;
90
+ }
91
+ /** 发给远端的 `model` 字段:优云智算版对外的模型名仍然是 `MiniMax-H3`。 */
92
+ export function apiModelOf(model) {
93
+ return isCompshareModel(model) ? "MiniMax-H3" : model.trim();
94
+ }
95
+ /** 优云智算版固定走自己的网关,其余模型用配置里的 Base URL。 */
96
+ export function gatewayOf(model, baseUrl) {
97
+ return isCompshareModel(model) ? COMP_SHARE_BASE_URL : rootOf(baseUrl);
98
+ }
99
+ /**
100
+ * 依据模型选择返回路径前缀。
101
+ * 官方站(api.minimaxi.com / api.minimax.cn)直接挂 `/v1`、`/v2`;
102
+ * 优云智算版(cp.compshare.cn)把 MiniMax 的接口放在 `/minimax/v1`、`/minimax/v2` 下。
103
+ */
104
+ export function pathPrefixOf(model) {
105
+ return isCompshareModel(model) ? COMP_SHARE_PATH_PREFIX : "";
106
+ }
107
+ /** 某个模型的能力;未知模型按协议给一套宽松区间。 */
108
+ export function capabilityOf(model) {
109
+ const trimmed = model.trim();
110
+ const known = MODEL_CAPABILITIES[trimmed];
111
+ if (known !== undefined)
112
+ return known;
113
+ const protocol = protocolOf(trimmed);
114
+ return protocol === "v2"
115
+ ? { protocol, resolutions: ["2K", "768P"], durationMin: 4, durationMax: 15, note: "v2(自定义模型)" }
116
+ : { protocol, resolutions: ["1080P", "768P"], durationMin: 6, durationMax: 10, note: "v1(自定义模型)" };
117
+ }
118
+ /**
119
+ * 把 baseUrl 收敛成主机根。
120
+ * 历史配置里存的是 `.../v1`,所以这里顺手把结尾的 `/v1`、`/v2` 剥掉——
121
+ * 路径一律由本模块按协议拼,避免出现 `/v1/v2/...` 这种组合。
122
+ */
123
+ export function rootOf(baseUrl) {
124
+ return baseUrl
125
+ .trim()
126
+ .replace(/\/+$/, "")
127
+ .replace(/\/(v1|v2)$/i, "");
128
+ }
129
+ /** 按模型能力把时长收敛到合法值。 */
130
+ export function normalizeDuration(model, value) {
131
+ const capability = capabilityOf(model);
132
+ const n = typeof value === "number" ? value : Number.parseInt(String(value ?? ""), 10);
133
+ const wanted = Number.isFinite(n) ? Math.round(n) : capability.durationMin;
134
+ if (capability.durations !== undefined && capability.durations.length > 0) {
135
+ // 定值档位:取最接近的一档。距离相同时取更长的那一档——片段越长,
136
+ // 「走三步」越容易完整落进画面,而这个插件要的正是步伐帧。
137
+ let best = capability.durations[0];
138
+ for (const candidate of capability.durations) {
139
+ const candidateGap = Math.abs(candidate - wanted);
140
+ const bestGap = Math.abs(best - wanted);
141
+ if (candidateGap < bestGap || (candidateGap === bestGap && candidate > best))
142
+ best = candidate;
143
+ }
144
+ return best;
145
+ }
146
+ return Math.min(capability.durationMax, Math.max(capability.durationMin, wanted));
147
+ }
148
+ /** 按模型能力把分辨率收敛到合法档位。 */
149
+ export function normalizeResolution(model, value) {
150
+ const capability = capabilityOf(model);
151
+ const wanted = String(value ?? "").trim();
152
+ return capability.resolutions.includes(wanted) ? wanted : capability.resolutions[0];
153
+ }
154
+ function headers(apiKey) {
155
+ return {
156
+ Authorization: `Bearer ${apiKey}`,
157
+ "Content-Type": "application/json"
158
+ };
159
+ }
160
+ function assertKey(apiKey) {
161
+ if (apiKey.trim() === "")
162
+ throw new MiniMaxError("尚未配置 MiniMax API Key(设置 → 游戏素材大师)");
163
+ }
164
+ /**
165
+ * 解析错误响应。平台上有两种风格:
166
+ * - v1:`{ base_resp: { status_code, status_msg } }`
167
+ * - v2:`{ type: "error", error: { type, message, http_code } }`(OpenAI 风格)
168
+ */
169
+ async function readError(response) {
170
+ const text = await response.text().catch(() => "");
171
+ if (text.trim() === "")
172
+ return { message: `HTTP ${response.status} ${response.statusText}` };
173
+ try {
174
+ const parsed = JSON.parse(text);
175
+ const base = parsed?.base_resp;
176
+ if (base !== undefined && base.status_code !== undefined && base.status_code !== 0) {
177
+ return { message: `[${base.status_code}] ${base.status_msg}`, code: String(base.status_code) };
178
+ }
179
+ const err = parsed?.error ?? parsed;
180
+ const message = typeof err?.message === "string"
181
+ ? err.message
182
+ : typeof parsed?.message === "string"
183
+ ? parsed.message
184
+ : text.slice(0, 500);
185
+ const code = typeof err?.code === "string" ? err.code : typeof err?.type === "string" ? err.type : undefined;
186
+ return { message, code };
187
+ }
188
+ catch {
189
+ return { message: text.slice(0, 500) };
190
+ }
191
+ }
192
+ async function requestJson(url, init, timeoutMs, what) {
193
+ const timeout = AbortSignal.timeout(Math.max(10000, timeoutMs));
194
+ let response;
195
+ try {
196
+ response = await fetch(url, { ...init, signal: timeout });
197
+ }
198
+ catch (error) {
199
+ if (timeout.aborted)
200
+ throw new MiniMaxError(`${what}超时(${Math.round(timeoutMs / 1000)} 秒)`);
201
+ throw new MiniMaxError(`无法连接 MiniMax:${error instanceof Error ? error.message : String(error)}`);
202
+ }
203
+ if (!response.ok) {
204
+ const { message, code } = await readError(response);
205
+ throw new MiniMaxError(`${what}失败(HTTP ${response.status}):${message}`, response.status, code);
206
+ }
207
+ const payload = (await response.json().catch(() => undefined));
208
+ const base = payload?.base_resp;
209
+ if (base !== undefined && base.status_code !== 0) {
210
+ throw new MiniMaxError(`${what}失败:[${base.status_code}] ${base.status_msg}`, response.status, String(base.status_code));
211
+ }
212
+ return payload;
213
+ }
214
+ /** 判断这次请求是「首尾帧模式」还是「多模态参考模式」。 */
215
+ export function mediaModeOf(input) {
216
+ const hasFrame = (input.firstFrameImage ?? "") !== "" || (input.lastFrameImage ?? "") !== "";
217
+ const hasRef = (input.referenceImages?.length ?? 0) > 0 || (input.referenceVideos?.length ?? 0) > 0;
218
+ if (hasFrame && hasRef) {
219
+ throw new MiniMaxError("首帧/尾帧模式与多模态参考模式不能混用:请二选一");
220
+ }
221
+ if (hasFrame)
222
+ return "frames";
223
+ if (hasRef)
224
+ return "reference";
225
+ return "text";
226
+ }
227
+ /** v2:多模态 content 数组。 */
228
+ function buildV2Body(input) {
229
+ const mode = mediaModeOf(input);
230
+ const content = [{ type: "text", text: input.prompt }];
231
+ if (mode === "frames") {
232
+ if ((input.firstFrameImage ?? "") !== "") {
233
+ content.push({ type: "image_url", image_url: { url: input.firstFrameImage }, role: "first_frame" });
234
+ }
235
+ if ((input.lastFrameImage ?? "") !== "") {
236
+ content.push({ type: "image_url", image_url: { url: input.lastFrameImage }, role: "last_frame" });
237
+ }
238
+ }
239
+ else if (mode === "reference") {
240
+ for (const url of input.referenceImages ?? []) {
241
+ content.push({ type: "image_url", image_url: { url }, role: "reference_image" });
242
+ }
243
+ for (const url of input.referenceVideos ?? []) {
244
+ content.push({ type: "video_url", video_url: { url }, role: "reference_video" });
245
+ }
246
+ }
247
+ const body = {
248
+ model: apiModelOf(input.model),
249
+ content,
250
+ resolution: normalizeResolution(input.model, input.resolution),
251
+ duration: normalizeDuration(input.model, input.duration),
252
+ // 首尾帧模式的宽高比由首帧图决定,官方规定恒为 adaptive;
253
+ // 参考模式可选;纯文生视频必须给具体比例(默认 16:9)。
254
+ ratio: input.ratio ?? (mode === "text" ? "16:9" : "adaptive")
255
+ };
256
+ // extra 只有 H3-Max 认;别的模型传了会被判为未声明字段。
257
+ if (/H3-Max/i.test(input.model) && input.promptOptimizer !== undefined) {
258
+ body.extra = { prompt_expansion_mode: input.promptOptimizer ? "balanced" : "disabled" };
259
+ }
260
+ return body;
261
+ }
262
+ /** v1:扁平参数,只支持首帧图;参考模式是 v2 才有的能力。 */
263
+ function buildV1Body(input) {
264
+ const mode = mediaModeOf(input);
265
+ if (mode === "reference") {
266
+ throw new MiniMaxError("参考图 / 参考视频模式需要 MiniMax-H3 系列(v2 协议),当前模型不支持");
267
+ }
268
+ if (mode === "text") {
269
+ throw new MiniMaxError("v1 协议只支持图生视频,请提供一张首帧图");
270
+ }
271
+ const body = {
272
+ model: input.model,
273
+ prompt: input.prompt,
274
+ first_frame_image: input.firstFrameImage
275
+ };
276
+ // duration / resolution 是 Hailuo 系列的参数,I2V-01 传了会报错。
277
+ if (/hailuo/i.test(input.model)) {
278
+ if (input.duration !== undefined)
279
+ body.duration = normalizeDuration(input.model, input.duration);
280
+ if (input.resolution !== undefined)
281
+ body.resolution = normalizeResolution(input.model, input.resolution);
282
+ }
283
+ if (input.promptOptimizer !== undefined)
284
+ body.prompt_optimizer = input.promptOptimizer;
285
+ return body;
286
+ }
287
+ /** 提交一个图生视频任务,返回 task_id。 */
288
+ export async function submitVideo(input) {
289
+ assertKey(input.apiKey);
290
+ if ((input.prompt ?? "").trim() === "")
291
+ throw new MiniMaxError("提示词不能为空");
292
+ // 优云智算版固定走它自己的网关;其余模型用配置里的 Base URL。
293
+ const root = gatewayOf(input.model, input.baseUrl);
294
+ const prefix = pathPrefixOf(input.model);
295
+ const isV2 = protocolOf(input.model) === "v2";
296
+ const url = isV2 ? `${root}${prefix}/v2/video_generation` : `${root}${prefix}/v1/video_generation`;
297
+ const body = isV2 ? buildV2Body(input) : buildV1Body(input);
298
+ const payload = await requestJson(url, { method: "POST", headers: headers(input.apiKey), body: JSON.stringify(body) }, input.timeoutMs, "提交视频任务");
299
+ const taskId = payload?.task_id ?? payload?.task?.id;
300
+ if (typeof taskId !== "string" || taskId === "") {
301
+ throw new MiniMaxError(`MiniMax 未返回 task_id:${JSON.stringify(payload).slice(0, 400)}`);
302
+ }
303
+ return taskId;
304
+ }
305
+ function mapV2Status(raw) {
306
+ switch (raw) {
307
+ case "succeeded":
308
+ return "succeeded";
309
+ case "failed":
310
+ case "cancelled":
311
+ return "failed";
312
+ case "running":
313
+ return "running";
314
+ default:
315
+ return "pending";
316
+ }
317
+ }
318
+ function mapV1Status(raw) {
319
+ switch (raw) {
320
+ case "Success":
321
+ return "succeeded";
322
+ case "Fail":
323
+ return "failed";
324
+ case "Processing":
325
+ case "Preparing":
326
+ case "Queueing":
327
+ return "running";
328
+ default:
329
+ return "pending";
330
+ }
331
+ }
332
+ export async function queryVideo(input) {
333
+ assertKey(input.apiKey);
334
+ const root = gatewayOf(input.model, input.baseUrl);
335
+ const prefix = pathPrefixOf(input.model);
336
+ if (protocolOf(input.model) === "v2") {
337
+ const payload = await requestJson(`${root}${prefix}/v2/query/video_generation/${encodeURIComponent(input.taskId)}`, { method: "GET", headers: headers(input.apiKey) }, input.timeoutMs, "查询视频任务");
338
+ const task = payload?.task ?? payload;
339
+ const remoteStatus = String(task?.status ?? "");
340
+ const videoUrl = typeof task?.content?.url === "string" && task.content.url !== "" ? task.content.url : undefined;
341
+ const errorMessage = task?.error !== undefined
342
+ ? [task.error.code, task.error.message].filter((v) => typeof v === "string" && v !== "").join(":")
343
+ : undefined;
344
+ return { status: mapV2Status(remoteStatus), remoteStatus, videoUrl, error: errorMessage, raw: payload };
345
+ }
346
+ const payload = await requestJson(`${root}${prefix}/v1/query/video_generation?task_id=${encodeURIComponent(input.taskId)}`, { method: "GET", headers: headers(input.apiKey) }, input.timeoutMs, "查询视频任务");
347
+ const remoteStatus = String(payload?.status ?? "");
348
+ const fileId = typeof payload?.file_id === "string" && payload.file_id !== "" ? payload.file_id : undefined;
349
+ return { status: mapV1Status(remoteStatus), remoteStatus, fileId, raw: payload };
350
+ }
351
+ /** v1 专用:用 file_id 换取下载地址。v2 直接给 content.url,不需要这一步。 */
352
+ export async function retrieveFile(input) {
353
+ assertKey(input.apiKey);
354
+ const payload = await requestJson(`${gatewayOf(input.model, input.baseUrl)}${pathPrefixOf(input.model)}/v1/files/retrieve?file_id=${encodeURIComponent(input.fileId)}`, { method: "GET", headers: headers(input.apiKey) }, input.timeoutMs, "获取视频下载地址");
355
+ const url = payload?.file?.download_url;
356
+ if (typeof url !== "string" || url === "") {
357
+ throw new MiniMaxError(`MiniMax 未返回下载地址:${JSON.stringify(payload).slice(0, 400)}`);
358
+ }
359
+ return url;
360
+ }
361
+ /** 把视频下载到本地。 */
362
+ export async function downloadVideo(url, timeoutMs) {
363
+ const timeout = AbortSignal.timeout(Math.max(30000, timeoutMs));
364
+ const response = await fetch(url, { signal: timeout });
365
+ if (!response.ok)
366
+ throw new MiniMaxError(`下载视频失败(HTTP ${response.status})`);
367
+ return Buffer.from(await response.arrayBuffer());
368
+ }
369
+ /**
370
+ * 连通性自检:查一个不存在的任务。
371
+ * 免费,且能精确区分「Key 无效」与「Key 有效但任务不存在」。
372
+ */
373
+ export async function testMiniMax(input) {
374
+ assertKey(input.apiKey);
375
+ const protocol = protocolOf(input.model);
376
+ try {
377
+ await queryVideo({ ...input, taskId: "00000000000000000000000000000000" });
378
+ }
379
+ catch (error) {
380
+ const status = error instanceof MiniMaxError ? error.status : undefined;
381
+ const code = error instanceof MiniMaxError ? error.code : undefined;
382
+ const message = error instanceof Error ? error.message : String(error);
383
+ // 2049 / 1004 = 鉴权失败;401 同理。
384
+ if (status === 401 || code === "2049" || code === "1004" || /invalid api key|authorized_error/i.test(message)) {
385
+ throw new MiniMaxError(`MiniMax API Key 无效:${message}`, status, code);
386
+ }
387
+ // 任务不存在(v2 的 record not found / v1 的内部错误)说明鉴权已经通过。
388
+ }
389
+ return { ok: true, model: input.model, protocol };
390
+ }