The swiss army knife of lossless video/audio editing
Adapt to the new native rules of @mifi/lint-config
Claude5fce53455002
diff --git a/.oxlintrc.json b/.oxlintrc.jsonindex 05bac6f3..37970120 100644--- a/.oxlintrc.json+++ b/.oxlintrc.json@@ -29,6 +29,14 @@// TODO stage 2 rules from @mifi/lint-config with many findings here (count in parentheses), turned off until fixed"unicorn-js/consistent-boolean-name": "off", // (95)"react/exhaustive-effect-dependencies": "off", // (81)+ "typescript/strict-void-return": "off", // (144)+ "vitest/prefer-strict-equal": "off", // (75)+ "typescript/promise-function-async": "off", // (50)+ "react/only-export-components": "off", // (48)+ "no-implicit-coercion": "off", // (25)+ "unicorn/consistent-function-scoping": "off", // (23)+ "promise/prefer-await-to-then": "off", // (13)+ "vitest/prefer-expect-resolves": "off", // (7)"jsx-a11y/prefer-tag-over-role": "off", // (60)"react/hooks": "off", // (32)"react/memo-dependencies": "off", // (20)diff --git a/script/afterPack.ts b/script/afterPack.tsindex a059a6fe..fc480de8 100644--- a/script/afterPack.ts+++ b/script/afterPack.ts@@ -3,7 +3,8 @@import assert from 'node:assert';import { existsSync } from 'node:fs';import { join } from 'node:path';-import { Arch, type AfterPackContext } from 'electron-builder';+import { Arch } from 'electron-builder';+import type { AfterPackContext } from 'electron-builder';import { execa } from 'execa';export default async function afterPack({ appOutDir, arch, electronPlatformName, packager }: AfterPackContext) {diff --git a/script/featureMedia.ts b/script/featureMedia.tsindex 53fd4303..18a374f5 100644--- a/script/featureMedia.ts+++ b/script/featureMedia.ts@@ -15,7 +15,8 @@ import { execa } from 'execa';import clipSources from './featureMedia/clips.ts';import musicTracks, { defaultMusic } from './featureMedia/music.ts';import scenarios from './featureMedia/scenarios.ts';-import { renderSocialVideo, type Caption, type Rect, type Zoom } from './featureMedia/socialVideo.ts';+import { renderSocialVideo } from './featureMedia/socialVideo.ts';+import type { Caption, Rect, Zoom } from './featureMedia/socialVideo.ts';// eslint-disable-next-line unicorn-js/no-unreadable-object-destructuring -- TODO fix (new rule in @mifi/lint-config)const { values: { clips = 'dist/feature-media-clips', music: musicArg = defaultMusic, scale: scaleArg = '1' }, positionals: [scenarioName] } = parseArgs({ allowPositionals: true, options: { clips: { type: 'string' }, music: { type: 'string' }, scale: { type: 'string' } } });diff --git a/script/xcrunWrapper.ts b/script/xcrunWrapper.tsindex 2d60139d..9ed08d06 100644--- a/script/xcrunWrapper.ts+++ b/script/xcrunWrapper.ts@@ -104,7 +104,7 @@ async function run() {if (!wantRetry) return; // successconsole.log('Retrying soon');// eslint-disable-next-line no-await-in-loop- await new Promise((resolve) => setTimeout(resolve, 1000));+ await new Promise((resolve) => { setTimeout(resolve, 1000); });}console.log('gave up');diff --git a/src/common/types.ts b/src/common/types.tsindex c2921984..ad05ccf0 100644--- a/src/common/types.ts+++ b/src/common/types.ts@@ -1,6 +1,7 @@import { z } from 'zod';-import { langNames, type SupportedLanguage } from './i18n.ts';+import { langNames } from './i18n.ts';+import type { SupportedLanguage } from './i18n.ts';export const keyboardActionSchema = z.enum(['addSegment', 'togglePlayResetSpeed', 'togglePlayNoResetSpeed', 'reducePlaybackRate', 'reducePlaybackRateMore', 'increasePlaybackRate', 'increasePlaybackRateMore', 'timelineToggleComfortZoom', 'seekPreviousFrame', 'seekNextFrame', 'captureSnapshot', 'captureSnapshotToClipboard', 'setCutStart', 'setCutEnd', 'removeCurrentSegment', 'removeCurrentCutpoint', 'cleanupFilesDialog', 'splitCurrentSegment', 'focusSegmentAtCursor', 'selectSegmentsAtCursor', 'increaseRotation', 'goToTimecode', 'seekBackwards', 'seekBackwards2', 'seekBackwards3', 'seekBackwardsPercent', 'seekBackwardsKeyframe', 'jumpCutStart', 'seekForwards', 'seekForwards2', 'seekForwards3', 'seekForwardsPercent', 'seekForwardsKeyframe', 'jumpCutEnd', 'jumpTimelineStart', 'jumpTimelineEnd', 'jumpFirstSegment', 'jumpPrevSegment', 'jumpSeekFirstSegment', 'jumpSeekPrevSegment', 'timelineZoomIn', 'batchPreviousFile', 'jumpLastSegment', 'jumpNextSegment', 'jumpSeekLastSegment', 'jumpSeekNextSegment', 'timelineZoomOut', 'batchNextFile', 'batchOpenSelectedFile', 'batchOpenPreviousFile', 'batchOpenNextFile', 'undo', 'redo', 'copySegmentsToClipboard', 'toggleFullscreenVideo', 'labelCurrentSegment', 'export', 'toggleKeyboardShortcuts', 'increaseVolume', 'decreaseVolume', 'toggleMuted', 'detectBlackScenes', 'detectSilentScenes', 'detectSceneChanges', 'toggleLastCommands', 'play', 'pause', 'reloadFile', 'html5ify', 'makeCursorTimeZero', 'togglePlayOnlyCurrentSegment', 'toggleLoopOnlyCurrentSegment', 'toggleLoopStartEndOnlyCurrentSegment', 'togglePlaySelectedSegments', 'toggleLoopSelectedSegments', 'editCurrentSegmentTags', 'duplicateCurrentSegment', 'reorderSegsByStartTime', 'invertAllSegments', 'fillSegmentsGaps', 'shiftAllSegmentTimes', 'alignSegmentTimesToKeyframes', 'readAllKeyframes', 'createSegmentsFromKeyframes', 'createFixedDurationSegments', 'createNumSegments', 'createFixedByteSizedSegments', 'createRandomSegments', 'shuffleSegments', 'combineOverlappingSegments', 'combineSelectedSegments', 'clearSegments', 'toggleSegmentsList', 'selectOnlyCurrentSegment', 'deselectAllSegments', 'selectAllSegments', 'toggleCurrentSegmentSelected', 'invertSelectedSegments', 'removeSelectedSegments', 'toggleStreamsSelector', 'extractAllStreams', 'showStreamsSelector', 'showIncludeExternalStreamsDialog', 'captureSnapshotAsCoverArt', 'extractCurrentSegmentFramesAsImages', 'extractSelectedSegmentsFramesAsImages', 'convertFormatBatch', 'convertFormatCurrentFile', 'fixInvalidDuration', 'decimate', 'closeBatch', 'concatBatch', 'toggleKeyframeCutMode', 'toggleCaptureFormat', 'toggleStripAudio', 'toggleStripVideo', 'toggleStripSubtitle', 'toggleStripThumbnail', 'toggleStripCurrentFilter', 'toggleStripAll', 'toggleDarkMode', 'setStartTimeOffset', 'toggleWaveformMode', 'toggleShowThumbnails', 'toggleShowKeyframes', 'toggleSettings', 'openSendReportDialog', 'openFilesDialog', 'openDirDialog', 'exportYouTube', 'closeCurrentFile', 'quit', 'selectAllMarkers', 'generateOverviewWaveform', 'selectSegmentsByLabel', 'selectSegmentsByExpr', 'labelSelectedSegments', 'mutateSegmentsByExpr']);export type KeyboardAction = z.infer<typeof keyboardActionSchema>;diff --git a/src/main/configStore.ts b/src/main/configStore.tsindex a6f8a41e..3a3b3f13 100644--- a/src/main/configStore.ts+++ b/src/main/configStore.ts@@ -225,7 +225,7 @@ async function tryCreateStore({ customStoragePath }: { customStoragePath: stringreturn;} catch (err) {// eslint-disable-next-line no-await-in-loop- await new Promise((r) => setTimeout(r, 2000));+ await new Promise((resolve) => { setTimeout(resolve, 2000); });logger.error('Failed to create config store, retrying', err);}}diff --git a/src/main/index.ts b/src/main/index.tsindex dbc51639..05550b7c 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -3,7 +3,8 @@ process.traceProcessWarnings = true;/* eslint-disable import/first */// eslint-disable-next-line import-js/no-extraneous-dependencies-import electron, { BrowserWindow, type BrowserWindowConstructorOptions, nativeTheme, shell, app, ipcMain, Notification, type NotificationConstructorOptions } from 'electron';+import electron, { BrowserWindow, nativeTheme, shell, app, ipcMain, Notification } from 'electron';+import type { BrowserWindowConstructorOptions, NotificationConstructorOptions } from 'electron';import i18n from 'i18next';// eslint-disable-next-line import-js/no-extraneous-dependenciesimport debounce from 'lodash/debounce.js';@@ -95,7 +96,7 @@ async function sendApiAction(action: string, args?: unknown[]) {const id = apiActionRequestsId;apiActionRequestsId += 1;mainWindow!.webContents.send('apiAction', { id, action, args } satisfies ApiActionRequest);- await new Promise<void>((resolve) => apiActionRequests.set(id, resolve));+ await new Promise<void>((resolve) => { apiActionRequests.set(id, resolve); });} catch (err) {logger.error('sendApiAction', err);}diff --git a/src/main/pathToFileURL.test.ts b/src/main/pathToFileURL.test.tsindex 141d20d0..9fb092e4 100644--- a/src/main/pathToFileURL.test.ts+++ b/src/main/pathToFileURL.test.ts@@ -8,14 +8,14 @@ import { pathToFileURL } from 'node:url';if (process.platform === 'win32') {describe('file uri windows only', () => {test('converts path to file url', () => {- expect(pathToFileURL(String.raw`C:\Users\sindresorhus\dev\te^st.jpg`).href).toEqual('file:///C:/Users/sindresorhus/dev/te%5Est.jpg');+ expect(pathToFileURL(String.raw`C:\Users\sindresorhus\dev\te^st.jpg`).href).toBe('file:///C:/Users/sindresorhus/dev/te%5Est.jpg');});});} else {describe('file uri non-windows', () => {// https://github.com/mifi/lossless-cut/issues/1941test('file with backslash', () => {- expect(pathToFileURL(String.raw`/has/back\slash`).href).toEqual('file:///has/back%5Cslash');+ expect(pathToFileURL(String.raw`/has/back\slash`).href).toBe('file:///has/back%5Cslash');});});}diff --git a/src/main/progress.ts b/src/main/progress.tsindex b2adc368..c5ed24b9 100644--- a/src/main/progress.ts+++ b/src/main/progress.ts@@ -4,10 +4,8 @@ export function parseFfmpegProgressLine({ line, customMatcher, duration: duratioduration: number | undefined,}) {let match = line.match(/frame=\s*\S+\s+fps=\s*\S+\s+q=\s*\S+\s+(?:size|Lsize)=\s*\S+\s+time=\s*(\S+)\s+/);- if (!match) {- // Audio only looks like this: "size= 233422kB time=01:45:50.68 bitrate= 301.1kbits/s speed= 353x "- match = line.match(/(?:size|Lsize)=\s*\S+\s+time=\s*(\S+)\s+/);- }+ // Audio only looks like this: "size= 233422kB time=01:45:50.68 bitrate= 301.1kbits/s speed= 353x "+ match ??= line.match(/(?:size|Lsize)=\s*\S+\s+time=\s*(\S+)\s+/);if (!match) {customMatcher?.(line);return undefined;diff --git a/src/preload/index.ts b/src/preload/index.tsindex 0dcb6391..13e74d1c 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -1,7 +1,9 @@+import type * as Electron from 'electron';+import type { RemoteRpcApi } from '../main/index.ts';// eslint-disable-next-line @typescript-eslint/no-require-imports-const { ipcRenderer } = require('electron') as typeof import('electron');+const { ipcRenderer } = require('electron') as typeof Electron;const apiProxy = new Proxy({} as RemoteRpcApi,diff --git a/src/renderer/src/MediaSourcePlayer.tsx b/src/renderer/src/MediaSourcePlayer.tsxindex e9530606..f2672a1f 100644--- a/src/renderer/src/MediaSourcePlayer.tsx+++ b/src/renderer/src/MediaSourcePlayer.tsx@@ -106,7 +106,7 @@ async function startPlayback({ path, slaveVideo, masterVideo, videoStreamIndex,// eslint-disable-next-line no-param-reassignslaveVideo.src = objectUrl;- await new Promise((resolve) => mediaSource.addEventListener('sourceopen', resolve, { once: true }));+ await new Promise((resolve) => { mediaSource.addEventListener('sourceopen', resolve, { once: true }); });// console.log(mediaSource.readyState); // openconst sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);diff --git a/src/renderer/src/StreamsSelector.tsx b/src/renderer/src/StreamsSelector.tsxindex dfa59143..ba1ceb6d 100644--- a/src/renderer/src/StreamsSelector.tsx+++ b/src/renderer/src/StreamsSelector.tsx@@ -18,11 +18,13 @@ import { getStreamFps } from './ffmpeg';import { getActiveDisposition, attachedPicDisposition, isGpsStream, isMov, hasFileEdits, hasStreamEdits } from './util/streams';import { fileMetadataKeys, getCodecTagSuggestions, getCopyableMetadata, getEffectiveMetadata, getLanguageSuggestions, getNonNativeMovMetadataKeys, isValidCodecTag, isValidCreationTime, isValidLanguageCode, needsHvc1Tag, streamMetadataKeys } from './util/metadata';import useUserSettings from './hooks/useUserSettings';-import TagEditor, { cancelTagEditOnEscape, type TagInfo } from './components/TagEditor';+import TagEditor, { cancelTagEditOnEscape } from './components/TagEditor';+import type { TagInfo } from './components/TagEditor';import SuggestionTextField from './components/SuggestionTextField';import Warning from './components/Warning';import type { FFprobeChapter, FFprobeFormat, FFprobeStream } from '../../common/ffprobe';-import { contentDispositionOptionsSchema, deleteDispositionValue, dispositionOptions, type ContentDispositionOptions, type FileParams, type FilesMeta, type FormatTimecode, type ParamsByFile, type StreamParams } from './types';+import { contentDispositionOptionsSchema, deleteDispositionValue, dispositionOptions } from './types';+import type { ContentDispositionOptions, FileParams, FilesMeta, FormatTimecode, ParamsByFile, StreamParams } from './types';import Button, { DialogButton } from './components/Button';import styles from './StreamsSelector.module.css';import Json5Dialog from './components/Json5Dialog';@@ -349,7 +351,7 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, patconst setStreamMetadata = useCallback((streamId: number, keyValues: Record<string, string>) => {updateStreamParams(editingFile, streamId, (params) => {// eslint-disable-next-line no-param-reassign- if (params.metadata == null) params.metadata = {};+ params.metadata ??= {};const { metadata } = params;Object.entries(keyValues).forEach(([tag, value]) => {metadata[tag] = tag === 'language' ? value.toLowerCase() : value;diff --git a/src/renderer/src/components/ConcatDialog.tsx b/src/renderer/src/components/ConcatDialog.tsxindex c20e28b8..05ebb331 100644--- a/src/renderer/src/components/ConcatDialog.tsx+++ b/src/renderer/src/components/ConcatDialog.tsx@@ -140,7 +140,7 @@ function ConcatDialog({ isShown, onHide, paths, mergedFileTemplate: storedMergedconst problems: Record<string, Problem[]> = {};function addProblem(path: string, error: Problem) {- if (!problems[path]) problems[path] = [];+ problems[path] ??= [];problems[path]!.push(error);}diff --git a/src/renderer/src/components/TextInput.tsx b/src/renderer/src/components/TextInput.tsxindex 35ad1358..e90b943d 100644--- a/src/renderer/src/components/TextInput.tsx+++ b/src/renderer/src/components/TextInput.tsx@@ -1,4 +1,5 @@-import { forwardRef, type CSSProperties, type InputHTMLAttributes } from 'react';+import { forwardRef } from 'react';+import type { CSSProperties, InputHTMLAttributes } from 'react';type Props = InputHTMLAttributes<HTMLInputElement> & { style?: CSSProperties };diff --git a/src/renderer/src/dialogs/extractFrames.tsx b/src/renderer/src/dialogs/extractFrames.tsxindex cb813673..32107a28 100644--- a/src/renderer/src/dialogs/extractFrames.tsx+++ b/src/renderer/src/dialogs/extractFrames.tsx@@ -45,6 +45,7 @@ export async function askExtractFramesAsImages({ segmentsNumFrames, plural, fps// eslint-disable-next-line unicorn-js/prefer-else-if -- TODO fix (new rule in @mifi/lint-config)if (captureChoice === 'selectNthSec' || captureChoice === 'selectNthFrame') {let nthFrame: number;+ // eslint-disable-next-line oxc/branches-sharing-code -- TODO fix (new rule in @mifi/lint-config)if (captureChoice === 'selectNthFrame') {const { value } = await getSwal().Swal.fire({text: i18n.t('Capture exactly one image every nth frame'),@@ -56,7 +57,6 @@ export async function askExtractFramesAsImages({ segmentsNumFrames, plural, fps});if (value == null) return undefined;const intervalFrames = parseInt(value, 10);- // eslint-disable-next-line unicorn-js/prefer-hoisting-branch-code -- TODO fix (new rule in @mifi/lint-config)if (Number.isNaN(intervalFrames) || intervalFrames < 1) return undefined;nthFrame = intervalFrames;} else {diff --git a/src/renderer/src/edlFormats.test.ts b/src/renderer/src/edlFormats.test.tsindex d8991bf3..97db2d61 100644--- a/src/renderer/src/edlFormats.test.ts+++ b/src/renderer/src/edlFormats.test.ts@@ -259,7 +259,7 @@ it('parses csv with frames', () => {cutSegments: parsed,getFrameCount: (sec) => getFrameCountRaw(fps, sec),});- expect(formatted).toEqual(`${['Start', 'End', 'Name'].join(',')}\n${csvFramesStr}`);+ expect(formatted).toBe(`${['Start', 'End', 'Name'].join(',')}\n${csvFramesStr}`);});const csvTimestampStr = `\diff --git a/src/renderer/src/hooks/useFfmpegOperations.ts b/src/renderer/src/hooks/useFfmpegOperations.tsindex e3391473..c2d804ae 100644--- a/src/renderer/src/hooks/useFfmpegOperations.ts+++ b/src/renderer/src/hooks/useFfmpegOperations.ts@@ -11,7 +11,8 @@ import { needsSmartCut, getCodecParams } from '../smartcut';import { getGuaranteedSegments, isDurationValid } from '../segments';import type { FFprobeStream } from '../../../common/ffprobe';import type { AvoidNegativeTs, FfmpegHwAccel, Html5ifyMode, PreserveMetadata } from '../../../common/types';-import { deleteDispositionValue, type AllFilesMeta, type Chapter, type CopyfileStreams, type LiteFFprobeStream, type ParamsByFile, type SegmentToExport } from '../types';+import { deleteDispositionValue } from '../types';+import type { AllFilesMeta, Chapter, CopyfileStreams, LiteFFprobeStream, ParamsByFile, SegmentToExport } from '../types';import type { LossyMode } from '../../../main';import { UserFacingError } from '../../errors';import mainApi from '../mainApi';diff --git a/src/renderer/src/hooks/useKeyboard.ts b/src/renderer/src/hooks/useKeyboard.tsindex 31a137a8..6c55be29 100644--- a/src/renderer/src/hooks/useKeyboard.ts+++ b/src/renderer/src/hooks/useKeyboard.ts@@ -108,7 +108,7 @@ export default ({ keyBindings, keyUpActions, getKeyboardAction, closeExportConfiuseEffect(() => {const keyBindingsByKeyCode = keyBindings.reduce<Record<string, KeyBinding[]>>((acc, kb) => {kb.keys.split('+').forEach((key) => {- if (!acc[key]) acc[key] = [];+ acc[key] ??= [];acc[key].push(kb);});return acc;diff --git a/src/renderer/src/hooks/useWaveform.ts b/src/renderer/src/hooks/useWaveform.tsindex 7df31017..82c277c9 100644--- a/src/renderer/src/hooks/useWaveform.ts+++ b/src/renderer/src/hooks/useWaveform.ts@@ -109,7 +109,7 @@ export default ({ filePath, relevantTime, fileDuration, waveformEnabled, audioSt// could be problematic if we spawn ffmpeg processes too often, so throttle it// eslint-disable-next-line @eslint-react/web-api-no-leaked-timeout -- TODO fix (new rule in @mifi/lint-config)- await new Promise((r) => setTimeout(r, 100));+ await new Promise((resolve) => { setTimeout(resolve, 100); });}})();diff --git a/src/renderer/src/test/util.ts b/src/renderer/src/test/util.tsindex 9b4c8b08..1897fc07 100644--- a/src/renderer/src/test/util.ts+++ b/src/renderer/src/test/util.ts@@ -1,9 +1,5 @@import fs from 'node:fs/promises';-import { join, dirname } from 'node:path';-import { fileURLToPath } from 'node:url';+import { join } from 'node:path';-// eslint-disable-next-line no-underscore-dangle-const __dirname = dirname(fileURLToPath(import.meta.url));--export const readFixture = async (name: string, encoding: BufferEncoding = 'utf8') => fs.readFile(join(__dirname, 'fixtures', name), encoding);-export const readFixtureBinary = async (name: string) => fs.readFile(join(__dirname, 'fixtures', name), null);+export const readFixture = async (name: string, encoding: BufferEncoding = 'utf8') => fs.readFile(join(import.meta.dirname, 'fixtures', name), encoding);+export const readFixtureBinary = async (name: string) => fs.readFile(join(import.meta.dirname, 'fixtures', name), null);diff --git a/src/renderer/src/util/streams.test.ts b/src/renderer/src/util/streams.test.tsindex 24151eb3..6408123d 100644--- a/src/renderer/src/util/streams.test.ts+++ b/src/renderer/src/util/streams.test.ts@@ -200,7 +200,7 @@ test('getEffectiveAvoidNegativeTs, leaves other values alone', () => {expect(getEffectiveAvoidNegativeTs({ avoidNegativeTs: 'auto', allFilesMeta, copyFileStreams })).toBe('auto');expect(getEffectiveAvoidNegativeTs({ avoidNegativeTs: 'disabled', allFilesMeta, copyFileStreams })).toBe('disabled');- expect(getEffectiveAvoidNegativeTs({ avoidNegativeTs: undefined, allFilesMeta, copyFileStreams })).toBe(undefined);+ expect(getEffectiveAvoidNegativeTs({ avoidNegativeTs: undefined, allFilesMeta, copyFileStreams })).toBeUndefined();});// see `streams1`: 0 is cover art, 1 and 4 are audio, 2 and 3 are video, 7 is subtitle