Skip to content

High performance self-hosted photo and video management solution.

chore(deps): update dependency eslint-plugin-unicorn to v78 (#32588)

renovate[bot]72e2bc8b0bc4
diff --git a/e2e/package.json b/e2e/package.json
index 452d4aa4af..5c29c3c11e 100644
--- a/e2e/package.json
+++ b/e2e/package.json
@@ -40,7 +40,7 @@
"eslint": "^10.0.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.1.3",
- "eslint-plugin-unicorn": "^76.0.0",
+ "eslint-plugin-unicorn": "^78.0.0",
"exiftool-vendored": "^39.0.0",
"globals": "^17.0.0",
"luxon": "^3.4.4",
diff --git a/e2e/src/ui/generators/timeline/distribution-patterns.ts b/e2e/src/ui/generators/timeline/distribution-patterns.ts
index 35f5ead7f7..42363e9e1e 100644
--- a/e2e/src/ui/generators/timeline/distribution-patterns.ts
+++ b/e2e/src/ui/generators/timeline/distribution-patterns.ts
@@ -14,9 +14,7 @@ type DayDistributionStrategy = (
rng: SeededRandom,
) => MockTimelineAsset[];
-/**
- * Strategies for determining total asset count per month
- */
+/** Strategies for determining total asset count per month */
export const ASSET_DISTRIBUTION: Record<MonthDistribution, AssetDistributionStrategy | null> = {
empty: null, // Special case - handled separately
sparse: (rng) => rng.nextInt(3, 9), // 3-8 assets
@@ -25,9 +23,7 @@ export const ASSET_DISTRIBUTION: Record<MonthDistribution, AssetDistributionStra
'very-dense': (rng) => rng.nextInt(80, 151), // 80-150 assets
};
-/**
- * Strategies for distributing assets across days within a month
- */
+/** Strategies for distributing assets across days within a month */
export const DAY_DISTRIBUTION: Record<DayPattern, DayDistributionStrategy> = {
'single-day': (year, month, daysInMonth, totalAssets, ownerId, rng) => {
// All assets on one day in the middle of the month
diff --git a/e2e/src/ui/generators/timeline/model-objects.ts b/e2e/src/ui/generators/timeline/model-objects.ts
index 1a45fdb6f0..4cdc4c1c04 100644
--- a/e2e/src/ui/generators/timeline/model-objects.ts
+++ b/e2e/src/ui/generators/timeline/model-objects.ts
@@ -1,6 +1,4 @@
-/**
- * Generator functions for timeline model objects
- */
+/** Generator functions for timeline model objects */
import { faker } from '@faker-js/faker';
import { AssetVisibility } from '@immich/sdk';
@@ -12,9 +10,7 @@ import { ASSET_DISTRIBUTION, DAY_DISTRIBUTION } from './distribution-patterns';
import type { MockTimelineAsset, MockTimelineData, SerializedTimelineData, TimelineConfig } from './timeline-config';
import { ASPECT_RATIO_WEIGHTS, GENERATION_CONSTANTS, validateTimelineConfig } from './timeline-config';
-/**
- * Generate a random aspect ratio based on weighted probabilities
- */
+/** Generate a random aspect ratio based on weighted probabilities */
export function generateAspectRatio(rng: SeededRandom): string {
const random = rng.next();
let cumulative = 0;
@@ -89,9 +85,7 @@ export function generateAsset(
return asset;
}
-/**
- * Generate assets for a specific day
- */
+/** Generate assets for a specific day */
export function generateDayAssets(
year: number,
month: number,
@@ -104,10 +98,10 @@ export function generateDayAssets(
}
/**
- * Distribute assets evenly across consecutive days
- *
- * @returns Array of generated timeline assets
- */
+Distribute assets evenly across consecutive days
+
+@returns Array of generated timeline assets
+*/
export function generateConsecutiveDays(
year: number,
month: number,
@@ -133,9 +127,7 @@ export function generateConsecutiveDays(
return assets;
}
-/**
- * Generate assets for a month with specified distribution pattern
- */
+/** Generate assets for a month with specified distribution pattern */
export function generateMonthAssets(
year: number,
month: number,
@@ -173,9 +165,7 @@ export function generateMonthAssets(
return assets;
}
-/**
- * Main generator function for timeline data
- */
+/** Main generator function for timeline data */
export function generateTimelineData(config: TimelineConfig): MockTimelineData {
validateTimelineConfig(config);
diff --git a/e2e/src/ui/generators/timeline/rest-response.ts b/e2e/src/ui/generators/timeline/rest-response.ts
index 5e6ef9d93e..c49fc103a0 100644
--- a/e2e/src/ui/generators/timeline/rest-response.ts
+++ b/e2e/src/ui/generators/timeline/rest-response.ts
@@ -1,6 +1,4 @@
-/**
- * REST API output functions for converting timeline data to API response formats
- */
+/** REST API output functions for converting timeline data to API response formats */
import {
AlbumUserRole,
@@ -19,9 +17,7 @@ import { signupDto } from 'src/fixtures.js';
import { parseTimeBucketKey } from 'src/ui/generators/timeline/utils.js';
import type { MockTimelineAsset, MockTimelineData } from './timeline-config';
-/**
- * Convert timeline/asset models to columnar format (parallel arrays)
- */
+/** Convert timeline/asset models to columnar format (parallel arrays) */
export function toColumnarFormat(assets: MockTimelineAsset[]): TimeBucketAssetResponseDto {
const result: TimeBucketAssetResponseDto = {
id: [],
@@ -70,11 +66,11 @@ export function toColumnarFormat(assets: MockTimelineAsset[]): TimeBucketAssetRe
}
/**
- * Extract a single bucket from timeline data (mimics getTimeBucket API)
- * Automatically handles both ISO timestamp and simple month formats
- * Returns data in columnar format matching the actual API
- * When albumId is provided, only returns assets from that album
- */
+Extract a single bucket from timeline data (mimics getTimeBucket API)
+Automatically handles both ISO timestamp and simple month formats
+Returns data in columnar format matching the actual API
+When albumId is provided, only returns assets from that album
+*/
export function getTimeBucket(
timelineData: MockTimelineData,
timeBucket: string,
@@ -141,16 +137,16 @@ export type Changes = {
};
/**
- * Helper function to determine if an asset should be included based on filter criteria
- * @param asset - The asset to check
- * @param isTrashed - Filter for trashed status (undefined means no filter)
- * @param isArchived - Filter for archived status (undefined means no filter)
- * @param isFavorite - Filter for favorite status (undefined means no filter)
- * @param deletedAssetIds - Set of IDs for assets that have been deleted
- * @param archivedAssetIds - Set of IDs for assets that have been archived
- * @param favoritedAssetIds - Set of IDs for assets that have been favorited
- * @returns true if the asset matches all filter criteria
- */
+Helper function to determine if an asset should be included based on filter criteria
+@param asset - The asset to check
+@param isTrashed - Filter for trashed status (undefined means no filter)
+@param isArchived - Filter for archived status (undefined means no filter)
+@param isFavorite - Filter for favorite status (undefined means no filter)
+@param deletedAssetIds - Set of IDs for assets that have been deleted
+@param archivedAssetIds - Set of IDs for assets that have been archived
+@param favoritedAssetIds - Set of IDs for assets that have been favorited
+@returns true if the asset matches all filter criteria
+*/
function shouldIncludeAsset(
asset: MockTimelineAsset,
isTrashed: boolean | undefined,
@@ -175,9 +171,9 @@ function shouldIncludeAsset(
return isFavorite === undefined || actuallyFavorited === isFavorite;
}
/**
- * Get summary for all buckets (mimics getTimeBuckets API)
- * When albumId is provided, only includes buckets that contain assets from that album
- */
+Get summary for all buckets (mimics getTimeBuckets API)
+When albumId is provided, only includes buckets that contain assets from that album
+*/
export function getTimeBuckets(
timelineData: MockTimelineData,
isTrashed: boolean | undefined,
@@ -279,9 +275,9 @@ const createDefaultOwner = (ownerId: string) => {
};
/**
- * Convert a TimelineAssetConfig to a full AssetResponseDto
- * This matches the response from GET /api/assets/:id
- */
+Convert a TimelineAssetConfig to a full AssetResponseDto
+This matches the response from GET /api/assets/:id
+*/
export function toAssetResponseDto(asset: MockTimelineAsset, owner?: UserResponseDto): AssetResponseDto {
const now = new Date().toISOString();
@@ -292,7 +288,7 @@ export function toAssetResponseDto(asset: MockTimelineAsset, owner?: UserRespons
make: null,
model: null,
exifImageWidth: asset.ratio > 1 ? 4000 : 3000,
- exifImageHeight: asset.ratio > 1 ? Math.round(4000 / asset.ratio) : Math.round(3000 * asset.ratio),
+ exifImageHeight: Math.round(asset.ratio > 1 ? 4000 : 3000 / asset.ratio),
fileSizeInByte: asset.fileSizeInByte,
orientation: '1',
dateTimeOriginal: asset.fileCreatedAt,
@@ -348,9 +344,9 @@ export function toAssetResponseDto(asset: MockTimelineAsset, owner?: UserRespons
}
/**
- * Get a single asset by ID from timeline data
- * This matches the response from GET /api/assets/:id
- */
+Get a single asset by ID from timeline data
+This matches the response from GET /api/assets/:id
+*/
export function getAsset(
timelineData: MockTimelineData,
assetId: string,
@@ -368,9 +364,9 @@ export function getAsset(
}
/**
- * Get a mock album from timeline data
- * This matches the response from GET /api/albums/:id
- */
+Get a mock album from timeline data
+This matches the response from GET /api/albums/:id
+*/
export function getAlbum(
timelineData: MockTimelineData,
ownerId: string,
diff --git a/e2e/src/ui/generators/timeline/timeline-config.ts b/e2e/src/ui/generators/timeline/timeline-config.ts
index d28d0c6d62..e5210634fc 100644
--- a/e2e/src/ui/generators/timeline/timeline-config.ts
+++ b/e2e/src/ui/generators/timeline/timeline-config.ts
@@ -57,9 +57,7 @@ export type MonthSpec = {
pattern: DayPattern;
};
-/**
- * Configuration for timeline data generation
- */
+/** Configuration for timeline data generation */
export type TimelineConfig = {
ownerId?: string;
months: MonthSpec[];
@@ -88,9 +86,7 @@ export type SerializedTimelineData = {
album: MockAlbum;
};
-/**
- * Validates a TimelineConfig object to ensure all values are within expected ranges
- */
+/** Validates a TimelineConfig object to ensure all values are within expected ranges */
export function validateTimelineConfig(config: TimelineConfig): void {
if (!config.months || config.months.length === 0) {
throw new Error('TimelineConfig must contain at least one month');
@@ -146,9 +142,7 @@ export function validateTimelineConfig(config: TimelineConfig): void {
}
}
-/**
- * Create a default timeline configuration
- */
+/** Create a default timeline configuration */
export function createDefaultTimelineConfig(): TimelineConfig {
const months: MonthSpec[] = [
// 2024 - Mix of patterns
diff --git a/e2e/src/ui/generators/timeline/utils.ts b/e2e/src/ui/generators/timeline/utils.ts
index 98ccdc661d..5bf11f5187 100644
--- a/e2e/src/ui/generators/timeline/utils.ts
+++ b/e2e/src/ui/generators/timeline/utils.ts
@@ -1,9 +1,7 @@
import { DateTime } from 'luxon';
import { GENERATION_CONSTANTS, MockTimelineAsset } from 'src/ui/generators/timeline/timeline-config.js';
-/**
- * Linear Congruential Generator for deterministic pseudo-random numbers
- */
+/** Linear Congruential Generator for deterministic pseudo-random numbers */
export class SeededRandom {
private seed: number;
@@ -11,38 +9,32 @@ export class SeededRandom {
this.seed = seed;
}
- /**
- * Generate next random number in range [0, 1)
- */
+ /** Generate next random number in range [0, 1) */
next(): number {
// LCG parameters from Numerical Recipes
this.seed = (this.seed * 1_664_525 + 1_013_904_223) % 2_147_483_647;
return this.seed / 2_147_483_647;
}
- /**
- * Generate random integer in range [min, max)
- */
+ /** Generate random integer in range [min, max) */
nextInt(min: number, max: number): number {
return Math.floor(this.next() * (max - min)) + min;
}
- /**
- * Generate random boolean with given probability
- */
+ /** Generate random boolean with given probability */
nextBoolean(probability = 0.5): boolean {
return this.next() < probability;
}
}
/**
- * Select random days using seed variation to avoid collisions.
- *
- * @param daysInMonth - Total number of days in the month
- * @param numDays - Number of days to select
- * @param rng - Random number generator instance
- * @returns Array of selected day numbers, sorted in descending order
- */
+Select random days using seed variation to avoid collisions.
+
+@param daysInMonth - Total number of days in the month
+@param numDays - Number of days to select
+@param rng - Random number generator instance
+@returns Array of selected day numbers, sorted in descending order
+*/
export function selectRandomDays(daysInMonth: number, numDays: number, rng: SeededRandom): number[] {
const selectedDays = new Set<number>();
const maxAttempts = numDays * GENERATION_CONSTANTS.MAX_SELECT_ATTEMPTS; // Safety limit
@@ -64,9 +56,7 @@ export function selectRandomDays(daysInMonth: number, numDays: number, rng: Seed
return [...selectedDays].toSorted((a, b) => b - a);
}
-/**
- * Select item from array using seeded random
- */
+/** Select item from array using seeded random */
export function selectRandom<T>(arr: T[], rng: SeededRandom): T {
if (arr.length === 0) {
throw new Error('Cannot select from empty array');
@@ -75,9 +65,7 @@ export function selectRandom<T>(arr: T[], rng: SeededRandom): T {
return arr[index];
}
-/**
- * Select multiple random items from array using seeded random without duplicates
- */
+/** Select multiple random items from array using seeded random without duplicates */
export function selectRandomMultiple<T>(arr: T[], count: number, rng: SeededRandom): T[] {
if (arr.length === 0) {
throw new Error('Cannot select from empty array');
@@ -104,11 +92,11 @@ export function selectRandomMultiple<T>(arr: T[], count: number, rng: SeededRand
}
/**
- * Parse timeBucket parameter to extract year-month key
- * Handles both formats:
- * - ISO timestamp: "2024-12-01T00:00:00.000Z" -> "2024-12-01"
- * - Simple format: "2024-12-01" -> "2024-12-01"
- */
+Parse timeBucket parameter to extract year-month key
+Handles both formats:
+- ISO timestamp: "2024-12-01T00:00:00.000Z" -> "2024-12-01"
+- Simple format: "2024-12-01" -> "2024-12-01"
+*/
export function parseTimeBucketKey(timeBucket: string): string {
if (!timeBucket) {
throw new Error('timeBucket parameter cannot be empty');
@@ -150,6 +138,7 @@ export function getMockAsset(
return null;
}
+ // eslint-disable-next-line unicorn/no-unnecessary-parameters
const isInDifferentPeriod = (date1: DateTime, date2: DateTime): boolean => {
if (unit === 'day') {
return !date1.startOf('day').equals(date2.startOf('day'));
diff --git a/e2e/src/ui/specs/asset-viewer/ocr.e2e-spec.ts b/e2e/src/ui/specs/asset-viewer/ocr.e2e-spec.ts
index 057c0d925c..abfa52d902 100644
--- a/e2e/src/ui/specs/asset-viewer/ocr.e2e-spec.ts
+++ b/e2e/src/ui/specs/asset-viewer/ocr.e2e-spec.ts
@@ -242,6 +242,7 @@ test.describe('OCR text interaction', () => {
return;
}
+ // eslint-disable-next-line unicorn/no-unnecessary-parameters
const createTouch = (id: number, x: number, y: number) => {
return new Touch({
identifier: id,
diff --git a/e2e/src/ui/specs/timeline/timeline.e2e-spec.ts b/e2e/src/ui/specs/timeline/timeline.e2e-spec.ts
index 29b008b3c8..903336ef04 100644
--- a/e2e/src/ui/specs/timeline/timeline.e2e-spec.ts
+++ b/e2e/src/ui/specs/timeline/timeline.e2e-spec.ts
@@ -150,10 +150,10 @@ test.describe('Timeline', () => {
});
test.describe('keyboard', () => {
/**
- * This text tests keyboard nativation, and also ensures that the scroll-to-asset behavior
- * scrolls the minimum amount. That is, if you are navigating using right arrow (auto scrolling
- * as necessary downwards), then the asset should always be at the lowest row of the grid.
- */
+ This text tests keyboard nativation, and also ensures that the scroll-to-asset behavior
+ scrolls the minimum amount. That is, if you are navigating using right arrow (auto scrolling
+ as necessary downwards), then the asset should always be at the lowest row of the grid.
+ */
test('Next/previous asset - ArrowRight/ArrowLeft', async ({ page }) => {
await pageUtils.openPhotosPage(page);
await thumbnailUtils.withAssetId(page, assets[0].id).focus();
diff --git a/e2e/src/utils.ts b/e2e/src/utils.ts
index c68de73cf9..02cce09835 100644
--- a/e2e/src/utils.ts
+++ b/e2e/src/utils.ts
@@ -270,13 +270,13 @@ export const utils = {
}
},
- waitForWebsocketEvent: ({ event, id, total: count, timeout: ms }: WaitOptions): Promise<void> => {
+ waitForWebsocketEvent: ({ event, id, total: count, timeout: ms = 10_000 }: WaitOptions): Promise<void> => {
return new Promise<void>((resolve, reject) => {
if (!id && !count) {
reject(new Error('id or count must be provided for waitForWebsocketEvent'));
}
- const timeout = setTimeout(() => reject(new Error(`Timed out waiting for ${event} event`)), ms || 10_000);
+ const timeout = setTimeout(() => reject(new Error(`Timed out waiting for ${event} event`)), ms);
const type = id ? `id=${id}` : `count=${count}`;
console.log(`Waiting for ${event} [${type}]`);
const set = events[event];
@@ -550,7 +550,7 @@ export const utils = {
{
headers: asBearerAuth(accessToken),
fetch: (...args: Parameters<typeof fetch>) =>
- // eslint-disable-next-line unicorn/no-invalid-argument-count, unicorn/prefer-await
+ // eslint-disable-next-line unicorn/prefer-await
fetch(...args).then((response) => {
setCookie = response.headers.getSetCookie();
return response;
@@ -660,10 +660,10 @@ export const utils = {
return !jobCounts.active && (!jobCounts.waiting || queues[queue].queueStatus.isPaused);
},
- waitForQueueFinish: (accessToken: string, queue: keyof QueuesResponseLegacyDto, ms?: number) => {
+ waitForQueueFinish: (accessToken: string, queue: keyof QueuesResponseLegacyDto, ms: number = 15_000) => {
// eslint-disable-next-line no-async-promise-executor
return new Promise<void>(async (resolve, reject) => {
- const timeout = setTimeout(() => reject(new Error('Timed out waiting for queue to empty')), ms || 15_000);
+ const timeout = setTimeout(() => reject(new Error('Timed out waiting for queue to empty')), ms);
while (true) {
const done = await utils.isQueueEmpty(accessToken, queue);
diff --git a/packages/cli/package.json b/packages/cli/package.json
index e9ae0517bb..b55e23cfba 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -33,7 +33,7 @@
"eslint": "^10.0.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.1.3",
- "eslint-plugin-unicorn": "^76.0.0",
+ "eslint-plugin-unicorn": "^78.0.0",
"globals": "^17.0.0",
"mock-fs": "^5.2.0",
"prettier": "^3.7.4",
diff --git a/packages/cli/src/queue.ts b/packages/cli/src/queue.ts
index 45e1c454f7..cfa0b81624 100644
--- a/packages/cli/src/queue.ts
+++ b/packages/cli/src/queue.ts
@@ -28,11 +28,11 @@ export const defaultQueueOptions = {
};
/**
- * An in-memory queue that processes tasks in parallel with a given concurrency.
- * @see {@link https://www.npmjs.com/package/fastq}
- * @template T - The type of the worker task data.
- * @template R - The type of the worker output data.
- */
+An in-memory queue that processes tasks in parallel with a given concurrency.
+@see {@link https://www.npmjs.com/package/fastq}
+@template T - The type of the worker task data.
+@template R - The type of the worker output data.
+*/
export class Queue<T, R> {
private readonly queue: fastq.queueAsPromised<string, Task<T, R>>;
private readonly store = new Map<string, Task<T, R>>();
@@ -40,10 +40,10 @@ export class Queue<T, R> {
readonly worker: (data: T) => Promise<R>;
/**
- * Create a new queue.
- * @param worker - The worker function that processes the task.
- * @param options - The queue options.
- */
+ Create a new queue.
+ @param worker - The worker function that processes the task.
+ @param options - The queue options.
+ */
constructor(worker: (data: T) => Promise<R>, options?: QueueOptions) {
this.options = { ...defaultQueueOptions, ...options };
this.worker = worker;
@@ -65,21 +65,21 @@ export class Queue<T, R> {
}
/**
- * Wait for the queue to be empty.
- * @returns Promise<void> - The returned Promise will be resolved when all tasks in the queue have been processed by a worker.
- * This promise could be ignored as it will not lead to a `unhandledRejection`.
- */
+ Wait for the queue to be empty.
+ @returns Promise<void> - The returned Promise will be resolved when all tasks in the queue have been processed by a worker.
+ This promise could be ignored as it will not lead to a `unhandledRejection`.
+ */
drained(): Promise<void> {
return this.queue.drained();
}
/**
- * Add a task at the end of the queue.
- * @see {@link https://www.npmjs.com/package/fastq}
- * @param data
- * @returns Promise<void> - A Promise that will be fulfilled (rejected) when the task is completed successfully (unsuccessfully).
- * This promise could be ignored as it will not lead to a `unhandledRejection`.
- */
+ Add a task at the end of the queue.
+ @see {@link https://www.npmjs.com/package/fastq}
+ @param data
+ @returns Promise<void> - A Promise that will be fulfilled (rejected) when the task is completed successfully (unsuccessfully).
+ This promise could be ignored as it will not lead to a `unhandledRejection`.
+ */
async push(data: T): Promise<Task<T, R>> {
const id = uniqueId();
const task: Task<T, R> = { id, status: 'idle', error: undefined, count: 0, data, result: undefined };
diff --git a/packages/cli/src/utils.ts b/packages/cli/src/utils.ts
index a49cede3be..2897a1ae27 100644
--- a/packages/cli/src/utils.ts
+++ b/packages/cli/src/utils.ts
@@ -218,9 +218,9 @@ export const sha1 = (filepath: string) => {
};
/**
- * Batches items and calls onBatch to process them
- * when the batch size is reached or the debounce time has passed.
- */
+Batches items and calls onBatch to process them
+when the batch size is reached or the debounce time has passed.
+*/
export class Batcher<T = unknown> {
private items: T[] = [];
private readonly batchSize: number;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6f491842b9..73392e7ffd 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -316,8 +316,8 @@ importers:
specifier: ^5.1.3
eslint-plugin-unicorn:
- specifier: ^76.0.0
+ specifier: ^78.0.0
exiftool-vendored:
specifier: ^39.0.0
version: 39.0.1
@@ -431,8 +431,8 @@ importers:
specifier: ^5.1.3
eslint-plugin-unicorn:
- specifier: ^76.0.0
+ specifier: ^78.0.0
globals:
specifier: ^17.0.0
version: 17.13.0
@@ -909,8 +909,8 @@ importers:
specifier: ^5.1.3
eslint-plugin-unicorn:
- specifier: ^76.0.0
+ specifier: ^78.0.0
globals:
specifier: ^17.0.0
version: 17.13.0
@@ -1180,8 +1180,8 @@ importers:
specifier: ^3.23.1
eslint-plugin-unicorn:
- specifier: ^76.0.0
+ specifier: ^78.0.0
factory.ts:
specifier: ^1.4.1
version: 1.4.2
@@ -7731,11 +7731,15 @@ packages:
svelte:
optional: true
- resolution: {integrity: sha512-3ywJrCMHKYhcBP5yFzGaOOX3dY7+iR3hvpuoS/0EnhRFgVWLejly+t4fOdJvWQxJdHZl1C+QBW7hybXPDld4Pw==}
+ resolution: {integrity: sha512-XTDqxcJeAmh2lhgU75TpuMDdFtPDnAU+DCW56nR5UzXTG+uOyvOGjV80O11my7kNb2bYSCPlWa8c4K8/rwlYog==}
engines: {node: '>=22'}
peerDependencies:
eslint: '>=10.4'
+ typescript: '*'
+ peerDependenciesMeta:
+ typescript:
+ optional: true
resolution: {integrity: sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==}
@@ -9725,6 +9729,9 @@ packages:
resolution: {integrity: sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==}
+ resolution: {integrity: sha512-Pa2ljlsEL6sVwFaYeyrOLSYbQt73JvGbPOYFq+9AElXiSnfI5Q4465RRZ1sHv7lDjDOnGRDDaqPXqClqWK/q1Q==}
+
resolution: {integrity: sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==}
@@ -9758,8 +9765,8 @@ packages:
resolution: {integrity: sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==}
- resolution: {integrity: sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==}
+ resolution: {integrity: sha512-oGYfQzHSG5dOMovQcJ3fyTmZlWAWpi0XA0sJwJs+i6OT88o1+Jtw/8z0CmdowSLxGhhFK89rQ/oXph/wN02PNw==}
resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==}
@@ -20909,7 +20916,7 @@ snapshots:
transitivePeerDependencies:
- ts-node
dependencies:
'@eslint-community/eslint-utils': 4.10.1([email protected]([email protected])([email protected]))
'@eslint/css-tree': 4.1.1
@@ -20925,6 +20932,8 @@ snapshots:
identifier-regex: 1.1.0
indent-string: 5.0.0
is-builtin-module: 5.0.0
+ micromark: 4.0.3([email protected])
+ parse5: 8.0.1
pluralize: 8.0.0
quote-js-string: 0.1.0
regjsparser: 0.13.4
@@ -20932,6 +20941,10 @@ snapshots:
semver: 7.8.5
strip-indent: 4.1.1
yaml: 2.9.1
+ optionalDependencies:
+ typescript: '@typescript/[email protected]'
+ transitivePeerDependencies:
+ - supports-color
dependencies:
@@ -23013,7 +23026,7 @@ snapshots:
decode-named-character-reference: 1.3.0
devlop: 1.1.0
mdast-util-to-string: 4.0.0
- micromark: 4.0.2([email protected])
+ micromark: 4.0.3([email protected])
micromark-util-decode-numeric-character-reference: 2.0.2
micromark-util-decode-string: 2.0.1
micromark-util-normalize-identifier: 2.0.1
@@ -23492,6 +23505,10 @@ snapshots:
micromark-util-decode-numeric-character-reference: 2.0.2
micromark-util-symbol: 2.0.1
+ dependencies:
+ micromark-util-types: 2.0.2
+
@@ -23535,7 +23552,7 @@ snapshots:
dependencies:
'@types/debug': 4.1.13
debug: 4.4.3([email protected])
@@ -23547,6 +23564,7 @@ snapshots:
micromark-util-chunked: 2.0.1
micromark-util-combine-extensions: 2.0.1
micromark-util-decode-numeric-character-reference: 2.0.2
+ micromark-util-edit-map: 1.0.0
micromark-util-encode: 2.0.1
micromark-util-normalize-identifier: 2.0.1
micromark-util-resolve-all: 2.0.1
diff --git a/server/package.json b/server/package.json
index 72f3b64498..d8c9d2bcec 100644
--- a/server/package.json
+++ b/server/package.json
@@ -156,7 +156,7 @@
"eslint-import-resolver-typescript": "^4.4.5",
"eslint-plugin-import-x": "^4.17.1",
"eslint-plugin-prettier": "^5.1.3",
- "eslint-plugin-unicorn": "^76.0.0",
+ "eslint-plugin-unicorn": "^78.0.0",
"globals": "^17.0.0",
"mock-fs": "^5.2.0",
"pngjs": "^7.0.0",
diff --git a/server/src/app.common.ts b/server/src/app.common.ts
index bf796efc8d..9d1960457f 100644
--- a/server/src/app.common.ts
+++ b/server/src/app.common.ts
@@ -28,14 +28,12 @@ export async function configureExpress(
ssr,
}: {
/**
- * Whether to allow swagger module to write to the specs.json
- * This is not desirable when the API is not available
- * @default true
- */
+ Whether to allow swagger module to write to the specs.json
+ This is not desirable when the API is not available
+ @default true
+ */
permitSwaggerWrite?: boolean;
- /**
- * Service to use for server-side rendering
- */
+ /** Service to use for server-side rendering */
ssr: typeof ApiService | typeof MaintenanceWorkerService;
},
) {
diff --git a/server/src/commands/media-location.command.ts b/server/src/commands/media-location.command.ts
index 8c39eb0b60..228812a20c 100644
--- a/server/src/commands/media-location.command.ts
+++ b/server/src/commands/media-location.command.ts
@@ -102,7 +102,7 @@ export class PromptConfirmMoveQuestions {
message: 'Do you want to proceed? [Y/n]',
name: 'value',
})
- value(value: string): boolean {
- return ['yes', 'y'].includes((value || 'y').toLowerCase());
+ value(value: string = 'y'): boolean {
+ return ['yes', 'y'].includes(value.toLowerCase());
}
}
diff --git a/server/src/decorators.ts b/server/src/decorators.ts
index 4a44ad91f1..895a71cb67 100644
--- a/server/src/decorators.ts
+++ b/server/src/decorators.ts
@@ -31,11 +31,11 @@ export const UpdatedAtTrigger = (name: string) =>
export const DATABASE_PARAMETER_CHUNK_SIZE = 65_500;
/**
- * Chunks an array or set into smaller collections of the same type and specified size.
- *
- * @param collection The collection to chunk.
- * @param size The size of each chunk.
- */
+Chunks an array or set into smaller collections of the same type and specified size.
+
+@param collection The collection to chunk.
+@param size The size of each chunk.
+*/
function chunks<T>(collection: Array<T>, size: number): Array<Array<T>>;
function chunks<T>(collection: Set<T>, size: number): Array<Set<T>>;
function chunks<T>(collection: Array<T> | Set<T>, size: number): Array<Array<T>> | Array<Set<T>> {
@@ -59,12 +59,12 @@ function chunks<T>(collection: Array<T> | Set<T>, size: number): Array<Array<T>>
}
/**
- * Wraps a method that takes a collection of parameters and sequentially calls it with chunks of the collection,
- * to overcome the maximum number of parameters allowed by the database driver.
- *
- * @param options.paramIndex The index of the function parameter to chunk. Defaults to 0.
- * @param options.flatten Whether to flatten the results. Defaults to false.
- */
+Wraps a method that takes a collection of parameters and sequentially calls it with chunks of the collection,
+to overcome the maximum number of parameters allowed by the database driver.
+
+@param options.paramIndex The index of the function parameter to chunk. Defaults to 0.
+@param options.flatten Whether to flatten the results. Defaults to false.
+*/
export function Chunked(
options: { paramIndex?: number; chunkSize?: number; mergeFn?: (results: any) => any } = {},
): MethodDecorator {
diff --git a/server/src/dtos/asset-media.dto.ts b/server/src/dtos/asset-media.dto.ts
index d4eb397bed..d8289e70a0 100644
--- a/server/src/dtos/asset-media.dto.ts
+++ b/server/src/dtos/asset-media.dto.ts
@@ -8,9 +8,9 @@ import { JsonParsed, isoDatetimeToDate, stringToBool } from 'src/validation.js';
export enum AssetMediaSize {
Original = 'original',
/**
- * An full-sized image extracted/converted from non-web-friendly formats like RAW/HIF.
- * or otherwise the original image itself.
- */
+ An full-sized image extracted/converted from non-web-friendly formats like RAW/HIF.
+ or otherwise the original image itself.
+ */
FULLSIZE = 'fullsize',
PREVIEW = 'preview',
THUMBNAIL = 'thumbnail',
@@ -41,9 +41,9 @@ const AssetMediaBaseSchema = z.object({
duration: z.coerce.number().int().min(0).optional().describe('Duration in milliseconds (for videos)'),
filename: z.string().optional().describe('Filename'),
/**
- * The properties below are added to correctly generate the API docs and client SDKs. Validation should be handled
- * in the controller. File parts never reach the request body, so they must be optional here
- */
+ The properties below are added to correctly generate the API docs and client SDKs. Validation should be handled
+ in the controller. File parts never reach the request body, so they must be optional here
+ */
[UploadFieldName.ASSET_DATA]: z
.any()
.optional()
diff --git a/server/src/dtos/env.dto.ts b/server/src/dtos/env.dto.ts
index 71658a6bfb..f15c587378 100644
--- a/server/src/dtos/env.dto.ts
+++ b/server/src/dtos/env.dto.ts
@@ -14,10 +14,10 @@ enum DatabaseSslMode {
const DatabaseSslModeSchema = z.enum(DatabaseSslMode).describe('Database SSL mode').meta({ id: 'DatabaseSslMode' });
const absolutePath = z.string().regex(/^\//, 'Must be an absolute path').optional();
/**
- * Treat certain strings as booleans and coerce them to boolean
- * Ideal for environment variables that are strings but should be treated as booleans
- * @docs https://zod.dev/api?id=stringbool
- */
+Treat certain strings as booleans and coerce them to boolean
+Ideal for environment variables that are strings but should be treated as booleans
+@docs https://zod.dev/api?id=stringbool
+*/
const stringBool = z.stringbool();
const trustedProxiesSchema = z
diff --git a/server/src/dtos/search.dto.ts b/server/src/dtos/search.dto.ts
index be39fd24a0..3f11e01fe9 100644
--- a/server/src/dtos/search.dto.ts
+++ b/server/src/dtos/search.dto.ts
@@ -323,9 +323,9 @@ export const isFullyAlbumConfined = (filter: SearchFilter): boolean =>
isAlbumConfined(filter) || (!!filter.or?.length && filter.or.every((branch) => isAlbumConfined(branch)));
/**
- * The structured shape and the deprecated flat search fields are mutually exclusive
- * TODO(v4): remove together with the deprecated flat fields.
- */
+The structured shape and the deprecated flat search fields are mutually exclusive
+TODO(v4): remove together with the deprecated flat fields.
+*/
const withShapeExclusivity = <T extends z.ZodObject<z.ZodRawShape>>(schema: T) => {
const deprecatedFields = Object.keys(schema.shape).filter(
(field) => (schema.shape[field] as z.ZodType).meta()?.deprecated,
diff --git a/server/src/enum.ts b/server/src/enum.ts
index 0d724ce7b0..683f3ca1be 100644
--- a/server/src/enum.ts
+++ b/server/src/enum.ts
@@ -59,9 +59,7 @@ export enum ChecksumAlgorithm {
}
export enum AssetFileType {
- /**
- * An full/large-size image extracted/converted from RAW photos
- */
+ /** An full/large-size image extracted/converted from RAW photos */
FullSize = 'fullsize',
Preview = 'preview',
Thumbnail = 'thumbnail',
@@ -362,9 +360,9 @@ export enum SharedLinkType {
Album = 'ALBUM',
/**
- * Individual asset
- * or group of assets that are not in an album
- */
+ Individual asset
+ or group of assets that are not in an album
+ */
Individual = 'INDIVIDUAL',
}
@@ -818,9 +816,9 @@ export enum DvProfile {
}
/**
- * Dolby Vision base-layer signal-compatibility ID from the DOVI configuration record.
- * Identifies what the base HEVC/AVC layer renders as on a non-DV decoder.
- */
+Dolby Vision base-layer signal-compatibility ID from the DOVI configuration record.
+Identifies what the base HEVC/AVC layer renders as on a non-DV decoder.
+*/
export enum DvSignalCompatibility {
None = 0,
Hdr10 = 1,
@@ -1227,9 +1225,7 @@ export enum AssetVisibility {
Archive = 'archive',
Timeline = 'timeline',
- /**
- * Video part of the LivePhotos and MotionPhotos
- */
+ /** Video part of the LivePhotos and MotionPhotos */
Hidden = 'hidden',
Locked = 'locked',
}
diff --git a/server/src/main.ts b/server/src/main.ts
index f1027b7408..540358c66b 100644
--- a/server/src/main.ts
+++ b/server/src/main.ts
@@ -10,23 +10,15 @@ import { SystemMetadataRepository } from 'src/repositories/system-metadata.repos
import { type DB } from 'src/schema/index.js';
import { getKyselyConfig } from 'src/utils/database.js';
-/**
- * Manages worker lifecycle
- */
+/** Manages worker lifecycle */
class Workers {
- /**
- * Currently running workers
- */
+ /** Currently running workers */
workers: Partial<Record<ImmichWorker, { kill: (signal: NodeJS.Signals) => Promise<void> | void }>> = {};
- /**
- * Fail-safe in case anything dies during restart
- */
+ /** Fail-safe in case anything dies during restart */
restarting = false;
- /**
- * Boot all enabled workers
- */
+ /** Boot all enabled workers */
async bootstrap() {
const isMaintenanceMode = await this.isMaintenanceMode();
const { workers } = new ConfigRepository().getEnv();
@@ -92,9 +84,9 @@ class Workers {
}
/**
- * Start an individual worker
- * @param name Worker
- */
+ Start an individual worker
+ @param name Worker
+ */
private startWorker(name: ImmichWorker) {
console.log(`Starting ${name} worker`);
diff --git a/server/src/maintenance/maintenance-worker.controller.ts b/server/src/maintenance/maintenance-worker.controller.ts
index ac814812f2..84eef08ed4 100644
--- a/server/src/maintenance/maintenance-worker.controller.ts
+++ b/server/src/maintenance/maintenance-worker.controller.ts
@@ -43,9 +43,7 @@ export class MaintenanceWorkerController {
private databaseBackupService: DatabaseBackupService,
) {}
- /**
- * {@link _ServerController.getServerConfig }
- */
+ /** {@link _ServerController.getServerConfig } */
@Get('server/config')
getServerConfig(): ServerConfigDto {
return this.service.getSystemConfig();
@@ -61,18 +59,14 @@ export class MaintenanceWorkerController {
return this.service.getVersion();
}
- /**
- * {@link _DatabaseBackupController.listDatabaseBackups}
- */
+ /** {@link _DatabaseBackupController.listDatabaseBackups} */
@Get('admin/database-backups')
@MaintenanceRoute()
listDatabaseBackups(): Promise<DatabaseBackupListResponseDto> {
return this.databaseBackupService.listBackups();
}
- /**
- * {@link _DatabaseBackupController.downloadDatabaseBackup}
- */
+ /** {@link _DatabaseBackupController.downloadDatabaseBackup} */
@Get('admin/database-backups/:filename')
@MaintenanceRoute()
async downloadDatabaseBackup(
@@ -83,18 +77,14 @@ export class MaintenanceWorkerController {
await sendFile(res, next, () => this.databaseBackupService.downloadBackup(filename), this.logger);
}
- /**
- * {@link _DatabaseBackupController.deleteDatabaseBackup}
- */
+ /** {@link _DatabaseBackupController.deleteDatabaseBackup} */
@Delete('admin/database-backups')
@MaintenanceRoute()
async deleteDatabaseBackup(@Body() dto: DatabaseBackupDeleteDto): Promise<void> {
return this.databaseBackupService.deleteBackup(dto.backups);
}
- /**
- * {@link _DatabaseBackupController.uploadDatabaseBackup}
- */
+ /** {@link _DatabaseBackupController.uploadDatabaseBackup} */
@Post('admin/database-backups/upload')
@MaintenanceRoute()
@UseInterceptors(FileInterceptor('file'))
diff --git a/server/src/maintenance/maintenance-worker.service.spec.ts b/server/src/maintenance/maintenance-worker.service.spec.ts
index e814aafb28..9d131be08a 100644
--- a/server/src/maintenance/maintenance-worker.service.spec.ts
+++ b/server/src/maintenance/maintenance-worker.service.spec.ts
@@ -282,9 +282,7 @@ describe(MaintenanceWorkerService.name, () => {
describe.skip('setAction'); // just calls setStatus+runAction
- /**
- * Actions
- */
+ /** Actions */
describe('action: start', () => {
it('should not do anything', async () => {
diff --git a/server/src/maintenance/maintenance-worker.service.ts b/server/src/maintenance/maintenance-worker.service.ts
index 415c16f8b6..6e51ac61aa 100644
--- a/server/src/maintenance/maintenance-worker.service.ts
+++ b/server/src/maintenance/maintenance-worker.service.ts
@@ -33,9 +33,7 @@ import { getConfig } from 'src/utils/config.js';
import { createMaintenanceLoginUrl, detectPriorInstall } from 'src/utils/maintenance.js';
import { getExternalDomain } from 'src/utils/misc.js';
-/**
- * This service is available inside of maintenance mode to manage maintenance mode
- */
+/** This service is available inside of maintenance mode to manage maintenance mode */
@Injectable()
export class MaintenanceWorkerService {
#secret: string | null = null;
@@ -87,9 +85,7 @@ export class MaintenanceWorkerService {
}
}
- /**
- * {@link _BaseService.configRepos}
- */
+ /** {@link _BaseService.configRepos} */
private get configRepos() {
return {
configRepo: this.configRepository,
@@ -98,25 +94,19 @@ export class MaintenanceWorkerService {
};
}
- /**
- * {@link _BaseService.prototype.getConfig}
- */
+ /** {@link _BaseService.prototype.getConfig} */
private getConfig(options: { withCache: boolean }) {
return getConfig(this.configRepos, options);
}
- /**
- * {@link _ServerService.getSystemConfig}
- */
+ /** {@link _ServerService.getSystemConfig} */
getSystemConfig() {
return {
maintenanceMode: true,
} as ServerConfigDto;
}
- /**
- * {@link _VersionService.getVersion}
- */
+ /** {@link _VersionService.getVersion} */
getVersion() {
return ServerVersionResponseDto.fromSemVer(serverVersion);
}
@@ -125,9 +115,7 @@ export class MaintenanceWorkerService {
return { res: 'pong' };
}
- /**
- * {@link _ApiService.ssr}
- */
+ /** {@link _ApiService.ssr} */
ssr(excludePaths: string[]) {
const { resourcePaths } = this.configRepository.getEnv();
@@ -158,9 +146,7 @@ export class MaintenanceWorkerService {
};
}
- /**
- * {@link _StorageService.detectMediaLocation}
- */
+ /** {@link _StorageService.detectMediaLocation} */
detectMediaLocation(): string {
const envData = this.configRepository.getEnv();
if (envData.storage.mediaLocation) {
diff --git a/server/src/repositories/album.repository.ts b/server/src/repositories/album.repository.ts
index 6a97043c1e..72fb46ed16 100644
--- a/server/src/repositories/album.repository.ts
+++ b/server/src/repositories/album.repository.ts
@@ -227,12 +227,12 @@ export class AlbumRepository {
}
/**
- * Get asset IDs for the given album ID.
- *
- * @param albumId Album ID to get asset IDs for.
- * @param assetIds Optional list of asset IDs to filter on.
- * @returns Set of Asset IDs for the given album ID.
- */
+ Get asset IDs for the given album ID.
+
+ @param albumId Album ID to get asset IDs for.
+ @param assetIds Optional list of asset IDs to filter on.
+ @returns Set of Asset IDs for the given album ID.
+ */
@GenerateSql({ params: [DummyValue.UUID, [DummyValue.UUID]] })
@ChunkedSet({ paramIndex: 1 })
async getAssetIds(albumId: string, assetIds: string[]): Promise<Set<string>> {
@@ -348,13 +348,13 @@ export class AlbumRepository {
}
/**
- * Makes sure all thumbnails for albums are updated by:
- * - Removing thumbnails from albums without assets
- * - Removing references of thumbnails to assets outside the album
- * - Setting a thumbnail when none is set and the album contains assets
- *
- * @returns Amount of updated album thumbnails or undefined when unknown
- */
+ Makes sure all thumbnails for albums are updated by:
+ - Removing thumbnails from albums without assets
+ - Removing references of thumbnails to assets outside the album
+ - Setting a thumbnail when none is set and the album contains assets
+
+ @returns Amount of updated album thumbnails or undefined when unknown
+ */
async updateThumbnails(): Promise<number | undefined> {
// Subquery for getting a new thumbnail.
@@ -399,9 +399,9 @@ export class AlbumRepository {
}
/**
- * Get per-user asset contribution counts for a single album.
- * Excludes deleted assets, orders by count desc.
- */
+ Get per-user asset contribution counts for a single album.
+ Excludes deleted assets, orders by count desc.
+ */
@GenerateSql({ params: [DummyValue.UUID] })
getContributorCounts(id: string) {
return this.db
diff --git a/server/src/repositories/media.repository.ts b/server/src/repositories/media.repository.ts
index 7f3bcfc3ad..f46d9b90de 100644
--- a/server/src/repositories/media.repository.ts
+++ b/server/src/repositories/media.repository.ts
@@ -73,10 +73,10 @@ export class MediaRepository {
}
/**
- *
- * @param input file path to the input image
- * @returns ExtractResult if succeeded, or null if failed
- */
+
+ @param input file path to the input image
+ @returns ExtractResult if succeeded, or null if failed
+ */
async extract(input: string): Promise<ExtractResult | null> {
for (const { tag, format } of [
{ tag: 'JpgFromRaw2', format: RawExtractedFormat.Jpeg },
@@ -305,9 +305,9 @@ export class MediaRepository {
}
/**
- * Needed for accurate segments, especially when remuxing, seeking and/or VFR is involved.
- * Scanning packets for keyframes in JS is much faster than -skip_frame nokey since it avoids decoding the video.
- */
+ Needed for accurate segments, especially when remuxing, seeking and/or VFR is involved.
+ Scanning packets for keyframes in JS is much faster than -skip_frame nokey since it avoids decoding the video.
+ */
probePackets(input: string, streamIndex: number): Promise<VideoPacketInfo | null> {
const ffprobe = spawn(
'ffprobe',
diff --git a/server/src/services/integrity.service.ts b/server/src/services/integrity.service.ts
index 5013620564..52160e3d23 100644
--- a/server/src/services/integrity.service.ts
+++ b/server/src/services/integrity.service.ts
@@ -38,28 +38,28 @@ import { ImmichFileResponse } from 'src/utils/file.js';
import { batched, handlePromiseError } from 'src/utils/misc.js';
/**
- * Untracked Files:
- * Files are detected in /data/encoded-video, /data/library, /data/upload
- * Checked against the asset table
- * Files are detected in /data/thumbs
- * Checked against the asset_file table
- *
- * * Can perform download or delete of files
- *
- * Missing Files:
- * Paths are queried from asset(originalPath, encodedVideoPath), asset_file(path)
- * Check whether files exist on disk
- *
- * * Reports must include origin (asset or asset_file) & ID for further action
- * * Can perform trash (asset) or delete (asset_file)
- *
- * Checksum Mismatch:
- * Paths & checksums are queried from asset(originalPath, checksum)
- * Check whether files match checksum, missing files ignored
- *
- * * Reports must include origin (as above) for further action
- * * Can perform download or trash (asset)
- */
+Untracked Files:
+ Files are detected in /data/encoded-video, /data/library, /data/upload
+ Checked against the asset table
+ Files are detected in /data/thumbs
+ Checked against the asset_file table
+
+Can perform download or delete of files
+
+Missing Files:
+ Paths are queried from asset(originalPath, encodedVideoPath), asset_file(path)
+ Check whether files exist on disk
+
+Reports must include origin (asset or asset_file) & ID for further action
+Can perform trash (asset) or delete (asset_file)
+
+Checksum Mismatch:
+ Paths & checksums are queried from asset(originalPath, checksum)
+ Check whether files match checksum, missing files ignored
+
+Reports must include origin (as above) for further action
+Can perform download or trash (asset)
+*/
@Injectable()
export class IntegrityService extends BaseService {
diff --git a/server/src/services/job.service.ts b/server/src/services/job.service.ts
index 97f604af05..8c725e07e1 100644
--- a/server/src/services/job.service.ts
+++ b/server/src/services/job.service.ts
@@ -98,9 +98,7 @@ export class JobService extends BaseService {
}
}
- /**
- * Queue follow up jobs
- */
+ /** Queue follow up jobs */
private async onDone(item: JobItem) {
switch (item.name) {
case JobName.SidecarCheck: {
diff --git a/server/src/services/maintenance.service.ts b/server/src/services/maintenance.service.ts
index fbdd3d4f65..31399da7b5 100644
--- a/server/src/services/maintenance.service.ts
+++ b/server/src/services/maintenance.service.ts
@@ -18,9 +18,7 @@ import {
} from 'src/utils/maintenance.js';
import { getExternalDomain } from 'src/utils/misc.js';
-/**
- * This service is available outside of maintenance mode to manage maintenance mode
- */
+/** This service is available outside of maintenance mode to manage maintenance mode */
@Injectable()
export class MaintenanceService extends BaseService {
getMaintenanceMode(): Promise<MaintenanceModeState> {
diff --git a/server/src/services/media.service.ts b/server/src/services/media.service.ts
index 07ffb491c4..5cfaf29a6a 100644
--- a/server/src/services/media.service.ts
+++ b/server/src/services/media.service.ts
@@ -169,8 +169,7 @@ export class MediaService extends BaseService {
let thumbhash: Buffer | undefined = generated?.thumbhash;
if (!thumbhash) {
- const extractedImage = await this.extractOriginalImage(asset, config.image);
- const { info, data, colorspace } = extractedImage;
+ const { info, data, colorspace } = await this.extractOriginalImage(asset, config.image);
thumbhash = await this.mediaRepository.generateThumbhash(
{ data, info },
@@ -290,8 +289,8 @@ export class MediaService extends BaseService {
private async generateImageThumbnails(asset: ThumbnailAsset, { image }: SystemConfig, useEdits: boolean = false) {
// Handle embedded preview extraction for RAW files
- const extractedImage = await this.extractOriginalImage(asset, image, useEdits);
- const { info, data, colorspace, generateFullsize, convertFullsize, extracted, isTransparent } = extractedImage;
+ const { info, data, colorspace, generateFullsize, convertFullsize, extracted, isTransparent } =
+ await this.extractOriginalImage(asset, image, useEdits);
const previewFormat = image.preview.format;
this.warnOnTransparencyLoss(isTransparent, previewFormat, asset.id);
diff --git a/server/src/services/storage-template.service.ts b/server/src/services/storage-template.service.ts
index 79299ac163..74869a5a14 100644
--- a/server/src/services/storage-template.service.ts
+++ b/server/src/services/storage-template.service.ts
@@ -268,7 +268,7 @@ export class StorageTemplateService extends BaseService {
private async getTemplatePath(
asset: StorageAsset,
metadata: MoveAssetMetadata,
- stillPhoto?: StorageAsset,
+ stillPhoto: StorageAsset = asset,
): Promise<string> {
const { storageLabel, filename } = metadata;
@@ -310,7 +310,7 @@ export class StorageTemplateService extends BaseService {
let albumName = null;
let albumStartDate = null;
let albumEndDate = null;
- const assetForMetadata = stillPhoto || asset;
+ const assetForMetadata = stillPhoto;
if (this.template.needsAlbum) {
// For motion videos, use the still photo's album information since motion videos
@@ -360,19 +360,19 @@ export class StorageTemplateService extends BaseService {
}
/**
- * In case of migrating duplicate filename to a new path, we need to check if it is already migrated
- * Due to the mechanism of appending +1, +2, +3, etc to the filename
- *
- * Example:
- * Source = upload/abc/def/FullSizeRender+7.heic
- * Expected Destination = upload/abc/def/FullSizeRender.heic
- *
- * The file is already at the correct location, but since there are other FullSizeRender.heic files in the
- * destination, it was renamed to FullSizeRender+7.heic.
- *
- * The lines below will be used to check if the differences between the source and destination is only the
- * +7 suffix, and if so, it will be considered as already migrated.
- */
+ In case of migrating duplicate filename to a new path, we need to check if it is already migrated
+ Due to the mechanism of appending +1, +2, +3, etc to the filename
+
+ Example:
+ Source = upload/abc/def/FullSizeRender+7.heic
+ Expected Destination = upload/abc/def/FullSizeRender.heic
+
+ The file is already at the correct location, but since there are other FullSizeRender.heic files in the
+ destination, it was renamed to FullSizeRender+7.heic.
+
+ The lines below will be used to check if the differences between the source and destination is only the
+ +7 suffix, and if so, it will be considered as already migrated.
+ */
if (source.startsWith(fullPath) && source.endsWith(`.${extension}`)) {
const diff = source.replace(fullPath, '').replace(`.${extension}`, '');
const hasDuplicationAnnotation = /^\+\d+$/.test(diff);
diff --git a/server/src/services/system-config.service.spec.ts b/server/src/services/system-config.service.spec.ts
index f4b72831b1..0f7e297f1e 100644
--- a/server/src/services/system-config.service.spec.ts
+++ b/server/src/services/system-config.service.spec.ts
@@ -420,14 +420,14 @@ describe(SystemConfigService.name, () => {
},
];
- for (const { should, externalDomain, result } of externalDomainTests) {
+ for (const { should, externalDomain, result = 'https://demo.immich.app' } of externalDomainTests) {
it(`should normalize an external domain ${should}`, async () => {
mocks.config.getEnv.mockReturnValue(mockEnvData({ configFile: 'immich-config.json' }));
const partialConfig = { server: { externalDomain } };
mocks.systemMetadata.readFile.mockResolvedValue(JSON.stringify(partialConfig));
const config = await sut.getAdminConfig();
- expect(config.server.externalDomain).toEqual(result ?? 'https://demo.immich.app');
+ expect(config.server.externalDomain).toEqual(result);
});
}
diff --git a/server/src/services/workflow-execution.service.ts b/server/src/services/workflow-execution.service.ts
index dbfa383591..b8149aa9b2 100644
--- a/server/src/services/workflow-execution.service.ts
+++ b/server/src/services/workflow-execution.service.ts
@@ -98,7 +98,6 @@ export class WorkflowExecutionService extends BaseService {
throw new Error('Hostname did not match any listed in methods[].allowedHosts in the plugin manifest');
}
- // eslint-disable-next-line unicorn/no-invalid-argument-count
const res = await fetch(...args);
return {
diff --git a/server/src/utils/database.ts b/server/src/utils/database.ts
index 51aac25b19..2d0b30a97b 100644
--- a/server/src/utils/database.ts
+++ b/server/src/utils/database.ts
@@ -355,8 +355,8 @@ export function withTags(eb: ExpressionBuilder<DB, 'asset'>) {
).as('tags');
}
-export function truncatedDate<O>(order: AssetOrderBy = AssetOrderBy.TakenAt, size?: 'DAY' | 'MONTH') {
- return sql<O>`date_trunc(${sql.lit(size ?? 'MONTH')}, ${sql.ref(order === AssetOrderBy.CreatedAt ? 'asset.createdAt' : 'localDateTime')} AT TIME ZONE 'UTC') AT TIME ZONE 'UTC'`;
+export function truncatedDate<O>(order: AssetOrderBy = AssetOrderBy.TakenAt, size: 'DAY' | 'MONTH' = 'MONTH') {
+ return sql<O>`date_trunc(${sql.lit(size)}, ${sql.ref(order === AssetOrderBy.CreatedAt ? 'asset.createdAt' : 'localDateTime')} AT TIME ZONE 'UTC') AT TIME ZONE 'UTC'`;
}
export function withTagId<O>(qb: SelectQueryBuilder<DB, 'asset', O>, tagId: string) {
@@ -1106,14 +1106,14 @@ export type ReindexVectorIndexOptions = { indexName: string; lists?: number };
type VectorIndexQueryOptions = { table: string; vectorExtension: VectorExtension } & ReindexVectorIndexOptions;
-export function vectorIndexQuery({ vectorExtension, table, indexName, lists }: VectorIndexQueryOptions): string {
+export function vectorIndexQuery({ vectorExtension, table, indexName, lists = 1 }: VectorIndexQueryOptions): string {
switch (vectorExtension) {
case DatabaseExtension.VectorChord: {
return `
CREATE INDEX IF NOT EXISTS ${indexName} ON ${table} USING vchordrq (embedding vector_cosine_ops) WITH (options = $$
residual_quantization = false
[build.internal]
- lists = [${lists ?? 1}]
+ lists = [${lists}]
spherical_centroids = true
build_threads = 4
sampling_factor = 1024
diff --git a/server/src/utils/date.ts b/server/src/utils/date.ts
index 0116055803..d978cd4e63 100644
--- a/server/src/utils/date.ts
+++ b/server/src/utils/date.ts
@@ -1,23 +1,17 @@
import { DateTime } from 'luxon';
import { isoDateToDate, isoDatetimeToDate } from 'src/validation.js';
-/**
- * Convert a date to a ISO 8601 datetime string.
- */
+/** Convert a date to a ISO 8601 datetime string. */
export const asDateTimeString = <T extends Date | string | undefined | null>(x: T) => {
return x instanceof Date ? isoDatetimeToDate.encode(x) : (x as Exclude<T, Date>);
};
-/**
- * Convert a date to a date string (yyyy-mm-dd).
- */
+/** Convert a date to a date string (yyyy-mm-dd). */
export const asDateString = (x: Date | string | null): string | null => {
return x instanceof Date ? isoDateToDate.encode(x) : x;
};
-/**
- * People born on February 29th are celebrated on February 28th in non-leap years.
- */
+/** People born on February 29th are celebrated on February 28th in non-leap years. */
export const isLeapDayObserved = ({ year, month, day }: { year: number; month: number; day: number }) => {
return month === 2 && day === 28 && !DateTime.local(year).isInLeapYear;
};
diff --git a/server/src/utils/duplicate.ts b/server/src/utils/duplicate.ts
index 9bf076657c..908dc4fcb4 100644
--- a/server/src/utils/duplicate.ts
+++ b/server/src/utils/duplicate.ts
@@ -1,27 +1,27 @@
import { AssetResponseDto } from 'src/dtos/asset-response.dto.js';
/**
- * Counts all truthy values in the exifInfo object.
- * This matches the client implementation in web/src/lib/utils/exif-utils.ts
- *
- * @param asset Asset with optional exifInfo
- * @returns Count of truthy EXIF values
- */
+Counts all truthy values in the exifInfo object.
+This matches the client implementation in web/src/lib/utils/exif-utils.ts
+
+@param asset Asset with optional exifInfo
+@returns Count of truthy EXIF values
+*/
export const getExifCount = (asset: AssetResponseDto): number => {
return Object.values(asset.exifInfo ?? {}).filter(Boolean).length;
};
/**
- * Suggests the best duplicate asset to keep from a list of duplicates.
- * This is a direct port of the client logic from web/src/lib/utils/duplicate-utils.ts
- *
- * The best asset is determined by the following criteria:
- * 1. Largest image file size in bytes
- * 2. Largest count of EXIF data (as tie-breaker)
- *
- * @param assets List of duplicate assets
- * @returns The best asset to keep, or undefined if empty list
- */
+Suggests the best duplicate asset to keep from a list of duplicates.
+This is a direct port of the client logic from web/src/lib/utils/duplicate-utils.ts
+
+The best asset is determined by the following criteria:
+ 1. Largest image file size in bytes
+ 2. Largest count of EXIF data (as tie-breaker)
+
+@param assets List of duplicate assets
+@returns The best asset to keep, or undefined if empty list
+*/
export const suggestDuplicate = (assets: AssetResponseDto[]): AssetResponseDto | undefined => {
if (assets.length === 0) {
return undefined;
@@ -48,12 +48,12 @@ export const suggestDuplicate = (assets: AssetResponseDto[]): AssetResponseDto |
};
/**
- * Suggests the best duplicate asset IDs to keep from a list of duplicates.
- * Returns an array with a single asset ID (the best candidate), or empty if no assets.
- *
- * @param assets List of duplicate assets
- * @returns Array of suggested asset IDs to keep (0 or 1 element)
- */
+Suggests the best duplicate asset IDs to keep from a list of duplicates.
+Returns an array with a single asset ID (the best candidate), or empty if no assets.
+
+@param assets List of duplicate assets
+@returns Array of suggested asset IDs to keep (0 or 1 element)
+*/
export const suggestDuplicateKeepAssetIds = (assets: AssetResponseDto[]): string[] => {
const suggested = suggestDuplicate(assets);
return suggested ? [suggested.id] : [];
diff --git a/server/src/utils/media.ts b/server/src/utils/media.ts
index 0d92aeb659..6493c2782f 100644
--- a/server/src/utils/media.ts
+++ b/server/src/utils/media.ts
@@ -71,6 +71,7 @@ export class BaseConfig implements VideoCodecSWConfig {
readonly presets = ['veryslow', 'slower', 'slow', 'medium', 'fast', 'faster', 'veryfast', 'superfast', 'ultrafast'];
protected constructor(
protected config: ConfigFFmpegDto,
+ // eslint-disable-next-line unicorn/no-object-as-default-parameter
protected tune: VideoTuning = { strictGop: false, lowLatency: false },
) {}
diff --git a/server/src/utils/mime-types.ts b/server/src/utils/mime-types.ts
index ce68361f95..a061059ed5 100644
--- a/server/src/utils/mime-types.ts
+++ b/server/src/utils/mime-types.ts
@@ -35,10 +35,10 @@ const raw = {
};
/**
- * list of supported image extensions from https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types excluding svg
- * @TODO share with the client
- * @see {@link web/src/lib/utils/asset-utils.ts#L329}
- **/
+list of supported image extensions from https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types excluding svg
+@TODO share with the client
+@see {@link web/src/lib/utils/asset-utils.ts#L329}
+*/
const webSupportedImage = {
'.avif': ['image/avif'],
'.bmp': ['image/bmp'],
diff --git a/server/src/utils/misc.ts b/server/src/utils/misc.ts
index dd2b5763bc..2197067923 100644
--- a/server/src/utils/misc.ts
+++ b/server/src/utils/misc.ts
@@ -52,9 +52,7 @@ export const getMethodNames = (instance: any) => {
export const getExternalDomain = (server: SystemConfig['server'], defaultDomain = 'https://my.immich.app') =>
server.externalDomain || defaultDomain;
-/**
- * @returns a list of strings representing the keys of the object in dot notation
- */
+/** @returns a list of strings representing the keys of the object in dot notation */
export const getKeysDeep = (target: unknown, path: string[] = []) => {
if (!target || typeof target !== 'object') {
return [];
diff --git a/server/src/utils/object.ts b/server/src/utils/object.ts
index 1d74dec6b9..672bb70251 100644
--- a/server/src/utils/object.ts
+++ b/server/src/utils/object.ts
@@ -1,15 +1,11 @@
import { isEqual, isPlainObject } from 'lodash-es';
-/**
- * Deeply clones and converts a class instance to a plain object.
- */
+/** Deeply clones and converts a class instance to a plain object. */
export function toPlainObject<T extends object>(obj: T): T {
return isPlainObject(obj) ? obj : structuredClone(obj);
}
-/**
- * Performs a deep comparison between objects, converting them to plain objects first if needed.
- */
+/** Performs a deep comparison between objects, converting them to plain objects first if needed. */
export function isEqualObject(value: object, other: object): boolean {
return isEqual(toPlainObject(value), toPlainObject(other));
}
diff --git a/server/src/utils/search-filter.ts b/server/src/utils/search-filter.ts
index 674947a087..cd8f7b7759 100644
--- a/server/src/utils/search-filter.ts
+++ b/server/src/utils/search-filter.ts
@@ -25,9 +25,7 @@ const canMatch = <T>(condition: EnumCondition<T>, value: T): boolean => {
);
};
-/**
- * The conditions that decide which `field` values the filter can return. A top-level condition decides alone, otherwise each branch itself.
- */
+/** The conditions that decide which `field` values the filter can return. A top-level condition decides alone, otherwise each branch itself. */
const decidingConditions = <F extends EnumField>(filter: SearchFilter, field: F) => {
if (filter[field] !== undefined) {
return [filter[field]];
@@ -39,9 +37,9 @@ const decidingConditions = <F extends EnumField>(filter: SearchFilter, field: F)
};
/**
- * Keeps locked assets out of search results unless the session is elevated: a filter that asks for
- * them is rejected with 401, and any other filter gets `visibility != locked` ANDed in.
- */
+Keeps locked assets out of search results unless the session is elevated: a filter that asks for
+them is rejected with 401, and any other filter gets `visibility != locked` ANDed in.
+*/
export const applyLockedVisibilityPolicy = (auth: AuthDto, filter: SearchFilter): SearchFilter => {
if (auth.session?.hasElevatedPermission) {
return filter;
diff --git a/server/src/utils/sync.ts b/server/src/utils/sync.ts
index 609eaaa1c3..1d9aa68791 100644
--- a/server/src/utils/sync.ts
+++ b/server/src/utils/sync.ts
@@ -29,6 +29,6 @@ export const serialize = <T extends keyof SyncItem, D extends SyncItem[T]>({
type,
data,
ids,
- ackType,
+ ackType = type,
}: SerializeOptions<T, D>) =>
- mapJsonLine({ type, data, ack: toAck({ type: ackType ?? type, updateId: ids[0], extraId: ids[1] }) });
+ mapJsonLine({ type, data, ack: toAck({ type: ackType, updateId: ids[0], extraId: ids[1] }) });
diff --git a/server/src/utils/transform.ts b/server/src/utils/transform.ts
index be5b9280bb..057ecc1e5f 100644
--- a/server/src/utils/transform.ts
+++ b/server/src/utils/transform.ts
@@ -72,9 +72,9 @@ type TransformState = {
};
/**
- * Transforms an array of points through a series of edit operations (crop, rotate, mirror).
- * Points should be in absolute pixel coordinates relative to the starting dimensions.
- */
+Transforms an array of points through a series of edit operations (crop, rotate, mirror).
+Points should be in absolute pixel coordinates relative to the starting dimensions.
+*/
export const transformPoints = (
points: Point[],
edits: AssetEditActionItem[],
diff --git a/server/src/validation.ts b/server/src/validation.ts
index 38a6052116..94ec30cd33 100644
--- a/server/src/validation.ts
+++ b/server/src/validation.ts
@@ -18,14 +18,14 @@ function isIPOrRange(value: string, options?: IsIPRangeOptions): boolean {
}
/**
- * Zod schema that validates an array of strings as IP addresses or IP/CIDR ranges.
- * When requireCIDR is true (default), plain IPs are rejected; only CIDR ranges are allowed.
- *
- * @example
- * z.string().optional().transform(...).pipe(IsIPRange())
- * @example
- * z.string().optional().transform(...).pipe(IsIPRange({ requireCIDR: false }))
- */
+Zod schema that validates an array of strings as IP addresses or IP/CIDR ranges.
+When requireCIDR is true (default), plain IPs are rejected; only CIDR ranges are allowed.
+
+@example
+z.string().optional().transform(...).pipe(IsIPRange())
+@example
+z.string().optional().transform(...).pipe(IsIPRange({ requireCIDR: false }))
+*/
export function IsIPRange(options?: IsIPRangeOptions) {
return z
.array(z.string())
@@ -33,12 +33,12 @@ export function IsIPRange(options?: IsIPRangeOptions) {
}
/**
- * Like z.object().partial(), but rejects objects where every field is undefined.
- * Use for update/patch DTOs where at least one field must be provided.
- *
- * @example
- * nonEmptyPartial({ name: z.string(), bio: z.string() }).meta({ id: 'UpdateDto' });
- */
+Like z.object().partial(), but rejects objects where every field is undefined.
+Use for update/patch DTOs where at least one field must be provided.
+
+@example
+nonEmptyPartial({ name: z.string(), bio: z.string() }).meta({ id: 'UpdateDto' });
+*/
export function nonEmptyPartial<T extends z.ZodRawShape>(shape: T) {
return z
.object(shape)
@@ -49,14 +49,14 @@ export function nonEmptyPartial<T extends z.ZodRawShape>(shape: T) {
}
/**
- * Zod schema that validates sibling-exclusion for object schemas.
- * Validation passes when the target property is missing, or when none of the sibling properties are present.
- * Use with .pipe() like IsIPRange.
- *
- * @example
- * const Schema = z.object({ a: z.string().optional(), b: z.string().optional() });
- * Schema.pipe(IsNotSiblingOf(Schema, 'a', ['b']));
- */
+Zod schema that validates sibling-exclusion for object schemas.
+Validation passes when the target property is missing, or when none of the sibling properties are present.
+Use with .pipe() like IsIPRange.
+
+@example
+const Schema = z.object({ a: z.string().optional(), b: z.string().optional() });
+Schema.pipe(IsNotSiblingOf(Schema, 'a', ['b']));
+*/
export function IsNotSiblingOf<
TSchema extends z.ZodObject<z.ZodRawShape>,
TKey extends z.infer<ReturnType<TSchema['keyof']>> & keyof z.infer<TSchema>,
@@ -122,18 +122,18 @@ const FilenameParamSchema = z.object({
export class FilenameParamDto extends createZodDto(FilenameParamSchema) {}
/**
- * The HTML5 email regex, but with unicode support, so that international email addresses
- * (unicode local parts and internationalized domain names) are accepted.
- * @see {@link z.regexes.html5Email}
- */
+The HTML5 email regex, but with unicode support, so that international email addresses
+(unicode local parts and internationalized domain names) are accepted.
+@see {@link z.regexes.html5Email}
+*/
const unicodeEmail =
/^[\p{L}\p{M}\p{N}.!#$%&'*+/=?^_`{|}~-]+@[\p{L}\p{N}](?:[\p{L}\p{M}\p{N}-]{0,61}[\p{L}\p{M}\p{N}])?(?:\.[\p{L}\p{N}](?:[\p{L}\p{M}\p{N}-]{0,61}[\p{L}\p{M}\p{N}])?)*$/u;
/**
- * Unified email validation
- * Converts email strings to lowercase and validates against a unicode aware email regex
- * @docs https://zod.dev/api?id=email
- */
+Unified email validation
+Converts email strings to lowercase and validates against a unicode aware email regex
+@docs https://zod.dev/api?id=email
+*/
export const toEmail = z
.email({
pattern: unicodeEmail,
@@ -142,9 +142,9 @@ export const toEmail = z
.transform((val) => val.toLowerCase());
/**
- * Parse ISO 8601 datetime strings to Date objects
- * @docs https://zod.dev/api?id=codec
- */
+Parse ISO 8601 datetime strings to Date objects
+@docs https://zod.dev/api?id=codec
+*/
export const isoDatetimeToDate = z
.codec(
z.iso.datetime({
@@ -160,9 +160,9 @@ export const isoDatetimeToDate = z
.meta({ example: '2024-01-01T00:00:00.000Z' });
/**
- * Parse ISO date strings to Date objects
- * @docs https://zod.dev/api?id=codec
- */
+Parse ISO date strings to Date objects
+@docs https://zod.dev/api?id=codec
+*/
export const isoDateToDate = z
.codec(
z.iso.date({
@@ -177,46 +177,44 @@ export const isoDateToDate = z
.meta({ example: '2024-01-01' });
/**
- * Latitude in range [-90, 90]. Reuse for body or query params.
- *
- * @example
- * // Regular (body): optional coordinates
- * latitudeSchema.optional().describe('Latitude coordinate')
- *
- * @example
- * // Pipe (query): coerce string to number then validate range
- * z.coerce.number().pipe(latitudeSchema).describe('Latitude (-90 to 90)')
- */
+Latitude in range [-90, 90]. Reuse for body or query params.
+
+@example
+// Regular (body): optional coordinates
+latitudeSchema.optional().describe('Latitude coordinate')
+
+@example
+// Pipe (query): coerce string to number then validate range
+z.coerce.number().pipe(latitudeSchema).describe('Latitude (-90 to 90)')
+*/
export const latitudeSchema = z.number().meta({ format: 'double' }).min(-90).max(90);
/**
- * Longitude in range [-180, 180]. Reuse for body or query params.
- *
- * @example
- * // Regular (body): optional coordinates
- * longitudeSchema.optional().describe('Longitude coordinate')
- *
- * @example
- * // Pipe (query): coerce string to number then validate range
- * z.coerce.number().pipe(longitudeSchema).describe('Longitude (-180 to 180)')
- */
+Longitude in range [-180, 180]. Reuse for body or query params.
+
+@example
+// Regular (body): optional coordinates
+longitudeSchema.optional().describe('Longitude coordinate')
+
+@example
+// Pipe (query): coerce string to number then validate range
+z.coerce.number().pipe(longitudeSchema).describe('Longitude (-180 to 180)')
+*/
export const longitudeSchema = z.number().meta({ format: 'double' }).min(-180).max(180);
/**
- * Parse string to boolean
- * This should be used for boolean query parameters and path parameters, but not for boolean request body parameters, as the first are always string.
- * We don't use z.coerce.boolean() as any truthy value is considered true
- * z.stringbool() is a more robust way to parse strings to booleans as it lets you specify the truthy and falsy values and the case sensitivity.
- * @docs https://zod.dev/api?id=coercion
- * @docs https://zod.dev/api?id=stringbool
- */
+Parse string to boolean
+This should be used for boolean query parameters and path parameters, but not for boolean request body parameters, as the first are always string.
+We don't use z.coerce.boolean() as any truthy value is considered true
+z.stringbool() is a more robust way to parse strings to booleans as it lets you specify the truthy and falsy values and the case sensitivity.
+@docs https://zod.dev/api?id=coercion
+@docs https://zod.dev/api?id=stringbool
+*/
export const stringToBool = z
.stringbool({ truthy: ['true'], falsy: ['false'], case: 'sensitive' })
.meta({ type: 'boolean' });
-/**
- * Parse JSON strings from multipart/form-data
- */
+/** Parse JSON strings from multipart/form-data */
export const JsonParsed = z.transform((val, ctx) => {
if (typeof val === 'string') {
try {
@@ -234,13 +232,13 @@ export const JsonParsed = z.transform((val, ctx) => {
});
/**
- * Hex color validation and normalization.
- * Accepts formats: #RGB, #RGBA, #RRGGBB, #RRGGBBAA (with or without # prefix).
- * Normalizes output to always include the # prefix.
- *
- * @example
- * hexColor.optional()
- */
+Hex color validation and normalization.
+Accepts formats: #RGB, #RGBA, #RRGGBB, #RRGGBBAA (with or without # prefix).
+Normalizes output to always include the # prefix.
+
+@example
+hexColor.optional()
+*/
const hexColorRegex = /^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/;
export const hexColor = z
.string()
diff --git a/server/test/medium/specs/repositories/asset-edit.repository.spec.ts b/server/test/medium/specs/repositories/asset-edit.repository.spec.ts
index 3feddd5b6b..f47ffc89ca 100644
--- a/server/test/medium/specs/repositories/asset-edit.repository.spec.ts
+++ b/server/test/medium/specs/repositories/asset-edit.repository.spec.ts
@@ -9,6 +9,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
const { ctx } = newMediumService(BaseService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/repositories/asset-job.repository.spec.ts b/server/test/medium/specs/repositories/asset-job.repository.spec.ts
index 33c78ea08e..6f414b24f8 100644
--- a/server/test/medium/specs/repositories/asset-job.repository.spec.ts
+++ b/server/test/medium/specs/repositories/asset-job.repository.spec.ts
@@ -15,6 +15,7 @@ const consume = async <T>(generator: AsyncIterableIterator<T>) => {
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
const { ctx } = newMediumService(BaseService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/repositories/asset.repository.spec.ts b/server/test/medium/specs/repositories/asset.repository.spec.ts
index 11596da98b..4dbf7e3ef2 100644
--- a/server/test/medium/specs/repositories/asset.repository.spec.ts
+++ b/server/test/medium/specs/repositories/asset.repository.spec.ts
@@ -10,6 +10,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
const { ctx } = newMediumService(BaseService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/repositories/memory.repository.spec.ts b/server/test/medium/specs/repositories/memory.repository.spec.ts
index 1f5cfb28d4..bf268bdfd3 100644
--- a/server/test/medium/specs/repositories/memory.repository.spec.ts
+++ b/server/test/medium/specs/repositories/memory.repository.spec.ts
@@ -9,6 +9,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
const { ctx } = newMediumService(BaseService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/repositories/person-user.repository.spec.ts b/server/test/medium/specs/repositories/person-user.repository.spec.ts
index 0413a82858..fa4340933f 100644
--- a/server/test/medium/specs/repositories/person-user.repository.spec.ts
+++ b/server/test/medium/specs/repositories/person-user.repository.spec.ts
@@ -13,6 +13,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
const { ctx } = newMediumService(BaseService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/repositories/tag.repository.spec.ts b/server/test/medium/specs/repositories/tag.repository.spec.ts
index 1923e7eb35..37ce21e021 100644
--- a/server/test/medium/specs/repositories/tag.repository.spec.ts
+++ b/server/test/medium/specs/repositories/tag.repository.spec.ts
@@ -8,6 +8,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
const { ctx } = newMediumService(BaseService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/activity.service.spec.ts b/server/test/medium/specs/services/activity.service.spec.ts
index bfd4c255e0..e5d1596fd0 100644
--- a/server/test/medium/specs/services/activity.service.spec.ts
+++ b/server/test/medium/specs/services/activity.service.spec.ts
@@ -15,6 +15,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(ActivityService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/album.service.spec.ts b/server/test/medium/specs/services/album.service.spec.ts
index ca413443b9..fe03f3cf25 100644
--- a/server/test/medium/specs/services/album.service.spec.ts
+++ b/server/test/medium/specs/services/album.service.spec.ts
@@ -12,6 +12,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(AlbumService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/api-key.service.spec.ts b/server/test/medium/specs/services/api-key.service.spec.ts
index 21a742e68d..c7dd90bc87 100644
--- a/server/test/medium/specs/services/api-key.service.spec.ts
+++ b/server/test/medium/specs/services/api-key.service.spec.ts
@@ -11,6 +11,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(ApiKeyService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/asset-media.service.spec.ts b/server/test/medium/specs/services/asset-media.service.spec.ts
index 5c99f2e29c..977d9ef0f7 100644
--- a/server/test/medium/specs/services/asset-media.service.spec.ts
+++ b/server/test/medium/specs/services/asset-media.service.spec.ts
@@ -22,6 +22,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(AssetMediaService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/asset.service.spec.ts b/server/test/medium/specs/services/asset.service.spec.ts
index 6d79d58e0f..858c62044b 100644
--- a/server/test/medium/specs/services/asset.service.spec.ts
+++ b/server/test/medium/specs/services/asset.service.spec.ts
@@ -23,6 +23,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(AssetService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/auth-admin.service.spec.ts b/server/test/medium/specs/services/auth-admin.service.spec.ts
index 623d536b16..22f7065b87 100644
--- a/server/test/medium/specs/services/auth-admin.service.spec.ts
+++ b/server/test/medium/specs/services/auth-admin.service.spec.ts
@@ -9,6 +9,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(AuthAdminService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/auth.service.spec.ts b/server/test/medium/specs/services/auth.service.spec.ts
index 5ba0810421..846886af89 100644
--- a/server/test/medium/specs/services/auth.service.spec.ts
+++ b/server/test/medium/specs/services/auth.service.spec.ts
@@ -22,6 +22,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(AuthService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/duplicate.service.spec.ts b/server/test/medium/specs/services/duplicate.service.spec.ts
index bdb0103e76..8f90d0a6fe 100644
--- a/server/test/medium/specs/services/duplicate.service.spec.ts
+++ b/server/test/medium/specs/services/duplicate.service.spec.ts
@@ -20,6 +20,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
const { sut, ctx } = newMediumService(DuplicateService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/integrity.service.spec.ts b/server/test/medium/specs/services/integrity.service.spec.ts
index ff4ec7810e..09b2311d06 100644
--- a/server/test/medium/specs/services/integrity.service.spec.ts
+++ b/server/test/medium/specs/services/integrity.service.spec.ts
@@ -20,6 +20,7 @@ import { getKyselyDB, makeStream } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(IntegrityService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/library.service.spec.ts b/server/test/medium/specs/services/library.service.spec.ts
index 00d8ec8042..8f69f8b225 100644
--- a/server/test/medium/specs/services/library.service.spec.ts
+++ b/server/test/medium/specs/services/library.service.spec.ts
@@ -31,10 +31,10 @@ let defaultDatabase: Kysely<DB>;
const fileModifiedAt = new Date(1_700_000_000_000);
-const createFile = async (filePath: string, modifiedAt: Date = fileModifiedAt) => {
+const createFile = async (filePath: string) => {
await mkdir(dirname(filePath), { recursive: true });
await writeFile(filePath, 'test');
- await utimes(filePath, modifiedAt, modifiedAt);
+ await utimes(filePath, fileModifiedAt, fileModifiedAt);
return filePath;
};
@@ -130,6 +130,7 @@ class LibraryTestContext extends MediumTestContext<typeof LibraryService> {
}
}
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
const ctx = new LibraryTestContext(db || defaultDatabase);
return { sut: ctx.sut, ctx };
diff --git a/server/test/medium/specs/services/memory.service.spec.ts b/server/test/medium/specs/services/memory.service.spec.ts
index 75fbff0c00..170d27e0de 100644
--- a/server/test/medium/specs/services/memory.service.spec.ts
+++ b/server/test/medium/specs/services/memory.service.spec.ts
@@ -19,6 +19,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(MemoryService, {
database: db || defaultDatabase,
@@ -47,10 +48,14 @@ const create = async (ctx: ReturnType<typeof setup>['ctx']) => {
const newPersonAsset = async (
ctx: ReturnType<typeof setup>['ctx'],
- { ownerId, personGroupId, localDateTime }: { ownerId: string; personGroupId: string; localDateTime?: string },
+ {
+ ownerId,
+ personGroupId,
+ localDateTime = '2024-06-13T12:00:00.000Z',
+ }: { ownerId: string; personGroupId: string; localDateTime?: string },
) => {
const assetRepo = ctx.get(AssetRepository);
- const { asset } = await ctx.newAsset({ ownerId, localDateTime: localDateTime ?? '2024-06-13T12:00:00.000Z' });
+ const { asset } = await ctx.newAsset({ ownerId, localDateTime });
await Promise.all([
ctx.newExif({ assetId: asset.id, make: 'Canon' }),
ctx.newJobStatus({ assetId: asset.id }),
diff --git a/server/test/medium/specs/services/metadata.service.spec.ts b/server/test/medium/specs/services/metadata.service.spec.ts
index 0c8bbaf152..68452cd543 100644
--- a/server/test/medium/specs/services/metadata.service.spec.ts
+++ b/server/test/medium/specs/services/metadata.service.spec.ts
@@ -30,6 +30,7 @@ type TimeZoneTest = {
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>, { realStorage = false } = {}) => {
const { sut, ctx } = newMediumService(MetadataService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/ocr.service.spec.ts b/server/test/medium/specs/services/ocr.service.spec.ts
index 6254d87608..16ae3b9d5d 100644
--- a/server/test/medium/specs/services/ocr.service.spec.ts
+++ b/server/test/medium/specs/services/ocr.service.spec.ts
@@ -15,6 +15,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(OcrService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/partner.service.spec.ts b/server/test/medium/specs/services/partner.service.spec.ts
index 7f06e6664c..cbcf2f75b9 100644
--- a/server/test/medium/specs/services/partner.service.spec.ts
+++ b/server/test/medium/specs/services/partner.service.spec.ts
@@ -12,6 +12,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(PartnerService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/passkey.service.spec.ts b/server/test/medium/specs/services/passkey.service.spec.ts
index 28762bcd7b..357d6b51f1 100644
--- a/server/test/medium/specs/services/passkey.service.spec.ts
+++ b/server/test/medium/specs/services/passkey.service.spec.ts
@@ -49,6 +49,7 @@ const authenticationResponse = {
},
};
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(PasskeyService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/plugin.service.spec.ts b/server/test/medium/specs/services/plugin.service.spec.ts
index 66e6974d2c..e3d4a16583 100644
--- a/server/test/medium/specs/services/plugin.service.spec.ts
+++ b/server/test/medium/specs/services/plugin.service.spec.ts
@@ -13,6 +13,7 @@ let defaultDatabase: Kysely<DB>;
const wasmBytes = Buffer.from('some-wasm-binary-data');
const sha256hash = Buffer.from('some-manifest-hash');
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(PluginService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/search.service.spec.ts b/server/test/medium/specs/services/search.service.spec.ts
index faab71eedd..0da99c3186 100644
--- a/server/test/medium/specs/services/search.service.spec.ts
+++ b/server/test/medium/specs/services/search.service.spec.ts
@@ -18,6 +18,7 @@ let defaultDatabase: Kysely<DB>;
const unitVector = (index: number) => JSON.stringify(Array.from({ length: 512 }, (_, i) => (i === index ? 1 : 0)));
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(SearchService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/shared-link.service.spec.ts b/server/test/medium/specs/services/shared-link.service.spec.ts
index 5bff8f295b..b23a07032b 100644
--- a/server/test/medium/specs/services/shared-link.service.spec.ts
+++ b/server/test/medium/specs/services/shared-link.service.spec.ts
@@ -16,6 +16,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(SharedLinkService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/sync.service.spec.ts b/server/test/medium/specs/services/sync.service.spec.ts
index edbeacddcf..20151053bc 100644
--- a/server/test/medium/specs/services/sync.service.spec.ts
+++ b/server/test/medium/specs/services/sync.service.spec.ts
@@ -13,6 +13,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(SyncService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/tag.service.spec.ts b/server/test/medium/specs/services/tag.service.spec.ts
index 2ed6ee063c..c2ade2c3f9 100644
--- a/server/test/medium/specs/services/tag.service.spec.ts
+++ b/server/test/medium/specs/services/tag.service.spec.ts
@@ -16,6 +16,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(TagService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/timeline.service.spec.ts b/server/test/medium/specs/services/timeline.service.spec.ts
index 030fc45fa6..2051f7fdf0 100644
--- a/server/test/medium/specs/services/timeline.service.spec.ts
+++ b/server/test/medium/specs/services/timeline.service.spec.ts
@@ -14,6 +14,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(TimelineService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/version.service.spec.ts b/server/test/medium/specs/services/version.service.spec.ts
index 19956d7bba..56ffe2a71d 100644
--- a/server/test/medium/specs/services/version.service.spec.ts
+++ b/server/test/medium/specs/services/version.service.spec.ts
@@ -13,6 +13,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(VersionService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/services/workflow.service.spec.ts b/server/test/medium/specs/services/workflow.service.spec.ts
index 7793f55f10..2479d831f6 100644
--- a/server/test/medium/specs/services/workflow.service.spec.ts
+++ b/server/test/medium/specs/services/workflow.service.spec.ts
@@ -13,6 +13,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = (db?: Kysely<DB>) => {
return newMediumService(WorkflowService, {
database: db || defaultDatabase,
diff --git a/server/test/medium/specs/sync/sync-album-asset-exif.spec.ts b/server/test/medium/specs/sync/sync-album-asset-exif.spec.ts
index 9961588ef5..45a535cb57 100644
--- a/server/test/medium/specs/sync/sync-album-asset-exif.spec.ts
+++ b/server/test/medium/specs/sync/sync-album-asset-exif.spec.ts
@@ -9,6 +9,7 @@ import { getKyselyDB, wait } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-album-asset.spec.ts b/server/test/medium/specs/sync/sync-album-asset.spec.ts
index 782b16818c..0412513bce 100644
--- a/server/test/medium/specs/sync/sync-album-asset.spec.ts
+++ b/server/test/medium/specs/sync/sync-album-asset.spec.ts
@@ -8,6 +8,7 @@ import { getKyselyDB, wait } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-album-to-asset.spec.ts b/server/test/medium/specs/sync/sync-album-to-asset.spec.ts
index dc3e9250ba..bbab79cdca 100644
--- a/server/test/medium/specs/sync/sync-album-to-asset.spec.ts
+++ b/server/test/medium/specs/sync/sync-album-to-asset.spec.ts
@@ -8,6 +8,7 @@ import { getKyselyDB, wait } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-album-user.spec.ts b/server/test/medium/specs/sync/sync-album-user.spec.ts
index 71ec278a1b..9daf1d89df 100644
--- a/server/test/medium/specs/sync/sync-album-user.spec.ts
+++ b/server/test/medium/specs/sync/sync-album-user.spec.ts
@@ -7,6 +7,7 @@ import { getKyselyDB, wait } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-album.spec.ts b/server/test/medium/specs/sync/sync-album.spec.ts
index 12ecc08543..231c8a6677 100644
--- a/server/test/medium/specs/sync/sync-album.spec.ts
+++ b/server/test/medium/specs/sync/sync-album.spec.ts
@@ -8,6 +8,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-asset-edit.spec.ts b/server/test/medium/specs/sync/sync-asset-edit.spec.ts
index f916ab8096..b75a268a43 100644
--- a/server/test/medium/specs/sync/sync-asset-edit.spec.ts
+++ b/server/test/medium/specs/sync/sync-asset-edit.spec.ts
@@ -9,6 +9,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-asset-exif.spec.ts b/server/test/medium/specs/sync/sync-asset-exif.spec.ts
index 0cb1ccefaa..da2a118b54 100644
--- a/server/test/medium/specs/sync/sync-asset-exif.spec.ts
+++ b/server/test/medium/specs/sync/sync-asset-exif.spec.ts
@@ -7,6 +7,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-asset-face.spec.ts b/server/test/medium/specs/sync/sync-asset-face.spec.ts
index 28208a4c8a..383ce1304a 100644
--- a/server/test/medium/specs/sync/sync-asset-face.spec.ts
+++ b/server/test/medium/specs/sync/sync-asset-face.spec.ts
@@ -8,6 +8,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-asset-metadata.spec.ts b/server/test/medium/specs/sync/sync-asset-metadata.spec.ts
index 2526068ef2..87cf47f9f9 100644
--- a/server/test/medium/specs/sync/sync-asset-metadata.spec.ts
+++ b/server/test/medium/specs/sync/sync-asset-metadata.spec.ts
@@ -7,6 +7,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-asset-ocr.spec.ts b/server/test/medium/specs/sync/sync-asset-ocr.spec.ts
index e004c5d542..98a95d2b79 100644
--- a/server/test/medium/specs/sync/sync-asset-ocr.spec.ts
+++ b/server/test/medium/specs/sync/sync-asset-ocr.spec.ts
@@ -8,6 +8,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-asset.spec.ts b/server/test/medium/specs/sync/sync-asset.spec.ts
index 4ded43372d..0b99375ed7 100644
--- a/server/test/medium/specs/sync/sync-asset.spec.ts
+++ b/server/test/medium/specs/sync/sync-asset.spec.ts
@@ -8,6 +8,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-client-disconnect.spec.ts b/server/test/medium/specs/sync/sync-client-disconnect.spec.ts
index 23c36d3693..f423dbe73f 100644
--- a/server/test/medium/specs/sync/sync-client-disconnect.spec.ts
+++ b/server/test/medium/specs/sync/sync-client-disconnect.spec.ts
@@ -22,6 +22,7 @@ class LineAutoClosingStream extends Writable {
private count: number;
lines: string[] = [];
+ // eslint-disable-next-line unicorn/no-unnecessary-parameters
constructor({ after }: { after: number }) {
super({ highWaterMark: 1 });
this.count = after;
diff --git a/server/test/medium/specs/sync/sync-complete.spec.ts b/server/test/medium/specs/sync/sync-complete.spec.ts
index 244bbc5d59..dd5a1ec017 100644
--- a/server/test/medium/specs/sync/sync-complete.spec.ts
+++ b/server/test/medium/specs/sync/sync-complete.spec.ts
@@ -10,6 +10,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-memory-asset.spec.ts b/server/test/medium/specs/sync/sync-memory-asset.spec.ts
index 9397a291fa..7c25fb88f5 100644
--- a/server/test/medium/specs/sync/sync-memory-asset.spec.ts
+++ b/server/test/medium/specs/sync/sync-memory-asset.spec.ts
@@ -7,6 +7,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-memory.spec.ts b/server/test/medium/specs/sync/sync-memory.spec.ts
index d872d7f03b..cdd887aa5b 100644
--- a/server/test/medium/specs/sync/sync-memory.spec.ts
+++ b/server/test/medium/specs/sync/sync-memory.spec.ts
@@ -7,6 +7,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-partner-asset-exif.spec.ts b/server/test/medium/specs/sync/sync-partner-asset-exif.spec.ts
index b8fdf4c20d..0cb0f34b76 100644
--- a/server/test/medium/specs/sync/sync-partner-asset-exif.spec.ts
+++ b/server/test/medium/specs/sync/sync-partner-asset-exif.spec.ts
@@ -7,6 +7,7 @@ import { getKyselyDB, wait } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-partner-asset.spec.ts b/server/test/medium/specs/sync/sync-partner-asset.spec.ts
index 0f01d99ded..6412b155fc 100644
--- a/server/test/medium/specs/sync/sync-partner-asset.spec.ts
+++ b/server/test/medium/specs/sync/sync-partner-asset.spec.ts
@@ -10,6 +10,7 @@ import { getKyselyDB, wait } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-partner-stack.spec.ts b/server/test/medium/specs/sync/sync-partner-stack.spec.ts
index fc2ebef87a..46ec468d28 100644
--- a/server/test/medium/specs/sync/sync-partner-stack.spec.ts
+++ b/server/test/medium/specs/sync/sync-partner-stack.spec.ts
@@ -10,6 +10,7 @@ import { getKyselyDB, wait } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-partner.spec.ts b/server/test/medium/specs/sync/sync-partner.spec.ts
index 1badfb1f9e..0e29f5e76b 100644
--- a/server/test/medium/specs/sync/sync-partner.spec.ts
+++ b/server/test/medium/specs/sync/sync-partner.spec.ts
@@ -8,6 +8,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-person.spec.ts b/server/test/medium/specs/sync/sync-person.spec.ts
index 5a05f9e63c..970dea33d6 100644
--- a/server/test/medium/specs/sync/sync-person.spec.ts
+++ b/server/test/medium/specs/sync/sync-person.spec.ts
@@ -8,6 +8,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-reset.spec.ts b/server/test/medium/specs/sync/sync-reset.spec.ts
index 2df4241452..3262028451 100644
--- a/server/test/medium/specs/sync/sync-reset.spec.ts
+++ b/server/test/medium/specs/sync/sync-reset.spec.ts
@@ -7,6 +7,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-stack.spec.ts b/server/test/medium/specs/sync/sync-stack.spec.ts
index f4895ad9f7..45309ba86e 100644
--- a/server/test/medium/specs/sync/sync-stack.spec.ts
+++ b/server/test/medium/specs/sync/sync-stack.spec.ts
@@ -7,6 +7,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/server/test/medium/specs/sync/sync-user-metadata.spec.ts b/server/test/medium/specs/sync/sync-user-metadata.spec.ts
index 806f418bc4..20c640abaa 100644
--- a/server/test/medium/specs/sync/sync-user-metadata.spec.ts
+++ b/server/test/medium/specs/sync/sync-user-metadata.spec.ts
@@ -7,6 +7,7 @@ import { getKyselyDB } from 'test/utils.js';
let defaultDatabase: Kysely<DB>;
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const setup = async (db?: Kysely<DB>) => {
const ctx = new SyncTestContext(db || defaultDatabase);
const { auth, user, session } = await ctx.newSyncAuthUser();
diff --git a/web/package.json b/web/package.json
index 925f5adb7d..3223464ad6 100644
--- a/web/package.json
+++ b/web/package.json
@@ -110,7 +110,7 @@
"eslint-plugin-compat": "^7.0.0",
"eslint-plugin-prettier": "^5.5.6",
"eslint-plugin-svelte": "^3.23.1",
- "eslint-plugin-unicorn": "^76.0.0",
+ "eslint-plugin-unicorn": "^78.0.0",
"factory.ts": "^1.4.1",
"globals": "^17.0.0",
"happy-dom": "^21.0.0",
diff --git a/web/src/lib/actions/click-outside.ts b/web/src/lib/actions/click-outside.ts
index 526f238f32..7d11b24182 100644
--- a/web/src/lib/actions/click-outside.ts
+++ b/web/src/lib/actions/click-outside.ts
@@ -7,11 +7,11 @@ interface Options {
}
/**
- * Calls a function when a click occurs outside of the element, or when the escape key is pressed.
- * @param node
- * @param options Object containing onOutclick and onEscape functions
- * @returns
- */
+Calls a function when a click occurs outside of the element, or when the escape key is pressed.
+@param node
+@param options Object containing onOutclick and onEscape functions
+@returns
+*/
export function clickOutside(node: HTMLElement, options: Options = {}): ActionReturn<Options> {
const handleClick = (event: MouseEvent) => {
const { onOutclick } = options;
diff --git a/web/src/lib/actions/context-menu-navigation.ts b/web/src/lib/actions/context-menu-navigation.ts
index ea4cf110ad..98f4adfbfe 100644
--- a/web/src/lib/actions/context-menu-navigation.ts
+++ b/web/src/lib/actions/context-menu-navigation.ts
@@ -3,33 +3,19 @@ import { tick } from 'svelte';
import type { Action } from 'svelte/action';
interface Options {
- /**
- * A function that is called when the dropdown should be closed.
- */
+ /** A function that is called when the dropdown should be closed. */
closeDropdown: () => void;
- /**
- * The container element that with direct children that should be navigated.
- */
+ /** The container element that with direct children that should be navigated. */
container?: HTMLElement;
- /**
- * Indicates if the dropdown is open.
- */
+ /** Indicates if the dropdown is open. */
isOpen: boolean;
- /**
- * Override the default behavior for the escape key.
- */
+ /** Override the default behavior for the escape key. */
onEscape?: (event: KeyboardEvent) => void;
- /**
- * A function that is called when the dropdown should be opened.
- */
+ /** A function that is called when the dropdown should be opened. */
openDropdown?: (event: KeyboardEvent) => void;
- /**
- * The id of the currently selected element.
- */
+ /** The id of the currently selected element. */
selectedId: string | undefined;
- /**
- * A function that is called when the selection changes, to notify consumers of the new selected id.
- */
+ /** A function that is called when the selection changes, to notify consumers of the new selected id. */
selectionChanged: (id: string | undefined) => void;
}
diff --git a/web/src/lib/actions/focus-outside.ts b/web/src/lib/actions/focus-outside.ts
index 829497ccdb..d8b64ce237 100644
--- a/web/src/lib/actions/focus-outside.ts
+++ b/web/src/lib/actions/focus-outside.ts
@@ -5,10 +5,10 @@ interface Options {
}
/**
- * Calls a function when focus leaves the element.
- * @param node
- * @param options Object containing onFocusOut function
- */
+Calls a function when focus leaves the element.
+@param node
+@param options Object containing onFocusOut function
+*/
export function focusOutside(node: HTMLElement, options: Options = {}) {
const { onFocusOut } = options;
diff --git a/web/src/lib/actions/focus-trap.ts b/web/src/lib/actions/focus-trap.ts
index 607ed2ac4e..2ecc5927e7 100644
--- a/web/src/lib/actions/focus-trap.ts
+++ b/web/src/lib/actions/focus-trap.ts
@@ -2,9 +2,7 @@ import { getTabbable } from '#lib/utils/focus-util.ts';
import { tick } from 'svelte';
interface Options {
- /**
- * Set whether the trap is active or not.
- */
+ /** Set whether the trap is active or not. */
active?: boolean;
}
diff --git a/web/src/lib/actions/list-navigation.ts b/web/src/lib/actions/list-navigation.ts
index 8c373753ab..e60b7d1506 100644
--- a/web/src/lib/actions/list-navigation.ts
+++ b/web/src/lib/actions/list-navigation.ts
@@ -2,10 +2,10 @@ import { shortcuts } from '#lib/actions/shortcut.ts';
import type { Action } from 'svelte/action';
/**
- * Enables keyboard navigation (up and down arrows) for a list of elements.
- * @param node Element which listens for keyboard events
- * @param container Element containing the list of elements
- */
+Enables keyboard navigation (up and down arrows) for a list of elements.
+@param node Element which listens for keyboard events
+@param container Element containing the list of elements
+*/
export const listNavigation: Action<HTMLElement, HTMLElement | undefined> = (
node: HTMLElement,
container?: HTMLElement,
diff --git a/web/src/lib/actions/scroll-memory.ts b/web/src/lib/actions/scroll-memory.ts
index 2b29caabf2..cab78599ac 100644
--- a/web/src/lib/actions/scroll-memory.ts
+++ b/web/src/lib/actions/scroll-memory.ts
@@ -3,30 +3,20 @@ import { handlePromiseError } from '#lib/utils.ts';
import { navigating } from '$app/state';
interface Options {
- /**
- * This must be kept the same in all subpages of this route for the scroll memory clearer to work.
- */
+ /** This must be kept the same in all subpages of this route for the scroll memory clearer to work. */
routeStartsWith: string;
- /**
- * Function to clear additional data/state before scrolling (ex infinite scroll).
- */
+ /** Function to clear additional data/state before scrolling (ex infinite scroll). */
beforeClear?: () => void;
}
interface PageOptions extends Options {
- /**
- * Function to save additional data/state before scrolling (ex infinite scroll).
- */
+ /** Function to save additional data/state before scrolling (ex infinite scroll). */
beforeSave?: () => void;
- /**
- * Function to load additional data/state before scrolling (ex infinite scroll).
- */
+ /** Function to load additional data/state before scrolling (ex infinite scroll). */
beforeScroll?: () => Promise<void>;
}
-/**
- * @param node The scroll slot element, typically from {@link UserPageLayout}
- */
+/** @param node The scroll slot element, typically from {@link UserPageLayout} */
export function scrollMemory(
node: HTMLElement,
{ routeStartsWith, beforeSave, beforeClear, beforeScroll }: PageOptions,
diff --git a/web/src/lib/actions/use-actions.ts b/web/src/lib/actions/use-actions.ts
index 0b09549a03..4f459e685d 100644
--- a/web/src/lib/actions/use-actions.ts
+++ b/web/src/lib/actions/use-actions.ts
@@ -1,7 +1,7 @@
/**
- * @license Apache-2.0
- * https://github.com/hperrin/svelte-material-ui/blob/master/packages/common/src/internal/useActions.ts
- */
+@license Apache-2.0
+https://github.com/hperrin/svelte-material-ui/blob/master/packages/common/src/internal/useActions.ts
+*/
export type SvelteActionReturnType<P> = void | {
update?: (newParams?: P) => void;
diff --git a/web/src/lib/components/HeaderActionButton.svelte b/web/src/lib/components/HeaderActionButton.svelte
index 9ff90d21cf..c1895ba8c2 100644
--- a/web/src/lib/components/HeaderActionButton.svelte
+++ b/web/src/lib/components/HeaderActionButton.svelte
@@ -7,13 +7,13 @@
variant?: Variants;
};
- const { action, variant }: Props = $props();
+ const { action, variant = 'ghost' }: Props = $props();
const { title, icon, color = 'secondary', onAction } = $derived(action);
</script>
{#if action.$if?.() ?? true}
<Button
- variant={variant ?? 'ghost'}
+ {variant}
size="small"
{color}
leadingIcon={icon}
diff --git a/web/src/lib/components/asset-viewer/AssetViewer.svelte b/web/src/lib/components/asset-viewer/AssetViewer.svelte
index 03b80c0b25..93e06c85c1 100644
--- a/web/src/lib/components/asset-viewer/AssetViewer.svelte
+++ b/web/src/lib/components/asset-viewer/AssetViewer.svelte
@@ -302,9 +302,7 @@
cursor.current = stack.assets[nextIndex];
};
- /**
- * Slide show mode
- */
+ /** Slide show mode */
let assetViewerHtmlElement = $state<HTMLElement>();
diff --git a/web/src/lib/components/asset-viewer/VideoRemoteViewer.svelte b/web/src/lib/components/asset-viewer/VideoRemoteViewer.svelte
index 5386d445ed..15c4ae5b65 100644
--- a/web/src/lib/components/asset-viewer/VideoRemoteViewer.svelte
+++ b/web/src/lib/components/asset-viewer/VideoRemoteViewer.svelte
@@ -23,7 +23,7 @@
break;
}
case CastState.IDLE: {
- await cast(assetFileUrl, true);
+ await cast(true);
break;
}
default: {
@@ -35,7 +35,7 @@
$effect(() => {
if (assetFileUrl) {
- void cast(assetFileUrl);
+ void cast();
}
});
@@ -47,11 +47,11 @@
previousPlayerState = castManager.castState;
});
- const cast = async (url: string, force: boolean = false) => {
- if (!url || !castManager.isCasting) {
+ const cast = async (force: boolean = false) => {
+ if (!assetFileUrl || !castManager.isCasting) {
return;
}
- const fullUrl = new URL(url, location.href);
+ const fullUrl = new URL(assetFileUrl, location.href);
try {
await castManager.loadMedia(fullUrl.href, force);
diff --git a/web/src/lib/components/asset-viewer/immich-time-range.ts b/web/src/lib/components/asset-viewer/immich-time-range.ts
index 12d6200d51..a995404071 100644
--- a/web/src/lib/components/asset-viewer/immich-time-range.ts
+++ b/web/src/lib/components/asset-viewer/immich-time-range.ts
@@ -4,7 +4,7 @@ import MediaTimeRange from 'media-chrome/media-time-range';
const COMMIT_DELAY_MS = 750;
/** Custom MediaTimeRange that only seeks after pointer release to avoid hammering the server.
- * Keyboard input uses timed debouncing instead since there's no release event. */
+Keyboard input uses timed debouncing instead since there's no release event. */
class ImmichTimeRange extends MediaTimeRange {
private seeking = false;
private pending: number | undefined;
diff --git a/web/src/lib/components/shared-components/Combobox.svelte b/web/src/lib/components/shared-components/Combobox.svelte
index d105b49e2e..d136d1e2ae 100644
--- a/web/src/lib/components/shared-components/Combobox.svelte
+++ b/web/src/lib/components/shared-components/Combobox.svelte
@@ -36,13 +36,9 @@
options?: ComboBoxOption[];
selectedOption?: ComboBoxOption | undefined;
placeholder?: string;
- /**
- * whether creating new items is allowed.
- */
+ /** whether creating new items is allowed. */
allowCreate?: boolean;
- /**
- * select first matching option on enter key.
- */
+ /** select first matching option on enter key. */
defaultFirstOption?: boolean;
onSelect?: (option: ComboBoxOption | undefined) => void;
forceFocus?: boolean;
@@ -61,13 +57,9 @@
forceFocus = false,
}: Props = $props();
- /**
- * Indicates whether or not the dropdown autocomplete list should be visible.
- */
+ /** Indicates whether or not the dropdown autocomplete list should be visible. */
let isOpen = $state(false);
- /**
- * Keeps track of whether the combobox is actively being used.
- */
+ /** Keeps track of whether the combobox is actively being used. */
let isActive = $state(false);
let searchQuery = $derived(selectedOption?.label || '');
let selectedIndex: number | undefined = $state();
@@ -78,13 +70,9 @@
const id = $props.id();
const inputId = `combobox-${id}`;
const listboxId = `listbox-${id}`;
- /**
- * Buffer distance between the dropdown and top/bottom of the viewport.
- */
+ /** Buffer distance between the dropdown and top/bottom of the viewport. */
const dropdownOffset = 15;
- /**
- * Minimum space required for the dropdown to be displayed at the bottom of the input.
- */
+ /** Minimum space required for the dropdown to be displayed at the bottom of the input. */
const bottomBreakpoint = 225;
const observer = new IntersectionObserver(
(entries) => {
diff --git a/web/src/lib/components/shared-components/context-menu/ButtonContextMenu.svelte b/web/src/lib/components/shared-components/context-menu/ButtonContextMenu.svelte
index a58343d7a4..576eaf6c43 100644
--- a/web/src/lib/components/shared-components/context-menu/ButtonContextMenu.svelte
+++ b/web/src/lib/components/shared-components/context-menu/ButtonContextMenu.svelte
@@ -16,21 +16,15 @@
type Props = {
icon: string;
title: string;
- /**
- * The alignment of the context menu relative to the button.
- */
+ /** The alignment of the context menu relative to the button. */
align?: Align;
- /**
- * The direction in which the context menu should open.
- */
+ /** The direction in which the context menu should open. */
// TODO change to start vs end
direction?: 'left' | 'right';
color?: Color;
size?: Size | undefined;
variant?: Variants | undefined;
- /**
- * Additional classes to apply to the button.
- */
+ /** Additional classes to apply to the button. */
buttonClass?: string | undefined;
hideContent?: boolean;
children?: Snippet;
diff --git a/web/src/lib/components/shared-components/progress-bar/ProgressBar.svelte b/web/src/lib/components/shared-components/progress-bar/ProgressBar.svelte
index c02befddfb..3f1e166d97 100644
--- a/web/src/lib/components/shared-components/progress-bar/ProgressBar.svelte
+++ b/web/src/lib/components/shared-components/progress-bar/ProgressBar.svelte
@@ -7,13 +7,11 @@
interface Props {
/**
- * Autoplay on mount
- * @default false
- */
+ Autoplay on mount
+ @default false
+ */
autoplay?: boolean;
- /**
- * Progress bar status
- */
+ /** Progress bar status */
status?: ProgressBarStatus;
hidden?: boolean;
duration?: number;
diff --git a/web/src/lib/components/timeline/Timeline.svelte b/web/src/lib/components/timeline/Timeline.svelte
index 110e4255dd..81405a44ec 100644
--- a/web/src/lib/components/timeline/Timeline.svelte
+++ b/web/src/lib/components/timeline/Timeline.svelte
@@ -36,8 +36,8 @@
isSelectionMode?: boolean;
singleSelect?: boolean;
/** `true` if this asset grid is responds to navigation events; if `true`, then look at the
- `AssetViewingStore.gridScrollTarget` and load and scroll to the asset specified, and
- additionally, update the page location/url with the asset as the timeline is scrolled */
+ `AssetViewingStore.gridScrollTarget` and load and scroll to the asset specified, and
+ additionally, update the page location/url with the asset as the timeline is scrolled */
enableRouting: boolean;
timelineManager?: TimelineManager;
options?: TimelineManagerOptions;
diff --git a/web/src/lib/elements/Portal.svelte b/web/src/lib/elements/Portal.svelte
index 8649227282..68630b7f82 100644
--- a/web/src/lib/elements/Portal.svelte
+++ b/web/src/lib/elements/Portal.svelte
@@ -2,9 +2,7 @@
import { handlePromiseError } from '#lib/utils.ts';
import { tick, type Snippet } from 'svelte';
- /**
- * Usage: <div use:portal={'css selector'}> or <div use:portal={document.body}>
- */
+ /** Usage: <div use:portal={'css selector'}> or <div use:portal={document.body}> */
export function portal(element: HTMLElement, target: HTMLElement | string = 'body') {
let targetElement;
async function update(newTarget: HTMLElement | string) {
@@ -65,9 +63,7 @@ Used for every occurrence of an HTML tag in a message
-->
<script lang="ts">
interface Props {
- /**
- * DOM Element or CSS Selector
- */
+ /** DOM Element or CSS Selector */
target?: HTMLElement | string;
children?: Snippet;
}
diff --git a/web/src/lib/elements/SkipLink.svelte b/web/src/lib/elements/SkipLink.svelte
index 599b6a472c..09593eeaa3 100644
--- a/web/src/lib/elements/SkipLink.svelte
+++ b/web/src/lib/elements/SkipLink.svelte
@@ -4,17 +4,11 @@
import { t } from 'svelte-i18n';
interface Props {
- /**
- * Target for the skip link to move focus to.
- */
+ /** Target for the skip link to move focus to. */
target?: string;
- /**
- * Text for the skip link button.
- */
+ /** Text for the skip link button. */
text?: string;
- /**
- * Breakpoint at which the skip link is visible. Defaults to always being visible.
- */
+ /** Breakpoint at which the skip link is visible. Defaults to always being visible. */
breakpoint?: 'sm' | 'md' | 'lg' | 'xl' | '2xl';
}
diff --git a/web/src/lib/managers/activity-manager.svelte.ts b/web/src/lib/managers/activity-manager.svelte.ts
index d22f573075..0c2d7eaf0a 100644
--- a/web/src/lib/managers/activity-manager.svelte.ts
+++ b/web/src/lib/managers/activity-manager.svelte.ts
@@ -54,8 +54,8 @@ class ActivityManager {
return this.#isLiked;
}
- #getCacheKey(albumId: string, assetId?: string) {
- return `${albumId}:${assetId ?? ''}`;
+ #getCacheKey(albumId: string, assetId: string = '') {
+ return `${albumId}:${assetId}`;
}
async init(albumId: string, assetId?: string) {
diff --git a/web/src/lib/managers/timeline-manager/timeline-manager.svelte.ts b/web/src/lib/managers/timeline-manager/timeline-manager.svelte.ts
index 522dcfe07f..9d532bd337 100644
--- a/web/src/lib/managers/timeline-manager/timeline-manager.svelte.ts
+++ b/web/src/lib/managers/timeline-manager/timeline-manager.svelte.ts
@@ -514,9 +514,7 @@ export class TimelineManager extends VirtualScrollManager {
return randomDay.viewerAssets[randomAssetIndex - accumulatedCount].asset;
}
- /**
- * Executes callback on assets, handling moves between groups and removals due to filter criteria.
- */
+ /** Executes callback on assets, handling moves between groups and removals due to filter criteria. */
update(ids: string[], callback: (asset: TimelineAsset) => void) {
// eslint-disable-next-line svelte/prefer-svelte-reactivity
return this.#runAssetCallback(new Set(ids), callback);
@@ -540,11 +538,11 @@ export class TimelineManager extends VirtualScrollManager {
}
/**
- * Adds assets to existing segments, creating new segments as needed.
- *
- * This is an internal method that assumes the provided assets are not already
- * present in the timeline. For updating existing assets, use updateAssetOperation().
- */
+ Adds assets to existing segments, creating new segments as needed.
+
+ This is an internal method that assumes the provided assets are not already
+ present in the timeline. For updating existing assets, use updateAssetOperation().
+ */
protected addAssetsUpsertSegments(assets: TimelineAsset[]) {
if (assets.length === 0) {
return;
diff --git a/web/src/lib/modals/timezone-utils.ts b/web/src/lib/modals/timezone-utils.ts
index ae86e46321..58f5912d05 100644
--- a/web/src/lib/modals/timezone-utils.ts
+++ b/web/src/lib/modals/timezone-utils.ts
@@ -2,38 +2,38 @@ import { DateTime, Duration } from 'luxon';
export type ZoneOption = {
/**
- * Timezone name with offset
- *
- * e.g. Asia/Jerusalem (+03:00)
- */
+ Timezone name with offset
+
+ e.g. Asia/Jerusalem (+03:00)
+ */
label: string;
/**
- * Timezone name
- *
- * e.g. Asia/Jerusalem
- */
+ Timezone name
+
+ e.g. Asia/Jerusalem
+ */
value: string;
/**
- * Timezone offset in minutes
- *
- * e.g. 300
- */
+ Timezone offset in minutes
+
+ e.g. 300
+ */
offsetMinutes: number;
/**
- * True iff the date is valid
- *
- * Dates may be invalid for various reasons, for example setting a day that does not exist (30 Feb 2024).
- * Due to daylight saving time, 2:30am is invalid for Europe/Berlin on Mar 31 2024.The two following local times
- * are one second apart:
- *
- * - Mar 31 2024 01:59:59 (GMT+0100, unix timestamp 1725058799)
- * - Mar 31 2024 03:00:00 (GMT+0200, unix timestamp 1711846800)
- *
- * Mar 31 2024 02:30:00 does not exist in Europe/Berlin, this is an invalid date/time/time zone combination.
- */
+ True iff the date is valid
+
+ Dates may be invalid for various reasons, for example setting a day that does not exist (30 Feb 2024).
+ Due to daylight saving time, 2:30am is invalid for Europe/Berlin on Mar 31 2024.The two following local times
+ are one second apart:
+
+ - Mar 31 2024 01:59:59 (GMT+0100, unix timestamp 1725058799)
+ - Mar 31 2024 03:00:00 (GMT+0200, unix timestamp 1711846800)
+
+ Mar 31 2024 02:30:00 does not exist in Europe/Berlin, this is an invalid date/time/time zone combination.
+ */
valid: boolean;
};
diff --git a/web/src/lib/route.ts b/web/src/lib/route.ts
index 09f448a3fd..f6c64878ab 100644
--- a/web/src/lib/route.ts
+++ b/web/src/lib/route.ts
@@ -14,11 +14,7 @@ export const fromQueueSlug = (slug: string): QueueName | undefined => {
};
type QueryValue = number | string | boolean;
-const asQueryString = (
- params?: Record<string, QueryValue | undefined>,
- options?: { skipEmptyStrings?: boolean; skipNullValues?: boolean },
-) => {
- const { skipEmptyStrings = true, skipNullValues = true } = options ?? {};
+const asQueryString = (params?: Record<string, QueryValue | undefined>) => {
const items = Object.entries(params ?? {})
.filter((item): item is [string, QueryValue] => {
const value = item[1];
@@ -27,11 +23,11 @@ const asQueryString = (
return false;
}
- if (skipNullValues && value === null) {
+ if (value === null) {
return false;
}
- return !(skipEmptyStrings && value === '');
+ return value !== '';
})
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
diff --git a/web/src/lib/stores/preferences.store.ts b/web/src/lib/stores/preferences.store.ts
index 54a96caea5..42602816b3 100644
--- a/web/src/lib/stores/preferences.store.ts
+++ b/web/src/lib/stores/preferences.store.ts
@@ -7,7 +7,7 @@ import { browser } from '$app/env';
export const locale = persisted('locale', 'default', {
serializer: {
parse: (text) => convertBCP47(text) || 'default',
- stringify: (object) => object ?? '',
+ stringify: (object = '') => object,
},
});
@@ -15,7 +15,7 @@ const preferredLocale = browser ? getPreferredLocale() : undefined;
export const lang = persisted<string>('lang', preferredLocale || defaultLang.code, {
serializer: {
parse: (text) => convertBCP47(text),
- stringify: (object) => object ?? '',
+ stringify: (object = '') => object,
},
});
diff --git a/web/src/lib/stores/sidebar.svelte.ts b/web/src/lib/stores/sidebar.svelte.ts
index 40114377aa..ee279e1e36 100644
--- a/web/src/lib/stores/sidebar.svelte.ts
+++ b/web/src/lib/stores/sidebar.svelte.ts
@@ -3,16 +3,12 @@ import { mediaQueryManager } from '#lib/stores/media-query-manager.svelte.ts';
class SidebarStore {
isOpen = $derived.by(() => mediaQueryManager.isFullSidebar);
- /**
- * Reset the sidebar visibility to the default, based on the current screen width.
- */
+ /** Reset the sidebar visibility to the default, based on the current screen width. */
reset() {
this.isOpen = mediaQueryManager.isFullSidebar;
}
- /**
- * Toggles the sidebar visibility, if available at the current screen width.
- */
+ /** Toggles the sidebar visibility, if available at the current screen width. */
toggle() {
this.isOpen = mediaQueryManager.isFullSidebar || !this.isOpen;
}
diff --git a/web/src/lib/utils.ts b/web/src/lib/utils.ts
index dd96eb1bbf..99ce124b6c 100644
--- a/web/src/lib/utils.ts
+++ b/web/src/lib/utils.ts
@@ -132,7 +132,7 @@ export const downloadRequest = <TBody = unknown>(options: DownloadRequestOptions
options = { url: options };
}
- const { signal, method, url, data: body, onDownloadProgress: onProgress } = options;
+ const { signal, method = 'GET', url, data: body, onDownloadProgress: onProgress } = options;
return new Promise<{ data: Blob; status: number }>((resolve, reject) => {
const xhr = new XMLHttpRequest();
@@ -155,7 +155,7 @@ export const downloadRequest = <TBody = unknown>(options: DownloadRequestOptions
signal.addEventListener('abort', () => xhr.abort());
}
- xhr.open(method || 'GET', url);
+ xhr.open(method, url);
xhr.responseType = 'blob';
if (body) {
diff --git a/web/src/lib/utils/actions.ts b/web/src/lib/utils/actions.ts
index d09baa746f..16a7c9b24c 100644
--- a/web/src/lib/utils/actions.ts
+++ b/web/src/lib/utils/actions.ts
@@ -56,10 +56,10 @@ const undoDeleteAssets = async (onUndoDelete: OnUndoDelete, assets: TimelineAsse
};
/**
- * Update the asset stack state in the asset store based on the provided stack response.
- * This function updates the stack information so that the icon is shown for the primary asset
- * and removes the non-primary assets from the timeline.
- */
+Update the asset stack state in the asset store based on the provided stack response.
+This function updates the stack information so that the icon is shown for the primary asset
+and removes the non-primary assets from the timeline.
+*/
export function updateStackedAssetInTimeline(timelineManager: TimelineManager, stack: StackResponseDto) {
timelineManager.update([stack.primaryAssetId], (asset) => {
asset.stack = {
diff --git a/web/src/lib/utils/album-utils.ts b/web/src/lib/utils/album-utils.ts
index a97087b031..c8ac5cddce 100644
--- a/web/src/lib/utils/album-utils.ts
+++ b/web/src/lib/utils/album-utils.ts
@@ -16,20 +16,20 @@ import { get } from 'svelte/store';
import { goto } from '$app/navigation';
/**
- * -------------------------
- * Albums General Management
- * -------------------------
- */
+-------------------------
+Albums General Management
+-------------------------
+*/
export const createAlbumAndRedirect = (name?: string, assetIds?: string[]) =>
executeMutation(createAlbumMutation, [{ createAlbumDto: { albumName: name ?? '', assetIds } }], {
onSuccess: (album) => void goto(Route.viewAlbum(album)),
});
/**
- * -------------
- * Album Sorting
- * -------------
- */
+-------------
+Album Sorting
+-------------
+*/
export interface AlbumSortOptionMetadata {
id: AlbumSortBy;
defaultOrder: SortOrder;
@@ -82,10 +82,10 @@ export const findFilterOption = (filter: string) => {
};
/**
- * --------------
- * Album Grouping
- * --------------
- */
+--------------
+Album Grouping
+--------------
+*/
export interface AlbumGroup {
id: string;
name: string;
@@ -136,10 +136,10 @@ export const getSelectedAlbumGroupOption = (settings: AlbumViewSettings) => {
};
/**
- * ----------------------------
- * Album Groups Collapse/Expand
- * ----------------------------
- */
+----------------------------
+Album Groups Collapse/Expand
+----------------------------
+*/
const getCollapsedAlbumGroups = (settings: AlbumViewSettings) => {
settings.collapsedGroups ??= {};
const { collapsedGroups, groupBy } = settings;
diff --git a/web/src/lib/utils/asset-utils.ts b/web/src/lib/utils/asset-utils.ts
index a1e33d72d7..ff397f179e 100644
--- a/web/src/lib/utils/asset-utils.ts
+++ b/web/src/lib/utils/asset-utils.ts
@@ -100,18 +100,16 @@ export const downloadArchive = async (fileName: string, options: Omit<DownloadIn
};
/**
- * Returns the lowercase filename extension without a dot (.) and
- * an empty string when not found.
- */
+Returns the lowercase filename extension without a dot (.) and
+an empty string when not found.
+*/
export function getFilenameExtension(filename: string): string {
const lastIndex = Math.max(0, filename.lastIndexOf('.'));
const startIndex = (lastIndex || Infinity) + 1;
return filename.slice(startIndex).toLowerCase();
}
-/**
- * Returns the filename of an asset including file extension
- */
+/** Returns the filename of an asset including file extension */
export function getAssetFilename(asset: AssetResponseDto): string {
const fileExtension = getFilenameExtension(asset.originalPath);
return `${asset.originalFileName}.${fileExtension}`;
@@ -152,9 +150,7 @@ export function getAssetResolution(asset: AssetResponseDto): string {
return `${asset.width} × ${asset.height}`;
}
-/**
- * Returns aspect ratio for the asset
- */
+/** Returns aspect ratio for the asset */
export function getAssetRatio(asset: AssetResponseDto) {
return asset.width && asset.height ? asset.width / asset.height : null;
}
@@ -222,9 +218,7 @@ async function addSupportedMimeTypes(): Promise<void> {
// eslint-disable-next-line unicorn/no-top-level-side-effects
void addSupportedMimeTypes();
-/**
- * Returns true if the asset is an image supported by web browsers, false otherwise
- */
+/** Returns true if the asset is an image supported by web browsers, false otherwise */
export function isWebCompatibleImage(asset: AssetResponseDto): boolean {
if (!asset.originalMimeType) {
return false;
diff --git a/web/src/lib/utils/byte-units.ts b/web/src/lib/utils/byte-units.ts
index e903c7829e..6f89a6a0a6 100644
--- a/web/src/lib/utils/byte-units.ts
+++ b/web/src/lib/utils/byte-units.ts
@@ -11,15 +11,15 @@ export const enum ByteUnit {
const byteUnits = [ByteUnit.B, ByteUnit.KiB, ByteUnit.MiB, ByteUnit.GiB, ByteUnit.TiB, ByteUnit.PiB, ByteUnit.EiB];
/**
- * Convert bytes to best human readable unit and number of that unit.
- *
- * * For `1024` bytes, returns `1` and `KiB`.
- * * For `1536` bytes, returns `1.5` and `KiB`.
- *
- * @param bytes number of bytes
- * @param maxPrecision maximum number of decimal places, default is `1`
- * @returns size (number) and unit (string)
- */
+Convert bytes to best human readable unit and number of that unit.
+
+* For `1024` bytes, returns `1` and `KiB`.
+* For `1536` bytes, returns `1.5` and `KiB`.
+
+@param bytes number of bytes
+@param maxPrecision maximum number of decimal places, default is `1`
+@returns size (number) and unit (string)
+*/
export function getBytesWithUnit(bytes: number, maxPrecision = 1): [number, ByteUnit] {
const magnitude = Math.floor(Math.log(bytes === 0 ? 1 : bytes) / Math.log(1024));
@@ -27,44 +27,44 @@ export function getBytesWithUnit(bytes: number, maxPrecision = 1): [number, Byte
}
/**
- * Localized number of bytes with a unit.
- *
- * For `1536` bytes:
- * * en: `1.5 KiB`
- * * de: `1,5 KiB`
- *
- * @param bytes number of bytes
- * @param locale locale to use, default is `navigator.language`
- * @param maxPrecision maximum number of decimal places, default is `1`
- * @returns localized bytes with unit as string
- */
+Localized number of bytes with a unit.
+
+For `1536` bytes:
+* en: `1.5 KiB`
+* de: `1,5 KiB`
+
+@param bytes number of bytes
+@param locale locale to use, default is `navigator.language`
+@param maxPrecision maximum number of decimal places, default is `1`
+@returns localized bytes with unit as string
+*/
export function getByteUnitString(bytes: number, locale?: string, maxPrecision = 1): string {
const [size, unit] = getBytesWithUnit(bytes, maxPrecision);
return `${size.toLocaleString(locale)} ${unit}`;
}
/**
- * Convert to bytes from on a specified unit.
- *
- * * `1, 'GiB'`, returns `1073741824` bytes
- *
- * @param size value to be converted
- * @param unit unit to convert from
- * @returns bytes (number)
- */
+Convert to bytes from on a specified unit.
+
+* `1, 'GiB'`, returns `1073741824` bytes
+
+@param size value to be converted
+@param unit unit to convert from
+@returns bytes (number)
+*/
export function convertToBytes(size: number, unit: ByteUnit): number {
return size * 1024 ** byteUnits.indexOf(unit);
}
/**
- * Convert from bytes to a specified unit.
- *
- * * `11073741824, 'GiB'`, returns `1` GiB
- *
- * @param bytes value to be converted
- * @param unit unit to convert to
- * @returns bytes (number)
- */
+Convert from bytes to a specified unit.
+
+* `11073741824, 'GiB'`, returns `1` GiB
+
+@param bytes value to be converted
+@param unit unit to convert to
+@returns bytes (number)
+*/
export function convertFromBytes(bytes: number, unit: ByteUnit): number {
return bytes / 1024 ** byteUnits.indexOf(unit);
}
diff --git a/web/src/lib/utils/cancellable-task.ts b/web/src/lib/utils/cancellable-task.ts
index c8cd9db4c0..499e619d6b 100644
--- a/web/src/lib/utils/cancellable-task.ts
+++ b/web/src/lib/utils/cancellable-task.ts
@@ -1,9 +1,7 @@
export class CancellableTask {
cancelToken: AbortController | null = null;
cancellable: boolean = true;
- /**
- * A promise that resolves once the bucket is loaded, and rejects if bucket is canceled.
- */
+ /** A promise that resolves once the bucket is loaded, and rejects if bucket is canceled. */
complete!: Promise<unknown>;
executed: boolean = false;
diff --git a/web/src/lib/utils/date-time.spec.ts b/web/src/lib/utils/date-time.spec.ts
index be0053990a..e8919fba02 100644
--- a/web/src/lib/utils/date-time.spec.ts
+++ b/web/src/lib/utils/date-time.spec.ts
@@ -19,11 +19,15 @@ describe('getShortDateRange', () => {
});
it('should correctly return month range if start and end date are in separate months within the same year', () => {
- expect(getShortDateRange('2022-01-01T00:00:00.000Z', '2022-02-01T00:00:00.000Z')).toEqual('Jan – Feb 2022');
+ expect(getShortDateRange('2022-01-01T00:00:00.000Z', '2022-02-01T00:00:00.000Z')).toEqual(
+ 'Jan\u{2009}–\u{2009}Feb 2022',
+ );
});
it('should correctly return range if start and end date are in separate months and years', () => {
- expect(getShortDateRange('2021-12-01T00:00:00.000Z', '2022-01-01T00:00:00.000Z')).toEqual('Dec 2021 – Jan 2022');
+ expect(getShortDateRange('2021-12-01T00:00:00.000Z', '2022-01-01T00:00:00.000Z')).toEqual(
+ 'Dec 2021\u{2009}–\u{2009}Jan 2022',
+ );
});
it('should correctly return long month if start and end date are within the same month, ignoring local time zone', () => {
@@ -38,17 +42,23 @@ describe('getShortDateRange', () => {
it('should correctly return month range if start and end date are in separate months within the same year, ignoring local time zone', () => {
vi.stubEnv('TZ', 'UTC+6');
- expect(getShortDateRange('2022-01-01T00:00:00.000Z', '2022-02-01T00:00:00.000Z')).toEqual('Jan – Feb 2022');
+ expect(getShortDateRange('2022-01-01T00:00:00.000Z', '2022-02-01T00:00:00.000Z')).toEqual(
+ 'Jan\u{2009}–\u{2009}Feb 2022',
+ );
});
it('should correctly return range if start and end date are in separate months and years, ignoring local time zone', () => {
vi.stubEnv('TZ', 'UTC+6');
- expect(getShortDateRange('2021-12-01T00:00:00.000Z', '2022-01-01T00:00:00.000Z')).toEqual('Dec 2021 – Jan 2022');
+ expect(getShortDateRange('2021-12-01T00:00:00.000Z', '2022-01-01T00:00:00.000Z')).toEqual(
+ 'Dec 2021\u{2009}–\u{2009}Jan 2022',
+ );
});
it('should correctly return range if start and end date are in separate months and years, ignoring local time zone', () => {
vi.stubEnv('TZ', 'UTC-6');
- expect(getShortDateRange('2021-12-01T00:00:00.000Z', '2022-01-01T00:00:00.000Z')).toEqual('Dec 2021 – Jan 2022');
+ expect(getShortDateRange('2021-12-01T00:00:00.000Z', '2022-01-01T00:00:00.000Z')).toEqual(
+ 'Dec 2021\u{2009}–\u{2009}Jan 2022',
+ );
});
it('should use the correct locale to return month range', () => {
@@ -58,7 +68,9 @@ describe('getShortDateRange', () => {
it('should use the correct locale to return month-year range', () => {
locale.set('fr');
- expect(getShortDateRange('2021-12-01T00:00:00.000Z', '2022-01-01T00:00:00.000Z')).toEqual('déc. 2021 – janv. 2022');
+ expect(getShortDateRange('2021-12-01T00:00:00.000Z', '2022-01-01T00:00:00.000Z')).toEqual(
+ 'déc. 2021\u{2009}–\u{2009}janv. 2022',
+ );
});
});
@@ -72,7 +84,7 @@ describe('getAlbumDateRange', () => {
});
it('should work', () => {
- expect(getAlbumDateRange('2021-01-01T00:00:00Z', '2021-01-05T00:00:00Z')).toEqual('Jan 1 – 5, 2021');
+ expect(getAlbumDateRange('2021-01-01T00:00:00Z', '2021-01-05T00:00:00Z')).toEqual('Jan 1\u{2009}–\u{2009}5, 2021');
});
it('should work with a single day range', () => {
@@ -81,17 +93,23 @@ describe('getAlbumDateRange', () => {
it('should use the proper locale', () => {
locale.set('fr');
- expect(getAlbumDateRange('2020-03-26T12:00:00Z', '2021-12-01T00:00:00Z')).toEqual('26 mars 2020 – 1 déc. 2021');
+ expect(getAlbumDateRange('2020-03-26T12:00:00Z', '2021-12-01T00:00:00Z')).toEqual(
+ '26 mars 2020\u{2009}–\u{2009}1 déc. 2021',
+ );
locale.set('en');
});
it('should correctly return range if start and end date are in separate months and years, ignoring local time zone', () => {
vi.stubEnv('TZ', 'UTC+6');
- expect(getAlbumDateRange('2021-12-01T00:00:00Z', '2022-01-01T00:00:00Z')).toEqual('Dec 1, 2021 – Jan 1, 2022');
+ expect(getAlbumDateRange('2021-12-01T00:00:00Z', '2022-01-01T00:00:00Z')).toEqual(
+ 'Dec 1, 2021\u{2009}–\u{2009}Jan 1, 2022',
+ );
});
it('should correctly return range if start and end date are in separate months and years, ignoring local time zone', () => {
vi.stubEnv('TZ', 'UTC-6');
- expect(getAlbumDateRange('2021-12-01T00:00:00Z', '2022-01-01T00:00:00Z')).toEqual('Dec 1, 2021 – Jan 1, 2022');
+ expect(getAlbumDateRange('2021-12-01T00:00:00Z', '2022-01-01T00:00:00Z')).toEqual(
+ 'Dec 1, 2021\u{2009}–\u{2009}Jan 1, 2022',
+ );
});
});
diff --git a/web/src/lib/utils/date-time.ts b/web/src/lib/utils/date-time.ts
index 5dbf46ce4c..2a2f7b097b 100644
--- a/web/src/lib/utils/date-time.ts
+++ b/web/src/lib/utils/date-time.ts
@@ -26,20 +26,18 @@ const getDateRange = (startTimestamp: string, endTimestamp: string, format: 'sho
};
/**
- * Get localized date range in short format like 'Oct – Nov 2026', with full month if start and end are the same: 'October 2026'.
- * Timestamps are expected to be date-only in UTC.
- */
+Get localized date range in short format like 'Oct – Nov 2026', with full month if start and end are the same: 'October 2026'.
+Timestamps are expected to be date-only in UTC.
+*/
export const getShortDateRange = (start: string, end: string) => getDateRange(start, end, 'short');
-/**
- * Get localized date range in long format. Timestamps are expected to be date-only in UTC.
- */
+/** Get localized date range in long format. Timestamps are expected to be date-only in UTC. */
export const getAlbumDateRange = (start: string, end: string) => getDateRange(start, end, 'long');
/**
- * Use this to convert from "5pm EST" to "5pm UTC"
- *
- * Useful with some APIs where you want to query by "today", but the values in the database are stored as UTC
- */
+Use this to convert from "5pm EST" to "5pm UTC"
+
+Useful with some APIs where you want to query by "today", but the values in the database are stored as UTC
+*/
export const asLocalTimeISO = (date: DateTime<true>) =>
(date.setZone('utc', { keepLocalTime: true }) as DateTime<true>).toISO();
diff --git a/web/src/lib/utils/duplicate-utils.ts b/web/src/lib/utils/duplicate-utils.ts
index a6776096ff..3ece216086 100644
--- a/web/src/lib/utils/duplicate-utils.ts
+++ b/web/src/lib/utils/duplicate-utils.ts
@@ -150,9 +150,9 @@ const metadataFields = [
keys: ['latitude', 'longitude'],
render: (asset, $t) =>
// eslint-disable-next-line eqeqeq
- asset.exifInfo?.latitude != null && asset.exifInfo?.longitude != null
- ? `${asset.exifInfo.latitude.toFixed(4)}, ${asset.exifInfo.longitude.toFixed(4)}`
- : $t('unknown'),
+ asset.exifInfo?.latitude == null || asset.exifInfo?.longitude == null
+ ? $t('unknown')
+ : `${asset.exifInfo.latitude.toFixed(4)}, ${asset.exifInfo.longitude.toFixed(4)}`,
},
{
icon: mdiCameraOutline,
diff --git a/web/src/lib/utils/editor.ts b/web/src/lib/utils/editor.ts
index 6c91f49245..9e9b914e1e 100644
--- a/web/src/lib/utils/editor.ts
+++ b/web/src/lib/utils/editor.ts
@@ -2,6 +2,7 @@ import type { EditActions } from '#lib/managers/edit/edit-manager.svelte.ts';
import type { MirrorParameters, RotateParameters } from '@immich/sdk';
import { compose, flipX, flipY, identity, rotate } from 'transformation-matrix';
+// eslint-disable-next-line unicorn/no-unnecessary-parameters
const isCloseToZero = (x: number, epsilon: number = 1e-15) => Math.abs(x) < epsilon;
export const normalizeTransformEdits = (
diff --git a/web/src/lib/utils/invocationTracker.ts b/web/src/lib/utils/invocationTracker.ts
index ca86b69053..8fa611331c 100644
--- a/web/src/lib/utils/invocationTracker.ts
+++ b/web/src/lib/utils/invocationTracker.ts
@@ -1,10 +1,10 @@
import { handleError } from '#lib/utils/handle-error.ts';
/**
- * Tracks the state of asynchronous invocations to handle race conditions and stale operations.
- * This class helps manage concurrent operations by tracking which invocations are active
- * and allowing operations to check if they're still valid.
- */
+Tracks the state of asynchronous invocations to handle race conditions and stale operations.
+This class helps manage concurrent operations by tracking which invocations are active
+and allowing operations to check if they're still valid.
+*/
export class InvocationTracker {
/** Counter for the number of invocations that have been started */
invocationsStarted = 0;
@@ -14,28 +14,26 @@ export class InvocationTracker {
constructor() {}
/**
- * Starts a new invocation and returns an object with utilities to manage the invocation lifecycle.
- * @returns An object containing methods to manage the invocation:
- * - isInvalidInvocationError: Checks if an error is an invalid invocation error
- * - checkStillValid: Throws an error if the invocation is no longer valid
- * - endInvocation: Marks the invocation as complete
- */
+ Starts a new invocation and returns an object with utilities to manage the invocation lifecycle.
+ @returns An object containing methods to manage the invocation:
+ - isInvalidInvocationError: Checks if an error is an invalid invocation error
+ - checkStillValid: Throws an error if the invocation is no longer valid
+ - endInvocation: Marks the invocation as complete
+ */
startInvocation() {
this.invocationsStarted++;
const invocation = this.invocationsStarted;
return {
/**
- * Throws an error if this invocation is no longer valid
- * @throws {Error} If the invocation is no longer valid
- */
+ Throws an error if this invocation is no longer valid
+ @throws {Error} If the invocation is no longer valid
+ */
isStillValid: () => {
return invocation === this.invocationsStarted;
},
- /**
- * Marks this invocation as complete
- */
+ /** Marks this invocation as complete */
endInvocation: () => {
this.invocationsEnded = invocation;
},
@@ -43,9 +41,9 @@ export class InvocationTracker {
}
/**
- * Checks if there are any active invocations
- * @returns True if there are active invocations, false otherwise
- */
+ Checks if there are any active invocations
+ @returns True if there are active invocations, false otherwise
+ */
isActive() {
return this.invocationsStarted !== this.invocationsEnded;
}
diff --git a/web/src/lib/utils/navigation.ts b/web/src/lib/utils/navigation.ts
index afd5aaaf67..2d77463627 100644
--- a/web/src/lib/utils/navigation.ts
+++ b/web/src/lib/utils/navigation.ts
@@ -70,9 +70,7 @@ function currentUrl() {
}
interface Route {
- /**
- * The route to target, or 'current' to stay on current route.
- */
+ /** The route to target, or 'current' to stay on current route. */
targetRoute: string | 'current';
}
diff --git a/web/src/lib/utils/ocr-utils.ts b/web/src/lib/utils/ocr-utils.ts
index 9bf80bd2a7..a44d58e157 100644
--- a/web/src/lib/utils/ocr-utils.ts
+++ b/web/src/lib/utils/ocr-utils.ts
@@ -31,10 +31,10 @@ const getVerticalMode = (width: number, height: number, text: string): VerticalM
};
/**
- * Calculate bounding box transform from OCR points. Result matrix can be used as input for css matrix3d.
- * @param points - Array of 4 corner points of the bounding box
- * @returns 4x4 matrix to transform the div with text onto the polygon defined by the corner points, and size to set on the source div.
- */
+Calculate bounding box transform from OCR points. Result matrix can be used as input for css matrix3d.
+@param points - Array of 4 corner points of the bounding box
+@returns 4x4 matrix to transform the div with text onto the polygon defined by the corner points, and size to set on the source div.
+*/
export const calculateBoundingBoxMatrix = (points: Point[]): Size & { matrix: number[] } => {
const [topLeft, topRight, bottomRight, bottomLeft] = points;
diff --git a/web/src/lib/utils/places-utils.ts b/web/src/lib/utils/places-utils.ts
index 4a2bb0c32a..54f0202591 100644
--- a/web/src/lib/utils/places-utils.ts
+++ b/web/src/lib/utils/places-utils.ts
@@ -3,10 +3,10 @@ import { type AssetResponseDto } from '@immich/sdk';
import { get } from 'svelte/store';
/**
- * --------------
- * Places Grouping
- * --------------
- */
+--------------
+Places Grouping
+--------------
+*/
export interface PlacesGroup {
id: string;
name: string;
@@ -14,10 +14,10 @@ export interface PlacesGroup {
}
/**
- * ----------------------------
- * Places Groups Collapse/Expand
- * ----------------------------
- */
+----------------------------
+Places Groups Collapse/Expand
+----------------------------
+*/
const getCollapsedPlacesGroups = (settings: PlacesViewSettings) => {
settings.collapsedGroups ??= {};
const { collapsedGroups, groupBy } = settings;
diff --git a/web/src/lib/utils/sw-messenger.ts b/web/src/lib/utils/sw-messenger.ts
index b656f3fc2c..7b0de18f7b 100644
--- a/web/src/lib/utils/sw-messenger.ts
+++ b/web/src/lib/utils/sw-messenger.ts
@@ -5,9 +5,7 @@ export class ServiceWorkerMessenger {
this.#serviceWorker = serviceWorker;
}
- /**
- * Send a one-way message to the service worker.
- */
+ /** Send a one-way message to the service worker. */
send(type: string, data: Record<string, unknown>) {
this.#serviceWorker.controller?.postMessage({
type,
diff --git a/web/src/routes/(user)/people/[personId]/[[photos=photos]]/[[assetId=id]]/+page.svelte b/web/src/routes/(user)/people/[personId]/[[photos=photos]]/[[assetId=id]]/+page.svelte
index 4b82c65dcd..c1a8afffc4 100644
--- a/web/src/routes/(user)/people/[personId]/[[photos=photos]]/[[assetId=id]]/+page.svelte
+++ b/web/src/routes/(user)/people/[personId]/[[photos=photos]]/[[assetId=id]]/+page.svelte
@@ -88,12 +88,12 @@
let suggestedPeople: PersonResponseDto[] = $state([]);
/**
- * Save the word used to search people name: for example,
- * if searching 'r' and the server returns 15 people with names starting with 'r',
- * there's no need to search again people with name starting with 'ri'.
- * However, it needs to make a new api request if searching 'r' returns 20 names (arbitrary value, the limit sent back by the server).
- * or if the new search word starts with another word / letter
- **/
+ Save the word used to search people name: for example,
+ if searching 'r' and the server returns 15 people with names starting with 'r',
+ there's no need to search again people with name starting with 'ri'.
+ However, it needs to make a new api request if searching 'r' returns 20 names (arbitrary value, the limit sent back by the server).
+ or if the new search word starts with another word / letter
+ */
let isSearchingPeople = $state(false);
let suggestionContainer: HTMLElement | undefined = $state();
diff --git a/web/src/routes/(user)/shared-links/(list)/SharedLinkCard.svelte b/web/src/routes/(user)/shared-links/(list)/SharedLinkCard.svelte
index 596f6d9a7b..273b840a97 100644
--- a/web/src/routes/(user)/shared-links/(list)/SharedLinkCard.svelte
+++ b/web/src/routes/(user)/shared-links/(list)/SharedLinkCard.svelte
@@ -16,7 +16,7 @@
let now = DateTime.now();
let expiresAt = $derived(sharedLink.expiresAt ? DateTime.fromISO(sharedLink.expiresAt) : undefined);
- let isExpired = $derived(expiresAt ? now > expiresAt : false);
+ let isExpired = $derived(expiresAt && now > expiresAt);
const getCountDownExpirationDate = (expiresAtDate: DateTime, now: DateTime) => {
const relativeUnits: ToRelativeUnit[] = ['days', 'hours', 'minutes', 'seconds'];
diff --git a/web/src/routes/(user)/utilities/duplicates/[[photos=photos]]/[[assetId=id]]/+page.svelte b/web/src/routes/(user)/utilities/duplicates/[[photos=photos]]/[[assetId=id]]/+page.svelte
index 8e61a21310..d106a3bb92 100644
--- a/web/src/routes/(user)/utilities/duplicates/[[photos=photos]]/[[assetId=id]]/+page.svelte
+++ b/web/src/routes/(user)/utilities/duplicates/[[photos=photos]]/[[assetId=id]]/+page.svelte
@@ -114,9 +114,9 @@
},
});
- const { success, error, errorMessage } = response[0];
+ const { success, error, errorMessage = error } = response[0];
if (!success) {
- throw new Error(errorMessage || error);
+ throw new Error(errorMessage);
}
duplicates = duplicates.filter((duplicate) => duplicate.duplicateId !== duplicateId);
diff --git a/web/src/routes/(user)/workflows/[workflowId]/WorkflowStepCard.svelte b/web/src/routes/(user)/workflows/[workflowId]/WorkflowStepCard.svelte
index 06060395b7..b750da9f2d 100644
--- a/web/src/routes/(user)/workflows/[workflowId]/WorkflowStepCard.svelte
+++ b/web/src/routes/(user)/workflows/[workflowId]/WorkflowStepCard.svelte
@@ -51,6 +51,7 @@
let dragImage = $state<Element>();
let isDropTarget = $state(false);
+ // eslint-disable-next-line unicorn/no-unnecessary-parameters
const truncate = (input: string, max = 24) => (input.length > max ? input.slice(0, max - 1) + '…' : input);
const formatConfigValue = (value: unknown): string => {
diff --git a/web/src/routes/UploadAssetPreview.svelte b/web/src/routes/UploadAssetPreview.svelte
index 9802dad6f5..23fb3aa9ee 100644
--- a/web/src/routes/UploadAssetPreview.svelte
+++ b/web/src/routes/UploadAssetPreview.svelte
@@ -26,11 +26,11 @@
let { uploadAsset }: Props = $props();
- const handleDismiss = (uploadAsset: UploadAsset) => {
+ const handleDismiss = () => {
uploadAssetsStore.removeItem(uploadAsset.id);
};
- const handleRetry = async (uploadAsset: UploadAsset) => {
+ const handleRetry = async () => {
uploadAssetsStore.removeItem(uploadAsset.id);
await fileUploadHandler({ files: [uploadAsset.file], albumId: uploadAsset.albumId });
};
@@ -76,16 +76,16 @@
>
<Icon icon={mdiOpenInNew} size="20" />
</a>
- <button type="button" onclick={() => handleDismiss(uploadAsset)} class="" aria-hidden="true" tabindex={-1}>
+ <button type="button" onclick={() => handleDismiss()} class="" aria-hidden="true" tabindex={-1}>
<Icon icon={mdiClose} size="20" />
</button>
</div>
{:else if uploadAsset.state === UploadState.ERROR}
<div class="flex items-center justify-between gap-1">
- <button type="button" onclick={() => handleRetry(uploadAsset)} class="" aria-hidden="true" tabindex={-1}>
+ <button type="button" onclick={() => handleRetry()} class="" aria-hidden="true" tabindex={-1}>
<Icon icon={mdiRestart} size="20" />
</button>
- <button type="button" onclick={() => handleDismiss(uploadAsset)} class="" aria-hidden="true" tabindex={-1}>
+ <button type="button" onclick={() => handleDismiss()} class="" aria-hidden="true" tabindex={-1}>
<Icon icon={mdiClose} size="20" />
</button>
</div>
diff --git a/web/src/routes/admin/server-status/ServerStatisticsPanel.svelte b/web/src/routes/admin/server-status/ServerStatisticsPanel.svelte
index 7714f69386..883581eafc 100644
--- a/web/src/routes/admin/server-status/ServerStatisticsPanel.svelte
+++ b/web/src/routes/admin/server-status/ServerStatisticsPanel.svelte
@@ -36,6 +36,7 @@
const [storage, storageUnit] = $derived(stats ? getStorageUsageWithUnit(stats.usage) : [undefined, undefined]);
+ // eslint-disable-next-line unicorn/no-unnecessary-parameters
const zeros = (value: number, maxLength = 13) => {
const valueLength = value.toString().length;
const zeroLength = maxLength - valueLength;
diff --git a/web/src/routes/auth/onboarding/+page.svelte b/web/src/routes/auth/onboarding/+page.svelte
index 7f1c3a8f6a..745c73d7a2 100644
--- a/web/src/routes/auth/onboarding/+page.svelte
+++ b/web/src/routes/auth/onboarding/+page.svelte
@@ -106,25 +106,21 @@
authManager.user.isAdmin && !serverConfig.isOnboarded ? OnboardingRole.SERVER : OnboardingRole.USER,
);
- let onboardingStepCount = $derived(onboardingSteps.filter((step) => shouldRunStep(step.role, userRole)).length);
+ let onboardingStepCount = $derived(onboardingSteps.filter((step) => shouldRunStep(step.role)).length);
let onboardingProgress = $derived(
- onboardingSteps.filter((step, i) => shouldRunStep(step.role, userRole) && i <= index).length - 1,
+ onboardingSteps.filter((step, i) => shouldRunStep(step.role) && i <= index).length - 1,
);
- const shouldRunStep = (stepRole: OnboardingRole, userRole: OnboardingRole) => {
+ const shouldRunStep = (stepRole: OnboardingRole) => {
return (
stepRole === OnboardingRole.USER ||
(stepRole === OnboardingRole.SERVER && userRole === OnboardingRole.SERVER && !serverConfig.isOnboarded)
);
};
- const previousStepIndex = $derived(
- onboardingSteps.findLastIndex((step, i) => shouldRunStep(step.role, userRole) && i < index),
- );
+ const previousStepIndex = $derived(onboardingSteps.findLastIndex((step, i) => shouldRunStep(step.role) && i < index));
- const nextStepIndex = $derived(
- onboardingSteps.findIndex((step, i) => shouldRunStep(step.role, userRole) && i > index),
- );
+ const nextStepIndex = $derived(onboardingSteps.findIndex((step, i) => shouldRunStep(step.role) && i > index));
const handleNextClicked = async () => {
if (nextStepIndex === -1) {