dsh-game-material-master 0.7.0 → 0.9.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.
@@ -0,0 +1,883 @@
1
+ /**
2
+ * 谱乐 AI(YourMusic)Open API 客户端。
3
+ *
4
+ * 文档:https://api.yourmusic.fun/docs
5
+ * OpenAPI:https://api.yourmusic.fun/v1/openapi.json
6
+ *
7
+ * 这一层只负责「把参数变成正确的 HTTP 请求 / 把响应变成结构化结果」,
8
+ * 不碰任务目录、不碰轮询循环 —— 那些在 `musicgen.ts` 里。
9
+ *
10
+ * 两个刻意的约束:
11
+ * 1. **所有文本长度都显式校验**:超限时明确报错,绝不静默截断。截断会把用户写好的
12
+ * 最后一段歌词悄悄丢掉,生成结果看着正常、内容却少了一截。
13
+ * 2. **下载只接受 http(s)**:工具类接口要公开音频 URL,如果 agent 传一个
14
+ * `http://127.0.0.1:…` 进来,那是一次 SSRF。`assertDownloadUrl` 会挡住
15
+ * 本机 / 私网地址;只有「用户把 Base URL 配成了一个本机地址」时才放行本机,
16
+ * 因为那说明用户自己在跑 mock / 反代。
17
+ */
18
+ import { createWriteStream } from "node:fs";
19
+ import { mkdir, readFile, rename, rm, stat } from "node:fs/promises";
20
+ import { basename, join } from "node:path";
21
+ import { randomUUID } from "node:crypto";
22
+ import { MUSIC_BITRATES, MUSIC_CONVERT_FORMATS, MUSIC_ENGINE_PRESETS, MUSIC_KEY_SCALES, MUSIC_LIMITS, MUSIC_MODES, MUSIC_PRO_STEM_FORMATS, MUSIC_SAMPLE_RATES, MUSIC_STEM_COUNTS, MUSIC_STEM_FORMATS, MUSIC_TIME_SIGNATURES, MUSIC_VOCAL_LANGUAGES, MUSIC_ENGINES, defaultModelOf, enginePresetOf, isMusicEngine, isMusicMode } from "./musicmodels.js";
23
+ export class MusicApiError extends Error {
24
+ status;
25
+ type;
26
+ code;
27
+ param;
28
+ requestId;
29
+ constructor(message, options = {}) {
30
+ super(message);
31
+ this.name = "MusicApiError";
32
+ this.status = options.status;
33
+ this.type = options.type;
34
+ this.code = options.code;
35
+ this.param = options.param;
36
+ this.requestId = options.requestId;
37
+ }
38
+ }
39
+ /** 统一 Base URL:去尾斜杠,并剥掉用户误填的 `/v1`(端点里已经带 /v1)。 */
40
+ export function normalizeMusicBaseUrl(value) {
41
+ let raw = typeof value === "string" ? value.trim() : "";
42
+ if (raw === "")
43
+ return "https://api.yourmusic.fun";
44
+ raw = raw.replace(/\/+$/u, "");
45
+ if (/\/v1$/iu.test(raw))
46
+ raw = raw.slice(0, -3).replace(/\/+$/u, "");
47
+ return raw === "" ? "https://api.yourmusic.fun" : raw;
48
+ }
49
+ /**
50
+ * 配置是否足以提交生成。
51
+ *
52
+ * 同时接受完整 Config(`musicApiKey`)与脱敏视图(`musicApiKeySet`):
53
+ * 界面、工具 intake、网关都读同一份判断,避免「界面说没配好、模型说配好了」。
54
+ */
55
+ export function musicBlocker(config) {
56
+ const hasKey = config?.musicApiKeySet === true || (typeof config?.musicApiKey === "string" && config.musicApiKey.trim() !== "");
57
+ if (!hasKey) {
58
+ return "还没配置谱乐 AI API Key:设置 → 游戏素材大师 → 音乐生成(谱乐 AI),配好点「测试连接」。";
59
+ }
60
+ return undefined;
61
+ }
62
+ function apiBase(config) {
63
+ return normalizeMusicBaseUrl(config.baseUrl);
64
+ }
65
+ function authHeaders(config) {
66
+ if (config.apiKey.trim() === "") {
67
+ throw new MusicApiError("尚未配置谱乐 AI API Key(设置 → 游戏素材大师 → 音乐生成)");
68
+ }
69
+ return {
70
+ Authorization: `Bearer ${config.apiKey.trim()}`,
71
+ Accept: "application/json"
72
+ };
73
+ }
74
+ async function readError(response) {
75
+ const text = await response.text().catch(() => "");
76
+ let body;
77
+ try {
78
+ const parsed = JSON.parse(text);
79
+ body = parsed?.error ?? parsed;
80
+ }
81
+ catch {
82
+ body = undefined;
83
+ }
84
+ const message = typeof body?.message === "string" && body.message.trim() !== ""
85
+ ? body.message
86
+ : text.trim().slice(0, 500) || `HTTP ${response.status} ${response.statusText}`;
87
+ const hint = statusHint(response.status);
88
+ return new MusicApiError(`${hint}${message}`, {
89
+ status: response.status,
90
+ type: typeof body?.type === "string" ? body.type : undefined,
91
+ code: typeof body?.code === "string" ? body.code : undefined,
92
+ param: typeof body?.param === "string" ? body.param : undefined,
93
+ requestId: typeof body?.request_id === "string" ? body.request_id : undefined
94
+ });
95
+ }
96
+ function statusHint(status) {
97
+ if (status === 401)
98
+ return "谱乐 AI API Key 无效或已过期:";
99
+ if (status === 402)
100
+ return "谱乐 AI 积分不足:";
101
+ if (status === 429)
102
+ return "谱乐 AI 请求过于频繁,请稍后再试:";
103
+ if (status === 404)
104
+ return "谱乐 AI 找不到该资源(可能尚未完成或不属于当前账号):";
105
+ if (status >= 500)
106
+ return "谱乐 AI 服务端错误:";
107
+ return `谱乐 AI 请求失败(HTTP ${status}):`;
108
+ }
109
+ async function requestJson(config, path, init = {}, options = {}) {
110
+ const base = apiBase(config);
111
+ const url = new URL(path.startsWith("/") ? path : `/${path}`, `${base}/`);
112
+ if (init.query !== undefined) {
113
+ for (const [key, value] of Object.entries(init.query)) {
114
+ if (value === undefined)
115
+ continue;
116
+ url.searchParams.set(key, String(value));
117
+ }
118
+ }
119
+ const timeout = AbortSignal.timeout(Math.max(10000, config.timeoutMs || 120000));
120
+ let response;
121
+ try {
122
+ response = await fetch(url.toString(), {
123
+ method: init.method ?? "GET",
124
+ headers: {
125
+ ...authHeaders(config),
126
+ ...(init.body === undefined ? {} : { "Content-Type": "application/json" })
127
+ },
128
+ ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
129
+ signal: timeout
130
+ });
131
+ }
132
+ catch (error) {
133
+ if (timeout.aborted)
134
+ throw new MusicApiError(`谱乐 AI 请求超时(${Math.round((config.timeoutMs || 120000) / 1000)} 秒)`);
135
+ throw new MusicApiError(`无法连接谱乐 AI:${error instanceof Error ? error.message : String(error)}`);
136
+ }
137
+ if (options.allow404 === true && response.status === 404) {
138
+ return { __notFound: true };
139
+ }
140
+ if (!response.ok)
141
+ throw await readError(response);
142
+ const text = await response.text();
143
+ if (text.trim() === "")
144
+ return {};
145
+ try {
146
+ return JSON.parse(text);
147
+ }
148
+ catch {
149
+ throw new MusicApiError(`谱乐 AI 返回了无法解析的 JSON:${text.slice(0, 300)}`, { status: response.status });
150
+ }
151
+ }
152
+ function text(value) {
153
+ return typeof value === "string" ? value.trim() : "";
154
+ }
155
+ function limitText(value, max, field, required = false) {
156
+ const out = text(value);
157
+ if (required && out === "")
158
+ throw new MusicApiError(`缺少必填参数:${field}`);
159
+ if (out.length > max)
160
+ throw new MusicApiError(`${field} 太长:${out.length} 字符,上限 ${max}。请精简后再提交。`);
161
+ return out;
162
+ }
163
+ function numIn(value, min, max, field) {
164
+ if (value === undefined || value === null || value === "")
165
+ return undefined;
166
+ const n = typeof value === "number" ? value : Number(value);
167
+ if (!Number.isFinite(n))
168
+ throw new MusicApiError(`${field} 必须是数字`);
169
+ if (n < min || n > max)
170
+ throw new MusicApiError(`${field} 超出范围:${n}(允许 ${min}–${max})`);
171
+ return n;
172
+ }
173
+ function oneOf(value, allowed, field) {
174
+ if (value === undefined || value === null || value === "")
175
+ return undefined;
176
+ const out = String(value);
177
+ if (!allowed.includes(out)) {
178
+ throw new MusicApiError(`${field} 取值不合法:${out}(允许:${allowed.join(" / ")})`);
179
+ }
180
+ return out;
181
+ }
182
+ function bool(value) {
183
+ return typeof value === "boolean" ? value : undefined;
184
+ }
185
+ function put(body, key, value) {
186
+ if (value !== undefined && value !== null && value !== "")
187
+ body[key] = value;
188
+ }
189
+ function titleOf(input) {
190
+ return limitText(input.title, MUSIC_LIMITS.title, "标题", true);
191
+ }
192
+ function sunoCommon(input, model, body) {
193
+ put(body, "negative_tags", limitText(input.negativeTags, MUSIC_LIMITS.sunoTags, "negative_tags"));
194
+ put(body, "vocal_gender", oneOf(input.vocalGender, ["male", "female"], "vocal_gender"));
195
+ put(body, "style_weight", numIn(input.styleWeight, 0, 1, "style_weight"));
196
+ put(body, "weirdness_constraint", numIn(input.weirdness, 0, 1, "weirdness_constraint"));
197
+ put(body, "duration", numIn(input.duration, 10, 360, "duration"));
198
+ put(body, "is_max_mode", bool(input.isMaxMode));
199
+ put(body, "aug_creativity", numIn(input.augCreativity, 0, 4, "aug_creativity"));
200
+ put(body, "model", model);
201
+ }
202
+ /**
203
+ * 把一次「引擎 + 模式 + 参数」变成真实端点与请求体。
204
+ *
205
+ * 参数校验放在这里,而不是让平台返回 400:平台的中文错误经常只说「参数错误」,
206
+ * agent 很难据此自我修正。这里会点名是哪个字段、允许什么范围。
207
+ */
208
+ export function buildGenerationRequest(input) {
209
+ if (!isMusicEngine(input.engine))
210
+ throw new MusicApiError(`未知音乐引擎:${String(input.engine)}`);
211
+ if (!isMusicMode(input.mode))
212
+ throw new MusicApiError(`未知生成模式:${String(input.mode)}`);
213
+ const engine = input.engine;
214
+ const mode = input.mode;
215
+ const preset = enginePresetOf(engine);
216
+ if (!preset.modes.some((entry) => entry.id === mode)) {
217
+ throw new MusicApiError(`${preset.label} 不支持「${mode}」模式(可用:${preset.modes.map((entry) => entry.id).join(" / ")})`);
218
+ }
219
+ const model = text(input.model) || preset.defaultModel;
220
+ if (!preset.models.some((entry) => entry.id === model)) {
221
+ throw new MusicApiError(`${preset.label} 没有模型「${model}」(可用:${preset.models.map((entry) => entry.id).join(" / ")})`);
222
+ }
223
+ const body = {};
224
+ if (engine === "suno") {
225
+ if (mode === "prompt") {
226
+ put(body, "prompt", limitText(input.prompt, MUSIC_LIMITS.sunoPrompt, "prompt", true));
227
+ put(body, "model", model);
228
+ put(body, "instrumental", bool(input.instrumental));
229
+ return { endpoint: "/v1/suno/generate/prompt", body, engine, mode, summary: `Suno prompt · ${model}` };
230
+ }
231
+ if (mode === "concat") {
232
+ const clipId = text(input.clipId);
233
+ if (clipId === "")
234
+ throw new MusicApiError("concat 需要 clipId(最后一首续写歌曲的 id)");
235
+ body.clip_id = clipId;
236
+ return { endpoint: "/v1/suno/generate/concat", body, engine, mode, summary: `Suno concat · ${clipId}` };
237
+ }
238
+ body.title = titleOf(input);
239
+ if (mode === "custom") {
240
+ put(body, "lyrics", limitText(input.lyrics, MUSIC_LIMITS.sunoLyrics, "lyrics"));
241
+ put(body, "tags", limitText(input.tags, MUSIC_LIMITS.sunoTags, "tags", true));
242
+ put(body, "instrumental", bool(input.instrumental));
243
+ sunoCommon(input, model, body);
244
+ return { endpoint: "/v1/suno/generate/custom", body, engine, mode, summary: `Suno custom · ${model} · ${body.title}` };
245
+ }
246
+ put(body, "tags", limitText(input.tags, MUSIC_LIMITS.sunoTags, "tags"));
247
+ put(body, "lyrics", limitText(input.lyrics, MUSIC_LIMITS.sunoLyrics, "lyrics"));
248
+ sunoCommon(input, model, body);
249
+ if (mode === "cover") {
250
+ const id = text(input.coverClipId);
251
+ if (id === "")
252
+ throw new MusicApiError("cover 需要 coverClipId(要翻唱的歌曲 id)");
253
+ body.cover_clip_id = id;
254
+ put(body, "audio_weight", numIn(input.audioWeight, 0, 1, "audio_weight"));
255
+ return { endpoint: "/v1/suno/generate/cover", body, engine, mode, summary: `Suno cover · ${id}` };
256
+ }
257
+ if (mode === "extend") {
258
+ const id = text(input.continueClipId);
259
+ if (id === "")
260
+ throw new MusicApiError("extend 需要 continueClipId(要续写的歌曲 id)");
261
+ body.continue_clip_id = id;
262
+ put(body, "continue_at", numIn(input.continueAt, 0, 3600, "continue_at"));
263
+ return { endpoint: "/v1/suno/generate/extend", body, engine, mode, summary: `Suno extend · ${id}` };
264
+ }
265
+ if (mode === "mashup") {
266
+ const ids = Array.isArray(input.sourceSongIds) ? input.sourceSongIds.map((id) => text(id)).filter(Boolean) : [];
267
+ if (ids.length < 2 || ids.length > 5)
268
+ throw new MusicApiError("mashup 需要 2–5 个 sourceSongIds");
269
+ body.source_clip_ids = ids;
270
+ return { endpoint: "/v1/suno/generate/mashup", body, engine, mode, summary: `Suno mashup · ${ids.join(" + ")}` };
271
+ }
272
+ if (mode === "sample") {
273
+ const id = text(input.coverClipId) || text(input.sourceSongIds?.[0]) || text(input.sourceSongId);
274
+ if (id === "")
275
+ throw new MusicApiError("sample 需要 sourceSongId(或 coverClipId)");
276
+ const start = numIn(input.startTime, 0, 3600, "start_time");
277
+ const end = numIn(input.endTime, 0, 3600, "end_time");
278
+ if (start === undefined || end === undefined || end <= start) {
279
+ throw new MusicApiError("sample 需要 start_time < end_time(秒)");
280
+ }
281
+ body.source_clip_id = id;
282
+ body.start_time = start;
283
+ body.end_time = end;
284
+ return { endpoint: "/v1/suno/generate/sample", body, engine, mode, summary: `Suno sample · ${id} ${start}–${end}s` };
285
+ }
286
+ }
287
+ if (engine === "mureka") {
288
+ const n = input.n === undefined ? undefined : Math.round(numIn(input.n, 1, 3, "n"));
289
+ put(body, "model", model);
290
+ put(body, "n", n);
291
+ if (mode === "prompt") {
292
+ put(body, "prompt", limitText(input.prompt, MUSIC_LIMITS.murekaPrompt, "prompt", true));
293
+ return { endpoint: "/v1/mureka/generate/prompt", body, engine, mode, summary: `Mureka prompt · ${model}` };
294
+ }
295
+ if (mode === "custom") {
296
+ body.title = limitText(input.title, MUSIC_LIMITS.title, "标题", true);
297
+ put(body, "lyrics", limitText(input.lyrics, MUSIC_LIMITS.murekaLyrics, "lyrics", true));
298
+ put(body, "tags", limitText(input.tags, MUSIC_LIMITS.murekaTags, "tags"));
299
+ return { endpoint: "/v1/mureka/generate/custom", body, engine, mode, summary: `Mureka custom · ${model}` };
300
+ }
301
+ if (mode === "instrumental") {
302
+ body.title = limitText(input.title, MUSIC_LIMITS.title, "标题", true);
303
+ put(body, "prompt", limitText(input.prompt, MUSIC_LIMITS.murekaPrompt, "prompt", true));
304
+ return { endpoint: "/v1/mureka/generate/instrumental", body, engine, mode, summary: `Mureka instrumental · ${model}` };
305
+ }
306
+ }
307
+ if (engine === "minimax") {
308
+ const instrumental = bool(input.instrumental) === true;
309
+ put(body, "prompt", limitText(input.prompt, MUSIC_LIMITS.minimaxPrompt, "prompt", true));
310
+ if (!instrumental) {
311
+ const lyrics = limitText(input.lyrics, MUSIC_LIMITS.minimaxLyrics, "lyrics");
312
+ if (lyrics.length < 10)
313
+ throw new MusicApiError("MiniMax 人声歌曲的 lyrics 至少 10 个字符(纯音乐请把 instrumental 设为 true)");
314
+ put(body, "lyrics", lyrics);
315
+ }
316
+ put(body, "title", limitText(input.title, MUSIC_LIMITS.title, "标题"));
317
+ put(body, "instrumental", instrumental);
318
+ put(body, "sample_rate", oneOf(input.sampleRate === undefined ? undefined : String(input.sampleRate), MUSIC_SAMPLE_RATES.map(String), "sample_rate"));
319
+ put(body, "bitrate", oneOf(input.bitrate === undefined ? undefined : String(input.bitrate), MUSIC_BITRATES.map(String), "bitrate"));
320
+ if (body.sample_rate !== undefined)
321
+ body.sample_rate = Number(body.sample_rate);
322
+ if (body.bitrate !== undefined)
323
+ body.bitrate = Number(body.bitrate);
324
+ put(body, "vocal_gender", text(input.vocalGender));
325
+ put(body, "model", model);
326
+ return { endpoint: "/v1/minimax/generate/custom", body, engine, mode, summary: `MiniMax custom · ${model}` };
327
+ }
328
+ // ACE-Step
329
+ body.title = limitText(input.title, MUSIC_LIMITS.title, "标题", true);
330
+ put(body, "model", model);
331
+ put(body, "instrumental", bool(input.instrumental));
332
+ put(body, "vocal_language", oneOf(input.vocalLanguage, MUSIC_VOCAL_LANGUAGES, "vocal_language"));
333
+ if (mode === "prompt") {
334
+ put(body, "prompt", limitText(input.prompt, 4000, "prompt", true));
335
+ return { endpoint: "/v1/ace-step/generate/prompt", body, engine, mode, summary: `ACE-Step prompt · ${model}` };
336
+ }
337
+ put(body, "tags", limitText(input.tags, 2000, "tags", true));
338
+ put(body, "lyrics", limitText(input.lyrics, 5000, "lyrics"));
339
+ put(body, "bpm", numIn(input.bpm, 30, 300, "bpm"));
340
+ put(body, "key_scale", oneOf(input.keyScale, MUSIC_KEY_SCALES, "key_scale"));
341
+ put(body, "time_signature", oneOf(input.timeSignature, MUSIC_TIME_SIGNATURES, "time_signature"));
342
+ put(body, "use_format", bool(input.useFormat));
343
+ return { endpoint: "/v1/ace-step/generate/custom", body, engine, mode, summary: `ACE-Step custom · ${model}` };
344
+ }
345
+ export async function submitGeneration(config, request) {
346
+ const payload = await requestJson(config, request.endpoint, { method: "POST", body: request.body });
347
+ const songs = Array.isArray(payload?.songs)
348
+ ? payload.songs
349
+ .filter((song) => typeof song?.id === "string" && song.id !== "")
350
+ .map((song) => ({ ...song, id: String(song.id), status: typeof song.status === "string" ? song.status : "pending" }))
351
+ : [];
352
+ if (songs.length === 0) {
353
+ throw new MusicApiError(`谱乐 AI 没有返回歌曲 id:${JSON.stringify(payload).slice(0, 400)}`);
354
+ }
355
+ return {
356
+ taskId: typeof payload?.task_id === "string" ? payload.task_id : undefined,
357
+ songs,
358
+ raw: payload
359
+ };
360
+ }
361
+ /** 上传文件的 MIME:只接受音乐模块实际会产出的格式。 */
362
+ function audioMimeOf(file) {
363
+ const ext = file.toLowerCase().split(".").pop() ?? "";
364
+ if (ext === "wav")
365
+ return "audio/wav";
366
+ if (ext === "m4a")
367
+ return "audio/mp4";
368
+ if (ext === "aac")
369
+ return "audio/aac";
370
+ if (ext === "flac")
371
+ return "audio/flac";
372
+ if (ext === "ogg")
373
+ return "audio/ogg";
374
+ return "audio/mpeg";
375
+ }
376
+ function sleep(ms) {
377
+ return new Promise((resolve) => setTimeout(resolve, ms));
378
+ }
379
+ export async function uploadSunoAudio(config, input) {
380
+ let info;
381
+ try {
382
+ info = await stat(input.filePath);
383
+ }
384
+ catch (error) {
385
+ throw new MusicApiError(`找不到要上传的音频:${input.filePath}(${error instanceof Error ? error.message : String(error)})`);
386
+ }
387
+ if (!info.isFile() || info.size <= 0)
388
+ throw new MusicApiError("要上传的音频文件是空的");
389
+ if (info.size > 300 * 1024 * 1024)
390
+ throw new MusicApiError(`音频超过 300MB 上限(${(info.size / 1024 / 1024).toFixed(1)} MB)`);
391
+ const buffer = await readFile(input.filePath);
392
+ const fileName = input.fileName?.trim() || basename(input.filePath);
393
+ const form = new FormData();
394
+ form.append("file", new Blob([buffer], { type: audioMimeOf(fileName) }), fileName);
395
+ if (input.copyright === true)
396
+ form.append("copyright_audio_flag", "1");
397
+ const url = new URL("/v1/suno/audio/upload", `${apiBase(config)}/`);
398
+ const timeout = AbortSignal.timeout(Math.max(30000, config.timeoutMs || 120000));
399
+ let response;
400
+ try {
401
+ // 不要手动设 Content-Type:fetch 会带 multipart 的 boundary。
402
+ response = await fetch(url.toString(), {
403
+ method: "POST",
404
+ headers: authHeaders(config),
405
+ body: form,
406
+ signal: timeout
407
+ });
408
+ }
409
+ catch (error) {
410
+ if (timeout.aborted)
411
+ throw new MusicApiError(`上传参考音频超时(${Math.round((config.timeoutMs || 120000) / 1000)} 秒)`);
412
+ throw new MusicApiError(`无法上传参考音频:${error instanceof Error ? error.message : String(error)}`);
413
+ }
414
+ if (!response.ok)
415
+ throw await readError(response);
416
+ const text = await response.text();
417
+ let payload = {};
418
+ if (text.trim() !== "") {
419
+ try {
420
+ payload = JSON.parse(text);
421
+ }
422
+ catch {
423
+ throw new MusicApiError(`谱乐 AI 上传接口返回了无法解析的 JSON:${text.slice(0, 300)}`, { status: response.status });
424
+ }
425
+ }
426
+ const taskId = typeof payload?.task_id === "string" ? payload.task_id : undefined;
427
+ if (taskId !== undefined) {
428
+ // 版权通道:异步任务,等 songs[0].id。
429
+ const deadline = Date.now() + Math.max(30000, input.pollTimeoutMs ?? 300000);
430
+ const interval = Math.max(500, input.pollIntervalMs ?? 3000);
431
+ for (;;) {
432
+ if (Date.now() >= deadline) {
433
+ throw new MusicApiError(`版权音频上传等待超时(task ${taskId});可以稍后用 listMusicHistory 或控制台查看。`);
434
+ }
435
+ await sleep(interval);
436
+ let status;
437
+ try {
438
+ status = await requestJson(config, `/v1/suno/audio/upload/${encodeURIComponent(taskId)}`);
439
+ }
440
+ catch (error) {
441
+ // 版权任务刚建好时可能短暂 404;按「还没完成」继续等。
442
+ if (error instanceof MusicApiError && error.status === 404)
443
+ continue;
444
+ throw error;
445
+ }
446
+ if (status?.status === "failed") {
447
+ const message = typeof status?.error_message === "string" && status.error_message !== "" ? status.error_message : "版权音频上传失败";
448
+ throw new MusicApiError(message);
449
+ }
450
+ const songs = Array.isArray(status?.songs) ? status.songs : [];
451
+ const songId = typeof songs[0]?.id === "string" ? songs[0].id : "";
452
+ if (songId !== "") {
453
+ return { songId, status: "succeeded", copyright: true, taskId, raw: status };
454
+ }
455
+ }
456
+ }
457
+ const songId = typeof payload?.id === "string" ? payload.id : "";
458
+ if (songId === "") {
459
+ throw new MusicApiError(`上传音频没有返回可用 id:${JSON.stringify(payload).slice(0, 400)}`);
460
+ }
461
+ return {
462
+ songId,
463
+ status: typeof payload?.status === "string" ? payload.status : "succeeded",
464
+ copyright: input.copyright === true,
465
+ raw: payload
466
+ };
467
+ }
468
+ export async function querySongs(config, ids) {
469
+ const clean = [...new Set(ids.map((id) => id.trim()).filter(Boolean))];
470
+ if (clean.length === 0)
471
+ return [];
472
+ try {
473
+ const payload = await requestJson(config, "/v1/music/generations/query", {
474
+ query: { songid: clean.join(",") }
475
+ });
476
+ if (!Array.isArray(payload))
477
+ return [];
478
+ return payload
479
+ .filter((song) => typeof song?.id === "string" && song.id !== "")
480
+ .map((song) => ({ ...song, id: String(song.id), status: typeof song.status === "string" ? song.status : "pending" }));
481
+ }
482
+ catch (error) {
483
+ // 404 = 歌曲还没完成(文档明确说 404 可能是 not yet completed)。交给轮询继续等。
484
+ if (error instanceof MusicApiError && error.status === 404)
485
+ return [];
486
+ throw error;
487
+ }
488
+ }
489
+ export async function musicHistory(config, options = {}) {
490
+ const page = Math.max(1, Math.round(options.page ?? 1));
491
+ const size = Math.min(100, Math.max(1, Math.round(options.size ?? 20)));
492
+ const filters = (options.filters ?? []).filter((entry) => ["uploads", "covers", "extensions"].includes(entry));
493
+ const payload = await requestJson(config, "/v1/music/generations/history", {
494
+ query: { page, size, ...(filters.length === 0 ? {} : { filters: filters.join(",") }) }
495
+ });
496
+ return {
497
+ data: Array.isArray(payload?.data) ? payload.data : [],
498
+ total: Number(payload?.total ?? 0),
499
+ page: Number(payload?.page ?? page),
500
+ size: Number(payload?.size ?? size),
501
+ totalPages: Number(payload?.total_pages ?? 0)
502
+ };
503
+ }
504
+ export async function requestWav(config, songId) {
505
+ const payload = await requestJson(config, "/v1/music/generations/wav", { method: "POST", body: { songid: songId } });
506
+ const url = typeof payload?.audio_wav_url === "string" ? payload.audio_wav_url : "";
507
+ if (url === "")
508
+ throw new MusicApiError(`谱乐 AI 没有返回 WAV 地址:${JSON.stringify(payload).slice(0, 300)}`);
509
+ return { id: typeof payload?.id === "string" ? payload.id : songId, url };
510
+ }
511
+ export async function generateLrc(config, ids) {
512
+ const clean = [...new Set(ids.map((id) => id.trim()).filter(Boolean))].slice(0, 10);
513
+ if (clean.length === 0)
514
+ throw new MusicApiError("getMusicLrc 需要至少一个歌曲 id");
515
+ const payload = await requestJson(config, "/v1/suno/lrc/generate", { method: "POST", body: { clip_ids: clean } });
516
+ const results = Array.isArray(payload?.results) ? payload.results : [];
517
+ return results.map((item) => ({
518
+ id: typeof item?.id === "string" ? item.id : "",
519
+ success: item?.success === true,
520
+ lrcAlignment: item?.lrc_alignment,
521
+ error: typeof item?.error === "string" ? item.error : undefined
522
+ }));
523
+ }
524
+ export async function submitStemSplit(config, input) {
525
+ assertDownloadUrl(input.audioUrl, config.baseUrl);
526
+ if (!MUSIC_STEM_COUNTS.includes(input.stemCount)) {
527
+ throw new MusicApiError(`stemCount 只能是 ${MUSIC_STEM_COUNTS.join(" / ")}`);
528
+ }
529
+ const outputFormat = oneOf(input.outputFormat, MUSIC_STEM_FORMATS, "output_format");
530
+ const payload = await requestJson(config, "/v1/tools/stems/split", {
531
+ method: "POST",
532
+ body: {
533
+ audio_url: input.audioUrl,
534
+ filename: input.filename,
535
+ stem_count: input.stemCount,
536
+ output_format: outputFormat
537
+ }
538
+ });
539
+ return toolTaskOf(payload, "stem_split");
540
+ }
541
+ export async function stemInstruments(config) {
542
+ const payload = await requestJson(config, "/v1/tools/stems/instruments");
543
+ const categories = Array.isArray(payload?.categories) ? payload.categories : [];
544
+ return { categories, fetchedAt: Date.now() };
545
+ }
546
+ export async function submitProStemSplit(config, input) {
547
+ assertDownloadUrl(input.audioUrl, config.baseUrl);
548
+ const itemCode = text(input.itemCode);
549
+ if (itemCode === "")
550
+ throw new MusicApiError("高级分轨需要 itemCode(见 listMusicStemInstruments)");
551
+ const outputFormat = oneOf(input.outputFormat, MUSIC_PRO_STEM_FORMATS, "output_format");
552
+ const payload = await requestJson(config, "/v1/tools/stems/professional/split", {
553
+ method: "POST",
554
+ body: {
555
+ audio_url: input.audioUrl,
556
+ item_code: itemCode,
557
+ filename: input.filename,
558
+ output_format: outputFormat
559
+ }
560
+ });
561
+ return toolTaskOf(payload, "professional_stem_split");
562
+ }
563
+ export async function toolTask(config, taskId) {
564
+ const id = text(taskId);
565
+ if (id === "")
566
+ throw new MusicApiError("taskId 不能为空");
567
+ // 分轨与转码共用同一个查询端点(文档里的 GET /v1/tools/stems/{task_id} 与
568
+ // GET /v1/tools/audio/convert/{task_id} 是两个路径,先按 stem 查,404 再查转码)。
569
+ try {
570
+ const payload = await requestJson(config, `/v1/tools/stems/${encodeURIComponent(id)}`, {}, { allow404: true });
571
+ if (!payload?.__notFound)
572
+ return toolTaskOf(payload, "stem_split");
573
+ }
574
+ catch (error) {
575
+ if (!(error instanceof MusicApiError) || error.status !== 404)
576
+ throw error;
577
+ }
578
+ const payload = await requestJson(config, `/v1/tools/audio/convert/${encodeURIComponent(id)}`);
579
+ return toolTaskOf(payload, "audio_convert");
580
+ }
581
+ function toolTaskOf(payload, fallbackType) {
582
+ const status = payload?.status;
583
+ const normalized = status === "succeeded" || status === "failed" || status === "processing" || status === "pending"
584
+ ? status
585
+ : "pending";
586
+ return {
587
+ taskId: typeof payload?.task_id === "string" ? payload.task_id : "",
588
+ status: normalized,
589
+ type: typeof payload?.type === "string" ? payload.type : fallbackType,
590
+ raw: payload
591
+ };
592
+ }
593
+ export async function submitMidi(config, input) {
594
+ assertDownloadUrl(input.audioUrl, config.baseUrl);
595
+ const payload = await requestJson(config, "/v1/tools/midi/convert", {
596
+ method: "POST",
597
+ body: { audio_url: input.audioUrl, audio_name: input.audioName }
598
+ });
599
+ const midiUrl = typeof payload?.result?.midi_url === "string" ? payload.result.midi_url : "";
600
+ if (midiUrl === "")
601
+ throw new MusicApiError(`转 MIDI 没有返回文件地址:${JSON.stringify(payload).slice(0, 300)}`);
602
+ return { midiUrl, raw: payload };
603
+ }
604
+ export async function submitSheetMusic(config, midiUrl) {
605
+ assertDownloadUrl(midiUrl, config.baseUrl);
606
+ const payload = await requestJson(config, "/v1/tools/sheet-music/convert", { method: "POST", body: { midi_url: midiUrl } });
607
+ return {
608
+ pdfUrl: typeof payload?.result?.files?.pdf_url === "string" ? payload.result.files.pdf_url : undefined,
609
+ xmlUrl: typeof payload?.result?.files?.xml_url === "string" ? payload.result.files.xml_url : undefined,
610
+ raw: payload
611
+ };
612
+ }
613
+ export async function submitStyleAnalysis(config, input) {
614
+ assertDownloadUrl(input.audioUrl, config.baseUrl);
615
+ const payload = await requestJson(config, "/v1/tools/style-analysis", {
616
+ method: "POST",
617
+ body: { audio_url: input.audioUrl, audio_name: input.audioName }
618
+ });
619
+ const result = payload?.result ?? {};
620
+ return {
621
+ instruments: Array.isArray(result.instruments) ? result.instruments.map(String) : [],
622
+ genres: Array.isArray(result.genres) ? result.genres.map(String) : [],
623
+ tags: Array.isArray(result.tags) ? result.tags.map(String) : [],
624
+ description: typeof result.description === "string" ? result.description : "",
625
+ raw: payload
626
+ };
627
+ }
628
+ export async function submitAudioConvert(config, input) {
629
+ assertDownloadUrl(input.sourceUrl, config.baseUrl);
630
+ const targetFormat = oneOf(input.targetFormat, MUSIC_CONVERT_FORMATS, "target_format");
631
+ const payload = await requestJson(config, "/v1/tools/audio/convert", {
632
+ method: "POST",
633
+ body: { source_url: input.sourceUrl, target_format: targetFormat }
634
+ });
635
+ return toolTaskOf(payload, "audio_convert");
636
+ }
637
+ // ── 下载 ────────────────────────────────────────────────────────────────
638
+ const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "0.0.0.0"]);
639
+ function hostIsLocal(hostname) {
640
+ const host = hostname.toLowerCase().replace(/^\[|\]$/gu, "");
641
+ if (LOCAL_HOSTS.has(host))
642
+ return true;
643
+ if (host.endsWith(".localhost"))
644
+ return true;
645
+ if (/^127\./u.test(host))
646
+ return true;
647
+ if (/^10\./u.test(host))
648
+ return true;
649
+ if (/^192\.168\./u.test(host))
650
+ return true;
651
+ if (/^172\.(1[6-9]|2\d|3[0-1])\./u.test(host))
652
+ return true;
653
+ if (/^169\.254\./u.test(host))
654
+ return true;
655
+ if (/^\[?f[cd][0-9a-f]{2}:/iu.test(host))
656
+ return true;
657
+ if (host.endsWith(".local"))
658
+ return true;
659
+ return false;
660
+ }
661
+ /**
662
+ * 允许下载/交给第三方工具的 URL 校验。
663
+ *
664
+ * 公网 Base URL 时拒绝本机/私网 —— 否则 agent 传入 `http://127.0.0.1:…` 就是一次
665
+ * SSRF。用户把 Base URL 配成本机(mock / 反代 / 本地服务)时放行本机,因为那是
666
+ * 用户自己的明确选择,自检也需要它。
667
+ */
668
+ export function assertDownloadUrl(raw, baseUrl) {
669
+ const value = text(raw);
670
+ if (value === "")
671
+ throw new MusicApiError("音频 URL 不能为空");
672
+ let parsed;
673
+ try {
674
+ parsed = new URL(value);
675
+ }
676
+ catch {
677
+ throw new MusicApiError(`不是合法的 URL:${value}`);
678
+ }
679
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
680
+ throw new MusicApiError(`只接受 http(s) URL:${value}`);
681
+ }
682
+ let baseHost = "";
683
+ try {
684
+ baseHost = new URL(normalizeMusicBaseUrl(baseUrl)).hostname;
685
+ }
686
+ catch {
687
+ baseHost = "";
688
+ }
689
+ const localBase = baseHost !== "" && hostIsLocal(baseHost);
690
+ if (!localBase && hostIsLocal(parsed.hostname)) {
691
+ throw new MusicApiError(`出于安全原因,不下载本机 / 私网地址:${value}`);
692
+ }
693
+ return parsed;
694
+ }
695
+ const EXT_BY_MIME = {
696
+ "audio/mpeg": "mp3",
697
+ "audio/mp3": "mp3",
698
+ "audio/wav": "wav",
699
+ "audio/x-wav": "wav",
700
+ "audio/wave": "wav",
701
+ "audio/mp4": "m4a",
702
+ "audio/x-m4a": "m4a",
703
+ "audio/aac": "aac",
704
+ "audio/flac": "flac",
705
+ "audio/ogg": "ogg",
706
+ "audio/midi": "mid",
707
+ "audio/x-midi": "mid",
708
+ "application/pdf": "pdf",
709
+ "application/xml": "xml",
710
+ "text/xml": "xml",
711
+ "application/zip": "zip",
712
+ "image/jpeg": "jpg",
713
+ "image/png": "png",
714
+ "image/webp": "webp"
715
+ };
716
+ /** 按文件头认音频/文档,避免扩展名造假。返回 undefined 时再退回 Content-Type / 调用方给的后缀。 */
717
+ export function sniffBinary(head) {
718
+ if (head.length >= 12 && head.toString("ascii", 0, 4) === "RIFF" && head.toString("ascii", 8, 12) === "WAVE") {
719
+ return { ext: "wav", mime: "audio/wav" };
720
+ }
721
+ if (head.length >= 4 && head.toString("ascii", 0, 4) === "fLaC")
722
+ return { ext: "flac", mime: "audio/flac" };
723
+ if (head.length >= 4 && head.toString("ascii", 0, 4) === "OggS")
724
+ return { ext: "ogg", mime: "audio/ogg" };
725
+ if (head.length >= 4 && head.toString("ascii", 0, 4) === "MThd")
726
+ return { ext: "mid", mime: "audio/midi" };
727
+ if (head.length >= 4 && head.toString("ascii", 0, 4) === "%PDF")
728
+ return { ext: "pdf", mime: "application/pdf" };
729
+ if (head.length >= 2 && head.toString("ascii", 0, 2) === "PK")
730
+ return { ext: "zip", mime: "application/zip" };
731
+ if (head.length >= 3 && head[0] === 0xff && (head[1] & 0xe0) === 0xe0)
732
+ return { ext: "mp3", mime: "audio/mpeg" };
733
+ if (head.length >= 3 && head.toString("ascii", 0, 3) === "ID3")
734
+ return { ext: "mp3", mime: "audio/mpeg" };
735
+ if (head.length >= 12 && head.toString("ascii", 4, 8) === "ftyp") {
736
+ const brand = head.toString("ascii", 8, 12).toLowerCase();
737
+ if (brand.includes("m4a") || brand.includes("mp4"))
738
+ return { ext: "m4a", mime: "audio/mp4" };
739
+ return { ext: "m4a", mime: "audio/mp4" };
740
+ }
741
+ if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff)
742
+ return { ext: "jpg", mime: "image/jpeg" };
743
+ if (head.length >= 8 && head[0] === 0x89 && head[1] === 0x50 && head[2] === 0x4e && head[3] === 0x47)
744
+ return { ext: "png", mime: "image/png" };
745
+ return undefined;
746
+ }
747
+ /**
748
+ * 下载到一个目录并返回落盘路径。先写 `.part` 再 rename,失败不留半截文件。
749
+ * 用流式读取 + 计数,避免把几百 MB 的音频整个读进内存。
750
+ */
751
+ export async function downloadToFile(rawUrl, destDir, config, options) {
752
+ const url = assertDownloadUrl(rawUrl, config.baseUrl);
753
+ const maxBytes = options.maxBytes ?? 200 * 1024 * 1024;
754
+ const timeout = AbortSignal.timeout(Math.max(30000, options.timeoutMs ?? 180000));
755
+ let response;
756
+ try {
757
+ response = await fetch(url.toString(), { signal: timeout });
758
+ }
759
+ catch (error) {
760
+ if (timeout.aborted)
761
+ throw new MusicApiError(`下载音频超时:${url.hostname}`);
762
+ throw new MusicApiError(`下载音频失败:${error instanceof Error ? error.message : String(error)}`);
763
+ }
764
+ if (!response.ok)
765
+ throw new MusicApiError(`下载音频失败(HTTP ${response.status}):${url.hostname}`, { status: response.status });
766
+ const contentType = (response.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
767
+ const contentLength = Number(response.headers.get("content-length") ?? 0);
768
+ if (Number.isFinite(contentLength) && contentLength > maxBytes) {
769
+ throw new MusicApiError(`文件太大:${(contentLength / 1024 / 1024).toFixed(1)}MB(上限 ${(maxBytes / 1024 / 1024).toFixed(0)}MB)`);
770
+ }
771
+ await mkdir(destDir, { recursive: true });
772
+ const tmp = join(destDir, `${options.stem}.${Date.now().toString(36)}-${randomUUID().slice(0, 6)}.part`);
773
+ const stream = createWriteStream(tmp);
774
+ let bytes = 0;
775
+ let head = Buffer.alloc(0);
776
+ let sniffed;
777
+ try {
778
+ const body = response.body;
779
+ if (body === null)
780
+ throw new MusicApiError("下载响应没有 body");
781
+ const reader = body.getReader();
782
+ for (;;) {
783
+ const { done, value } = await reader.read();
784
+ if (done)
785
+ break;
786
+ if (value === undefined)
787
+ continue;
788
+ const chunk = Buffer.from(value);
789
+ if (head.length < 16)
790
+ head = Buffer.concat([head, chunk.subarray(0, 16 - head.length)]);
791
+ if (sniffed === undefined && head.length >= 4)
792
+ sniffed = sniffBinary(head);
793
+ bytes += chunk.length;
794
+ if (bytes > maxBytes) {
795
+ await reader.cancel().catch(() => undefined);
796
+ throw new MusicApiError(`文件太大:超过 ${(maxBytes / 1024 / 1024).toFixed(0)}MB 上限`);
797
+ }
798
+ if (!stream.write(chunk)) {
799
+ await new Promise((resolve) => stream.once("drain", () => resolve()));
800
+ }
801
+ }
802
+ await new Promise((resolve, reject) => {
803
+ stream.once("error", reject);
804
+ stream.end(() => resolve());
805
+ });
806
+ }
807
+ catch (error) {
808
+ stream.destroy();
809
+ await rm(tmp, { force: true }).catch(() => undefined);
810
+ throw error instanceof MusicApiError ? error : new MusicApiError(`下载写入失败:${error instanceof Error ? error.message : String(error)}`);
811
+ }
812
+ if (options.requireAudio === true) {
813
+ const audioExts = new Set(["mp3", "m4a", "wav", "flac", "ogg", "aac"]);
814
+ if (sniffed === undefined || !audioExts.has(sniffed.ext)) {
815
+ await rm(tmp, { force: true }).catch(() => undefined);
816
+ throw new MusicApiError(`下载到的内容不是音频(Content-Type: ${contentType || "unknown"},文件头无法识别);已丢弃,稍后可重试`);
817
+ }
818
+ }
819
+ const byMime = EXT_BY_MIME[contentType];
820
+ const byUrl = extFromUrl(url);
821
+ const ext = sniffed?.ext ?? byMime ?? byUrl ?? options.fallbackExt ?? "bin";
822
+ const mime = sniffed?.mime ?? contentType ?? "application/octet-stream";
823
+ const file = join(destDir, `${safeStem(options.stem)}.${ext}`);
824
+ await rm(file, { force: true }).catch(() => undefined);
825
+ await rename(tmp, file);
826
+ return { file, bytes, ext, mime };
827
+ }
828
+ function extFromUrl(url) {
829
+ const match = /\.([a-z0-9]{2,5})$/iu.exec(url.pathname);
830
+ return match?.[1]?.toLowerCase();
831
+ }
832
+ /** 文件名主名:去掉路径分隔符与控制字符,限制长度。 */
833
+ export function safeStem(value) {
834
+ const base = basename(String(value ?? "")).replace(/[^\w.\-()\u4e00-\u9fa5]+/gu, "_").replace(/^[._]+/u, "");
835
+ return base === "" ? "music" : base.slice(0, 80);
836
+ }
837
+ /**
838
+ * 测试连接:读一页历史,不生成、不扣生成积分。
839
+ *
840
+ * 402 视为「Key 有效但积分不足」——这时连接本身是通的,不该报成 Key 错误。
841
+ */
842
+ export async function testMusicConnection(config) {
843
+ try {
844
+ const history = await musicHistory(config, { page: 1, size: 1 });
845
+ return {
846
+ ok: true,
847
+ total: history.total,
848
+ message: `连接正常(历史记录 ${history.total} 首)`
849
+ };
850
+ }
851
+ catch (error) {
852
+ if (error instanceof MusicApiError && error.status === 402) {
853
+ return { ok: true, warning: error.message, message: "Key 有效,但当前积分不足;仍可读取历史,生成会被拒绝。" };
854
+ }
855
+ throw error;
856
+ }
857
+ }
858
+ /** 供界面/工具展示的引擎摘要(不包含 Key)。 */
859
+ export function musicEngineSummary() {
860
+ return MUSIC_ENGINE_PRESETS.map((engine) => ({
861
+ id: engine.id,
862
+ label: engine.label,
863
+ hint: engine.hint,
864
+ defaultModel: engine.defaultModel,
865
+ models: engine.models.map((model) => ({ ...model })),
866
+ modes: engine.modes.map((mode) => ({ ...mode }))
867
+ }));
868
+ }
869
+ /** 校验引擎/模式的辅助(界面传错时给出明确错误)。 */
870
+ export function assertEngineMode(engine, mode) {
871
+ if (!isMusicEngine(engine))
872
+ throw new MusicApiError(`未知音乐引擎:${String(engine)}(可用:${MUSIC_ENGINES.join(" / ")})`);
873
+ if (!isMusicMode(mode))
874
+ throw new MusicApiError(`未知生成模式:${String(mode)}(可用:${MUSIC_MODES.join(" / ")})`);
875
+ if (!enginePresetOf(engine).modes.some((entry) => entry.id === mode)) {
876
+ throw new MusicApiError(`${enginePresetOf(engine).label} 不支持「${mode}」模式`);
877
+ }
878
+ return { engine, mode };
879
+ }
880
+ /** 默认模型(给建任务时兜底)。 */
881
+ export function fallbackModel(engine) {
882
+ return isMusicEngine(engine) ? defaultModelOf(engine) : defaultModelOf("suno");
883
+ }