diff --git a/.github/workflows/bun-audit.yml b/.github/workflows/bun-audit.yml
index 468f7ee..6f709ea 100644
--- a/.github/workflows/bun-audit.yml
+++ b/.github/workflows/bun-audit.yml
@@ -2,7 +2,7 @@ name: Dependency Audit
on:
schedule:
- - cron: '0 0 * * 0' # Weekly Sunday 00:00 UTC
+ - cron: '0 0 * * 0'
workflow_dispatch:
jobs:
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 158ef53..b16a4e1 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -24,7 +24,6 @@ jobs:
- run: bun install --frozen-lockfile
- uses: j178/prek-action@v3.1.0
with:
- # Branch protection applies to local commits, not CI checkouts.
extra-args: --all-files --skip no-commit-to-branch
- run: bunx tsc --noEmit -p electron/tsconfig.json
diff --git a/.github/workflows/dependabot-automerge.yml b/.github/workflows/dependabot-automerge.yml
index fea6bd4..7c98a4d 100644
--- a/.github/workflows/dependabot-automerge.yml
+++ b/.github/workflows/dependabot-automerge.yml
@@ -23,7 +23,6 @@ jobs:
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
- # Auto-merge waits for the required status checks enforced by the dev branch rules.
- name: Enable automerge for patch and minor updates
if: >-
steps.metadata.outputs.package-ecosystem == 'bun' &&
diff --git a/bunfig.toml b/bunfig.toml
index 2e87a1e..55af992 100644
--- a/bunfig.toml
+++ b/bunfig.toml
@@ -1,3 +1,2 @@
[install]
-# Only resolve new package versions published at least 3 days ago (versions already pinned in bun.lock are unaffected)
minimumReleaseAge = 259200
diff --git a/containers/nginx.conf b/containers/nginx.conf
index 52bcd97..f564f79 100644
--- a/containers/nginx.conf
+++ b/containers/nginx.conf
@@ -1,20 +1,5 @@
-# Production server for the container image (copied to
-# /etc/nginx/conf.d/default.conf in the Containerfile).
-#
-# The Content-Security-Policy here must stay in sync with the fallback
-# in src/index.html (GitHub Pages cannot send custom HTTP headers, so the meta
-# tag is its only enforcement). If the inline theme script in index.html
-# changes, recompute its sha256 and update script-src in both places.
-# The one intended difference: frame-ancestors exists only here, because
-# browsers ignore it in a tag and log an error on every page load.
-#
-# Policy notes:
-# - img-src allows blob:/data:/https: (IndexedDB posters via object URLs,
-# inline SVG placeholder, TMDB/MyAnimeList/AniList CDN posters).
-# - connect-src enumerates the API + image origins the app fetches from
-# (poster save uses fetch() on image CDN URLs, so those need connect-src).
-# - style-src 'unsafe-inline' is required: Angular injects component styles
-# at runtime. No external stylesheets are used.
+# style-src 'unsafe-inline' is required: Angular injects component styles
+# at runtime. No external stylesheets are used.
server {
listen 80;
server_name _;
@@ -22,7 +7,7 @@ server {
root /usr/share/nginx/html;
index index.html;
- add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; object-src 'none'; frame-ancestors 'none'; script-src 'self' 'sha256-Hq3FIAQiTPolQXnEfi9wb+iJcaXWvqDZulbwr3WX+IE='; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data: https:; connect-src 'self' https://api.themoviedb.org https://api.jikan.moe https://graphql.anilist.co https://image.tmdb.org https://cdn.myanimelist.net https://s4.anilist.co; font-src 'self' data:; manifest-src 'self'; worker-src 'self'" always;
+ add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; object-src 'none'; frame-ancestors 'none'; script-src 'self' 'sha256-toZFmdk2CkvU3nyUgzTVJAy/6YfDgBH8RrDVwKZXNAo='; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data: https:; connect-src 'self' https://api.themoviedb.org https://api.jikan.moe https://graphql.anilist.co https://image.tmdb.org https://cdn.myanimelist.net https://s4.anilist.co; font-src 'self' data:; manifest-src 'self'; worker-src 'self'" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "no-referrer" always;
diff --git a/e2e/journey.e2e.ts b/e2e/journey.e2e.ts
index d4031fd..ed5c241 100644
--- a/e2e/journey.e2e.ts
+++ b/e2e/journey.e2e.ts
@@ -1,9 +1,5 @@
import { expect, test } from '@playwright/test';
-// The one browser test. Component and service behaviour is covered by the
-// Vitest specs; this proves what they cannot: the production bundle boots under
-// its Content-Security-Policy, real clicks reach the controls, and the
-// collection persists in the browser's own IndexedDB.
test('add a series, watch an episode, and delete the series', async ({ page }) => {
const title = 'Browser Journey Series';
const problems: string[] = [];
@@ -48,7 +44,6 @@ test('add a series, watch an episode, and delete the series', async ({ page }) =
await expect(page).toHaveURL(/\/items$/);
await expect(page.getByText('No items found')).toBeVisible();
await nav.getByRole('link', { name: 'History' }).click();
- // History outlives its item by design.
await expect(page.getByText(`${title} (deleted)`)).toBeVisible();
expect(problems).toEqual([]);
diff --git a/e2e/serve.mjs b/e2e/serve.mjs
index de1f76d..32cc3b1 100644
--- a/e2e/serve.mjs
+++ b/e2e/serve.mjs
@@ -1,5 +1,3 @@
-// Serves the production build for the browser tests, with the same SPA
-// fallback as containers/nginx.conf.
import { join, normalize } from 'node:path';
const root = join(import.meta.dirname, '../dist/watch-list/browser');
diff --git a/electron/preload.ts b/electron/preload.ts
index 083d3fa..e92264a 100644
--- a/electron/preload.ts
+++ b/electron/preload.ts
@@ -1,7 +1,5 @@
import { contextBridge } from 'electron';
-// Expose a minimal, secure API surface. Extend here when IPC is needed.
-// Keeping contextIsolation + sandbox enabled (see main.ts).
contextBridge.exposeInMainWorld('electronAPI', {
platform: process.platform,
});
diff --git a/playwright.config.ts b/playwright.config.ts
index bdfc82c..f7c6a84 100644
--- a/playwright.config.ts
+++ b/playwright.config.ts
@@ -1,8 +1,5 @@
import { defineConfig, devices } from '@playwright/test';
-// Set E2E_BASE_URL to test an already running deployment (CI points it at the
-// nginx container, the only place the real security headers exist). Without it
-// the production build is created and served locally.
const externalBaseUrl = process.env['E2E_BASE_URL'];
const localPort = 4300;
// Playwright's downloaded Chromium cannot start on every OS (NixOS, for one).
diff --git a/scripts/build.mjs b/scripts/build.mjs
index 6ef2ca3..609ea64 100755
--- a/scripts/build.mjs
+++ b/scripts/build.mjs
@@ -31,7 +31,6 @@ const version = getVersion();
const hash = getHash();
const buildDate = getBuildDate();
-// All args after script name are forwarded to ng build (e.g. --configuration=..., --base-href ...)
const extraArgs = process.argv.slice(2);
const defines = [
diff --git a/src/app/components/conflict-recovery/conflict-recovery.component.ts b/src/app/components/conflict-recovery/conflict-recovery.component.ts
index 78e80c5..46c6ffd 100644
--- a/src/app/components/conflict-recovery/conflict-recovery.component.ts
+++ b/src/app/components/conflict-recovery/conflict-recovery.component.ts
@@ -1,7 +1,6 @@
import { Component, inject, input, output, signal } from '@angular/core';
import { StorageService } from '../../services/storage.service';
-/** Refresh shared collection state without navigating away from recoverable drafts. */
@Component({
selector: 'app-conflict-recovery',
template: `
diff --git a/src/app/components/home/home.component.spec.ts b/src/app/components/home/home.component.spec.ts
index de0e0c8..60667e7 100644
--- a/src/app/components/home/home.component.spec.ts
+++ b/src/app/components/home/home.component.spec.ts
@@ -270,14 +270,12 @@ describe('HomeComponent', () => {
});
it('shows empty states for nextSeries/nextMovie', async () => {
- // No series in list
setup({ watchItems: [], inProgressSeries: [], nextSeries: null, nextMovie: null });
let fixture = TestBed.createComponent(HomeComponent);
fixture.detectChanges();
await fixture.whenStable();
expect(fixture.nativeElement.textContent).toContain('No series in your watch list');
- // Has series but none in progress
const seriesNotStarted = createItem({
id: 's1',
title: 'S',
@@ -296,7 +294,6 @@ describe('HomeComponent', () => {
await fixture.whenStable();
expect(fixture.nativeElement.textContent).toContain('No series currently being watched');
- // Has in-progress but not watchable (all future)
const inProg = createItem({
id: 's2',
title: 'S2',
@@ -310,7 +307,6 @@ describe('HomeComponent', () => {
await fixture.whenStable();
expect(fixture.nativeElement.textContent).toContain('No aired series episodes available');
- // Movies
setup({ watchItems: [], inProgressSeries: [], nextSeries: null, nextMovie: null });
fixture = TestBed.createComponent(HomeComponent);
fixture.detectChanges();
diff --git a/src/app/components/home/home.component.ts b/src/app/components/home/home.component.ts
index 1fd4c50..f879b24 100644
--- a/src/app/components/home/home.component.ts
+++ b/src/app/components/home/home.component.ts
@@ -55,7 +55,6 @@ import { DiscussionLinkComponent } from '../discussion-link/discussion-link.comp
@if (nextSeries()) {
-
{
if (!this.deferringItem()) return;
- // Keep the preview accurate if the duration chooser is left open.
const timer = setInterval(() => this.previewNow.set(Date.now()), 1000);
onCleanup(() => clearInterval(timer));
});
diff --git a/src/app/components/item-card/item-card.component.ts b/src/app/components/item-card/item-card.component.ts
index e125a1a..86133b3 100644
--- a/src/app/components/item-card/item-card.component.ts
+++ b/src/app/components/item-card/item-card.component.ts
@@ -1,4 +1,4 @@
-import { Component, input, computed, effect, inject, signal } from '@angular/core';
+import { Component, input, computed, inject, linkedSignal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterLink } from '@angular/router';
import { ReadonlyItem as Item } from '../../models/item.model';
@@ -83,12 +83,10 @@ export class ItemCardComponent {
readonly posterUrl = injectPosterUrl(() => this.item().posterId);
placeholderUrl = computed(() => getPlaceholderUrl());
statusColorClass = computed(() => statusLineColor(this.item().status));
- revealed = signal(false);
+ revealed = linkedSignal({ source: () => this.item().id, computation: () => false });
shouldBlur = computed(() => {
- const mode = this.providerSettings.settings().adultDisplayMode;
- // 'blur' blurs everywhere; 'hide' still blurs where card remains visible (next*), since next* is not filtered
- // 'show' never blurs
- return this.item().isAdult && mode !== 'show' && !!this.posterUrl() && !this.revealed();
+ const concealsAdultPosters = this.providerSettings.settings().adultDisplayMode !== 'show';
+ return this.item().isAdult && concealsAdultPosters && !!this.posterUrl() && !this.revealed();
});
progressPercent = computed(() => {
@@ -98,12 +96,4 @@ export class ItemCardComponent {
lastWatchedDate = computed(() => {
return getMostRecentWatchDate(this.item());
});
-
- constructor() {
- effect(() => {
- // Reset click-to-reveal when item identity changes
- void this.item().id;
- this.revealed.set(false);
- });
- }
}
diff --git a/src/app/components/item-detail/item-detail.component.ts b/src/app/components/item-detail/item-detail.component.ts
index e325f26..03205ab 100644
--- a/src/app/components/item-detail/item-detail.component.ts
+++ b/src/app/components/item-detail/item-detail.component.ts
@@ -21,7 +21,7 @@ import { ConflictRecoveryComponent } from '../conflict-recovery/conflict-recover
template: `
- @if (item()) {
+ @if (itemSnapshot()) {
Edit Item
@@ -91,8 +91,7 @@ export class ItemDetailComponent {
readonly groups = this.groupService.groups;
readonly mutation = new MutationFeedback(itemMutationFailure);
- // Capture a baseline per routed item; live collection updates must not reset an open draft.
- readonly item = toSignal(
+ readonly itemSnapshot = toSignal(
this.route.paramMap.pipe(
map((params) => {
const id = params.get('id');
@@ -102,16 +101,16 @@ export class ItemDetailComponent {
{ initialValue: null },
);
readonly itemExists = computed(() =>
- this.watchListService.items().some((item) => item.id === this.item()?.id),
+ this.watchListService.items().some((item) => item.id === this.itemSnapshot()?.id),
);
readonly formValue = computed(() => {
- const currentItem = this.item();
+ const currentItem = this.itemSnapshot();
return currentItem ? createItemFormValue(currentItem) : createDefaultItemFormValue();
});
confirmDelete = signal(false);
async saveChanges(formValue: ItemFormValue): Promise
{
- const currentItem = this.item();
+ const currentItem = this.itemSnapshot();
if (!currentItem) return;
const result = await this.mutation.run(
@@ -133,7 +132,7 @@ export class ItemDetailComponent {
}
async deleteItem(): Promise {
- const currentItem = this.item();
+ const currentItem = this.itemSnapshot();
if (currentItem) {
const result = await this.mutation.run(
() => this.watchListService.deleteItem(currentItem.id),
diff --git a/src/app/components/item-form-interactions.spec.ts b/src/app/components/item-form-interactions.spec.ts
index 83e1384..7c9fee6 100644
--- a/src/app/components/item-form-interactions.spec.ts
+++ b/src/app/components/item-form-interactions.spec.ts
@@ -52,7 +52,6 @@ describe('Settled item form interactions', () => {
fixture.detectChanges();
expect(root.querySelector('img[src="blob:owned-poster"]')).not.toBeNull();
});
- // A draft is previewable, but must not be persisted separately from its item.
expect(await TestBed.inject(ImageStorageService).exportImages()).toEqual([]);
const held = holdStorageWrite(0);
root.querySelector('form')!.dispatchEvent(new Event('submit', { cancelable: true }));
@@ -280,9 +279,7 @@ describe('Settled item form interactions', () => {
'retains an uploaded draft poster after failed %s and retries with it',
async (command) => {
vi.stubGlobal('createImageBitmap', async () => ({
- close() {
- /* native image decoder boundary */
- },
+ close: () => undefined,
}));
vi.stubGlobal(
'URL',
@@ -291,7 +288,7 @@ describe('Settled item form interactions', () => {
return 'blob:draft-poster';
}
static override revokeObjectURL() {
- /* native object URL boundary */
+ return undefined;
}
},
);
diff --git a/src/app/components/item-form-navigation.spec.ts b/src/app/components/item-form-navigation.spec.ts
index 832f9fa..a7767f5 100644
--- a/src/app/components/item-form-navigation.spec.ts
+++ b/src/app/components/item-form-navigation.spec.ts
@@ -139,7 +139,7 @@ describe('Item form navigation with pending saves', () => {
expect(next).toBe(screen);
expect(harness.routeNativeElement).toBe(root);
expect(router.url).toBe('/items/other/edit');
- expect(next.item()?.id).toBe('other');
+ expect(next.itemSnapshot()?.id).toBe('other');
expect(root.querySelector('#title')?.value).toBe('Other item');
});
});
@@ -180,9 +180,7 @@ async function openForm(mode: 'add' | 'edit') {
async function setup() {
Object.defineProperty(globalThis, 'indexedDB', { configurable: true, value: new IDBFactory() });
vi.stubGlobal('createImageBitmap', async () => ({
- close() {
- /* native image decoder boundary */
- },
+ close: () => undefined,
}));
vi.stubGlobal(
'URL',
@@ -191,7 +189,7 @@ async function setup() {
return 'blob:uploaded-poster';
}
static override revokeObjectURL() {
- /* native object URL boundary */
+ return undefined;
}
},
);
diff --git a/src/app/components/item-list/item-list.component.spec.ts b/src/app/components/item-list/item-list.component.spec.ts
index 9583d99..d02c4be 100644
--- a/src/app/components/item-list/item-list.component.spec.ts
+++ b/src/app/components/item-list/item-list.component.spec.ts
@@ -229,7 +229,6 @@ describe('ItemListComponent', () => {
setup({ watchItems: items, sortField: 'lastWatched', sortDirection: 'asc' });
const fixture = TestBed.createComponent(ItemListComponent);
fixture.detectChanges();
- // a: 2026-01-01, c: 2026-02-01, b: 2026-03-01
expect(fixture.componentInstance.filteredItems().map((i) => i.id)).toEqual(['a', 'c', 'b']);
});
@@ -314,7 +313,6 @@ describe('ItemListComponent', () => {
fixture.detectChanges();
const selects = fixture.nativeElement.querySelectorAll('select');
- // group + sortField = 2 selects, sort direction is now a toggle button
expect(selects.length).toBe(2);
const sortBySelect = fixture.nativeElement.querySelector('select[aria-label="Sort by"]');
@@ -341,7 +339,6 @@ describe('ItemListComponent', () => {
window.localStorage.clear();
window.localStorage.setItem('itemSortField', 'invalid');
window.localStorage.setItem('itemSortDirection', 'invalid');
- // Bypass setup helper to test invalid persistence directly
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
diff --git a/src/app/components/item-mutation-feedback.ts b/src/app/components/item-mutation-feedback.ts
index 309d0d1..134a39f 100644
--- a/src/app/components/item-mutation-feedback.ts
+++ b/src/app/components/item-mutation-feedback.ts
@@ -6,7 +6,6 @@ export function itemMutationFailure(error: unknown, failureMessage: string) {
return `${failureMessage}${detail} Please try again or return to Items.`;
}
-/** Keep draft posters owned by their mounted picker until the command settles. */
export const canLeaveItemForm: CanDeactivateFn<{ mutation: MutationFeedback } | null> = (
component,
) => !component?.mutation.busy();
diff --git a/src/app/components/mutation-feedback.ts b/src/app/components/mutation-feedback.ts
index f492243..0da6ce0 100644
--- a/src/app/components/mutation-feedback.ts
+++ b/src/app/components/mutation-feedback.ts
@@ -1,7 +1,6 @@
import { signal } from '@angular/core';
import type { MutationResult } from '../services/storage.service';
-/** One settled command at a time; callers own wording and post-success interaction. */
export class MutationFeedback {
readonly busy = signal(false);
readonly error = signal(null);
@@ -9,7 +8,6 @@ export class MutationFeedback {
constructor(private readonly describeFailure: (error: unknown, action: string) => string) {}
- /** Unlocks before returning success; rejected and duplicate attempts return undefined. */
async run(operation: () => Promise>, action: string) {
if (this.busy()) return;
this.busy.set(true);
diff --git a/src/app/components/poster-drafts.spec.ts b/src/app/components/poster-drafts.spec.ts
index c55e55b..ac3204c 100644
--- a/src/app/components/poster-drafts.spec.ts
+++ b/src/app/components/poster-drafts.spec.ts
@@ -53,7 +53,6 @@ describe('Provisional poster lifecycle', () => {
const downloaded = new Response();
vi.spyOn(downloaded, 'blob').mockResolvedValue(new Blob(['download'], { type: 'image/png' }));
finish(downloaded);
- // Native decoding is the final asynchronous preparation boundary before publishing a draft.
await vi.waitFor(() =>
expect(createImageBitmap).toHaveBeenCalledTimes(action === 'supersede' ? 2 : 1),
);
diff --git a/src/app/components/poster-picker/poster-picker.component.spec.ts b/src/app/components/poster-picker/poster-picker.component.spec.ts
index 82c156f..5d5bfbb 100644
--- a/src/app/components/poster-picker/poster-picker.component.spec.ts
+++ b/src/app/components/poster-picker/poster-picker.component.spec.ts
@@ -527,7 +527,6 @@ describe('PosterPickerComponent', () => {
expect(fixture.componentInstance.showPosterSearch()).toBe(true);
expect(fixture.componentInstance.posterSearchQuery()).toBe('');
- // with no seed
const fixture2 = TestBed.createComponent(PosterPickerComponent);
fixture2.componentRef.setInput('searchSeed', '');
fixture2.detectChanges();
@@ -596,7 +595,6 @@ describe('PosterPickerComponent', () => {
fixture.componentRef.setInput('posterId', 'image-1');
fixture.detectChanges();
- // Simulate that draftPosterIds contains image-1
(fixture.componentInstance as unknown as { draftPosterIds: Set }).draftPosterIds.add(
'image-1',
);
@@ -687,7 +685,6 @@ describe('PosterPickerComponent', () => {
await Promise.resolve();
await new Promise((r) => setTimeout(r, 0));
- // Should not throw and not set error because destroyed
expect(fixture.componentInstance.posterError()).toBe('');
});
@@ -697,7 +694,6 @@ describe('PosterPickerComponent', () => {
fixture.componentRef.setInput('posterId', 'old-id');
fixture.detectChanges();
- // Simulate draft contains old-id
(fixture.componentInstance as unknown as { draftPosterIds: Set }).draftPosterIds.add(
'old-id',
);
diff --git a/src/app/components/settings/settings.component.spec.ts b/src/app/components/settings/settings.component.spec.ts
index d374be2..534f3d4 100644
--- a/src/app/components/settings/settings.component.spec.ts
+++ b/src/app/components/settings/settings.component.spec.ts
@@ -490,8 +490,6 @@ describe('SettingsComponent', () => {
expect(byText('Import Data')?.disabled).toBe(true);
expect(byText('Cancel')?.disabled).toBe(true);
- // The picker is disabled while importing, but a file staged meanwhile
- // must not be discarded by the running import's cleanup.
await fixture.componentInstance.onFileSelected({ target: pick('b.json') } as unknown as Event);
await fixture.componentInstance.confirmImport();
expect(exportService.importData).toHaveBeenCalledOnce();
@@ -773,7 +771,6 @@ describe('SettingsComponent', () => {
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('— Built');
- // DatePipe 'medium' formats ISO to locale string containing year and month
expect(fixture.nativeElement.textContent).toContain('2026');
expect(fixture.nativeElement.textContent).toContain('Aug');
});
@@ -831,7 +828,6 @@ describe('SettingsComponent', () => {
const fixture = TestBed.createComponent(SettingsComponent);
expect(fixture.componentInstance.includeAdult()).toBe(false);
- // Simulate import changing provider settings on disk
providerMock.isAdultIncluded.mockReturnValue(true);
providerMock.isEnabled.mockReturnValue(true);
providerMock.getAdultDisplayMode.mockReturnValue('hide' as const);
diff --git a/src/app/components/settings/settings.component.ts b/src/app/components/settings/settings.component.ts
index 2d49cba..c13ae8f 100644
--- a/src/app/components/settings/settings.component.ts
+++ b/src/app/components/settings/settings.component.ts
@@ -682,15 +682,15 @@ export class SettingsComponent implements OnInit, OnDestroy {
retainFile = error instanceof CollectionConflictError;
this.setError(importError, retainFile || error instanceof UnsupportedSchemaVersionError);
} finally {
- // A file staged while this import ran belongs to the next confirmation;
- // only clear the pending state when it is still this call's file.
- if (!retainFile && this.pendingImportFile() === file) {
- this.pendingImportFile.set(null);
- }
+ if (!retainFile) this.clearPendingImportIfStill(file);
this.importInProgress.set(false);
}
}
+ private clearPendingImportIfStill(file: File) {
+ if (this.pendingImportFile() === file) this.pendingImportFile.set(null);
+ }
+
private setError(message: string | null, persistent = false) {
clearTimeout(this.errorTimeout);
this.errorTimeout = undefined;
diff --git a/src/app/directives/file-picker-focus.directive.ts b/src/app/directives/file-picker-focus.directive.ts
index 8949391..133bb5e 100644
--- a/src/app/directives/file-picker-focus.directive.ts
+++ b/src/app/directives/file-picker-focus.directive.ts
@@ -3,13 +3,12 @@ import { Directive } from '@angular/core';
@Directive({
selector: 'input[type="file"][appFilePickerFocus]',
host: {
- '(change)': 'restoreFocus()',
- '(cancel)': 'restoreFocus()',
+ '(change)': 'focusWindowWhenPickerCloses()',
+ '(cancel)': 'focusWindowWhenPickerCloses()',
},
})
export class FilePickerFocusDirective {
- restoreFocus(): void {
- // Request renderer focus whenever the native file picker closes, including cancellation.
+ focusWindowWhenPickerCloses(): void {
if (typeof window !== 'undefined' && typeof window.focus === 'function') {
window.focus();
}
diff --git a/src/app/domain/availability-deferral.ts b/src/app/domain/availability-deferral.ts
index 34fa033..134b2e9 100644
--- a/src/app/domain/availability-deferral.ts
+++ b/src/app/domain/availability-deferral.ts
@@ -1,7 +1,6 @@
import { ReadonlyItem, SeriesProgress } from '../models/item.model';
import { isEpisodicType } from './item.constants';
-/** Elapsed hours, bounded by the ISO date range supported by persistence. */
export function deferralReturnDate(hours: number, now = Date.now()) {
if (!Number.isSafeInteger(hours) || hours <= 0) return null;
const until = now + hours * 3_600_000;
diff --git a/src/app/domain/item-edit.ts b/src/app/domain/item-edit.ts
index 74b2bb5..23f07e4 100644
--- a/src/app/domain/item-edit.ts
+++ b/src/app/domain/item-edit.ts
@@ -6,15 +6,15 @@ type EditableFields = Omit<
'id' | 'createdAt' | 'watchHistory' | 'progress' | 'availabilityDeferral'
>;
-/** Omitted properties are untouched; null progress/season entries explicitly remove them. */
-export type ItemEdit = Partial & {
- progress?:
- | (Partial> & {
- seasons?: Record | null>;
- })
- | null;
+const REMOVE = null;
+type Remove = typeof REMOVE;
+type SeasonPatch = Partial | Remove;
+type ProgressPatch = Partial> & {
+ seasons?: Record;
};
+export type ItemEdit = Partial & { progress?: ProgressPatch | Remove };
+
export function createItemEdit(
before: EditableFields & Pick- ,
after: EditableFields & Pick
- ,
@@ -24,14 +24,14 @@ export function createItemEdit(
const edit: ItemEdit = changedFields(editableFields(before), editableFields(after));
const base = previous ?? (isEpisodicType(before.type) ? defaultProgress() : undefined);
if (!next) {
- if (previous) edit.progress = null;
+ if (previous) edit.progress = REMOVE;
} else {
const { seasons: oldSeasons, ...oldPosition } = base ?? defaultProgress();
const { seasons: newSeasons, ...newPosition } = next;
- const seasons: Record
| null> = {};
+ const seasons: Record = {};
for (const old of oldSeasons) {
if (!newSeasons.some((season) => season.seasonNumber === old.seasonNumber)) {
- seasons[old.seasonNumber] = null;
+ seasons[old.seasonNumber] = REMOVE;
}
}
for (const season of newSeasons) {
@@ -39,7 +39,7 @@ export function createItemEdit(
const changes = old ? changedFields(old, season) : season;
if (Object.keys(changes).length) seasons[season.seasonNumber] = changes;
}
- const progress: NonNullable = changedFields(oldPosition, newPosition);
+ const progress: ProgressPatch = changedFields(oldPosition, newPosition);
if (Object.keys(seasons).length) progress.seasons = seasons;
if (Object.keys(progress).length || !base) edit.progress = progress;
}
@@ -49,7 +49,7 @@ export function createItemEdit(
export function applyItemEdit(item: Item, edit: ItemEdit): Item {
const { progress, ...fields } = edit;
const updated = { ...item, ...fields };
- if (progress === null || !isEpisodicType(updated.type)) {
+ if (progress === REMOVE || !isEpisodicType(updated.type)) {
delete updated.progress;
} else if (progress) {
const { seasons, ...position } = progress;
@@ -57,7 +57,7 @@ export function applyItemEdit(item: Item, edit: ItemEdit): Item {
const records = new Map(current.seasons.map((season) => [season.seasonNumber, season]));
for (const [key, changes] of Object.entries(seasons ?? {})) {
const seasonNumber = Number(key);
- if (changes === null) records.delete(seasonNumber);
+ if (changes === REMOVE) records.delete(seasonNumber);
else records.set(seasonNumber, { ...records.get(seasonNumber), ...changes, seasonNumber });
}
updated.progress = {
diff --git a/src/app/domain/poster-references.ts b/src/app/domain/poster-references.ts
index 68e4d83..b779c06 100644
--- a/src/app/domain/poster-references.ts
+++ b/src/app/domain/poster-references.ts
@@ -1,7 +1,6 @@
import { Item } from '../models/item.model';
-/** Mutates only the detached import/export items, never the published collection. */
-export function removeUnavailablePosterReferences(
+export function deleteUnavailablePosterIds(
items: Record,
availableIds: ReadonlySet,
) {
diff --git a/src/app/domain/storage-schema.spec.ts b/src/app/domain/storage-schema.spec.ts
index 8e67d98..79806d0 100644
--- a/src/app/domain/storage-schema.spec.ts
+++ b/src/app/domain/storage-schema.spec.ts
@@ -227,7 +227,6 @@ describe('storage version compatibility', () => {
expect(() => normalizeStorageData(newer)).toThrow(/newer version of Watch List/);
expect(newer).toEqual(original);
- // A future schema may replace today's required fields entirely.
expect(() => normalizeStorageData({ schemaVersion: newer.schemaVersion })).toThrow(
/newer version of Watch List/,
);
diff --git a/src/app/domain/storage-schema.ts b/src/app/domain/storage-schema.ts
index 1a00f4c..ae6fc0b 100644
--- a/src/app/domain/storage-schema.ts
+++ b/src/app/domain/storage-schema.ts
@@ -6,8 +6,6 @@ import { Item } from '../models/item.model';
const PositiveIntegerSchema = z.number().int().positive();
const NonblankStringSchema = z.string().refine((value) => value.trim().length > 0);
-// History and creation dates must be real dates. Release metadata deliberately
-// retains its older, more permissive YYYY-MM-DD contract below.
const DateSchema = z.union([z.iso.date(), z.iso.datetime({ offset: true, local: true })]);
const SeasonInfoSchema = z.object({
@@ -78,8 +76,6 @@ const DeletedItemHistorySchema = z.object({
deletedAt: DateSchema,
});
-// Migration handles untrusted records, not domain objects. Only parsing each
-// record below grants it a domain type.
// Keep all own keys: z.record discards __proto__ before recovery can count it.
const UntrustedRecordsSchema = z.custom>(isRecord);
const StorageEnvelopeSchema = z.object({
@@ -234,8 +230,6 @@ function migrateStorageData(data: StorageEnvelope): StorageEnvelope {
if (migrated.schemaVersion < 3) {
for (const item of Object.values(migrated.items)) {
- // Malformed records (null, primitives) pass through to quarantine,
- // which drops them after migration salvages the valid items.
if (!isRecord(item)) {
continue;
}
@@ -279,27 +273,20 @@ function migrateStorageData(data: StorageEnvelope): StorageEnvelope {
if (!isRecord(item)) {
continue;
}
- // Remote URLs must never survive the offline-image migration. Existing
- // posters are deliberately cleared instead of being fetched at startup.
delete item['posterPath'];
}
migrated.schemaVersion = 6;
}
if (migrated.schemaVersion < 7) {
- // Introduce 'paused' status. No auto-migration: existing 'not-started' items
- // remain in backlog even if they were previously paused via the lie.
migrated.schemaVersion = 7;
}
if (migrated.schemaVersion < 8) {
- // Widen ItemType to include 'ova' and 'ona'. No data migration needed;
- // existing 'series'|'movie' values remain valid under the expanded enum.
migrated.schemaVersion = 8;
}
if (migrated.schemaVersion < 9) {
- // Introduce required isAdult. Existing items lack the field; default to false (SFW).
for (const item of Object.values(migrated.items)) {
if (!isRecord(item)) {
continue;
@@ -312,12 +299,10 @@ function migrateStorageData(data: StorageEnvelope): StorageEnvelope {
}
if (migrated.schemaVersion < 10) {
- // Optional per-season release delay: absent counts mean zero, with no baseline rewrite.
migrated.schemaVersion = 10;
}
if (migrated.schemaVersion < 11) {
- // Optional episode-specific availability deferrals; existing records stay valid.
migrated.schemaVersion = 11;
}
diff --git a/src/app/models/readonly.ts b/src/app/models/readonly.ts
index 54e960d..3349332 100644
--- a/src/app/models/readonly.ts
+++ b/src/app/models/readonly.ts
@@ -1,7 +1,5 @@
-/** Read models share settled state; command drafts remain mutable. */
export type DeepReadonly = { readonly [K in keyof T]: DeepReadonly };
-/** Freeze once at publication, rather than cloning on each reactive read. */
export function freezeReadModel(value: T): DeepReadonly {
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
for (const child of Object.values(value)) freezeReadModel(child);
diff --git a/src/app/services/browser-settings-storage.service.ts b/src/app/services/browser-settings-storage.service.ts
index 3d79442..69544ff 100644
--- a/src/app/services/browser-settings-storage.service.ts
+++ b/src/app/services/browser-settings-storage.service.ts
@@ -1,6 +1,5 @@
import { Injectable, signal } from '@angular/core';
-/** Optional browser settings never gate access to the collection. */
@Injectable({ providedIn: 'root' })
export class BrowserSettingsStorage {
private readonly failed = signal(false);
diff --git a/src/app/services/group-item-mutations.spec.ts b/src/app/services/group-item-mutations.spec.ts
index 02d918c..1148152 100644
--- a/src/app/services/group-item-mutations.spec.ts
+++ b/src/app/services/group-item-mutations.spec.ts
@@ -17,8 +17,6 @@ describe('Group and item mutation coexistence', () => {
async (groupAction) => {
const { storage, groups, items, target } = await setup();
- // Start the real item command after the group put succeeds but before its
- // transaction completes. No application methods or queue internals are mocked.
let itemWrite: ReturnType | undefined;
const saveItem = () => runItemCommand(items, itemAction, target);
const put = IDBObjectStore.prototype.put;
diff --git a/src/app/services/group.service.spec.ts b/src/app/services/group.service.spec.ts
index 0822e93..7c1c46f 100644
--- a/src/app/services/group.service.spec.ts
+++ b/src/app/services/group.service.spec.ts
@@ -233,7 +233,6 @@ describe('GroupService', () => {
return service.reorderGroups(['films', DEFAULT_GROUP_ID]);
}
})();
- // These commands are invoked before the first transaction settles.
const second =
firstKind === 'create'
? service.createGroup('Second')
diff --git a/src/app/services/group.service.ts b/src/app/services/group.service.ts
index 3fbf682..087adc9 100644
--- a/src/app/services/group.service.ts
+++ b/src/app/services/group.service.ts
@@ -43,7 +43,6 @@ export class GroupService {
throw new Error('Cannot delete the ungrouped group');
}
delete data.groups[groupId];
- // Group removal and item reassignment commit together.
Object.values(data.items).forEach((item) => {
if (item.groupId === groupId) item.groupId = DEFAULT_GROUP_ID;
});
@@ -65,7 +64,6 @@ export class GroupService {
}
});
- // Keep any groups not in the reorder list
Object.values(data.groups).forEach((group) => {
if (!groups.has(group.id)) {
groups.set(group.id, group);
diff --git a/src/app/services/image-storage.service.spec.ts b/src/app/services/image-storage.service.spec.ts
index 8df874b..733a34f 100644
--- a/src/app/services/image-storage.service.spec.ts
+++ b/src/app/services/image-storage.service.spec.ts
@@ -305,7 +305,6 @@ describe('ImageStorageService', () => {
const storage = TestBed.inject(StorageService);
await storage.importDataWithImages(storage.getData(), [
{ id, blob: createImageBlob() },
- // A damaged unrelated blob must never be read by a selected export.
{ id: 'unrelated', blob: null as unknown as Blob },
]);
@@ -537,7 +536,6 @@ describe('ImageStorageService', () => {
const [v1, v2] = await Promise.all([p1, p2]);
expect(v1).toBe('blob:mock-url');
expect(v2).toBe('blob:mock-url');
- // second call still cached returns same resolved value
await expect(service.getUrl(id)).resolves.toBe('blob:mock-url');
});
@@ -628,7 +626,6 @@ describe('ImageStorageService', () => {
await service.getUrl(id);
const before = imageVersion();
service.invalidateAll();
- // revoke is async (void), wait a tick
await new Promise((r) => setTimeout(r, 0));
expect(imageVersion()).toBeGreaterThan(before);
expect(URL.revokeObjectURL).toHaveBeenCalled();
@@ -639,7 +636,6 @@ describe('ImageStorageService', () => {
const blob = createImageBlob('abc', 'image/png');
const id = await service.storeFile(blob);
const urlPromise = service.getUrl(id);
- // Make URL.createObjectURL throw? Actually revoke path catches errors
URL.revokeObjectURL = vi.fn(() => {
throw new Error('revoke fail');
}) as unknown as typeof URL.revokeObjectURL;
diff --git a/src/app/services/image-storage.service.ts b/src/app/services/image-storage.service.ts
index b444d9b..85e6362 100644
--- a/src/app/services/image-storage.service.ts
+++ b/src/app/services/image-storage.service.ts
@@ -39,7 +39,6 @@ export class ImageStorageService {
imagesInvalidated.subscribe((id) => this.refreshCache(id));
}
- /** Prepare a UI draft; only a collection command can persist it with an item reference. */
async storeFile(file: Blob): Promise {
await this.ensureWritable();
await this.validateImage(file);
@@ -61,7 +60,6 @@ export class ImageStorageService {
return this.storeFile(await response.blob());
}
- /** Releasing a UI draft never deletes persistent images or committed ownership. */
discardDraft(id: string): void {
if (this.storageService.discardProvisionalImage(id)) {
this.setPosterMissing(id, false);
diff --git a/src/app/services/import-export.service.spec.ts b/src/app/services/import-export.service.spec.ts
index a934266..e7330e5 100644
--- a/src/app/services/import-export.service.spec.ts
+++ b/src/app/services/import-export.service.spec.ts
@@ -69,7 +69,6 @@ describe('import version compatibility', () => {
}
: {
data: newer,
- // Newer image formats must not hide the version explanation behind an image error.
images: format === 'portable' ? [] : { futureFormat: true },
preferences: { providerSettings: { tmdb: true } },
};
@@ -92,7 +91,6 @@ describe('import version compatibility', () => {
request.onsuccess = () => resolve(request.result);
});
expect(images).toEqual([image]);
- // Rejection must not lock an otherwise compatible collection.
await expect(storage.replaceData(original)).resolves.toMatchObject({
durability: 'persistent',
});
@@ -241,7 +239,6 @@ describe('ImportExportService', () => {
it('always includes non-sensitive preferences and never leaks tokens', async () => {
storageService.getData.mockReturnValue({ items: [] });
- // Simulate tokens in localStorage – service must not read them
const store: Record = {};
const mockStorage = {
getItem: (k: string) => store[k] ?? null,
@@ -520,47 +517,6 @@ describe('ImportExportService', () => {
);
});
- it.each(['provider', 'discussion'])(
- 'ignores a failed %s preference import without failing the data import',
- async (source) => {
- const payload = {
- data: { items: [] },
- images: [],
- preferences: {
- providerSettings: { tmdb: 'bad', titlePreference: ['bad'] },
- discussionSettings: { enabled: true, urlTemplate: 'https://example.com/{title}' },
- },
- };
- const file = mockFile(JSON.stringify(payload));
- const importPreferences =
- source === 'provider'
- ? providerSettings.importSettings
- : vi.spyOn(TestBed.inject(DiscussionSettingsService), 'importSettings');
- importPreferences.mockImplementation(() => {
- throw new Error('invalid');
- });
- storageService.importDataWithImages.mockResolvedValue({
- durability: 'persistent',
- dropped: { groups: 0, items: 0, deletedItems: 0 },
- repairedGroupReferences: 0,
- });
- imageStorage.parseExportedImages.mockResolvedValue([]);
-
- await expect(importExportService.importData(file)).resolves.toEqual({
- durability: 'persistent',
- dropped: { groups: 0, items: 0, deletedItems: 0 },
- repairedGroupReferences: 0,
- });
- expect(storageService.importDataWithImages).toHaveBeenCalledWith(
- { items: [] },
- [],
- importContext,
- );
- expect(providerSettings.importSettings).toHaveBeenCalled();
- expect(importPreferences).toHaveBeenCalled();
- },
- );
-
it('returns the omissions and repairs from the storage service', async () => {
const file = mockFile(JSON.stringify({ data: { items: [] }, images: [] }));
const dropped = { groups: 1, items: 2, deletedItems: 0 };
@@ -604,7 +560,6 @@ describe('ImportExportService', () => {
includeAdult: false,
}),
);
- // importSettings should only receive providerSettings, never the injected token keys
const calledWith = providerSettings.importSettings.mock.calls[0][0] as Record<
string,
unknown
diff --git a/src/app/services/import-export.service.ts b/src/app/services/import-export.service.ts
index 67ae629..a2c116e 100644
--- a/src/app/services/import-export.service.ts
+++ b/src/app/services/import-export.service.ts
@@ -3,7 +3,7 @@ import { MutationResult, StorageService } from './storage.service';
import { ExportedImage, ImageStorageService } from './image-storage.service';
import { ProviderSettings, ProviderSettingsService } from './provider-settings.service';
import { assertSupportedStorageVersion, NormalizationReport } from '../domain/storage-schema';
-import { removeUnavailablePosterReferences } from '../domain/poster-references';
+import { deleteUnavailablePosterIds } from '../domain/poster-references';
import { DiscussionSettings, DiscussionSettingsService } from './discussion-settings.service';
export interface ExportPreferences {
@@ -50,8 +50,6 @@ export class ImportExportService {
private discussionSettings = inject(DiscussionSettingsService);
async exportData(): Promise {
- // Export the collection visible when the action starts, not later edits made
- // while poster reads/encoding are pending. Only its referenced posters belong here.
const data = this.storageService.getData();
const posterIds = new Set(
Object.values(data.items).flatMap((item) => (item.posterId ? [item.posterId] : [])),
@@ -64,7 +62,7 @@ export class ImportExportService {
unavailable = true;
}
const availableIds = new Set(images.map((image) => image.id));
- const omittedIds = removeUnavailablePosterReferences(data.items, availableIds);
+ const omittedIds = deleteUnavailablePosterIds(data.items, availableIds);
const posters = { included: images.length, omittedIds, unavailable };
const payload: PortableExport = {
data,
@@ -75,8 +73,6 @@ export class ImportExportService {
discussionSettings: this.discussionSettings.exportSettings(),
},
};
- // TMDB credentials are never read or exported here. User-configured discussion
- // URL templates are intentionally portable, alongside the provider preferences.
this.downloadJson(payload, 'watch-list-export');
return posters;
}
@@ -110,12 +106,10 @@ export class ImportExportService {
}
async importData(file: File): Promise {
- // Confirmation belongs to the currently reviewed context, before async file preparation.
const context = this.storageService.captureImportContext();
try {
const text = await file.text();
const payload: unknown = JSON.parse(text);
- // Unknown fields on a newer raw document may resemble today's export wrapper.
assertSupportedStorageVersion(payload);
const data = isPortableExport(payload) ? payload.data : payload;
assertSupportedStorageVersion(data);
@@ -158,17 +152,8 @@ export class ImportExportService {
if (!isPortableExport(payload) || !hasPreferences(payload)) {
return;
}
- // Never import sensitive keys; ProviderSettingsService normalizes and ignores unknown fields.
- try {
- this.providerSettings.importSettings(payload.preferences.providerSettings);
- } catch {
- // Invalid preferences must never break the data import.
- }
- try {
- this.discussionSettings.importSettings(payload.preferences.discussionSettings);
- } catch {
- // Invalid preferences must never break the data import.
- }
+ this.providerSettings.importSettings(payload.preferences.providerSettings);
+ this.discussionSettings.importSettings(payload.preferences.discussionSettings);
}
}
@@ -189,14 +174,12 @@ function readPosterCoverage(payload: unknown): PosterCoverage | undefined {
function assertLosslessJson(value: unknown, seen = new WeakSet()): void {
if (value === null || typeof value === 'string' || typeof value === 'boolean') return;
if (typeof value === 'number' && Number.isFinite(value) && !Object.is(value, -0)) return;
- // Repeated references also lose their identity in JSON, even without a cycle.
if (typeof value !== 'object' || seen.has(value)) {
throw new UnsupportedRecoveryFormatError();
}
seen.add(value);
const keys = Object.keys(value);
if (Array.isArray(value)) {
- // JSON drops extra array properties and turns holes into null.
if (keys.length !== value.length || keys.some((key, index) => key !== String(index))) {
throw new UnsupportedRecoveryFormatError();
}
diff --git a/src/app/services/indexeddb-write.test-utils.ts b/src/app/services/indexeddb-write.test-utils.ts
index b66df13..fabfdfa 100644
--- a/src/app/services/indexeddb-write.test-utils.ts
+++ b/src/app/services/indexeddb-write.test-utils.ts
@@ -1,7 +1,6 @@
import { IDBObjectStore } from 'fake-indexeddb';
import { vi } from 'vitest';
-/** Observe request success or abort selected collection writes before transaction completion. */
export function controlStorageWrites(
outcomes: boolean[] = [],
onRequestSuccess?: (index: number, store: IDBObjectStore) => void,
@@ -25,7 +24,6 @@ export function controlStorageWrites(
});
}
-/** Keep a real transaction pending until release, without mocking application persistence. */
export function holdStorageWrite(index: number, onRequestSuccess?: (index: number) => void) {
let released = false;
let transaction: IDBTransaction | undefined;
@@ -58,7 +56,6 @@ export function holdStorageWrite(index: number, onRequestSuccess?: (index: numbe
};
}
-/** Hold ownership cleanup after its delete request succeeds but before it commits. */
export function holdPosterCleanup() {
let released = false;
let signalStarted = () => undefined as void;
diff --git a/src/app/services/item-sort.service.spec.ts b/src/app/services/item-sort.service.spec.ts
index 4257c75..d0202d1 100644
--- a/src/app/services/item-sort.service.spec.ts
+++ b/src/app/services/item-sort.service.spec.ts
@@ -134,7 +134,6 @@ describe('ItemSortService', () => {
try {
service.setField('title');
service.setDirection('asc');
- // in-memory should still update
expect(service.field()).toBe('title');
expect(service.direction()).toBe('asc');
} finally {
diff --git a/src/app/services/item-sort.service.ts b/src/app/services/item-sort.service.ts
index 7ed9a03..63765f9 100644
--- a/src/app/services/item-sort.service.ts
+++ b/src/app/services/item-sort.service.ts
@@ -34,27 +34,13 @@ export class ItemSortService {
}
private loadField(): SortField {
- try {
- const raw = this.settingsStorage.read(SORT_FIELD_KEY);
- if (raw && isSortField(raw)) {
- return raw;
- }
- } catch {
- // ignore read errors, fallback to default
- }
- return DEFAULT_SORT_FIELD;
+ const raw = this.settingsStorage.read(SORT_FIELD_KEY);
+ return raw && isSortField(raw) ? raw : DEFAULT_SORT_FIELD;
}
private loadDirection(): SortDirection {
- try {
- const raw = this.settingsStorage.read(SORT_DIRECTION_KEY);
- if (raw && isSortDirection(raw)) {
- return raw;
- }
- } catch {
- // ignore read errors
- }
- return DEFAULT_SORT_DIRECTION;
+ const raw = this.settingsStorage.read(SORT_DIRECTION_KEY);
+ return raw && isSortDirection(raw) ? raw : DEFAULT_SORT_DIRECTION;
}
private saveField(field: SortField): void {
diff --git a/src/app/services/jikan-suggestion.service.ts b/src/app/services/jikan-suggestion.service.ts
index 2cf6cb0..f31c71a 100644
--- a/src/app/services/jikan-suggestion.service.ts
+++ b/src/app/services/jikan-suggestion.service.ts
@@ -142,7 +142,6 @@ export class JikanSuggestionService {
const firstEpisodeAirDate = this.extractDate(candidate.aired);
- // Only return a season entry if we have at least episode count or air date
if (totalEpisodes === undefined && !firstEpisodeAirDate) {
return null;
}
diff --git a/src/app/services/poster-context-conflicts.spec.ts b/src/app/services/poster-context-conflicts.spec.ts
index 02304cb..0984edd 100644
--- a/src/app/services/poster-context-conflicts.spec.ts
+++ b/src/app/services/poster-context-conflicts.spec.ts
@@ -142,7 +142,6 @@ describe('Poster persistence context conflicts', () => {
});
expect(reloaded.storage.getGroups()[0].name).toBe('Concurrent edit');
expect(await reloaded.images.getUrl(posterId)).toBe('blob:poster');
- // A reload adopts the poster revision too, so its next edit must succeed.
await reloaded.storage.mutate((draft) => {
draft.items[reloaded.storage.getItems()[0].id].title = 'Edited after reload';
});
diff --git a/src/app/services/poster-ownership.spec.ts b/src/app/services/poster-ownership.spec.ts
index 4381288..b6e1379 100644
--- a/src/app/services/poster-ownership.spec.ts
+++ b/src/app/services/poster-ownership.spec.ts
@@ -62,7 +62,6 @@ describe('Committed poster ownership', () => {
expect(reloaded.getData()).toEqual(previous);
expect(storage.getData()).toEqual(previous);
expect(await freshImages.getUrl(oldPoster)).toBe('blob:poster');
- // Resolve through a separate storage context: a pending draft is not a persisted image.
expect(await persistentImages().getUrl(posterId)).toBeNull();
expect(await images.getUrl(posterId)).toBe('blob:poster');
await save();
@@ -140,7 +139,6 @@ describe('Committed poster ownership', () => {
const posterId = await images.storeFile(new Blob(['poster'], { type: 'image/png' }));
const { value: first } = await watch.addItem({ ...movie, posterId });
const { value: second } = await watch.addItem({ ...movie, title: 'Second', posterId });
- // Portable imports may legitimately give multiple items the same poster identity.
const data = storage.getData();
await storage.importDataWithImages(data, [{ id: posterId, blob: image() }]);
expect(await images.getUrl(posterId)).toBe('blob:poster');
@@ -223,7 +221,6 @@ describe('Committed poster ownership', () => {
await peer.initialize();
let peerRefresh = Promise.resolve();
controlStorageWrites([], (index) => {
- // Queue the peer's read behind the new owner's write, ahead of cleanup.
if (index === 1) peerRefresh = peer.refresh();
});
const removal = watch.deleteItem(first.id);
@@ -318,7 +315,6 @@ async function setup() {
}
function persistentImages() {
- // Independent services avoid a provisional-image map or an object-URL cache masking disk state.
const storage = TestBed.runInInjectionContext(() => new StorageService());
return TestBed.runInInjectionContext(() => {
const injector = TestBed.inject(Injector);
diff --git a/src/app/services/poster-reader.ts b/src/app/services/poster-reader.ts
index d68ee44..a85f141 100644
--- a/src/app/services/poster-reader.ts
+++ b/src/app/services/poster-reader.ts
@@ -1,7 +1,6 @@
import { effect, inject, signal, untracked } from '@angular/core';
import { ImageStorageService } from './image-storage.service';
-/** Read a cached poster for this injection lifetime, retaining it while a replacement loads. */
export function injectPosterUrl(posterId: () => string | undefined) {
const images = inject(ImageStorageService);
const url = signal(null);
diff --git a/src/app/services/provider-settings.service.ts b/src/app/services/provider-settings.service.ts
index eb323b7..ee67de7 100644
--- a/src/app/services/provider-settings.service.ts
+++ b/src/app/services/provider-settings.service.ts
@@ -163,8 +163,6 @@ export class ProviderSettingsService {
return DEFAULT_ADULT_DISPLAY_MODE;
}
- // Strict reset: any invalid entry (wrong length, duplicate, unknown lang) falls back to default.
- // Alternative lenient dedup/filter was considered but we prefer explicit reset to avoid drift.
private normalizeTitlePreference(value: unknown): TitlePreference {
if (!Array.isArray(value) || value.length !== 3) {
return [...DEFAULT_TITLE_PREFERENCE];
diff --git a/src/app/services/round-robin.service.spec.ts b/src/app/services/round-robin.service.spec.ts
index 7d77b0c..ef925e6 100644
--- a/src/app/services/round-robin.service.spec.ts
+++ b/src/app/services/round-robin.service.spec.ts
@@ -104,15 +104,10 @@ describe('RoundRobinService', () => {
watchHistory: [{ date: '2026-04-01T00:00:00.000Z' }],
}),
]);
- // b has older last watched, should be suggested first
expect(service.nextSeries()?.id).toBe('b');
});
it('implements round-robin when all others have been watched', async () => {
- // Two series, 'a' oldest but 'b' has no watch history, so canSuggest for 'b' is false, for 'a' is true? Let's craft
- // canSuggest checks if all otherSeries have watchHistory length >0
- // If b has empty history, then for target a, other=b has empty => allOthersWatched false => canSuggest false for a
- // For target b, other=a has history => true => canSuggest true for b => b should be returned
await saveItems([
createSeries({
id: 'a',
@@ -129,15 +124,10 @@ describe('RoundRobinService', () => {
firstEpisodeAirDate: '2020-01-01',
}),
]);
- // sorted by last watched: b (no history => uses createdAt? actually getMostRecentWatchDate falls back to createdAt)
- // For b, lastWatched is createdAt 2026-01-02, for a it's 2026-04-01, so b is older => watchable sorted [b,a]
- // Loop: canSuggest(b) -> other=a has history => true => return b
expect(service.nextSeries()?.id).toBe('b');
});
it('falls back to first watchable when no series can be suggested', async () => {
- // Both have empty history, so for each, allOthersWatched is false (other has empty)
- // No canSuggest true, should return watchable[0] (oldest)
await saveItems([
createSeries({
id: 'a',
@@ -156,7 +146,6 @@ describe('RoundRobinService', () => {
]);
const result = service.nextSeries();
expect(result).not.toBeNull();
- // watchable sorted [a,b] because both have same fallback? a older
expect(result?.id).toBe('a');
});
@@ -255,7 +244,6 @@ describe('RoundRobinService', () => {
episode: 2,
firstEpisodeAirDate: '2026-05-01',
});
- // Change progress to season 2 but seasons only has season 1
(missingSeason as Item).progress = {
season: 2,
episode: 1,
@@ -299,7 +287,6 @@ describe('RoundRobinService', () => {
createdAt: '2026-01-01T00:00:00.000Z',
firstEpisodeAirDate: '2026-00-01',
});
- // year 2026 ok, month 0 -> falsy? 0 is falsy, so returns null
expect(service.hasAiredCurrentEpisode(badMonth)).toBe(true);
});
diff --git a/src/app/services/round-robin.service.ts b/src/app/services/round-robin.service.ts
index edbf738..8c0a1a4 100644
--- a/src/app/services/round-robin.service.ts
+++ b/src/app/services/round-robin.service.ts
@@ -40,7 +40,6 @@ export class RoundRobinService {
if (this.document.visibilityState === 'visible') refresh();
};
refresh();
- // Re-arm the timer when a deferral is saved, cleared, or loaded.
effect(refresh);
window.addEventListener('focus', refresh);
this.document.addEventListener('visibilitychange', onVisibilityChange);
diff --git a/src/app/services/session-recovery.spec.ts b/src/app/services/session-recovery.spec.ts
index 93427f9..ffbe805 100644
--- a/src/app/services/session-recovery.spec.ts
+++ b/src/app/services/session-recovery.spec.ts
@@ -99,7 +99,6 @@ describe('session metadata recovery', () => {
).toBeNull();
expect(storage.getInMemorySessionSignal()()).toBe(true);
- // Reconnecting a poster reader must never reload older disk data over session edits.
openFailure.mockRestore();
expect(await TestBed.inject(ImageStorageService).exportImages()).toEqual([]);
await storage.initialize();
@@ -109,7 +108,6 @@ describe('session metadata recovery', () => {
const reloaded = TestBed.runInInjectionContext(() => new StorageService());
await reloaded.initialize();
expect(reloaded.getData().groups['ungrouped'].name).toBe('Older disk collection');
- // Explicit recovery into a persistent context is deliberate and can then survive reload.
await reloaded.importDataWithImages(JSON.parse(text).data, []);
const recovered = TestBed.runInInjectionContext(() => new StorageService());
await recovered.initialize();
@@ -229,7 +227,6 @@ describe('session metadata recovery', () => {
vi.spyOn(IDBObjectStore.prototype, 'clear').mockImplementation(function (
this: IDBObjectStore,
) {
- // A real failing image-store request: adding the already-present key raises ConstraintError.
return this.add({ id: 'old-poster' }) as unknown as IDBRequest;
});
const file = new File([], 'metadata-only.json');
diff --git a/src/app/services/storage.service.spec.ts b/src/app/services/storage.service.spec.ts
index ccf2a02..82ec88e 100644
--- a/src/app/services/storage.service.spec.ts
+++ b/src/app/services/storage.service.spec.ts
@@ -493,8 +493,6 @@ describe('StorageService', () => {
},
};
await writeRecord(database, raw);
- // Even an unavailable corruption-backup/write path must not turn compatibility into
- // the generic in-memory fallback. This also detects any normalization write.
const put = vi.spyOn(FakeIDBObjectStore.prototype, 'put').mockImplementation(() => {
throw new Error('Writes unavailable');
});
@@ -618,7 +616,6 @@ describe('StorageService', () => {
await service.initialize();
const database = await openTestDatabase();
const raw = { schemaVersion: CURRENT_SCHEMA_VERSION + 1, futureRecords: ['keep'] };
- // A separate preflight read would let the upgrade commit before the stale save.
const upgrade = upgradeAfterNextRead(database, raw);
await service.replaceData(withGroup(service.getData(), 'edited'));
@@ -1335,7 +1332,6 @@ describe('StorageService', () => {
'keeps publication ordered across startup when saves settle (%s, %s)',
async (firstSucceeds, secondSucceeds) => {
const service = createStorageService();
- // Replacements reserve their place before startup, publishing only once settled.
const first = service.replaceData(withGroup(createDefaultStorageData(), 'first'));
await service.initialize();
abortStorageWrites([firstSucceeds, secondSucceeds]);
@@ -1646,7 +1642,6 @@ function upgradeAfterNextRead(database: IDBDatabase, raw: unknown) {
if (this.name === 'storage' && key === 'watch-list-data') {
request.addEventListener('success', () => {
spy.mockRestore();
- // Queue another tab's write before the reader can queue a replacement.
void writeRecord(database, raw).then(resolve, reject);
});
}
diff --git a/src/app/services/storage.service.ts b/src/app/services/storage.service.ts
index 9943a0a..85f8902 100644
--- a/src/app/services/storage.service.ts
+++ b/src/app/services/storage.service.ts
@@ -9,7 +9,7 @@ import {
} from '../domain/storage-schema';
import type { NormalizationReport, NormalizationResult } from '../domain/storage-schema';
import type { StoredImage } from './image-storage.service';
-import { removeUnavailablePosterReferences } from '../domain/poster-references';
+import { deleteUnavailablePosterIds } from '../domain/poster-references';
import { imagesInvalidated } from './image-invalidation';
import {
WatchListDatabase,
@@ -19,7 +19,6 @@ import {
} from './watch-list-database.service';
const DATA_KEY = 'watch-list-data';
-// Local concurrency metadata stays out of portable documents and schema migration.
const REVISION_KEY = 'watch-list-revision';
const BACKUP_PREFIX = 'watch-list-data-backup-';
const BACKUP_LIMIT = 10;
@@ -76,7 +75,6 @@ export class StorageService {
if (!this.initialization) {
this.loading.set(true);
this.initializationError.set(null);
- // Poster reads can recover independently, so preserve edits even after their error clears.
const preserveSession =
this.inMemorySession() &&
this.data() &&
@@ -118,19 +116,12 @@ export class StorageService {
return this.getData();
}
- /** Explicit validated collection replacement for import/recovery, retaining owned posters. */
async replaceData(data: StorageData) {
return this.enqueueMutation(() => undefined, {
replacement: validateSaveData(data),
});
}
- /**
- * Commands and explicit replacements share invocation order in this service instance.
- * An intent edits a detached draft of the latest successful state after earlier writes settle.
- * Keep the callback synchronous and side-effect free. Rejection discards its entire draft;
- * success publishes only after transaction completion (or explicitly as session-only).
- */
async mutate(intent: (draft: StorageData) => T): Promise> {
return this.enqueueMutation(intent);
}
@@ -149,10 +140,6 @@ export class StorageService {
return this.provisionalImages.delete(id);
}
- /** Capture the blob at command invocation: form destruction can only release its draft,
- * never the command's copy. The image and its first committed reference share a transaction.
- * A rejected command leaves a mounted form's draft available for explicit retry.
- */
mutateWithPoster(intent: (draft: StorageData) => T, posterId?: string) {
return this.enqueueMutation(intent, {
posterId,
@@ -232,8 +219,6 @@ export class StorageService {
(error: unknown) => this.reportSaveFailure(error),
);
const result = await mutation;
- // Publication and the collection queue settle at commit. Await cleanup outside that
- // queue entry: commands already queued must be able to run before ownership is rechecked.
if (removedPosters.length && this.persistentStorage) {
try {
await this.cleanupPosters(removedPosters);
@@ -244,7 +229,6 @@ export class StorageService {
return result;
}
- /** Bind asynchronous file preparation to the context in which import was confirmed. */
captureImportContext() {
this.assertMutationReady();
return this.importContext;
@@ -262,7 +246,7 @@ export class StorageService {
}
const normalized = normalizeStorageData(data);
const availableIds = new Set(images.map((image) => image.id));
- const omittedPosterIds = removeUnavailablePosterReferences(normalized.data.items, availableIds);
+ const omittedPosterIds = deleteUnavailablePosterIds(normalized.data.items, availableIds);
const result = await this.enqueueMutation(() => undefined, {
replacement: normalized.data,
images: images.map((image) => ({ ...image })),
@@ -280,8 +264,6 @@ export class StorageService {
const cleanup = this.writeQueue.then(async () => {
if (this.conflict()) throw new CollectionConflictError();
this.assertWritable();
- // The local queue holds ownership stable until cleanup settles. Avoid an empty
- // write (and revision bump) when later commands have reclaimed every candidate.
const owned = new Set(
Object.values(this.settledData?.items ?? {}).map((item) => item.posterId),
);
@@ -320,7 +302,6 @@ export class StorageService {
return this.refreshing.asReadonly();
}
- /** Refresh committed state in place: mounted forms keep ownership of their drafts. */
refresh(): Promise {
if (this.refreshing())
return Promise.reject(new Error('The collection is already refreshing.'));
@@ -419,8 +400,6 @@ export class StorageService {
}
private reportSaveFailure(error: unknown, message = 'Failed to save watch-list data:') {
- // A rejected command needs refresh/retry feedback. Best-effort cleanup uses the
- // same revision protection, but must not present its committed command as unsaved.
if (error instanceof CollectionConflictError && this.settledData) this.conflict.set(true);
this.saveError.set(
this.compatibilityError() ? null : error instanceof Error ? error.message : String(error),
@@ -496,8 +475,6 @@ export class StorageService {
this.publishLoadedData(defaults);
} catch (error) {
if (this.compatibilityError()) return;
- // Another initializer may have won the first revision or normalization write.
- // Read its committed state rather than publishing defaults or a stale snapshot.
if (error instanceof CollectionConflictError) return this.loadData(allowSessionFallback);
if (!allowSessionFallback) throw error;
if (this.databaseError()) throw error;
@@ -636,8 +613,6 @@ export class StorageService {
);
return false;
} catch (error) {
- // Only a poster-store acquisition/cleanup failure permits metadata-only recovery.
- // Metadata failures, conflicts, and image-containing imports must still reject.
if (images.length || !(error instanceof PosterStorageError)) throw error;
await this.writeData(data);
return true;
@@ -690,8 +665,6 @@ export class StorageService {
try {
transaction = database.transaction(stores, 'readwrite');
} catch (error) {
- // No transaction or write has started. A metadata-only import can retry
- // without posters, with the normal revision and compatibility checks.
throw stores.includes(IMAGE_STORE_NAME) ? new PosterStorageError(error) : error;
}
const nextRevision = crypto.randomUUID();
@@ -706,8 +679,6 @@ export class StorageService {
};
transaction.onerror = () => reject(failure ?? transaction.error ?? new Error(message));
transaction.onabort = () => reject(failure ?? transaction.error ?? new Error(message));
- // Reading and writing in one transaction prevents another tab from upgrading
- // the document between the compatibility check and any collection/poster changes.
const request = transaction.objectStore(STORE_NAME).get(DATA_KEY) as IDBRequest;
const revision = transaction.objectStore(STORE_NAME).get(REVISION_KEY) as IDBRequest;
revision.onsuccess = () => {
diff --git a/src/app/services/suggestion-search.test-utils.ts b/src/app/services/suggestion-search.test-utils.ts
index f9a8894..b58bad8 100644
--- a/src/app/services/suggestion-search.test-utils.ts
+++ b/src/app/services/suggestion-search.test-utils.ts
@@ -5,7 +5,6 @@ import { AnilistSuggestionService } from './anilist-suggestion.service';
import { JikanSuggestionService } from './jikan-suggestion.service';
import { TmdbSuggestionService } from './tmdb-suggestion.service';
-// Control external provider responses while exercising the real search lifecycle.
export function createSuggestionProviders() {
const search = vi.fn<(query: string, source: SuggestionSource) => Observable>(() =>
of([]),
diff --git a/src/app/services/watch-list-database.service.ts b/src/app/services/watch-list-database.service.ts
index 6f703ad..dad2b3a 100644
--- a/src/app/services/watch-list-database.service.ts
+++ b/src/app/services/watch-list-database.service.ts
@@ -1,7 +1,6 @@
import { Injectable, signal } from '@angular/core';
const DATABASE_NAME = 'watch-list';
-// Version 2 could be created by poster reads with only the images store.
const DATABASE_VERSION = 3;
const OPEN_TIMEOUT_MS = 5_000;
export const STORAGE_STORE_NAME = 'storage';
diff --git a/src/app/utils/discussion-link.utils.ts b/src/app/utils/discussion-link.utils.ts
index 1a32f11..7751ff0 100644
--- a/src/app/utils/discussion-link.utils.ts
+++ b/src/app/utils/discussion-link.utils.ts
@@ -13,7 +13,6 @@ export function validateDiscussionTemplate(template: string): string | null {
if (!/^https?:\/\//i.test(template)) {
return 'Enter an absolute HTTP or HTTPS URL.';
}
- // Keep the destination explicit; placeholders belong in the path, query, or fragment.
if (/[{}]/.test(template.match(/^https?:\/\/([^/?#]*)/i)?.[1] ?? '')) {
return 'Placeholders cannot be used in the URL host.';
}
@@ -47,7 +46,6 @@ export function buildDiscussionUrl(
(_, name: keyof typeof values) => encodeURIComponent(values[name]),
);
} catch {
- // Malformed Unicode in an imported title must not prevent rendering history.
return null;
}
}
diff --git a/src/app/utils/progress.utils.spec.ts b/src/app/utils/progress.utils.spec.ts
index b5f77fe..3895ec2 100644
--- a/src/app/utils/progress.utils.spec.ts
+++ b/src/app/utils/progress.utils.spec.ts
@@ -64,7 +64,7 @@ describe('calculateProgress', () => {
progress: { season: 1, episode: 6, seasons: [{ seasonNumber: 1, totalEpisodes: 10 }] },
}),
),
- ).toBe(50); // (6-1)/10 =50%
+ ).toBe(50);
expect(
calculateProgress(
item({
diff --git a/src/app/utils/search-stream.utils.ts b/src/app/utils/search-stream.utils.ts
index 348ac20..bb6d1c1 100644
--- a/src/app/utils/search-stream.utils.ts
+++ b/src/app/utils/search-stream.utils.ts
@@ -57,7 +57,6 @@ export function createSearchStream(
});
}
- // Settings can remove the selected provider without a menu interaction.
effect(() => {
const source = selectedSource();
if (lastRequest && lastRequest.source !== source) untracked(request);
@@ -80,7 +79,6 @@ export function createSearchStream(
selectedSource.set(source);
request();
},
- // Selection updates the displayed query without scheduling another search.
dismiss(value = '') {
query.set(value);
lastRequest = undefined;
diff --git a/src/app/utils/sort.utils.spec.ts b/src/app/utils/sort.utils.spec.ts
index 9bda0f9..07eb96a 100644
--- a/src/app/utils/sort.utils.spec.ts
+++ b/src/app/utils/sort.utils.spec.ts
@@ -151,7 +151,6 @@ describe('sort.utils', () => {
title: 'B',
watchHistory: [{ date: '2026-05-01T00:00:00.000Z' }],
});
- // a lastWatched is 2026-06-01 > b 2026-05-01
expect(compareItems(a, b, 'lastWatched', 'asc')).toBeGreaterThan(0);
expect(compareItems(b, a, 'lastWatched', 'asc')).toBeLessThan(0);
});
@@ -186,7 +185,6 @@ describe('sort.utils', () => {
createdAt: '2026-01-01T00:00:00.000Z',
watchHistory: [{ date: '2026-02-01T00:00:00.000Z' }],
});
- // a lastWatched = 2026-10-01, b = 2026-02-01
expect(compareItems(a, b, 'lastWatched', 'asc')).toBeGreaterThan(0);
});
@@ -202,7 +200,6 @@ describe('sort.utils', () => {
watchHistory: [{ date: 'not-a-date' }],
createdAt: '2026-02-01T00:00:00.000Z',
});
- // invalid history treated as -Infinity, so asc: invalid first, desc: valid first
expect(compareItems(invalid, valid, 'lastWatched', 'asc')).toBeLessThan(0);
expect(compareItems(invalid, valid, 'lastWatched', 'desc')).toBeGreaterThan(0);
expect(compareItems(valid, invalid, 'lastWatched', 'asc')).toBeGreaterThan(0);
@@ -223,7 +220,6 @@ describe('sort.utils', () => {
title: 'B',
watchHistory: [{ date: '2026-03-01T00:00:00.000Z' }],
});
- // withInvalid most recent is 2026-04-01 > valid 2026-03-01
expect(compareItems(withInvalid, valid, 'lastWatched', 'asc')).toBeGreaterThan(0);
});
@@ -354,19 +350,16 @@ describe('sort.utils', () => {
title: 'V2',
watchHistory: [{ date: '2026-05-01T00:00:00.000Z' }],
});
- // ascending: invalid (-Infinity) first, then v1, then v2
expect(sortItems([valid2, invalid, valid1], 'lastWatched', 'asc').map((i) => i.id)).toEqual([
'inv',
'v1',
'v2',
]);
- // descending: v2, v1, invalid last
expect(sortItems([invalid, valid1, valid2], 'lastWatched', 'desc').map((i) => i.id)).toEqual([
'v2',
'v1',
'inv',
]);
- // does not produce NaN, stable equality for invalid-only
const onlyInvalid = [
item({ id: 'a', title: 'A', watchHistory: [{ date: 'bad' }] }),
item({ id: 'b', title: 'B', watchHistory: [{ date: 'also-bad' }] }),
diff --git a/src/app/utils/sort.utils.ts b/src/app/utils/sort.utils.ts
index b45d9fb..0499539 100644
--- a/src/app/utils/sort.utils.ts
+++ b/src/app/utils/sort.utils.ts
@@ -76,7 +76,6 @@ function compareByStatus(a: Item, b: Item, direction: SortDirection): number {
return direction === 'asc' ? primary : -primary;
}
- // Tie-breaker: most recently watched first, regardless of direction.
const recent = toTimestamp(getMostRecentWatchDate(b)) - toTimestamp(getMostRecentWatchDate(a));
if (recent !== 0 && !Number.isNaN(recent)) {
return recent;
diff --git a/src/content-security-policy.spec.ts b/src/content-security-policy.spec.ts
new file mode 100644
index 0000000..1f2bde1
--- /dev/null
+++ b/src/content-security-policy.spec.ts
@@ -0,0 +1,47 @@
+import { createHash } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+
+const indexHtml = readFileSync('src/index.html', 'utf8');
+const nginxConf = readFileSync('containers/nginx.conf', 'utf8');
+
+const metaPolicy = indexHtml.match(/http-equiv="Content-Security-Policy"\s+content="([^"]+)"/)?.[1];
+const headerPolicy = nginxConf.match(/add_header Content-Security-Policy "([^"]+)"/)?.[1];
+const inlineScripts = [
+ ...indexHtml.matchAll(/