run prettier

This commit is contained in:
2026-02-28 21:15:22 -08:00
parent e4038127cb
commit cbff3f9ad9
146 changed files with 891 additions and 584 deletions

View File

@@ -239,7 +239,8 @@ export class AnkiIntegration {
}
private createProxyServer(): AnkiConnectProxyServer {
const { AnkiConnectProxyServer } = require('./anki-integration/anki-connect-proxy') as typeof import('./anki-integration/anki-connect-proxy');
const { AnkiConnectProxyServer } =
require('./anki-integration/anki-connect-proxy') as typeof import('./anki-integration/anki-connect-proxy');
return new AnkiConnectProxyServer({
shouldAutoUpdateNewCards: () => this.config.behavior?.autoUpdateNewCards !== false,
processNewCard: (noteId: number) => this.processNewCard(noteId),

View File

@@ -27,9 +27,11 @@ test('proxy enqueues addNote result for enrichment', async () => {
logError: () => undefined,
});
(proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}).maybeEnqueueFromRequest(
(
proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}
).maybeEnqueueFromRequest(
{ action: 'addNote' },
Buffer.from(JSON.stringify({ result: 42, error: null }), 'utf8'),
);
@@ -50,9 +52,11 @@ test('proxy enqueues addNote bare numeric response for enrichment', async () =>
logError: () => undefined,
});
(proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}).maybeEnqueueFromRequest({ action: 'addNote' }, Buffer.from('42', 'utf8'));
(
proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}
).maybeEnqueueFromRequest({ action: 'addNote' }, Buffer.from('42', 'utf8'));
await waitForCondition(() => processed.length === 1);
assert.deepEqual(processed, [42]);
@@ -71,9 +75,11 @@ test('proxy de-duplicates addNotes IDs within the same response', async () => {
logError: () => undefined,
});
(proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}).maybeEnqueueFromRequest(
(
proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}
).maybeEnqueueFromRequest(
{ action: 'addNotes' },
Buffer.from(JSON.stringify({ result: [101, 102, 101, null], error: null }), 'utf8'),
);
@@ -94,17 +100,15 @@ test('proxy enqueues note IDs from multi action addNote/addNotes results', async
logError: () => undefined,
});
(proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}).maybeEnqueueFromRequest(
(
proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}
).maybeEnqueueFromRequest(
{
action: 'multi',
params: {
actions: [
{ action: 'version' },
{ action: 'addNote' },
{ action: 'addNotes' },
],
actions: [{ action: 'version' }, { action: 'addNote' }, { action: 'addNotes' }],
},
},
Buffer.from(JSON.stringify({ result: [6, 777, [888, 777, null]], error: null }), 'utf8'),
@@ -126,9 +130,11 @@ test('proxy enqueues note IDs from bare multi action results', async () => {
logError: () => undefined,
});
(proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}).maybeEnqueueFromRequest(
(
proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}
).maybeEnqueueFromRequest(
{
action: 'multi',
params: {
@@ -154,17 +160,15 @@ test('proxy enqueues note IDs from multi action envelope results', async () => {
logError: () => undefined,
});
(proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}).maybeEnqueueFromRequest(
(
proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}
).maybeEnqueueFromRequest(
{
action: 'multi',
params: {
actions: [
{ action: 'version' },
{ action: 'addNote' },
{ action: 'addNotes' },
],
actions: [{ action: 'version' }, { action: 'addNote' }, { action: 'addNotes' }],
},
},
Buffer.from(
@@ -196,9 +200,11 @@ test('proxy skips auto-enrichment when auto-update is disabled', async () => {
logError: () => undefined,
});
(proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}).maybeEnqueueFromRequest(
(
proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}
).maybeEnqueueFromRequest(
{ action: 'addNote' },
Buffer.from(JSON.stringify({ result: 303, error: null }), 'utf8'),
);
@@ -219,9 +225,11 @@ test('proxy ignores addNote when upstream response reports error', async () => {
logError: () => undefined,
});
(proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}).maybeEnqueueFromRequest(
(
proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}
).maybeEnqueueFromRequest(
{ action: 'addNote' },
Buffer.from(JSON.stringify({ result: 123, error: 'duplicate' }), 'utf8'),
);
@@ -248,9 +256,11 @@ test('proxy does not fallback-enqueue latest note for multi requests without add
logError: () => undefined,
});
(proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}).maybeEnqueueFromRequest(
(
proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}
).maybeEnqueueFromRequest(
{
action: 'multi',
params: {
@@ -283,9 +293,11 @@ test('proxy fallback-enqueues latest note for addNote responses without note IDs
logError: () => undefined,
});
(proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}).maybeEnqueueFromRequest(
(
proxy as unknown as {
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
}
).maybeEnqueueFromRequest(
{ action: 'addNote' },
Buffer.from(JSON.stringify({ result: 0, error: null }), 'utf8'),
);
@@ -304,13 +316,15 @@ test('proxy detects self-referential loop configuration', () => {
logError: () => undefined,
});
const result = (proxy as unknown as {
isSelfReferentialProxy: (options: {
host: string;
port: number;
upstreamUrl: string;
}) => boolean;
}).isSelfReferentialProxy({
const result = (
proxy as unknown as {
isSelfReferentialProxy: (options: {
host: string;
port: number;
upstreamUrl: string;
}) => boolean;
}
).isSelfReferentialProxy({
host: '127.0.0.1',
port: 8766,
upstreamUrl: 'http://localhost:8766',

View File

@@ -175,7 +175,9 @@ export class AnkiConnectProxyServer {
}
const action =
typeof requestJson.action === 'string' ? requestJson.action : String(requestJson.action ?? '');
typeof requestJson.action === 'string'
? requestJson.action
: String(requestJson.action ?? '');
if (action !== 'addNote' && action !== 'addNotes' && action !== 'multi') {
return;
}

View File

@@ -89,7 +89,11 @@ test('findDuplicateNote checks both source expression/word values when both fiel
if (query.includes('昨日は雨だった。')) {
return [];
}
if (query.includes('"Word:雨"') || query.includes('"word:雨"') || query.includes('"Expression:雨"')) {
if (
query.includes('"Word:雨"') ||
query.includes('"word:雨"') ||
query.includes('"Expression:雨"')
) {
return [200];
}
return [];

View File

@@ -32,9 +32,7 @@ export async function findDuplicateNote(
);
const deckValue = deps.getDeck();
const queryPrefixes = deckValue
? [`"deck:${escapeAnkiSearchValue(deckValue)}" `, '']
: [''];
const queryPrefixes = deckValue ? [`"deck:${escapeAnkiSearchValue(deckValue)}" `, ''] : [''];
try {
const noteIds = new Set<number>();

View File

@@ -112,12 +112,7 @@ export class FieldGroupingWorkflow {
const keepNoteId = choice.keepNoteId;
const deleteNoteId = choice.deleteNoteId;
await this.performMerge(
keepNoteId,
deleteNoteId,
expression,
choice.deleteDuplicate,
);
await this.performMerge(keepNoteId, deleteNoteId, expression, choice.deleteDuplicate);
return true;
} catch (error) {
this.deps.logError('Field grouping manual merge failed:', (error as Error).message);

View File

@@ -51,18 +51,10 @@ function createWorkflowHarness() {
return out;
},
findDuplicateNote: async (_expression, _excludeNoteId, _noteInfo) => null,
handleFieldGroupingAuto: async (
_originalNoteId,
_newNoteId,
_newNoteInfo,
_expression,
) => undefined,
handleFieldGroupingManual: async (
_originalNoteId,
_newNoteId,
_newNoteInfo,
_expression,
) => false,
handleFieldGroupingAuto: async (_originalNoteId, _newNoteId, _newNoteInfo, _expression) =>
undefined,
handleFieldGroupingManual: async (_originalNoteId, _newNoteId, _newNoteInfo, _expression) =>
false,
processSentence: (text: string, _noteFields: Record<string, string>) => text,
resolveConfiguredFieldName: (noteInfo: NoteUpdateWorkflowNoteInfo, preferred?: string) => {
if (!preferred) return null;

View File

@@ -748,6 +748,9 @@ test('runtime options registry is centralized', () => {
const ids = RUNTIME_OPTION_REGISTRY.map((entry) => entry.id);
assert.deepEqual(ids, [
'anki.autoUpdateNewCards',
'subtitle.annotation.nPlusOne',
'subtitle.annotation.jlpt',
'subtitle.annotation.frequency',
'anki.nPlusOneMatchMode',
'anki.kikuFieldGrouping',
]);

View File

@@ -62,7 +62,9 @@ test('domain registry builders each contribute entries to composed registry', ()
});
test('default keybindings include primary and secondary subtitle track cycling on J keys', () => {
const keybindingMap = new Map(DEFAULT_KEYBINDINGS.map((binding) => [binding.key, binding.command]));
const keybindingMap = new Map(
DEFAULT_KEYBINDINGS.map((binding) => [binding.key, binding.command]),
);
assert.deepEqual(keybindingMap.get('KeyJ'), ['cycle', 'sid']);
assert.deepEqual(keybindingMap.get('Shift+KeyJ'), ['cycle', 'secondary-sid']);
});

View File

@@ -5,6 +5,8 @@ export function buildIntegrationConfigOptionRegistry(
defaultConfig: ResolvedConfig,
runtimeOptionRegistry: RuntimeOptionRegistryEntry[],
): ConfigOptionRegistryEntry[] {
const runtimeOptionById = new Map(runtimeOptionRegistry.map((entry) => [entry.id, entry]));
return [
{
path: 'ankiConnect.enabled',
@@ -54,7 +56,7 @@ export function buildIntegrationConfigOptionRegistry(
kind: 'boolean',
defaultValue: defaultConfig.ankiConnect.behavior.autoUpdateNewCards,
description: 'Automatically update newly added cards.',
runtime: runtimeOptionRegistry[0],
runtime: runtimeOptionById.get('anki.autoUpdateNewCards'),
},
{
path: 'ankiConnect.nPlusOne.matchMode',
@@ -105,7 +107,7 @@ export function buildIntegrationConfigOptionRegistry(
enumValues: ['auto', 'manual', 'disabled'],
defaultValue: defaultConfig.ankiConnect.isKiku.fieldGrouping,
description: 'Kiku duplicate-card field grouping mode.',
runtime: runtimeOptionRegistry[1],
runtime: runtimeOptionById.get('anki.kikuFieldGrouping'),
},
{
path: 'jimaku.languagePreference',

View File

@@ -19,6 +19,42 @@ export function buildRuntimeOptionRegistry(
behavior: { autoUpdateNewCards: value === true },
}),
},
{
id: 'subtitle.annotation.nPlusOne',
path: 'ankiConnect.nPlusOne.highlightEnabled',
label: 'N+1 Annotation',
scope: 'subtitle',
valueType: 'boolean',
allowedValues: [true, false],
defaultValue: defaultConfig.ankiConnect.nPlusOne.highlightEnabled,
requiresRestart: false,
formatValueForOsd: (value) => (value === true ? 'On' : 'Off'),
toAnkiPatch: () => ({}),
},
{
id: 'subtitle.annotation.jlpt',
path: 'subtitleStyle.enableJlpt',
label: 'JLPT Annotation',
scope: 'subtitle',
valueType: 'boolean',
allowedValues: [true, false],
defaultValue: defaultConfig.subtitleStyle.enableJlpt,
requiresRestart: false,
formatValueForOsd: (value) => (value === true ? 'On' : 'Off'),
toAnkiPatch: () => ({}),
},
{
id: 'subtitle.annotation.frequency',
path: 'subtitleStyle.frequencyDictionary.enabled',
label: 'Frequency Annotation',
scope: 'subtitle',
valueType: 'boolean',
allowedValues: [true, false],
defaultValue: defaultConfig.subtitleStyle.frequencyDictionary.enabled,
requiresRestart: false,
formatValueForOsd: (value) => (value === true ? 'On' : 'Off'),
toAnkiPatch: () => ({}),
},
{
id: 'anki.nPlusOneMatchMode',
path: 'ankiConnect.nPlusOne.matchMode',

View File

@@ -111,7 +111,8 @@ export function applySubtitleDomainConfig(context: ResolveContext): void {
frequencyDictionary: {
...resolved.subtitleStyle.frequencyDictionary,
...(isObject((src.subtitleStyle as { frequencyDictionary?: unknown }).frequencyDictionary)
? ((src.subtitleStyle as { frequencyDictionary?: unknown }).frequencyDictionary as ResolvedConfig['subtitleStyle']['frequencyDictionary'])
? ((src.subtitleStyle as { frequencyDictionary?: unknown })
.frequencyDictionary as ResolvedConfig['subtitleStyle']['frequencyDictionary'])
: {}),
},
secondary: {
@@ -152,7 +153,9 @@ export function applySubtitleDomainConfig(context: ResolveContext): void {
);
}
const hoverTokenColor = asColor((src.subtitleStyle as { hoverTokenColor?: unknown }).hoverTokenColor);
const hoverTokenColor = asColor(
(src.subtitleStyle as { hoverTokenColor?: unknown }).hoverTokenColor,
);
if (hoverTokenColor !== undefined) {
resolved.subtitleStyle.hoverTokenColor = hoverTokenColor;
} else if ((src.subtitleStyle as { hoverTokenColor?: unknown }).hoverTokenColor !== undefined) {
@@ -174,7 +177,8 @@ export function applySubtitleDomainConfig(context: ResolveContext): void {
(src.subtitleStyle as { hoverTokenBackgroundColor?: unknown }).hoverTokenBackgroundColor !==
undefined
) {
resolved.subtitleStyle.hoverTokenBackgroundColor = fallbackSubtitleStyleHoverTokenBackgroundColor;
resolved.subtitleStyle.hoverTokenBackgroundColor =
fallbackSubtitleStyleHoverTokenBackgroundColor;
warn(
'subtitleStyle.hoverTokenBackgroundColor',
(src.subtitleStyle as { hoverTokenBackgroundColor?: unknown }).hoverTokenBackgroundColor,
@@ -208,7 +212,8 @@ export function applySubtitleDomainConfig(context: ResolveContext): void {
if (sourcePath !== undefined) {
resolved.subtitleStyle.frequencyDictionary.sourcePath = sourcePath;
} else if ((frequencyDictionary as { sourcePath?: unknown }).sourcePath !== undefined) {
resolved.subtitleStyle.frequencyDictionary.sourcePath = fallbackFrequencyDictionary.sourcePath;
resolved.subtitleStyle.frequencyDictionary.sourcePath =
fallbackFrequencyDictionary.sourcePath;
warn(
'subtitleStyle.frequencyDictionary.sourcePath',
(frequencyDictionary as { sourcePath?: unknown }).sourcePath,
@@ -260,7 +265,8 @@ export function applySubtitleDomainConfig(context: ResolveContext): void {
if (singleColor !== undefined) {
resolved.subtitleStyle.frequencyDictionary.singleColor = singleColor;
} else if ((frequencyDictionary as { singleColor?: unknown }).singleColor !== undefined) {
resolved.subtitleStyle.frequencyDictionary.singleColor = fallbackFrequencyDictionary.singleColor;
resolved.subtitleStyle.frequencyDictionary.singleColor =
fallbackFrequencyDictionary.singleColor;
warn(
'subtitleStyle.frequencyDictionary.singleColor',
(frequencyDictionary as { singleColor?: unknown }).singleColor,

View File

@@ -25,7 +25,8 @@ function humanizeKey(key: string): string {
function buildInlineOptionComment(path: string, value: unknown): string {
const registryEntry = OPTION_REGISTRY_BY_PATH.get(path);
const baseDescription = registryEntry?.description ?? TOP_LEVEL_SECTION_DESCRIPTION_BY_KEY.get(path);
const baseDescription =
registryEntry?.description ?? TOP_LEVEL_SECTION_DESCRIPTION_BY_KEY.get(path);
const description =
baseDescription && baseDescription.trim().length > 0
? normalizeCommentText(baseDescription)

View File

@@ -132,16 +132,15 @@ export function createAnilistTokenStore(
}
return decrypted;
}
if (
typeof parsed.plaintextToken === 'string' &&
parsed.plaintextToken.trim().length > 0
) {
if (typeof parsed.plaintextToken === 'string' && parsed.plaintextToken.trim().length > 0) {
if (storage.isEncryptionAvailable()) {
if (!isSafeStorageUsable()) {
return null;
}
const plaintext = parsed.plaintextToken.trim();
notifyUser('AniList token plaintext fallback payload found. Migrating to encrypted storage.');
notifyUser(
'AniList token plaintext fallback payload found. Migrating to encrypted storage.',
);
this.saveToken(plaintext);
return plaintext;
}

View File

@@ -283,8 +283,7 @@ export function handleCliCommand(
return;
}
const shouldStart =
args.start || args.toggle || args.toggleVisibleOverlay;
const shouldStart = args.start || args.toggle || args.toggleVisibleOverlay;
const needsOverlayRuntime = commandNeedsOverlayRuntime(args);
const shouldInitializeOverlayRuntime = needsOverlayRuntime || args.start;

View File

@@ -71,7 +71,8 @@ test('createFrequencyDictionaryLookup aggregates duplicate-term logs into a sing
assert.equal(lookup('猫'), 100);
assert.equal(
logs.filter((entry) => entry.includes('Frequency dictionary ignored 2 duplicate term entries')).length,
logs.filter((entry) => entry.includes('Frequency dictionary ignored 2 duplicate term entries'))
.length,
1,
);
assert.equal(

View File

@@ -32,7 +32,7 @@ function parsePositiveFrequencyString(value: string): number | null {
const chunks = numericPrefix.split(',');
const normalizedNumber =
chunks.length <= 1
? chunks[0] ?? ''
? (chunks[0] ?? '')
: chunks.slice(1).every((chunk) => /^\d{3}$/.test(chunk))
? chunks.join('')
: (chunks[0] ?? '');

View File

@@ -62,10 +62,7 @@ export {
updateOverlayWindowBounds,
} from './overlay-window';
export { initializeOverlayRuntime } from './overlay-runtime-init';
export {
setVisibleOverlayVisible,
updateVisibleOverlayVisibility,
} from './overlay-visibility';
export { setVisibleOverlayVisible, updateVisibleOverlayVisibility } from './overlay-visibility';
export {
MPV_REQUEST_ID_SECONDARY_SUB_VISIBILITY,
MpvIpcClient,

View File

@@ -150,7 +150,12 @@ test('registerIpcHandlers rejects malformed runtime-option payloads', async () =
});
const validResult = await setHandler!({}, 'anki.autoUpdateNewCards', true);
assert.deepEqual(validResult, { ok: true });
assert.deepEqual(calls, [{ id: 'anki.autoUpdateNewCards', value: true }]);
const validSubtitleAnnotationResult = await setHandler!({}, 'subtitle.annotation.jlpt', false);
assert.deepEqual(validSubtitleAnnotationResult, { ok: true });
assert.deepEqual(calls, [
{ id: 'anki.autoUpdateNewCards', value: true },
{ id: 'subtitle.annotation.jlpt', value: false },
]);
const cycleHandler = handlers.handle.get(IPC_CHANNELS.request.cycleRuntimeOption);
assert.ok(cycleHandler);
@@ -215,9 +220,7 @@ test('registerIpcHandlers ignores malformed fire-and-forget payloads', () => {
handlers.on.get(IPC_CHANNELS.command.saveSubtitlePosition)!({}, { yPercent: 'bad' });
handlers.on.get(IPC_CHANNELS.command.saveSubtitlePosition)!({}, { yPercent: 42 });
assert.deepEqual(saves, [
{ yPercent: 42 },
]);
assert.deepEqual(saves, [{ yPercent: 42 }]);
handlers.on.get(IPC_CHANNELS.command.overlayModalClosed)!({}, 'not-a-modal');
handlers.on.get(IPC_CHANNELS.command.overlayModalClosed)!({}, 'subsync');

View File

@@ -62,7 +62,8 @@ export function createJellyfinTokenStore(
}
const decrypted = safeStorage.decryptString(encrypted).trim();
const session = JSON.parse(decrypted) as Partial<JellyfinStoredSession>;
const accessToken = typeof session.accessToken === 'string' ? session.accessToken.trim() : '';
const accessToken =
typeof session.accessToken === 'string' ? session.accessToken.trim() : '';
const userId = typeof session.userId === 'string' ? session.userId.trim() : '';
if (!accessToken || !userId) return null;
return { accessToken, userId };
@@ -88,7 +89,9 @@ export function createJellyfinTokenStore(
(typeof parsed.encryptedToken === 'string' && parsed.encryptedToken.length > 0) ||
(typeof parsed.plaintextToken === 'string' && parsed.plaintextToken.trim().length > 0)
) {
logger.warn('Ignoring legacy Jellyfin token-only store payload because userId is missing.');
logger.warn(
'Ignoring legacy Jellyfin token-only store payload because userId is missing.',
);
}
} catch (error) {
logger.error('Failed to read Jellyfin session store.', error);

View File

@@ -34,10 +34,7 @@ export function sendToVisibleOverlayRuntime<T extends string>(options: {
const isLoading = typeof webContents.isLoading === 'function' ? webContents.isLoading() : false;
const currentURL = typeof webContents.getURL === 'function' ? webContents.getURL() : '';
const isReady =
!isLoading &&
currentURL !== '' &&
currentURL !== 'about:blank';
const isReady = !isLoading && currentURL !== '' && currentURL !== 'about:blank';
if (!isReady) {
if (typeof webContents.once !== 'function') {

View File

@@ -85,7 +85,9 @@ export function parseClipboardVideoPath(text: string): string | null {
return isSupportedVideoPath(unquoted) ? unquoted : null;
}
export function collectDroppedVideoPaths(dataTransfer: DropDataTransferLike | null | undefined): string[] {
export function collectDroppedVideoPaths(
dataTransfer: DropDataTransferLike | null | undefined,
): string[] {
if (!dataTransfer) return [];
const out: string[] = [];

View File

@@ -117,13 +117,9 @@ test('runtime-option broadcast still uses expected channel', () => {
},
);
let state = false;
const changed = setOverlayDebugVisualizationEnabledRuntime(
state,
true,
(enabled) => {
state = enabled;
},
);
const changed = setOverlayDebugVisualizationEnabledRuntime(state, true, (enabled) => {
state = enabled;
});
assert.equal(changed, true);
assert.equal(state, true);
assert.deepEqual(broadcasts, [['runtime-options:changed', []]]);

View File

@@ -41,13 +41,12 @@ test('initializeOverlayRuntime skips Anki integration when ankiConnect.enabled i
setIntegrationCalls += 1;
},
showDesktopNotification: () => {},
createFieldGroupingCallback: () =>
async () => ({
keepNoteId: 1,
deleteNoteId: 2,
deleteDuplicate: false,
cancelled: false,
}),
createFieldGroupingCallback: () => async () => ({
keepNoteId: 1,
deleteNoteId: 2,
deleteDuplicate: false,
cancelled: false,
}),
getKnownWordCacheStatePath: () => '/tmp/known-words-cache.json',
});
@@ -96,13 +95,12 @@ test('initializeOverlayRuntime starts Anki integration when ankiConnect.enabled
setIntegrationCalls += 1;
},
showDesktopNotification: () => {},
createFieldGroupingCallback: () =>
async () => ({
keepNoteId: 3,
deleteNoteId: 4,
deleteDuplicate: false,
cancelled: false,
}),
createFieldGroupingCallback: () => async () => ({
keepNoteId: 3,
deleteNoteId: 4,
deleteDuplicate: false,
cancelled: false,
}),
getKnownWordCacheStatePath: () => '/tmp/known-words-cache.json',
});

View File

@@ -23,7 +23,8 @@ type CreateAnkiIntegrationArgs = {
};
function createDefaultAnkiIntegration(args: CreateAnkiIntegrationArgs): AnkiIntegrationLike {
const { AnkiIntegration } = require('../../anki-integration') as typeof import('../../anki-integration');
const { AnkiIntegration } =
require('../../anki-integration') as typeof import('../../anki-integration');
return new AnkiIntegration(
args.config,
args.subtitleTimingTracker as never,
@@ -76,7 +77,10 @@ export function initializeOverlayRuntime(options: {
options.registerGlobalShortcuts();
const createWindowTrackerHandler = options.createWindowTracker ?? createWindowTracker;
const windowTracker = createWindowTrackerHandler(options.backendOverride, options.getMpvSocketPath());
const windowTracker = createWindowTrackerHandler(
options.backendOverride,
options.getMpvSocketPath(),
);
options.setWindowTracker(windowTracker);
if (windowTracker) {
windowTracker.onGeometryChange = (geometry: WindowGeometry) => {

View File

@@ -138,3 +138,35 @@ test('subtitle processing refresh can use explicit text override', async () => {
assert.deepEqual(emitted, [{ text: 'initial', tokens: [] }]);
});
test('subtitle processing cache invalidation only affects future subtitle events', async () => {
const emitted: SubtitleData[] = [];
const callsByText = new Map<string, number>();
const controller = createSubtitleProcessingController({
tokenizeSubtitle: async (text) => {
callsByText.set(text, (callsByText.get(text) ?? 0) + 1);
return { text, tokens: [] };
},
emitSubtitle: (payload) => emitted.push(payload),
});
controller.onSubtitleChange('same');
await flushMicrotasks();
controller.onSubtitleChange('other');
await flushMicrotasks();
controller.onSubtitleChange('same');
await flushMicrotasks();
assert.equal(callsByText.get('same'), 1);
assert.equal(emitted.length, 3);
controller.invalidateTokenizationCache();
assert.equal(emitted.length, 3);
controller.onSubtitleChange('different');
await flushMicrotasks();
controller.onSubtitleChange('same');
await flushMicrotasks();
assert.equal(callsByText.get('same'), 2);
});

View File

@@ -10,6 +10,7 @@ export interface SubtitleProcessingControllerDeps {
export interface SubtitleProcessingController {
onSubtitleChange: (text: string) => void;
refreshCurrentSubtitle: (textOverride?: string) => void;
invalidateTokenizationCache: () => void;
}
export function createSubtitleProcessingController(
@@ -126,5 +127,8 @@ export function createSubtitleProcessingController(
refreshRequested = true;
processLatest();
},
invalidateTokenizationCache: () => {
tokenizationCache.clear();
},
};
}

View File

@@ -52,7 +52,12 @@ test('annotateTokens known-word match mode uses headword vs surface', () => {
test('annotateTokens excludes frequency for particle/bound_auxiliary and pos1 exclusions', () => {
const tokens = [
makeToken({ surface: 'は', headword: 'は', partOfSpeech: PartOfSpeech.particle, frequencyRank: 3 }),
makeToken({
surface: 'は',
headword: 'は',
partOfSpeech: PartOfSpeech.particle,
frequencyRank: 3,
}),
makeToken({
surface: 'です',
headword: 'です',

View File

@@ -7,12 +7,7 @@ import {
DEFAULT_ANNOTATION_POS2_EXCLUSION_CONFIG,
resolveAnnotationPos2ExclusionSet,
} from '../../../token-pos2-exclusions';
import {
JlptLevel,
MergedToken,
NPlusOneMatchMode,
PartOfSpeech,
} from '../../../types';
import { JlptLevel, MergedToken, NPlusOneMatchMode, PartOfSpeech } from '../../../types';
import { shouldIgnoreJlptByTerm, shouldIgnoreJlptForMecabPos1 } from '../jlpt-token-filter';
const KATAKANA_TO_HIRAGANA_OFFSET = 0x60;
@@ -67,10 +62,7 @@ function normalizePos1Tag(pos1: string | undefined): string {
return typeof pos1 === 'string' ? pos1.trim() : '';
}
function isExcludedByTagSet(
normalizedTag: string,
exclusions: ReadonlySet<string>,
): boolean {
function isExcludedByTagSet(normalizedTag: string, exclusions: ReadonlySet<string>): boolean {
if (!normalizedTag) {
return false;
}
@@ -350,10 +342,7 @@ function isLikelyFrequencyNoiseToken(token: MergedToken): boolean {
continue;
}
if (
shouldIgnoreJlptByTerm(trimmedCandidate) ||
shouldIgnoreJlptByTerm(normalizedCandidate)
) {
if (shouldIgnoreJlptByTerm(trimmedCandidate) || shouldIgnoreJlptByTerm(normalizedCandidate)) {
return true;
}
@@ -442,13 +431,12 @@ export function annotateTokens(
}));
const frequencyEnabled = options.frequencyEnabled !== false;
const frequencyMarkedTokens =
frequencyEnabled
? applyFrequencyMarking(knownMarkedTokens, pos1Exclusions, pos2Exclusions)
: knownMarkedTokens.map((token) => ({
...token,
frequencyRank: undefined,
}));
const frequencyMarkedTokens = frequencyEnabled
? applyFrequencyMarking(knownMarkedTokens, pos1Exclusions, pos2Exclusions)
: knownMarkedTokens.map((token) => ({
...token,
frequencyRank: undefined,
}));
const jlptEnabled = options.jlptEnabled !== false;
const jlptMarkedTokens = jlptEnabled

View File

@@ -116,7 +116,9 @@ class ParserEnrichmentWorkerRuntime {
}
private handleWorkerFailure(error: Error): void {
logger.debug(`Parser enrichment worker unavailable, falling back to main thread: ${error.message}`);
logger.debug(
`Parser enrichment worker unavailable, falling back to main thread: ${error.message}`,
);
for (const pending of this.pending.values()) {
pending.reject(error);
}

View File

@@ -1256,10 +1256,7 @@ function getResolvedConfig() {
}
function getRuntimeBooleanOption(
id:
| 'subtitle.annotation.nPlusOne'
| 'subtitle.annotation.jlpt'
| 'subtitle.annotation.frequency',
id: 'subtitle.annotation.nPlusOne' | 'subtitle.annotation.jlpt' | 'subtitle.annotation.frequency',
fallback: boolean,
): boolean {
const value = appState.runtimeOptionsManager?.getOptionValue(id);
@@ -2318,7 +2315,10 @@ const {
getResolvedConfig().ankiConnect.nPlusOne.minSentenceWords,
getJlptLevel: (text) => appState.jlptLevelLookup(text),
getJlptEnabled: () =>
getRuntimeBooleanOption('subtitle.annotation.jlpt', getResolvedConfig().subtitleStyle.enableJlpt),
getRuntimeBooleanOption(
'subtitle.annotation.jlpt',
getResolvedConfig().subtitleStyle.enableJlpt,
),
getFrequencyDictionaryEnabled: () =>
getRuntimeBooleanOption(
'subtitle.annotation.frequency',

View File

@@ -214,9 +214,13 @@ test('handleOverlayModalClosed hides modal window only after all pending modals
runtime.sendToActiveOverlayWindow('runtime-options:open', undefined, {
restoreOnModalClose: 'runtime-options',
});
runtime.sendToActiveOverlayWindow('subsync:open-manual', { sourceTracks: [] }, {
restoreOnModalClose: 'subsync',
});
runtime.sendToActiveOverlayWindow(
'subsync:open-manual',
{ sourceTracks: [] },
{
restoreOnModalClose: 'subsync',
},
);
runtime.handleOverlayModalClosed('runtime-options');
assert.equal(window.getHideCount(), 0);
@@ -267,9 +271,13 @@ test('modal runtime notifies callers when modal input state becomes active/inact
runtime.sendToActiveOverlayWindow('runtime-options:open', undefined, {
restoreOnModalClose: 'runtime-options',
});
runtime.sendToActiveOverlayWindow('subsync:open-manual', { sourceTracks: [] }, {
restoreOnModalClose: 'subsync',
});
runtime.sendToActiveOverlayWindow(
'subsync:open-manual',
{ sourceTracks: [] },
{
restoreOnModalClose: 'subsync',
},
);
assert.deepEqual(state, []);
runtime.notifyOverlayModalOpened('runtime-options');
assert.deepEqual(state, [true]);
@@ -352,9 +360,13 @@ test('handleOverlayModalClosed hides modal window for single kiku modal', () =>
setModalWindowBounds: () => {},
});
runtime.sendToActiveOverlayWindow('kiku:field-grouping-open', { test: true }, {
restoreOnModalClose: 'kiku',
});
runtime.sendToActiveOverlayWindow(
'kiku:field-grouping-open',
{ test: true },
{
restoreOnModalClose: 'kiku',
},
);
runtime.handleOverlayModalClosed('kiku');
assert.equal(window.getHideCount(), 1);

View File

@@ -3,7 +3,9 @@ import type {
createMaybeProbeAnilistDurationHandler,
} from './anilist-media-guess';
type MaybeProbeAnilistDurationMainDeps = Parameters<typeof createMaybeProbeAnilistDurationHandler>[0];
type MaybeProbeAnilistDurationMainDeps = Parameters<
typeof createMaybeProbeAnilistDurationHandler
>[0];
type EnsureAnilistMediaGuessMainDeps = Parameters<typeof createEnsureAnilistMediaGuessHandler>[0];
export function createBuildMaybeProbeAnilistDurationMainDepsHandler(
@@ -19,13 +21,17 @@ export function createBuildMaybeProbeAnilistDurationMainDepsHandler(
});
}
export function createBuildEnsureAnilistMediaGuessMainDepsHandler(deps: EnsureAnilistMediaGuessMainDeps) {
export function createBuildEnsureAnilistMediaGuessMainDepsHandler(
deps: EnsureAnilistMediaGuessMainDeps,
) {
return (): EnsureAnilistMediaGuessMainDeps => ({
getState: () => deps.getState(),
setState: (state) => deps.setState(state),
resolveMediaPathForJimaku: (currentMediaPath) => deps.resolveMediaPathForJimaku(currentMediaPath),
resolveMediaPathForJimaku: (currentMediaPath) =>
deps.resolveMediaPathForJimaku(currentMediaPath),
getCurrentMediaPath: () => deps.getCurrentMediaPath(),
getCurrentMediaTitle: () => deps.getCurrentMediaTitle(),
guessAnilistMediaInfo: (mediaPath, mediaTitle) => deps.guessAnilistMediaInfo(mediaPath, mediaTitle),
guessAnilistMediaInfo: (mediaPath, mediaTitle) =>
deps.guessAnilistMediaInfo(mediaPath, mediaTitle),
});
}

View File

@@ -6,8 +6,12 @@ import type {
createSetAnilistMediaGuessRuntimeStateHandler,
} from './anilist-media-state';
type GetCurrentAnilistMediaKeyMainDeps = Parameters<typeof createGetCurrentAnilistMediaKeyHandler>[0];
type ResetAnilistMediaTrackingMainDeps = Parameters<typeof createResetAnilistMediaTrackingHandler>[0];
type GetCurrentAnilistMediaKeyMainDeps = Parameters<
typeof createGetCurrentAnilistMediaKeyHandler
>[0];
type ResetAnilistMediaTrackingMainDeps = Parameters<
typeof createResetAnilistMediaTrackingHandler
>[0];
type GetAnilistMediaGuessRuntimeStateMainDeps = Parameters<
typeof createGetAnilistMediaGuessRuntimeStateHandler
>[0];

View File

@@ -47,7 +47,8 @@ export function createBuildMaybeRunAnilistPostWatchUpdateMainDepsHandler(
hasAttemptedUpdateKey: (key: string) => deps.hasAttemptedUpdateKey(key),
processNextAnilistRetryUpdate: () => deps.processNextAnilistRetryUpdate(),
refreshAnilistClientSecretState: () => deps.refreshAnilistClientSecretState(),
enqueueRetry: (key: string, title: string, episode: number) => deps.enqueueRetry(key, title, episode),
enqueueRetry: (key: string, title: string, episode: number) =>
deps.enqueueRetry(key, title, episode),
markRetryFailure: (key: string, message: string) => deps.markRetryFailure(key, message),
markRetrySuccess: (key: string) => deps.markRetrySuccess(key),
refreshRetryQueueState: () => deps.refreshRetryQueueState(),

View File

@@ -64,7 +64,11 @@ export function createProcessNextAnilistRetryUpdateHandler(deps: {
return { ok: false, message: 'AniList token unavailable for queued retry.' };
}
const result = await deps.updateAnilistPostWatchProgress(accessToken, queued.title, queued.episode);
const result = await deps.updateAnilistPostWatchProgress(
accessToken,
queued.title,
queued.episode,
);
if (result.status === 'updated' || result.status === 'skipped') {
deps.markSuccess(queued.key);
deps.rememberAttemptedUpdateKey(queued.key);
@@ -166,7 +170,11 @@ export function createMaybeRunAnilistPostWatchUpdateHandler(deps: {
return;
}
const result = await deps.updateAnilistPostWatchProgress(accessToken, guess.title, guess.episode);
const result = await deps.updateAnilistPostWatchProgress(
accessToken,
guess.title,
guess.episode,
);
if (result.status === 'updated') {
deps.rememberAttemptedUpdateKey(attemptKey);
deps.markRetrySuccess(attemptKey);

View File

@@ -44,7 +44,8 @@ export function createBuildHandleAnilistSetupProtocolUrlMainDepsHandler(
deps: HandleAnilistSetupProtocolUrlMainDeps,
) {
return (): HandleAnilistSetupProtocolUrlMainDeps => ({
consumeAnilistSetupTokenFromUrl: (rawUrl: string) => deps.consumeAnilistSetupTokenFromUrl(rawUrl),
consumeAnilistSetupTokenFromUrl: (rawUrl: string) =>
deps.consumeAnilistSetupTokenFromUrl(rawUrl),
logWarn: (message: string, details: unknown) => deps.logWarn(message, details),
});
}

View File

@@ -66,11 +66,7 @@ export function createRegisterSubminerProtocolClientHandler(deps: {
getArgv: () => string[];
execPath: string;
resolvePath: (value: string) => string;
setAsDefaultProtocolClient: (
scheme: string,
path?: string,
args?: string[],
) => boolean;
setAsDefaultProtocolClient: (scheme: string, path?: string, args?: string[]) => boolean;
logWarn: (message: string, details?: unknown) => void;
}) {
return (): void => {

View File

@@ -259,7 +259,8 @@ test('open anilist setup handler no-ops when existing setup window focused', ()
test('open anilist setup handler wires navigation, fallback, and lifecycle', () => {
let openHandler: ((params: { url: string }) => { action: 'deny' }) | null = null;
let willNavigateHandler: ((event: { preventDefault: () => void }, url: string) => void) | null = null;
let willNavigateHandler: ((event: { preventDefault: () => void }, url: string) => void) | null =
null;
let didNavigateHandler: ((event: unknown, url: string) => void) | null = null;
let didFinishLoadHandler: (() => void) | null = null;
let didFailLoadHandler:
@@ -276,7 +277,12 @@ test('open anilist setup handler wires navigation, fallback, and lifecycle', ()
openHandler = handler;
},
on: (
event: 'will-navigate' | 'will-redirect' | 'did-navigate' | 'did-fail-load' | 'did-finish-load',
event:
| 'will-navigate'
| 'will-redirect'
| 'did-navigate'
| 'did-fail-load'
| 'did-finish-load',
handler: (...args: any[]) => void,
) => {
if (event === 'will-navigate') willNavigateHandler = handler as never;

View File

@@ -126,7 +126,11 @@ export function createAnilistSetupDidNavigateHandler(deps: {
}
export function createAnilistSetupDidFailLoadHandler(deps: {
onLoadFailure: (details: { errorCode: number; errorDescription: string; validatedURL: string }) => void;
onLoadFailure: (details: {
errorCode: number;
errorDescription: string;
validatedURL: string;
}) => void;
}) {
return (details: { errorCode: number; errorDescription: string; validatedURL: string }): void => {
deps.onLoadFailure(details);
@@ -175,7 +179,11 @@ export function createAnilistSetupFallbackHandler(deps: {
logWarn: (message: string) => void;
}) {
return {
onLoadFailure: (details: { errorCode: number; errorDescription: string; validatedURL: string }) => {
onLoadFailure: (details: {
errorCode: number;
errorDescription: string;
validatedURL: string;
}) => {
deps.logError('AniList setup window failed to load', details);
deps.openSetupInBrowser();
if (!deps.setupWindow.isDestroyed()) {
@@ -298,12 +306,7 @@ export function createOpenAnilistSetupWindowHandler<TWindow extends AnilistSetup
});
setupWindow.webContents.on(
'did-fail-load',
(
_event: unknown,
errorCode: number,
errorDescription: string,
validatedURL: string,
) => {
(_event: unknown, errorCode: number, errorDescription: string, validatedURL: string) => {
handleDidFailLoad({
errorCode,
errorDescription,

View File

@@ -65,9 +65,7 @@ export function findAnilistSetupDeepLinkArgvUrl(argv: readonly string[]): string
return null;
}
export function consumeAnilistSetupCallbackUrl(
deps: ConsumeAnilistSetupCallbackUrlDeps,
): boolean {
export function consumeAnilistSetupCallbackUrl(deps: ConsumeAnilistSetupCallbackUrlDeps): boolean {
const token = extractAnilistAccessTokenFromUrl(deps.rawUrl);
if (!token) {
return false;

View File

@@ -12,7 +12,9 @@ type ConfigWithAnilistToken = {
};
};
export function createRefreshAnilistClientSecretStateHandler<TConfig extends ConfigWithAnilistToken>(deps: {
export function createRefreshAnilistClientSecretStateHandler<
TConfig extends ConfigWithAnilistToken,
>(deps: {
getResolvedConfig: () => TConfig;
isAnilistTrackingEnabled: (config: TConfig) => boolean;
getCachedAccessToken: () => string | null;

View File

@@ -24,7 +24,9 @@ export function createBuildUpdateLastCardFromClipboardMainDepsHandler<TAnki>(dep
});
}
export function createBuildRefreshKnownWordCacheMainDepsHandler(deps: RefreshKnownWordCacheMainDeps) {
export function createBuildRefreshKnownWordCacheMainDepsHandler(
deps: RefreshKnownWordCacheMainDeps,
) {
return (): RefreshKnownWordCacheMainDeps => ({
getAnkiIntegration: () => deps.getAnkiIntegration(),
missingIntegrationMessage: deps.missingIntegrationMessage,
@@ -42,8 +44,10 @@ export function createBuildTriggerFieldGroupingMainDepsHandler<TAnki>(deps: {
return () => ({
getAnkiIntegration: () => deps.getAnkiIntegration(),
showMpvOsd: (text: string) => deps.showMpvOsd(text),
triggerFieldGroupingCore: (options: { ankiIntegration: TAnki; showMpvOsd: (text: string) => void }) =>
deps.triggerFieldGroupingCore(options),
triggerFieldGroupingCore: (options: {
ankiIntegration: TAnki;
showMpvOsd: (text: string) => void;
}) => deps.triggerFieldGroupingCore(options),
});
}
@@ -58,8 +62,10 @@ export function createBuildMarkLastCardAsAudioCardMainDepsHandler<TAnki>(deps: {
return () => ({
getAnkiIntegration: () => deps.getAnkiIntegration(),
showMpvOsd: (text: string) => deps.showMpvOsd(text),
markLastCardAsAudioCardCore: (options: { ankiIntegration: TAnki; showMpvOsd: (text: string) => void }) =>
deps.markLastCardAsAudioCardCore(options),
markLastCardAsAudioCardCore: (options: {
ankiIntegration: TAnki;
showMpvOsd: (text: string) => void;
}) => deps.markLastCardAsAudioCardCore(options),
});
}

View File

@@ -52,8 +52,7 @@ export function createBuildOnWillQuitCleanupDepsHandler(deps: {
destroyTray: () => deps.destroyTray(),
stopConfigHotReload: () => deps.stopConfigHotReload(),
restorePreviousSecondarySubVisibility: () => deps.restorePreviousSecondarySubVisibility(),
restoreMpvSubVisibility: () =>
deps.restoreMpvSubVisibility(),
restoreMpvSubVisibility: () => deps.restoreMpvSubVisibility(),
unregisterAllGlobalShortcuts: () => deps.unregisterAllGlobalShortcuts(),
stopSubtitleWebsocket: () => deps.stopSubtitleWebsocket(),
stopTexthookerService: () => deps.stopTexthookerService(),

View File

@@ -1,8 +1,6 @@
import type { AppReadyRuntimeDepsFactoryInput } from '../app-lifecycle';
export function createBuildAppReadyRuntimeMainDepsHandler(
deps: AppReadyRuntimeDepsFactoryInput,
) {
export function createBuildAppReadyRuntimeMainDepsHandler(deps: AppReadyRuntimeDepsFactoryInput) {
return (): AppReadyRuntimeDepsFactoryInput => ({
loadSubtitlePosition: deps.loadSubtitlePosition,
resolveKeybindings: deps.resolveKeybindings,
@@ -27,8 +25,7 @@ export function createBuildAppReadyRuntimeMainDepsHandler(
prewarmSubtitleDictionaries: deps.prewarmSubtitleDictionaries,
startBackgroundWarmups: deps.startBackgroundWarmups,
texthookerOnlyMode: deps.texthookerOnlyMode,
shouldAutoInitializeOverlayRuntimeFromConfig:
deps.shouldAutoInitializeOverlayRuntimeFromConfig,
shouldAutoInitializeOverlayRuntimeFromConfig: deps.shouldAutoInitializeOverlayRuntimeFromConfig,
initializeOverlayRuntime: deps.initializeOverlayRuntime,
handleInitialArgs: deps.handleInitialArgs,
onCriticalConfigErrors: deps.onCriticalConfigErrors,

View File

@@ -70,7 +70,8 @@ test('open yomitan settings main deps map async open callbacks', async () => {
const extension = { id: 'ext' };
const deps = createBuildOpenYomitanSettingsMainDepsHandler({
ensureYomitanExtensionLoaded: async () => extension,
openYomitanSettingsWindow: ({ yomitanExt }) => calls.push(`open:${(yomitanExt as { id: string }).id}`),
openYomitanSettingsWindow: ({ yomitanExt }) =>
calls.push(`open:${(yomitanExt as { id: string }).id}`),
getExistingWindow: () => currentWindow,
setWindow: (window) => {
currentWindow = window;

View File

@@ -2,9 +2,7 @@ import { createCliCommandContext } from './cli-command-context';
import { createBuildCliCommandContextDepsHandler } from './cli-command-context-deps';
import { createBuildCliCommandContextMainDepsHandler } from './cli-command-context-main-deps';
type CliCommandContextMainDeps = Parameters<
typeof createBuildCliCommandContextMainDepsHandler
>[0];
type CliCommandContextMainDeps = Parameters<typeof createBuildCliCommandContextMainDepsHandler>[0];
export function createCliCommandContextFactory(deps: CliCommandContextMainDeps) {
const buildCliCommandContextMainDepsHandler = createBuildCliCommandContextMainDepsHandler(deps);

View File

@@ -34,11 +34,11 @@ function createDeps() {
triggerFieldGrouping: async () => {},
triggerSubsyncFromConfig: async () => {},
markLastCardAsAudioCard: async () => {},
getAnilistStatus: () => ({} as never),
getAnilistStatus: () => ({}) as never,
clearAnilistToken: () => {},
openAnilistSetup: () => {},
openJellyfinSetup: () => {},
getAnilistQueueStatus: () => ({} as never),
getAnilistQueueStatus: () => ({}) as never,
retryAnilistQueueNow: async () => ({ ok: true, message: 'ok' }),
runJellyfinCommand: async () => {},
openYomitanSettings: () => {},

View File

@@ -15,12 +15,11 @@ export function createCliCommandRuntimeHandler<TCliContext>(deps: {
cliContext: TCliContext,
) => void;
}) {
const handleTexthookerOnlyModeTransitionHandler =
createHandleTexthookerOnlyModeTransitionHandler(
createBuildHandleTexthookerOnlyModeTransitionMainDepsHandler(
deps.handleTexthookerOnlyModeTransitionMainDeps,
)(),
);
const handleTexthookerOnlyModeTransitionHandler = createHandleTexthookerOnlyModeTransitionHandler(
createBuildHandleTexthookerOnlyModeTransitionMainDepsHandler(
deps.handleTexthookerOnlyModeTransitionMainDeps,
)(),
);
return (args: CliArgs, source: CliCommandSource = 'initial'): void => {
handleTexthookerOnlyModeTransitionHandler(args);

View File

@@ -13,9 +13,10 @@ export type AppendClipboardVideoToQueueRuntimeDeps = {
sendMpvCommand: (command: (string | number)[]) => void;
};
export function appendClipboardVideoToQueueRuntime(
deps: AppendClipboardVideoToQueueRuntimeDeps,
): { ok: boolean; message: string } {
export function appendClipboardVideoToQueueRuntime(deps: AppendClipboardVideoToQueueRuntimeDeps): {
ok: boolean;
message: string;
} {
const mpvClient = deps.getMpvClient();
if (!mpvClient || !mpvClient.connected) {
return { ok: false, message: 'MPV is not connected.' };

View File

@@ -6,7 +6,8 @@ test('composeJellyfinRemoteHandlers returns callable jellyfin remote handlers',
let lastProgressAt = 0;
const composed = composeJellyfinRemoteHandlers({
getConfiguredSession: () => null,
getClientInfo: () => ({ clientName: 'SubMiner', clientVersion: 'test', deviceId: 'dev' }) as never,
getClientInfo: () =>
({ clientName: 'SubMiner', clientVersion: 'test', deviceId: 'dev' }) as never,
getJellyfinConfig: () => ({ enabled: false }) as never,
playJellyfinItem: async () => {},
logWarn: () => {},

View File

@@ -141,7 +141,7 @@ export function composeMpvRuntimeHandlers<
if (!options.tokenizer.createMecabTokenizerAndCheckMainDeps.getMecabTokenizer()) {
await createMecabTokenizerAndCheck().catch(() => {});
}
await prewarmSubtitleDictionaries({ showLoadingOsd: true });
await prewarmSubtitleDictionaries({ showLoadingOsd: true });
})().finally(() => {
tokenizationWarmupInFlight = null;
});

View File

@@ -39,7 +39,10 @@ export function createConfigDerivedRuntime(deps: ConfigDerivedRuntimeDeps): {
deps.defaultJimakuLanguagePreference,
),
getJimakuMaxEntryResults: () =>
getJimakuMaxEntryResultsCore(() => deps.getResolvedConfig(), deps.defaultJimakuMaxEntryResults),
getJimakuMaxEntryResultsCore(
() => deps.getResolvedConfig(),
deps.defaultJimakuMaxEntryResults,
),
resolveJimakuApiKey: () => resolveJimakuApiKeyCore(() => deps.getResolvedConfig()),
jimakuFetchJson: <T>(
endpoint: string,

View File

@@ -111,7 +111,7 @@ test('config hot reload applied main deps builder maps callbacks', () => {
test('config hot reload runtime main deps builder maps runtime callbacks', () => {
const calls: string[] = [];
const deps = createBuildConfigHotReloadRuntimeMainDepsHandler({
getCurrentConfig: () => ({ id: 1 } as never as ResolvedConfig),
getCurrentConfig: () => ({ id: 1 }) as never as ResolvedConfig,
reloadConfigStrict: () =>
({
ok: true,
@@ -144,5 +144,10 @@ test('config hot reload runtime main deps builder maps runtime callbacks', () =>
deps.onRestartRequired([]);
deps.onInvalidConfig('bad');
deps.onValidationWarnings('/tmp/config.jsonc', []);
assert.deepEqual(calls, ['hot-reload', 'restart-required', 'invalid-config', 'validation-warnings']);
assert.deepEqual(calls, [
'hot-reload',
'restart-required',
'invalid-config',
'validation-warnings',
]);
});

View File

@@ -3,7 +3,12 @@ import type {
ConfigHotReloadRuntimeDeps,
} from '../../core/services/config-hot-reload';
import type { ReloadConfigStrictResult } from '../../config';
import type { ConfigHotReloadPayload, ConfigValidationWarning, ResolvedConfig, SecondarySubMode } from '../../types';
import type {
ConfigHotReloadPayload,
ConfigValidationWarning,
ResolvedConfig,
SecondarySubMode,
} from '../../types';
import type { createConfigHotReloadMessageHandler } from './config-hot-reload-handlers';
type ConfigWatchListener = (eventType: string, filename: string | null) => void;

View File

@@ -29,7 +29,8 @@ test('jlpt dictionary runtime main deps builder maps search paths and log prefix
const deps = createBuildJlptDictionaryRuntimeMainDepsHandler({
isJlptEnabled: () => true,
getDictionaryRoots: () => ['/root/a'],
getJlptDictionarySearchPaths: ({ getDictionaryRoots }) => getDictionaryRoots().map((path) => `${path}/jlpt`),
getJlptDictionarySearchPaths: ({ getDictionaryRoots }) =>
getDictionaryRoots().map((path) => `${path}/jlpt`),
setJlptLevelLookup: () => calls.push('set-lookup'),
logInfo: (message) => calls.push(`log:${message}`),
})();

View File

@@ -12,20 +12,24 @@ test('get configured shortcuts main deps map config resolver inputs', () => {
const build = createBuildGetConfiguredShortcutsMainDepsHandler({
getResolvedConfig: () => config,
defaultConfig: defaults,
resolveConfiguredShortcuts: (nextConfig, nextDefaults) => ({ nextConfig, nextDefaults }) as never,
resolveConfiguredShortcuts: (nextConfig, nextDefaults) =>
({ nextConfig, nextDefaults }) as never,
});
const deps = build();
assert.equal(deps.getResolvedConfig(), config);
assert.equal(deps.defaultConfig, defaults);
assert.deepEqual(deps.resolveConfiguredShortcuts(config, defaults), { nextConfig: config, nextDefaults: defaults });
assert.deepEqual(deps.resolveConfiguredShortcuts(config, defaults), {
nextConfig: config,
nextDefaults: defaults,
});
});
test('register global shortcuts main deps map callbacks and flags', () => {
const calls: string[] = [];
const mainWindow = { id: 'main' };
const build = createBuildRegisterGlobalShortcutsMainDepsHandler({
getConfiguredShortcuts: () => ({ copySubtitle: 's' } as never),
getConfiguredShortcuts: () => ({ copySubtitle: 's' }) as never,
registerGlobalShortcutsCore: () => calls.push('register'),
toggleVisibleOverlay: () => calls.push('toggle-visible'),
openYomitanSettings: () => calls.push('open-yomitan'),

View File

@@ -32,15 +32,17 @@ export function createGlobalShortcutsRuntimeHandlers(deps: {
const getConfiguredShortcutsMainDeps = createBuildGetConfiguredShortcutsMainDepsHandler(
deps.getConfiguredShortcutsMainDeps,
)();
const getConfiguredShortcutsHandler =
createGetConfiguredShortcutsHandler(getConfiguredShortcutsMainDeps);
const getConfiguredShortcutsHandler = createGetConfiguredShortcutsHandler(
getConfiguredShortcutsMainDeps,
);
const getConfiguredShortcuts = () => getConfiguredShortcutsHandler();
const registerGlobalShortcutsMainDeps = createBuildRegisterGlobalShortcutsMainDepsHandler(
deps.buildRegisterGlobalShortcutsMainDeps(getConfiguredShortcuts),
)();
const registerGlobalShortcutsHandler =
createRegisterGlobalShortcutsHandler(registerGlobalShortcutsMainDeps);
const registerGlobalShortcutsHandler = createRegisterGlobalShortcutsHandler(
registerGlobalShortcutsMainDeps,
);
const registerGlobalShortcuts = () => registerGlobalShortcutsHandler();
const refreshGlobalAndOverlayShortcutsMainDeps =

View File

@@ -5,10 +5,7 @@ import type { RegisterGlobalShortcutsServiceOptions } from '../../core/services/
export function createGetConfiguredShortcutsHandler(deps: {
getResolvedConfig: () => Config;
defaultConfig: Config;
resolveConfiguredShortcuts: (
config: Config,
defaultConfig: Config,
) => ConfiguredShortcuts;
resolveConfiguredShortcuts: (config: Config, defaultConfig: Config) => ConfiguredShortcuts;
}) {
return (): ConfiguredShortcuts =>
deps.resolveConfiguredShortcuts(deps.getResolvedConfig(), deps.defaultConfig);

View File

@@ -5,7 +5,7 @@ import { createBuildImmersionTrackerStartupMainDepsHandler } from './immersion-s
test('immersion tracker startup main deps builder maps callbacks', () => {
const calls: string[] = [];
const deps = createBuildImmersionTrackerStartupMainDepsHandler({
getResolvedConfig: () => ({ immersionTracking: { enabled: true } } as never),
getResolvedConfig: () => ({ immersionTracking: { enabled: true } }) as never,
getConfiguredDbPath: () => '/tmp/immersion.db',
createTrackerService: () => {
calls.push('create');
@@ -21,9 +21,12 @@ test('immersion tracker startup main deps builder maps callbacks', () => {
assert.deepEqual(deps.getResolvedConfig(), { immersionTracking: { enabled: true } });
assert.equal(deps.getConfiguredDbPath(), '/tmp/immersion.db');
assert.deepEqual(deps.createTrackerService({ dbPath: '/tmp/immersion.db', policy: {} as never }), {
id: 'tracker',
});
assert.deepEqual(
deps.createTrackerService({ dbPath: '/tmp/immersion.db', policy: {} as never }),
{
id: 'tracker',
},
);
deps.setTracker(null);
assert.equal(deps.getMpvClient()?.connected, true);
deps.seedTrackerFromCurrentMedia();

View File

@@ -24,7 +24,7 @@ test('initial args handler no-ops without initial args', () => {
test('initial args handler ensures tray in background mode', () => {
let ensuredTray = false;
const handleInitialArgs = createHandleInitialArgsHandler({
getInitialArgs: () => ({ start: true } as never),
getInitialArgs: () => ({ start: true }) as never,
isBackgroundMode: () => true,
ensureTray: () => {
ensuredTray = true;
@@ -44,7 +44,7 @@ test('initial args handler auto-connects mpv when needed', () => {
let connectCalls = 0;
let logged = false;
const handleInitialArgs = createHandleInitialArgsHandler({
getInitialArgs: () => ({ start: true } as never),
getInitialArgs: () => ({ start: true }) as never,
isBackgroundMode: () => false,
ensureTray: () => {},
isTexthookerOnlyMode: () => false,
@@ -69,7 +69,7 @@ test('initial args handler auto-connects mpv when needed', () => {
test('initial args handler forwards args to cli handler', () => {
const seenSources: string[] = [];
const handleInitialArgs = createHandleInitialArgsHandler({
getInitialArgs: () => ({ start: true } as never),
getInitialArgs: () => ({ start: true }) as never,
isBackgroundMode: () => false,
ensureTray: () => {},
isTexthookerOnlyMode: () => false,

View File

@@ -5,7 +5,7 @@ import { createInitialArgsRuntimeHandler } from './initial-args-runtime-handler'
test('initial args runtime handler composes main deps and runs initial command flow', () => {
const calls: string[] = [];
const handleInitialArgs = createInitialArgsRuntimeHandler({
getInitialArgs: () => ({ start: true } as never),
getInitialArgs: () => ({ start: true }) as never,
isBackgroundMode: () => true,
ensureTray: () => calls.push('tray'),
isTexthookerOnlyMode: () => false,
@@ -20,5 +20,10 @@ test('initial args runtime handler composes main deps and runs initial command f
handleInitialArgs();
assert.deepEqual(calls, ['tray', 'log:Auto-connecting MPV client for immersion tracking', 'connect', 'cli:initial']);
assert.deepEqual(calls, [
'tray',
'log:Auto-connecting MPV client for immersion tracking',
'connect',
'cli:initial',
]);
});

View File

@@ -1,6 +1,8 @@
import type { MpvCommandFromIpcRuntimeDeps } from '../ipc-mpv-command';
export function createBuildMpvCommandFromIpcRuntimeMainDepsHandler(deps: MpvCommandFromIpcRuntimeDeps) {
export function createBuildMpvCommandFromIpcRuntimeMainDepsHandler(
deps: MpvCommandFromIpcRuntimeDeps,
) {
return (): MpvCommandFromIpcRuntimeDeps => ({
triggerSubsyncFromConfig: () => deps.triggerSubsyncFromConfig(),
openRuntimeOptionsPalette: () => deps.openRuntimeOptionsPalette(),

View File

@@ -1,4 +1,7 @@
import { createHandleMpvCommandFromIpcHandler, createRunSubsyncManualFromIpcHandler } from './ipc-bridge-actions';
import {
createHandleMpvCommandFromIpcHandler,
createRunSubsyncManualFromIpcHandler,
} from './ipc-bridge-actions';
import {
createBuildHandleMpvCommandFromIpcMainDepsHandler,
createBuildRunSubsyncManualFromIpcMainDepsHandler,
@@ -22,10 +25,10 @@ export function createIpcRuntimeHandlers<TRequest, TResult>(deps: {
handleMpvCommandFromIpcMainDeps,
);
const runSubsyncManualFromIpcMainDeps =
createBuildRunSubsyncManualFromIpcMainDepsHandler<TRequest, TResult>(
deps.runSubsyncManualFromIpcDeps,
)();
const runSubsyncManualFromIpcMainDeps = createBuildRunSubsyncManualFromIpcMainDepsHandler<
TRequest,
TResult
>(deps.runSubsyncManualFromIpcDeps)();
const runSubsyncManualFromIpc = createRunSubsyncManualFromIpcHandler<TRequest, TResult>(
runSubsyncManualFromIpcMainDeps,
);

View File

@@ -94,7 +94,11 @@ export function createHandleJellyfinListCommands(deps: {
if (!args.jellyfinItemId) {
throw new Error('Missing --jellyfin-item-id for --jellyfin-subtitles.');
}
const tracks = await deps.listJellyfinSubtitleTracks(session, clientInfo, args.jellyfinItemId);
const tracks = await deps.listJellyfinSubtitleTracks(
session,
clientInfo,
args.jellyfinItemId,
);
if (tracks.length === 0) {
deps.logInfo('No Jellyfin subtitle tracks found for item.');
return true;

View File

@@ -1,15 +1,7 @@
import type {
createHandleJellyfinAuthCommands,
} from './jellyfin-cli-auth';
import type {
createHandleJellyfinListCommands,
} from './jellyfin-cli-list';
import type {
createHandleJellyfinPlayCommand,
} from './jellyfin-cli-play';
import type {
createHandleJellyfinRemoteAnnounceCommand,
} from './jellyfin-cli-remote-announce';
import type { createHandleJellyfinAuthCommands } from './jellyfin-cli-auth';
import type { createHandleJellyfinListCommands } from './jellyfin-cli-list';
import type { createHandleJellyfinPlayCommand } from './jellyfin-cli-play';
import type { createHandleJellyfinRemoteAnnounceCommand } from './jellyfin-cli-remote-announce';
type HandleJellyfinAuthCommandsMainDeps = Parameters<typeof createHandleJellyfinAuthCommands>[0];
type HandleJellyfinListCommandsMainDeps = Parameters<typeof createHandleJellyfinListCommands>[0];

View File

@@ -3,7 +3,9 @@ import type {
createGetResolvedJellyfinConfigHandler,
} from './jellyfin-client-info';
type GetResolvedJellyfinConfigMainDeps = Parameters<typeof createGetResolvedJellyfinConfigHandler>[0];
type GetResolvedJellyfinConfigMainDeps = Parameters<
typeof createGetResolvedJellyfinConfigHandler
>[0];
type GetJellyfinClientInfoMainDeps = Parameters<typeof createGetJellyfinClientInfoHandler>[0];
export function createBuildGetResolvedJellyfinConfigMainDepsHandler(

View File

@@ -8,7 +8,7 @@ import {
test('get resolved jellyfin config returns jellyfin section from resolved config', () => {
const jellyfin = { url: 'https://jellyfin.local' } as never;
const getConfig = createGetResolvedJellyfinConfigHandler({
getResolvedConfig: () => ({ jellyfin } as never),
getResolvedConfig: () => ({ jellyfin }) as never,
loadStoredSession: () => null,
getEnv: () => undefined,
});
@@ -68,8 +68,7 @@ test('get resolved jellyfin config uses stored user id when env token set withou
},
}) as never,
loadStoredSession: () => ({ accessToken: 'stored-token', userId: 'stored-user' }),
getEnv: (key: string) =>
key === 'SUBMINER_JELLYFIN_ACCESS_TOKEN' ? 'env-token' : undefined,
getEnv: (key: string) => (key === 'SUBMINER_JELLYFIN_ACCESS_TOKEN' ? 'env-token' : undefined),
});
assert.deepEqual(getConfig(), {
@@ -81,7 +80,7 @@ test('get resolved jellyfin config uses stored user id when env token set withou
test('jellyfin client info resolves defaults when fields are missing', () => {
const getClientInfo = createGetJellyfinClientInfoHandler({
getResolvedJellyfinConfig: () => ({ clientName: '', clientVersion: '', deviceId: '' } as never),
getResolvedJellyfinConfig: () => ({ clientName: '', clientVersion: '', deviceId: '' }) as never,
getDefaultJellyfinConfig: () =>
({
clientName: 'SubMiner',

View File

@@ -2,7 +2,9 @@ import type { createPlayJellyfinItemInMpvHandler } from './jellyfin-playback-lau
type PlayJellyfinItemInMpvMainDeps = Parameters<typeof createPlayJellyfinItemInMpvHandler>[0];
export function createBuildPlayJellyfinItemInMpvMainDepsHandler(deps: PlayJellyfinItemInMpvMainDeps) {
export function createBuildPlayJellyfinItemInMpvMainDepsHandler(
deps: PlayJellyfinItemInMpvMainDeps,
) {
return (): PlayJellyfinItemInMpvMainDeps => ({
ensureMpvConnectedForPlayback: () => deps.ensureMpvConnectedForPlayback(),
getMpvClient: () => deps.getMpvClient(),

View File

@@ -136,6 +136,8 @@ test('createHandleJellyfinRemoteGeneralCommand mutates active playback indices',
assert.equal(playback.subtitleStreamIndex, null);
assert.ok(calls.includes('progress:true'));
assert.ok(
calls.some((entry) => entry.includes('Ignoring unsupported Jellyfin GeneralCommand: UnsupportedCommand')),
calls.some((entry) =>
entry.includes('Ignoring unsupported Jellyfin GeneralCommand: UnsupportedCommand'),
),
);
});

View File

@@ -44,7 +44,9 @@ export type JellyfinRemoteProgressReporterDeps = {
logDebug: (message: string, error: unknown) => void;
};
export function createReportJellyfinRemoteProgressHandler(deps: JellyfinRemoteProgressReporterDeps) {
export function createReportJellyfinRemoteProgressHandler(
deps: JellyfinRemoteProgressReporterDeps,
) {
return async (force = false): Promise<void> => {
const playback = deps.getActivePlayback();
if (!playback) return;

View File

@@ -3,8 +3,12 @@ import type {
createStopJellyfinRemoteSessionHandler,
} from './jellyfin-remote-session-lifecycle';
type StartJellyfinRemoteSessionMainDeps = Parameters<typeof createStartJellyfinRemoteSessionHandler>[0];
type StopJellyfinRemoteSessionMainDeps = Parameters<typeof createStopJellyfinRemoteSessionHandler>[0];
type StartJellyfinRemoteSessionMainDeps = Parameters<
typeof createStartJellyfinRemoteSessionHandler
>[0];
type StopJellyfinRemoteSessionMainDeps = Parameters<
typeof createStopJellyfinRemoteSessionHandler
>[0];
export function createBuildStartJellyfinRemoteSessionMainDepsHandler(
deps: StartJellyfinRemoteSessionMainDeps,

View File

@@ -16,7 +16,11 @@ test('open jellyfin setup window main deps builder maps callbacks', async () =>
accessToken: 'token',
userId: 'uid',
}),
getJellyfinClientInfo: () => ({ clientName: 'SubMiner', clientVersion: '1.0', deviceId: 'dev' }),
getJellyfinClientInfo: () => ({
clientName: 'SubMiner',
clientVersion: '1.0',
deviceId: 'dev',
}),
saveStoredSession: () => calls.push('save'),
patchJellyfinConfig: () => calls.push('patch'),
logInfo: (message) => calls.push(`info:${message}`),
@@ -38,12 +42,15 @@ test('open jellyfin setup window main deps builder maps callbacks', async () =>
username: 'u',
password: 'p',
});
assert.deepEqual(await deps.authenticateWithPassword('s', 'u', 'p', deps.getJellyfinClientInfo()), {
serverUrl: 'http://127.0.0.1:8096',
username: 'alice',
accessToken: 'token',
userId: 'uid',
});
assert.deepEqual(
await deps.authenticateWithPassword('s', 'u', 'p', deps.getJellyfinClientInfo()),
{
serverUrl: 'http://127.0.0.1:8096',
username: 'alice',
accessToken: 'token',
userId: 'uid',
},
);
deps.saveStoredSession({ accessToken: 'token', userId: 'uid' });
deps.patchJellyfinConfig({
serverUrl: 'http://127.0.0.1:8096',
@@ -57,5 +64,13 @@ test('open jellyfin setup window main deps builder maps callbacks', async () =>
deps.clearSetupWindow();
deps.setSetupWindow({} as never);
assert.equal(deps.encodeURIComponent('a b'), 'a%20b');
assert.deepEqual(calls, ['save', 'patch', 'info:ok', 'error:bad', 'osd:toast', 'clear', 'set-window']);
assert.deepEqual(calls, [
'save',
'patch',
'info:ok',
'error:bad',
'osd:toast',
'clear',
'set-window',
]);
});

View File

@@ -50,7 +50,11 @@ test('createHandleJellyfinSetupSubmissionHandler applies successful login', asyn
accessToken: 'token',
userId: 'uid',
}),
getJellyfinClientInfo: () => ({ clientName: 'SubMiner', clientVersion: '1.0', deviceId: 'did' }),
getJellyfinClientInfo: () => ({
clientName: 'SubMiner',
clientVersion: '1.0',
deviceId: 'did',
}),
saveStoredSession: (session) => {
savedSession = session;
calls.push('save');
@@ -86,7 +90,11 @@ test('createHandleJellyfinSetupSubmissionHandler reports failure to OSD', async
authenticateWithPassword: async () => {
throw new Error('bad credentials');
},
getJellyfinClientInfo: () => ({ clientName: 'SubMiner', clientVersion: '1.0', deviceId: 'did' }),
getJellyfinClientInfo: () => ({
clientName: 'SubMiner',
clientVersion: '1.0',
deviceId: 'did',
}),
saveStoredSession: () => calls.push('save'),
patchJellyfinConfig: () => calls.push('patch'),
logInfo: () => calls.push('info'),
@@ -180,7 +188,11 @@ test('createOpenJellyfinSetupWindowHandler no-ops when existing setup window is
authenticateWithPassword: async () => {
throw new Error('should not auth');
},
getJellyfinClientInfo: () => ({ clientName: 'SubMiner', clientVersion: '1.0', deviceId: 'did' }),
getJellyfinClientInfo: () => ({
clientName: 'SubMiner',
clientVersion: '1.0',
deviceId: 'did',
}),
saveStoredSession: () => {},
patchJellyfinConfig: () => {},
logInfo: () => {},
@@ -196,14 +208,18 @@ test('createOpenJellyfinSetupWindowHandler no-ops when existing setup window is
});
test('createOpenJellyfinSetupWindowHandler wires navigation, load, and window lifecycle', async () => {
let willNavigateHandler: ((event: { preventDefault: () => void }, url: string) => void) | null = null;
let willNavigateHandler: ((event: { preventDefault: () => void }, url: string) => void) | null =
null;
let closedHandler: (() => void) | null = null;
let prevented = false;
const calls: string[] = [];
const fakeWindow = {
focus: () => {},
webContents: {
on: (event: 'will-navigate', handler: (event: { preventDefault: () => void }, url: string) => void) => {
on: (
event: 'will-navigate',
handler: (event: { preventDefault: () => void }, url: string) => void,
) => {
if (event === 'will-navigate') {
willNavigateHandler = handler;
}
@@ -233,7 +249,11 @@ test('createOpenJellyfinSetupWindowHandler wires navigation, load, and window li
accessToken: 'token',
userId: 'uid',
}),
getJellyfinClientInfo: () => ({ clientName: 'SubMiner', clientVersion: '1.0', deviceId: 'did' }),
getJellyfinClientInfo: () => ({
clientName: 'SubMiner',
clientVersion: '1.0',
deviceId: 'did',
}),
saveStoredSession: () => calls.push('save'),
patchJellyfinConfig: () => calls.push('patch'),
logInfo: () => calls.push('info'),
@@ -249,7 +269,9 @@ test('createOpenJellyfinSetupWindowHandler wires navigation, load, and window li
assert.ok(closedHandler);
assert.deepEqual(calls.slice(0, 2), ['load:data-url', 'set-window']);
const navHandler = willNavigateHandler as ((event: { preventDefault: () => void }, url: string) => void) | null;
const navHandler = willNavigateHandler as
| ((event: { preventDefault: () => void }, url: string) => void)
| null;
if (!navHandler) {
throw new Error('missing will-navigate handler');
}

View File

@@ -109,7 +109,9 @@ export function parseJellyfinSetupSubmissionUrl(rawUrl: string): {
}
export function createHandleJellyfinSetupSubmissionHandler(deps: {
parseSubmissionUrl: (rawUrl: string) => { server: string; username: string; password: string } | null;
parseSubmissionUrl: (
rawUrl: string,
) => { server: string; username: string; password: string } | null;
authenticateWithPassword: (
server: string,
username: string,
@@ -179,20 +181,22 @@ export function createHandleJellyfinSetupWindowClosedHandler(deps: {
};
}
export function createHandleJellyfinSetupWindowOpenedHandler(deps: {
setSetupWindow: () => void;
}) {
export function createHandleJellyfinSetupWindowOpenedHandler(deps: { setSetupWindow: () => void }) {
return (): void => {
deps.setSetupWindow();
};
}
export function createOpenJellyfinSetupWindowHandler<TWindow extends JellyfinSetupWindowLike>(deps: {
export function createOpenJellyfinSetupWindowHandler<
TWindow extends JellyfinSetupWindowLike,
>(deps: {
maybeFocusExistingSetupWindow: () => boolean;
createSetupWindow: () => TWindow;
getResolvedJellyfinConfig: () => { serverUrl?: string | null; username?: string | null };
buildSetupFormHtml: (defaultServer: string, defaultUser: string) => string;
parseSubmissionUrl: (rawUrl: string) => { server: string; username: string; password: string } | null;
parseSubmissionUrl: (
rawUrl: string,
) => { server: string; username: string; password: string } | null;
authenticateWithPassword: (
server: string,
username: string,
@@ -258,9 +262,7 @@ export function createOpenJellyfinSetupWindowHandler<TWindow extends JellyfinSet
},
});
});
void setupWindow.loadURL(
`data:text/html;charset=utf-8,${deps.encodeURIComponent(formHtml)}`,
);
void setupWindow.loadURL(`data:text/html;charset=utf-8,${deps.encodeURIComponent(formHtml)}`);
setupWindow.on('closed', () => {
handleWindowClosed();
});

View File

@@ -117,13 +117,7 @@ export function createPreloadJellyfinExternalSubtitlesHandler(deps: {
seenUrls.add(track.deliveryUrl);
const labelBase = (track.title || track.language || '').trim();
const label = labelBase || `Jellyfin Subtitle ${track.index}`;
deps.sendMpvCommand([
'sub-add',
track.deliveryUrl,
'cached',
label,
track.language || '',
]);
deps.sendMpvCommand(['sub-add', track.deliveryUrl, 'cached', label, track.language || '']);
}
await deps.wait(250);

View File

@@ -39,27 +39,28 @@ export function createCopyCurrentSubtitleHandler<TSubtitleTimingTracker>(deps: {
};
}
export function createHandleMineSentenceDigitHandler<TSubtitleTimingTracker, TAnkiIntegration>(
deps: {
getSubtitleTimingTracker: () => TSubtitleTimingTracker;
getAnkiIntegration: () => TAnkiIntegration;
getCurrentSecondarySubText: () => string | undefined;
showMpvOsd: (text: string) => void;
logError: (message: string, err: unknown) => void;
onCardsMined: (count: number) => void;
handleMineSentenceDigitCore: (
count: number,
options: {
subtitleTimingTracker: TSubtitleTimingTracker;
ankiIntegration: TAnkiIntegration;
getCurrentSecondarySubText: () => string | undefined;
showMpvOsd: (text: string) => void;
logError: (message: string, err: unknown) => void;
onCardsMined: (count: number) => void;
},
) => void;
},
) {
export function createHandleMineSentenceDigitHandler<
TSubtitleTimingTracker,
TAnkiIntegration,
>(deps: {
getSubtitleTimingTracker: () => TSubtitleTimingTracker;
getAnkiIntegration: () => TAnkiIntegration;
getCurrentSecondarySubText: () => string | undefined;
showMpvOsd: (text: string) => void;
logError: (message: string, err: unknown) => void;
onCardsMined: (count: number) => void;
handleMineSentenceDigitCore: (
count: number,
options: {
subtitleTimingTracker: TSubtitleTimingTracker;
ankiIntegration: TAnkiIntegration;
getCurrentSecondarySubText: () => string | undefined;
showMpvOsd: (text: string) => void;
logError: (message: string, err: unknown) => void;
onCardsMined: (count: number) => void;
},
) => void;
}) {
return (count: number): void => {
deps.handleMineSentenceDigitCore(count, {
subtitleTimingTracker: deps.getSubtitleTimingTracker(),

View File

@@ -7,7 +7,10 @@ test('mpv runtime service main deps builder maps state and callbacks', () => {
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
class FakeClient {
constructor(public socketPath: string, public options: unknown) {}
constructor(
public socketPath: string,
public options: unknown,
) {}
}
const build = createBuildMpvClientRuntimeServiceFactoryDepsHandler({

View File

@@ -22,7 +22,8 @@ export function createBuildMpvClientRuntimeServiceFactoryDepsHandler<
setOverlayVisible: (visible: boolean) => deps.setOverlayVisible(visible),
isVisibleOverlayVisible: () => deps.isVisibleOverlayVisible(),
getReconnectTimer: () => deps.getReconnectTimer(),
setReconnectTimer: (timer: ReturnType<typeof setTimeout> | null) => deps.setReconnectTimer(timer),
setReconnectTimer: (timer: ReturnType<typeof setTimeout> | null) =>
deps.setReconnectTimer(timer),
},
bindEventHandlers: (client: TClient) => deps.bindEventHandlers(client),
});

View File

@@ -15,9 +15,7 @@ export function createBuildApplyJellyfinMpvDefaultsMainDepsHandler(
});
}
export function createBuildGetDefaultSocketPathMainDepsHandler(
deps: GetDefaultSocketPathMainDeps,
) {
export function createBuildGetDefaultSocketPathMainDepsHandler(deps: GetDefaultSocketPathMainDeps) {
return (): GetDefaultSocketPathMainDeps => ({
platform: deps.platform,
});

View File

@@ -97,8 +97,7 @@ export function createBindMpvMainEventHandlersHandler(deps: {
const handleMpvMediaPathChange = createHandleMpvMediaPathChangeHandler({
updateCurrentMediaPath: (path) => deps.updateCurrentMediaPath(path),
reportJellyfinRemoteStopped: () => deps.reportJellyfinRemoteStopped(),
restoreMpvSubVisibility: () =>
deps.restoreMpvSubVisibility(),
restoreMpvSubVisibility: () => deps.restoreMpvSubVisibility(),
getCurrentAnilistMediaKey: () => deps.getCurrentAnilistMediaKey(),
resetAnilistMediaTracking: (mediaKey) => deps.resetAnilistMediaTracking(mediaKey),
maybeProbeAnilistDuration: (mediaKey) => deps.maybeProbeAnilistDuration(mediaKey),

View File

@@ -1,6 +1,8 @@
import type { createUpdateMpvSubtitleRenderMetricsHandler } from './mpv-subtitle-render-metrics';
type UpdateMpvSubtitleRenderMetricsMainDeps = Parameters<typeof createUpdateMpvSubtitleRenderMetricsHandler>[0];
type UpdateMpvSubtitleRenderMetricsMainDeps = Parameters<
typeof createUpdateMpvSubtitleRenderMetricsHandler
>[0];
export function createBuildUpdateMpvSubtitleRenderMetricsMainDepsHandler(
deps: UpdateMpvSubtitleRenderMetricsMainDeps,

View File

@@ -22,7 +22,10 @@ test('numeric shortcut runtime main deps builder maps callbacks', () => {
},
})();
assert.equal(deps.globalShortcut.register('1', () => {}), true);
assert.equal(
deps.globalShortcut.register('1', () => {}),
true,
);
deps.globalShortcut.unregister('1');
deps.showMpvOsd('x');
deps.setTimer(() => calls.push('tick'), 1000);

View File

@@ -1,6 +1,8 @@
import type { NumericShortcutRuntimeOptions } from '../../core/services/numeric-shortcut';
export function createBuildNumericShortcutRuntimeMainDepsHandler(deps: NumericShortcutRuntimeOptions) {
export function createBuildNumericShortcutRuntimeMainDepsHandler(
deps: NumericShortcutRuntimeOptions,
) {
return (): NumericShortcutRuntimeOptions => ({
globalShortcut: deps.globalShortcut,
showMpvOsd: (text: string) => deps.showMpvOsd(text),

View File

@@ -3,8 +3,12 @@ import type {
createStartNumericShortcutSessionHandler,
} from './numeric-shortcut-session-handlers';
type CancelNumericShortcutSessionMainDeps = Parameters<typeof createCancelNumericShortcutSessionHandler>[0];
type StartNumericShortcutSessionMainDeps = Parameters<typeof createStartNumericShortcutSessionHandler>[0];
type CancelNumericShortcutSessionMainDeps = Parameters<
typeof createCancelNumericShortcutSessionHandler
>[0];
type StartNumericShortcutSessionMainDeps = Parameters<
typeof createStartNumericShortcutSessionHandler
>[0];
export function createBuildCancelNumericShortcutSessionMainDepsHandler(
deps: CancelNumericShortcutSessionMainDeps,

View File

@@ -20,8 +20,9 @@ export function createNumericShortcutSessionRuntimeHandlers(deps: {
const cancelPendingMultiCopyMainDeps = createBuildCancelNumericShortcutSessionMainDepsHandler({
session: deps.multiCopySession,
})();
const cancelPendingMultiCopyHandler =
createCancelNumericShortcutSessionHandler(cancelPendingMultiCopyMainDeps);
const cancelPendingMultiCopyHandler = createCancelNumericShortcutSessionHandler(
cancelPendingMultiCopyMainDeps,
);
const startPendingMultiCopyMainDeps = createBuildStartNumericShortcutSessionMainDepsHandler({
session: deps.multiCopySession,
@@ -32,8 +33,9 @@ export function createNumericShortcutSessionRuntimeHandlers(deps: {
cancelled: 'Cancelled',
},
})();
const startPendingMultiCopyHandler =
createStartNumericShortcutSessionHandler(startPendingMultiCopyMainDeps);
const startPendingMultiCopyHandler = createStartNumericShortcutSessionHandler(
startPendingMultiCopyMainDeps,
);
const cancelPendingMineSentenceMultipleMainDeps =
createBuildCancelNumericShortcutSessionMainDepsHandler({

View File

@@ -14,9 +14,7 @@ export function createBuildOverlayContentMeasurementStoreMainDepsHandler(
});
}
export function createBuildOverlayModalRuntimeMainDepsHandler(
deps: OverlayWindowResolver,
) {
export function createBuildOverlayModalRuntimeMainDepsHandler(deps: OverlayWindowResolver) {
return (): OverlayWindowResolver => ({
getMainWindow: () => deps.getMainWindow(),
getModalWindow: () => deps.getModalWindow(),

View File

@@ -35,12 +35,15 @@ test('overlay main action main deps builders map callbacks', () => {
showMpvOsd: (text) => calls.push(`osd:${text}`),
sendMpvCommand: (command) => calls.push(`cmd:${command.join(':')}`),
})();
assert.deepEqual(append.appendClipboardVideoToQueueRuntime({
getMpvClient: () => ({ connected: true }),
readClipboardText: () => '/tmp/v.mkv',
showMpvOsd: () => {},
sendMpvCommand: () => {},
}), { ok: true, message: 'ok' });
assert.deepEqual(
append.appendClipboardVideoToQueueRuntime({
getMpvClient: () => ({ connected: true }),
readClipboardText: () => '/tmp/v.mkv',
showMpvOsd: () => {},
sendMpvCommand: () => {},
}),
{ ok: true, message: 'ok' },
);
assert.equal(append.readClipboardText(), '/tmp/v.mkv');
assert.equal(typeof append.getMpvClient(), 'object');
append.showMpvOsd('queued');

View File

@@ -8,7 +8,9 @@ import type {
type SetOverlayVisibleMainDeps = Parameters<typeof createSetOverlayVisibleHandler>[0];
type ToggleOverlayMainDeps = Parameters<typeof createToggleOverlayHandler>[0];
type HandleOverlayModalClosedMainDeps = Parameters<typeof createHandleOverlayModalClosedHandler>[0];
type AppendClipboardVideoToQueueMainDeps = Parameters<typeof createAppendClipboardVideoToQueueHandler>[0];
type AppendClipboardVideoToQueueMainDeps = Parameters<
typeof createAppendClipboardVideoToQueueHandler
>[0];
export function createBuildSetOverlayVisibleMainDepsHandler(deps: SetOverlayVisibleMainDeps) {
return (): SetOverlayVisibleMainDeps => ({
@@ -34,7 +36,8 @@ export function createBuildAppendClipboardVideoToQueueMainDepsHandler(
deps: AppendClipboardVideoToQueueMainDeps,
) {
return (): AppendClipboardVideoToQueueMainDeps => ({
appendClipboardVideoToQueueRuntime: (options) => deps.appendClipboardVideoToQueueRuntime(options),
appendClipboardVideoToQueueRuntime: (options) =>
deps.appendClipboardVideoToQueueRuntime(options),
getMpvClient: () => deps.getMpvClient(),
readClipboardText: () => deps.readClipboardText(),
showMpvOsd: (text: string) => deps.showMpvOsd(text),

View File

@@ -9,9 +9,7 @@ export function createSetOverlayVisibleHandler(deps: {
};
}
export function createToggleOverlayHandler(deps: {
toggleVisibleOverlay: () => void;
}) {
export function createToggleOverlayHandler(deps: { toggleVisibleOverlay: () => void }) {
return (): void => {
deps.toggleVisibleOverlay();
};
@@ -26,9 +24,10 @@ export function createHandleOverlayModalClosedHandler(deps: {
}
export function createAppendClipboardVideoToQueueHandler(deps: {
appendClipboardVideoToQueueRuntime: (
options: AppendClipboardVideoToQueueRuntimeDeps,
) => { ok: boolean; message: string };
appendClipboardVideoToQueueRuntime: (options: AppendClipboardVideoToQueueRuntimeDeps) => {
ok: boolean;
message: string;
};
getMpvClient: () => AppendClipboardVideoToQueueRuntimeDeps['getMpvClient'] extends () => infer T
? T
: never;

View File

@@ -25,7 +25,6 @@ function parseSubVisibility(value: unknown): boolean {
return true;
}
export function createEnsureOverlayMpvSubtitlesHiddenHandler(deps: {
getMpvClient: () => MpvVisibilityClient | null;
getSavedSubVisibility: () => boolean | null;

View File

@@ -9,7 +9,7 @@ test('overlay runtime bootstrap no-ops when already initialized', () => {
initializeOverlayRuntimeCore: () => {
coreCalls += 1;
},
buildOptions: () => ({} as never),
buildOptions: () => ({}) as never,
setOverlayRuntimeInitialized: () => {},
startBackgroundWarmups: () => {},
});

View File

@@ -32,7 +32,10 @@ test('broadcast runtime options changed main deps builder maps callbacks', () =>
broadcastToOverlayWindows: (channel) => calls.push(channel),
})();
deps.broadcastRuntimeOptionsChangedRuntime(() => [], () => {});
deps.broadcastRuntimeOptionsChangedRuntime(
() => [],
() => {},
);
deps.broadcastToOverlayWindows('runtime-options:changed');
assert.deepEqual(deps.getRuntimeOptionsState(), []);
assert.deepEqual(calls, ['broadcast-runtime', 'runtime-options:changed']);

View File

@@ -14,11 +14,15 @@ type RestorePreviousSecondarySubVisibilityMainDeps = Parameters<
type BroadcastRuntimeOptionsChangedMainDeps = Parameters<
typeof createBroadcastRuntimeOptionsChangedHandler
>[0];
type SendToActiveOverlayWindowMainDeps = Parameters<typeof createSendToActiveOverlayWindowHandler>[0];
type SendToActiveOverlayWindowMainDeps = Parameters<
typeof createSendToActiveOverlayWindowHandler
>[0];
type SetOverlayDebugVisualizationEnabledMainDeps = Parameters<
typeof createSetOverlayDebugVisualizationEnabledHandler
>[0];
type OpenRuntimeOptionsPaletteMainDeps = Parameters<typeof createOpenRuntimeOptionsPaletteHandler>[0];
type OpenRuntimeOptionsPaletteMainDeps = Parameters<
typeof createOpenRuntimeOptionsPaletteHandler
>[0];
export function createBuildGetRuntimeOptionsStateMainDepsHandler(
deps: GetRuntimeOptionsStateMainDeps,
@@ -61,11 +65,7 @@ export function createBuildSetOverlayDebugVisualizationEnabledMainDepsHandler(
deps: SetOverlayDebugVisualizationEnabledMainDeps,
) {
return (): SetOverlayDebugVisualizationEnabledMainDeps => ({
setOverlayDebugVisualizationEnabledRuntime: (
currentEnabled,
nextEnabled,
setCurrentEnabled,
) =>
setOverlayDebugVisualizationEnabledRuntime: (currentEnabled, nextEnabled, setCurrentEnabled) =>
deps.setOverlayDebugVisualizationEnabledRuntime(
currentEnabled,
nextEnabled,

View File

@@ -49,7 +49,10 @@ test('runtime options state handler returns list from manager', () => {
test('restore previous secondary subtitle visibility no-ops without connected mpv client', () => {
let restored = false;
const restore = createRestorePreviousSecondarySubVisibilityHandler({
getMpvClient: () => ({ connected: false, restorePreviousSecondarySubVisibility: () => (restored = true) }),
getMpvClient: () => ({
connected: false,
restorePreviousSecondarySubVisibility: () => (restored = true),
}),
});
restore();
assert.equal(restored, false);
@@ -58,7 +61,10 @@ test('restore previous secondary subtitle visibility no-ops without connected mp
test('restore previous secondary subtitle visibility calls runtime when connected', () => {
let restored = false;
const restore = createRestorePreviousSecondarySubVisibilityHandler({
getMpvClient: () => ({ connected: true, restorePreviousSecondarySubVisibility: () => (restored = true) }),
getMpvClient: () => ({
connected: true,
restorePreviousSecondarySubVisibility: () => (restored = true),
}),
});
restore();
assert.equal(restored, true);
@@ -82,7 +88,8 @@ test('broadcast runtime options changed passes through state getter and broadcas
requiresRestart: false,
},
],
broadcastToOverlayWindows: (channel, payload) => calls.push(`emit:${channel}:${JSON.stringify(payload)}`),
broadcastToOverlayWindows: (channel, payload) =>
calls.push(`emit:${channel}:${JSON.stringify(payload)}`),
});
broadcast();

View File

@@ -70,10 +70,8 @@ export function createSetOverlayDebugVisualizationEnabledHandler(deps: {
setCurrentEnabled: (enabled: boolean) => void;
}) {
return (enabled: boolean): void => {
deps.setOverlayDebugVisualizationEnabledRuntime(
deps.getCurrentEnabled(),
enabled,
(next) => deps.setCurrentEnabled(next),
deps.setOverlayDebugVisualizationEnabledRuntime(deps.getCurrentEnabled(), enabled, (next) =>
deps.setCurrentEnabled(next),
);
};
}

View File

@@ -6,7 +6,9 @@ import type {
} from './overlay-shortcuts-lifecycle';
type RegisterOverlayShortcutsMainDeps = Parameters<typeof createRegisterOverlayShortcutsHandler>[0];
type UnregisterOverlayShortcutsMainDeps = Parameters<typeof createUnregisterOverlayShortcutsHandler>[0];
type UnregisterOverlayShortcutsMainDeps = Parameters<
typeof createUnregisterOverlayShortcutsHandler
>[0];
type SyncOverlayShortcutsMainDeps = Parameters<typeof createSyncOverlayShortcutsHandler>[0];
type RefreshOverlayShortcutsMainDeps = Parameters<typeof createRefreshOverlayShortcutsHandler>[0];

View File

@@ -21,26 +21,30 @@ export function createOverlayShortcutsRuntimeHandlers(deps: {
const registerOverlayShortcutsMainDeps = createBuildRegisterOverlayShortcutsMainDepsHandler(
deps.overlayShortcutsRuntimeMainDeps,
)();
const registerOverlayShortcutsHandler =
createRegisterOverlayShortcutsHandler(registerOverlayShortcutsMainDeps);
const registerOverlayShortcutsHandler = createRegisterOverlayShortcutsHandler(
registerOverlayShortcutsMainDeps,
);
const unregisterOverlayShortcutsMainDeps =
createBuildUnregisterOverlayShortcutsMainDepsHandler(
deps.overlayShortcutsRuntimeMainDeps,
)();
const unregisterOverlayShortcutsHandler =
createUnregisterOverlayShortcutsHandler(unregisterOverlayShortcutsMainDeps);
const unregisterOverlayShortcutsMainDeps = createBuildUnregisterOverlayShortcutsMainDepsHandler(
deps.overlayShortcutsRuntimeMainDeps,
)();
const unregisterOverlayShortcutsHandler = createUnregisterOverlayShortcutsHandler(
unregisterOverlayShortcutsMainDeps,
);
const syncOverlayShortcutsMainDeps = createBuildSyncOverlayShortcutsMainDepsHandler(
deps.overlayShortcutsRuntimeMainDeps,
)();
const syncOverlayShortcutsHandler = createSyncOverlayShortcutsHandler(syncOverlayShortcutsMainDeps);
const syncOverlayShortcutsHandler = createSyncOverlayShortcutsHandler(
syncOverlayShortcutsMainDeps,
);
const refreshOverlayShortcutsMainDeps = createBuildRefreshOverlayShortcutsMainDepsHandler(
deps.overlayShortcutsRuntimeMainDeps,
)();
const refreshOverlayShortcutsHandler =
createRefreshOverlayShortcutsHandler(refreshOverlayShortcutsMainDeps);
const refreshOverlayShortcutsHandler = createRefreshOverlayShortcutsHandler(
refreshOverlayShortcutsMainDeps,
);
return {
registerOverlayShortcuts: () => registerOverlayShortcutsHandler(),

View File

@@ -6,7 +6,7 @@ test('overlay shortcuts runtime main deps builder maps lifecycle and action call
const calls: string[] = [];
let shortcutsRegistered = false;
const deps = createBuildOverlayShortcutsRuntimeMainDepsHandler({
getConfiguredShortcuts: () => ({ copySubtitle: 's' } as never),
getConfiguredShortcuts: () => ({ copySubtitle: 's' }) as never,
getShortcutsRegistered: () => shortcutsRegistered,
setShortcutsRegistered: (registered) => {
shortcutsRegistered = registered;

View File

@@ -11,7 +11,8 @@ export function createBuildSetVisibleOverlayVisibleMainDepsHandler(
) {
return (): SetVisibleOverlayVisibleMainDeps => ({
setVisibleOverlayVisibleCore: (options) => deps.setVisibleOverlayVisibleCore(options),
setVisibleOverlayVisibleState: (visible: boolean) => deps.setVisibleOverlayVisibleState(visible),
setVisibleOverlayVisibleState: (visible: boolean) =>
deps.setVisibleOverlayVisibleState(visible),
updateVisibleOverlayVisibility: () => deps.updateVisibleOverlayVisibility(),
onVisibleOverlayEnabled: deps.onVisibleOverlayEnabled,
});

Some files were not shown because too many files have changed in this diff Show More