@napuketto/media 0.2.3 → 0.3.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/dist/index.d.mts +5 -3
- package/dist/index.mjs +94 -27
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -84,13 +84,15 @@ export declare function decodeSilkToWav(input: string, options?: DecodeSilkToWav
|
|
|
84
84
|
export declare function encodePcmToSilk(input: string, sampleRate?: number): Promise<string>;
|
|
85
85
|
/** 获取 SILK 音频信息(时长 / 采样率)。 */
|
|
86
86
|
export declare function getSilkInfo(input: string, sampleRate?: number): Promise<AudioInfo>;
|
|
87
|
+
/** 按协议调用方的信任边界选择远程媒体出站模式。 */
|
|
88
|
+
type MediaOutboundPolicy = "public-only" | "compat";
|
|
87
89
|
/** 下载选项。 */
|
|
88
90
|
interface DownloadUrlOptions {
|
|
89
91
|
/** 超时毫秒(缺省 15s,覆盖整个下载过程)。 */
|
|
90
92
|
timeoutMs?: number | undefined;
|
|
91
93
|
/** 大小上限字节(缺省 30MB)。 */
|
|
92
94
|
maxBytes?: number | undefined;
|
|
93
|
-
/**
|
|
95
|
+
/** 初始源的附加请求头。传输/路由头忽略,跨源重定向清空所有调用者头。 */
|
|
94
96
|
headers?: Record<string, string> | undefined;
|
|
95
97
|
}
|
|
96
98
|
/**
|
|
@@ -100,7 +102,7 @@ interface DownloadUrlOptions {
|
|
|
100
102
|
*/
|
|
101
103
|
export declare function downloadUrl(url: string, dest: string, options?: DownloadUrlOptions): Promise<number>;
|
|
102
104
|
/** 下载公网 HTTP(S) URL。每一跳校验实际连接使用的地址。 */
|
|
103
|
-
export declare function downloadPublicUrl(url: string, dest: string, options?:
|
|
105
|
+
export declare function downloadPublicUrl(url: string, dest: string, options?: DownloadUrlOptions): Promise<number>;
|
|
104
106
|
/** 从 Content-Type / URL 路径推断扩展名(缺省 .bin;下载命名用)。 */
|
|
105
107
|
export declare function inferExtension(contentType: string | null, url: string): string;
|
|
106
108
|
/** 读取图片尺寸(image-size 同步 API,内部读文件 + 计算)。 */
|
|
@@ -119,4 +121,4 @@ export declare function getVideoInfo(input: string): Promise<VideoInfo>;
|
|
|
119
121
|
* 缺失 / 输出未生成均抛 MediaError,由调用方决定降级策略。
|
|
120
122
|
*/
|
|
121
123
|
export declare function extractVideoFrame(input: string, outputPath: string): Promise<string>;
|
|
122
|
-
export type { AudioInfo, DecodeSilkToWavOptions, DecodedAudio, DecodedWav, DownloadUrlOptions, FileTypeResult, ImageSize, TranscodeOptions, VideoInfo };
|
|
124
|
+
export type { AudioInfo, DecodeSilkToWavOptions, DecodedAudio, DecodedWav, DownloadUrlOptions, FileTypeResult, ImageSize, MediaOutboundPolicy, TranscodeOptions, VideoInfo };
|
package/dist/index.mjs
CHANGED
|
@@ -358,7 +358,7 @@ function publicLookup(checkLiteral, signal) {
|
|
|
358
358
|
};
|
|
359
359
|
}
|
|
360
360
|
function createPublicRequest(checkLiteral) {
|
|
361
|
-
return async (url, signal) => {
|
|
361
|
+
return async (url, signal, headers) => {
|
|
362
362
|
if (url.username !== "" || url.password !== "") throw new MediaError("公网下载策略拒绝 URL 凭据");
|
|
363
363
|
const host = url.hostname.replace(ADDRESS_BRACKETS, "");
|
|
364
364
|
if (isIP(host) !== 0) assertPublicAddress(host);
|
|
@@ -368,22 +368,25 @@ function createPublicRequest(checkLiteral) {
|
|
|
368
368
|
rejectUnauthorized: true,
|
|
369
369
|
signal,
|
|
370
370
|
autoSelectFamily: true,
|
|
371
|
-
headers: {
|
|
371
|
+
headers: {
|
|
372
|
+
...headers,
|
|
373
|
+
"accept-encoding": "identity"
|
|
374
|
+
},
|
|
372
375
|
lookup: publicLookup(checkLiteral, signal)
|
|
373
376
|
};
|
|
374
377
|
return new Promise((resolve, reject) => {
|
|
375
378
|
get$2(url, options, (response) => {
|
|
376
379
|
const status = response.statusCode ?? 0;
|
|
377
380
|
const encoding = response.headers["content-encoding"];
|
|
378
|
-
if (status >= 200 && status < 300 && encoding && encoding !== "identity") {
|
|
381
|
+
if (status >= 200 && status < 300 && encoding && encoding.toLowerCase() !== "identity") {
|
|
379
382
|
response.destroy();
|
|
380
383
|
reject(new MediaError("公网下载响应使用了不支持的内容编码"));
|
|
381
384
|
return;
|
|
382
385
|
}
|
|
383
386
|
resolve({
|
|
384
387
|
status,
|
|
385
|
-
headers: { get: (name) => response.headers[name]?.toString() ?? null },
|
|
386
|
-
body:
|
|
388
|
+
headers: { get: (name) => response.headers[name.toLowerCase()]?.toString() ?? null },
|
|
389
|
+
body: response
|
|
387
390
|
});
|
|
388
391
|
}).once("error", reject);
|
|
389
392
|
});
|
|
@@ -425,6 +428,50 @@ const REDIRECT_STATUS = /* @__PURE__ */ new Set([
|
|
|
425
428
|
const ALLOWED_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:"]);
|
|
426
429
|
/** 扩展名字符合法性(URL pathname 提取校验)。 */
|
|
427
430
|
const EXT_RE = /^\.[a-z0-9]+$/i;
|
|
431
|
+
const MEDIA_EXTENSIONS = /* @__PURE__ */ new Map([
|
|
432
|
+
["image/avif", ".avif"],
|
|
433
|
+
["image/bmp", ".bmp"],
|
|
434
|
+
["image/gif", ".gif"],
|
|
435
|
+
["image/heic", ".heic"],
|
|
436
|
+
["image/heif", ".heif"],
|
|
437
|
+
["image/jpeg", ".jpeg"],
|
|
438
|
+
["image/png", ".png"],
|
|
439
|
+
["image/svg+xml", ".svg"],
|
|
440
|
+
["image/tiff", ".tiff"],
|
|
441
|
+
["image/vnd.microsoft.icon", ".ico"],
|
|
442
|
+
["image/webp", ".webp"],
|
|
443
|
+
["image/x-icon", ".ico"],
|
|
444
|
+
["audio/aac", ".aac"],
|
|
445
|
+
["audio/amr", ".amr"],
|
|
446
|
+
["audio/flac", ".flac"],
|
|
447
|
+
["audio/mp4", ".m4a"],
|
|
448
|
+
["audio/mpeg", ".mpeg"],
|
|
449
|
+
["audio/ogg", ".ogg"],
|
|
450
|
+
["audio/opus", ".opus"],
|
|
451
|
+
["audio/silk", ".silk"],
|
|
452
|
+
["audio/wav", ".wav"],
|
|
453
|
+
["audio/webm", ".webm"],
|
|
454
|
+
["audio/x-wav", ".wav"],
|
|
455
|
+
["video/mpeg", ".mpeg"],
|
|
456
|
+
["video/mp4", ".mp4"],
|
|
457
|
+
["video/ogg", ".ogv"],
|
|
458
|
+
["video/quicktime", ".mov"],
|
|
459
|
+
["video/webm", ".webm"],
|
|
460
|
+
["video/x-matroska", ".mkv"]
|
|
461
|
+
]);
|
|
462
|
+
const MANAGED_REQUEST_HEADERS = /* @__PURE__ */ new Set([
|
|
463
|
+
"accept-encoding",
|
|
464
|
+
"connection",
|
|
465
|
+
"content-length",
|
|
466
|
+
"expect",
|
|
467
|
+
"forwarded",
|
|
468
|
+
"host",
|
|
469
|
+
"keep-alive",
|
|
470
|
+
"te",
|
|
471
|
+
"trailer",
|
|
472
|
+
"transfer-encoding",
|
|
473
|
+
"upgrade"
|
|
474
|
+
]);
|
|
428
475
|
/** WHATWG URL 归一化后的 IPv4-mapped IPv6(::ffff:h:h,低 32 位为 IPv4)。 */
|
|
429
476
|
const IPV4_MAPPED_RE = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/;
|
|
430
477
|
/**
|
|
@@ -493,20 +540,37 @@ function assertDownloadUrlSafe(raw) {
|
|
|
493
540
|
function isRedirect(status) {
|
|
494
541
|
return REDIRECT_STATUS.has(status);
|
|
495
542
|
}
|
|
543
|
+
function initialRequestHeaders(input) {
|
|
544
|
+
if (input === void 0) return void 0;
|
|
545
|
+
const headers = new Headers();
|
|
546
|
+
for (const [name, value] of Object.entries(input)) {
|
|
547
|
+
const key = name.toLowerCase();
|
|
548
|
+
if (!MANAGED_REQUEST_HEADERS.has(key) && !key.startsWith("proxy-") && !key.startsWith("sec-") && !key.startsWith("x-forwarded-")) headers.append(key, value);
|
|
549
|
+
}
|
|
550
|
+
return Object.fromEntries(headers);
|
|
551
|
+
}
|
|
552
|
+
async function closeBody(body) {
|
|
553
|
+
if (body instanceof Readable) body.destroy();
|
|
554
|
+
else await body?.cancel().catch(() => void 0);
|
|
555
|
+
}
|
|
496
556
|
/**
|
|
497
557
|
* 发起请求并手动跟随重定向:每一跳都先过 assertDownloadUrlSafe。
|
|
498
558
|
* 返回非 30x 的最终响应。
|
|
499
559
|
*/
|
|
500
|
-
async function requestFollowingRedirects(url, request, signal) {
|
|
501
|
-
let current = url;
|
|
560
|
+
async function requestFollowingRedirects(url, request, signal, callerHeaders) {
|
|
561
|
+
let current = assertDownloadUrlSafe(url);
|
|
562
|
+
let headers = initialRequestHeaders(callerHeaders);
|
|
502
563
|
for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
|
|
503
|
-
|
|
504
|
-
const response = await request(
|
|
564
|
+
signal.throwIfAborted();
|
|
565
|
+
const response = await request(current, signal, headers);
|
|
505
566
|
if (!isRedirect(response.status)) return response;
|
|
506
|
-
|
|
507
|
-
|
|
567
|
+
await closeBody(response.body);
|
|
568
|
+
if (hop === MAX_REDIRECTS) break;
|
|
569
|
+
const location = response.headers.get("Location");
|
|
508
570
|
if (location === null || location === "") throw new MediaError(`重定向缺少 Location(HTTP ${response.status})`);
|
|
509
|
-
|
|
571
|
+
const next = assertDownloadUrlSafe(new URL(location, current).href);
|
|
572
|
+
if (next.origin !== current.origin) headers = void 0;
|
|
573
|
+
current = next;
|
|
510
574
|
}
|
|
511
575
|
throw new MediaError(`重定向次数超过上限(${MAX_REDIRECTS})`);
|
|
512
576
|
}
|
|
@@ -521,13 +585,14 @@ async function writeCapped(body, temp, maxBytes, signal) {
|
|
|
521
585
|
}
|
|
522
586
|
callback(null, chunk);
|
|
523
587
|
} });
|
|
524
|
-
|
|
588
|
+
const source = body instanceof Readable ? body : Readable.fromWeb(body);
|
|
589
|
+
await pipeline(source, counter, createWriteStream(temp, { flags: "wx" }), { signal });
|
|
525
590
|
return total;
|
|
526
591
|
}
|
|
527
592
|
/** 下载失败的统一错误类型(保留超时语义,其余包成 MediaError)。 */
|
|
528
|
-
function toMediaError(err, timeoutMs) {
|
|
593
|
+
function toMediaError(err, timeoutMs, aborted) {
|
|
529
594
|
if (err instanceof MediaError) return err;
|
|
530
|
-
if (err instanceof Error && (err.name === "AbortError" || err.name === "TimeoutError")) return new MediaError(`下载超时(${timeoutMs}ms)`, { cause: err });
|
|
595
|
+
if (aborted || err instanceof Error && (err.name === "AbortError" || err.name === "TimeoutError")) return new MediaError(`下载超时(${timeoutMs}ms)`, { cause: err });
|
|
531
596
|
return new MediaError(err instanceof Error ? err.message : "下载失败", { cause: err });
|
|
532
597
|
}
|
|
533
598
|
/**
|
|
@@ -536,8 +601,8 @@ function toMediaError(err, timeoutMs) {
|
|
|
536
601
|
* 失败不留半成品(临时文件已清理)。
|
|
537
602
|
*/
|
|
538
603
|
async function downloadUrl(url, dest, options = {}) {
|
|
539
|
-
return download(url, dest, options, (target, signal) => fetch(target.href, {
|
|
540
|
-
...
|
|
604
|
+
return download(url, dest, options, (target, signal, headers) => fetch(target.href, {
|
|
605
|
+
...headers === void 0 ? {} : { headers },
|
|
541
606
|
redirect: "manual",
|
|
542
607
|
signal
|
|
543
608
|
}));
|
|
@@ -555,10 +620,10 @@ async function download(url, dest, options, request) {
|
|
|
555
620
|
const temp = `${dest}.part-${process$1.pid}-${randomUUID()}`;
|
|
556
621
|
let body = null;
|
|
557
622
|
try {
|
|
558
|
-
const response = await requestFollowingRedirects(url, request, controller.signal);
|
|
623
|
+
const response = await requestFollowingRedirects(url, request, controller.signal, options.headers);
|
|
559
624
|
body = response.body;
|
|
560
625
|
if (response.status < 200 || response.status >= 300) throw new MediaError(`HTTP ${response.status}`);
|
|
561
|
-
const declared = Number(response.headers.get("
|
|
626
|
+
const declared = Number(response.headers.get("Content-Length") ?? "0");
|
|
562
627
|
if (declared > maxBytes) throw new MediaError(`文件超过大小上限(${declared} > ${maxBytes} 字节)`);
|
|
563
628
|
if (body === null) throw new MediaError("响应无 body");
|
|
564
629
|
await mkdir(dirname(dest), { recursive: true });
|
|
@@ -567,26 +632,28 @@ async function download(url, dest, options, request) {
|
|
|
567
632
|
await rename(temp, dest);
|
|
568
633
|
return written;
|
|
569
634
|
} catch (err) {
|
|
635
|
+
const error = toMediaError(err, timeoutMs, controller.signal.aborted);
|
|
570
636
|
await rm(temp, { force: true }).catch(() => void 0);
|
|
571
|
-
throw
|
|
637
|
+
throw error;
|
|
572
638
|
} finally {
|
|
573
639
|
clearTimeout(timer);
|
|
574
|
-
await body
|
|
640
|
+
await closeBody(body);
|
|
575
641
|
}
|
|
576
642
|
}
|
|
577
643
|
/** 从 Content-Type / URL 路径推断扩展名(缺省 .bin;下载命名用)。 */
|
|
578
644
|
function inferExtension(contentType, url) {
|
|
579
645
|
if (contentType !== null) {
|
|
580
646
|
const base = contentType.split(";")[0]?.trim().toLowerCase() ?? "";
|
|
581
|
-
const
|
|
582
|
-
if (
|
|
583
|
-
if (sub !== void 0 && sub !== "") return `.${sub}`;
|
|
584
|
-
}
|
|
647
|
+
const ext = MEDIA_EXTENSIONS.get(base);
|
|
648
|
+
if (ext !== void 0) return ext;
|
|
585
649
|
}
|
|
586
650
|
try {
|
|
587
651
|
const pathname = new URL(url).pathname;
|
|
588
|
-
const
|
|
589
|
-
if (
|
|
652
|
+
const dot = pathname.lastIndexOf(".");
|
|
653
|
+
if (dot > pathname.lastIndexOf("/")) {
|
|
654
|
+
const ext = pathname.slice(dot);
|
|
655
|
+
if (ext.length <= 6 && EXT_RE.test(ext)) return ext.toLowerCase();
|
|
656
|
+
}
|
|
590
657
|
} catch {}
|
|
591
658
|
return ".bin";
|
|
592
659
|
}
|