在前面的空行、空格或注释上,parseSrt 会发生未处理的 TypeError 错误
作者: codeCraft-Ritik创建于 2026年9月16日更新于 2026年9月17日
标签bug
index 0000000..f000000 100644
--- a/packages/captions/src/parse-srt.ts
+++ b/packages/captions/src/parse-srt.ts
@@ -14,7 +14,7 @@ function toSeconds(time: string) {
throw new Error(`Invalid timestamp:${time}`);
}
- const [seconds, millis] = third.split(',');
+ const [seconds, millis] = third.trim().split(/[,.]/);
if (!seconds) {
throw new Error(`Invalid timestamp:${time}`);
}
@@ -40,16 +40,21 @@ export type ParseSrtOutput = {
};
export const parseSrt = ({input}: ParseSrtInput): ParseSrtOutput => {
- const inputLines = input.split('\n');
+ const normalized = input
+ .replace(/^\uFEFF/, '')
+ .replace(/\r\n/g, '\n')
+ .replace(/\r/g, '\n');
+ const inputLines = normalized.split('\n');
const captions: Caption[] = [];
for (let i = 0; i < inputLines.length; i++) {
const line = inputLines[i];
const nextLine = inputLines[i + 1];
- if (line?.match(/([0-9]+)/) && nextLine?.includes(' --> ')) {
+ if (line?.match(/^\s*\d+\s*$/) && nextLine?.includes(' --> ')) {
const nextLineSplit = nextLine.split(' --> ');
- const start = toSeconds(nextLineSplit[0] as string);
- const end = toSeconds(nextLineSplit[1] as string);
+ const start = toSeconds((nextLineSplit[0] as string).trim());
+ const end = toSeconds((nextLineSplit[1] as string).trim());
captions.push({
text: '',
startMs: start * 1000,
@@ -60,9
…内容来源: refinedev/refine