Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
chore: clean up and eslint fixes
Kyle Mendell3426e870a34a
diff --git a/src/lib/components/universal-table.svelte b/src/lib/components/universal-table.svelteindex 1331f7ed7..24a15343d 100644--- a/src/lib/components/universal-table.svelte+++ b/src/lib/components/universal-table.svelte@@ -74,7 +74,7 @@},columns,getRowId: idKey- ? (originalRow: TData, _index: number, _parent?: RowData) => {+ ? (originalRow: TData) => {return String(originalRow[idKey]);}: undefined,@@ -129,7 +129,7 @@}const newSelectedIdsArray = Object.entries(selectedRowIds)- .filter(([_, selected]) => selected)+ .filter(([key, selected]) => selected).map(([id]) => id);const sortedCurrentProp = [...(selectedIds || [])].sort();diff --git a/src/lib/services/docker/auto-update-service.ts b/src/lib/services/docker/auto-update-service.tsindex d005cbb14..85707fad7 100644--- a/src/lib/services/docker/auto-update-service.ts+++ b/src/lib/services/docker/auto-update-service.ts@@ -1,18 +1,14 @@-import { listContainers, getContainer, recreateContainer } from './container-service'; // Import recreateContainer, remove restartContainer+import { listContainers, getContainer, recreateContainer } from './container-service';import { listStacks, getStack, fullyRedeployStack } from './stack-service';import { pullImage, getImage, listImages } from './image-service';import { getSettings } from '../settings-service';-import yaml from 'js-yaml'; // Add js-yaml import+import yaml from 'js-yaml';import type { ServiceContainer } from '$lib/types/docker';import type { Stack } from '$lib/types/docker/stack.type';-// Track which entities are being updated to avoid concurrent updatesconst updatingContainers = new Set<string>();const updatingStacks = new Set<string>();-/**- * Checks for container image updates and applies them if configured- */export async function checkAndUpdateContainers(): Promise<{checked: number;updated: number;@@ -20,25 +16,17 @@ export async function checkAndUpdateContainers(): Promise<{}> {const settings = await getSettings();- // Skip if global auto-update is disabledif (!settings.autoUpdate) {return { checked: 0, updated: 0, errors: [] };}const containers = await listContainers();-- // Get detailed container info for each container to access labelsconst eligibleContainers: ServiceContainer[] = [];for (const container of containers) {- // Skip containers that aren't runningif (container.state !== 'running') continue;-try {- // Get detailed container info to access labelsconst containerDetails = await getContainer(container.id);-- // Check if auto-update label exists and is set to trueif (containerDetails?.labels?.['arcane.auto-update'] === 'true') {eligibleContainers.push(container);}@@ -53,11 +41,9 @@ export async function checkAndUpdateContainers(): Promise<{errors: [] as Array<{ id: string; error: string }>};- // Process eligible containersfor (const container of eligibleContainers) {- const containerId = container.id; // Use consistent ID variable+ const containerId = container.id;try {- // Skip if already being updatedif (updatingContainers.has(containerId)) {console.log(`Auto-update: Skipping ${container.name} (${containerId}), already in progress.`);continue;@@ -67,17 +53,11 @@ export async function checkAndUpdateContainers(): Promise<{if (updateAvailable) {updatingContainers.add(containerId);console.log(`Auto-update: Update found for container ${container.name} (${containerId}). Recreating...`);-- // Pull the latest image firstconsole.log(`Auto-update: Pulling latest image ${container.image} for ${container.name}...`);await pullImage(container.image);-- // Recreate the container using the new helper functionawait recreateContainer(containerId);-console.log(`Auto-update: Container ${container.name} recreated successfully`);results.updated++;-updatingContainers.delete(containerId);} else {console.log(`Auto-update: Container ${container.name} (${containerId}) is up-to-date.`);@@ -89,7 +69,6 @@ export async function checkAndUpdateContainers(): Promise<{id: containerId,error: msg});- // Ensure the lock is released even on errorupdatingContainers.delete(containerId);}}@@ -97,9 +76,6 @@ export async function checkAndUpdateContainers(): Promise<{return results;}-/**- * Checks for stack updates and applies them if configured- */export async function checkAndUpdateStacks(): Promise<{checked: number;updated: number;@@ -107,7 +83,6 @@ export async function checkAndUpdateStacks(): Promise<{}> {const settings = await getSettings();- // Skip if global auto-update is disabledif (!settings.autoUpdate) {return { checked: 0, updated: 0, errors: [] };}@@ -116,28 +91,23 @@ export async function checkAndUpdateStacks(): Promise<{const eligibleStacksForProcessing: Stack[] = [];for (const listedStack of allListedStacks) {- // Only consider running or partially running stacksif (listedStack.status !== 'running' && listedStack.status !== 'partially running') {continue;}-try {- // Fetch full stack details to get composeContent for label checkingconst fullStack = await getStack(listedStack.id);if (!fullStack.composeContent) {console.warn(`Auto-update: Stack ${listedStack.id} has no compose content, skipping eligibility check.`);continue;}-- const composeData = yaml.load(fullStack.composeContent) as any;+ const composeData = yaml.load(fullStack.composeContent) as Record<string, unknown>;let stackIsEligibleByLabel = false;-- if (composeData && composeData.services) {- for (const serviceName in composeData.services) {- const service = composeData.services[serviceName];+ if (composeData && typeof composeData === 'object' && 'services' in composeData) {+ const services = (composeData as { services: Record<string, any> }).services;+ for (const serviceName in services) {+ const service = services[serviceName];if (service.labels) {let labelValue: string | undefined = undefined;- // Docker Compose labels can be an array of "key=value" strings or a map/objectif (Array.isArray(service.labels)) {const foundLabel = service.labels.find((l: string) => l.startsWith('arcane.stack.auto-update='));if (foundLabel) {@@ -146,18 +116,14 @@ export async function checkAndUpdateStacks(): Promise<{} else if (typeof service.labels === 'object' && service.labels !== null) {labelValue = service.labels['arcane.stack.auto-update'];}-if (labelValue === 'true') {stackIsEligibleByLabel = true;- break; // Found one service with the label, stack is eligible+ break;}}}}-if (stackIsEligibleByLabel) {- // Use the listedStack object as it's from the initial list.- // fullStack could also be used if preferred, ensure types are compatible.eligibleStacksForProcessing.push(listedStack);}} catch (error) {@@ -166,32 +132,24 @@ export async function checkAndUpdateStacks(): Promise<{}const results = {- checked: eligibleStacksForProcessing.length, // Number of stacks found eligible and processed+ checked: eligibleStacksForProcessing.length,updated: 0,errors: [] as Array<{ id: string; error: string }>};- // Process eligible stacksfor (const stackToUpdate of eligibleStacksForProcessing) {try {- // Skip if already being updatedif (updatingStacks.has(stackToUpdate.id)) {console.log(`Auto-update: Skipping stack ${stackToUpdate.name} (${stackToUpdate.id}), already in progress.`);continue;}-- // checkStackImagesUpdate will call getStack internally again to ensure it has the latest- // composeContent before checking images. This is acceptable.const updateAvailable = await checkStackImagesUpdate(stackToUpdate);if (updateAvailable) {updatingStacks.add(stackToUpdate.id);-console.log(`Auto-update: Redeploying stack ${stackToUpdate.name} (${stackToUpdate.id})`);await fullyRedeployStack(stackToUpdate.id);-console.log(`Auto-update: Stack ${stackToUpdate.name} redeployed successfully`);results.updated++;-updatingStacks.delete(stackToUpdate.id);} else {console.log(`Auto-update: Stack ${stackToUpdate.name} (${stackToUpdate.id}) is up-to-date or no images triggered an update.`);@@ -203,41 +161,28 @@ export async function checkAndUpdateStacks(): Promise<{id: stackToUpdate.id,error: msg});- updatingStacks.delete(stackToUpdate.id); // Ensure lock is released on error+ updatingStacks.delete(stackToUpdate.id);}}return results;}-/**- * Checks if a container's image has an update available- */async function checkContainerImageUpdate(container: ServiceContainer): Promise<boolean> {try {const imageRef = container.image;- // Skip digest-only references (e.g. sha256:… – they can’t be updated by tag)if (/^sha256:[A-Fa-f0-9]{64}$/.test(imageRef)) {return false;}-- // Current image digestconst currentImage = await getImage(container.imageId);if (!currentImage) return false;-- // Pull the image to check for updates (but don't use it yet)await pullImage(imageRef);-- // Get the fresh image infoconst lastColon = imageRef.lastIndexOf(':');const imageName = lastColon === -1 ? imageRef : imageRef.slice(0, lastColon);const tag = lastColon === -1 ? 'latest' : imageRef.slice(lastColon + 1);const freshImages = await listImages();const freshImage = freshImages.find((img) => (img.repo === imageName || img.repo.endsWith(`/${imageName}`)) && img.tag === tag);-if (!freshImage) return false;-- // Compare image IDs - if different, update is availablereturn freshImage.id !== container.imageId;} catch (error: unknown) {console.error(`Error checking for image update for ${container.name}:`, error);@@ -245,93 +190,69 @@ async function checkContainerImageUpdate(container: ServiceContainer): Promise<b}}-/**- * Checks if any images referenced in a stack's compose file have updates available.- * Iterates through all images and returns true if at least one has a new digest.- */async function checkStackImagesUpdate(stack: Stack): Promise<boolean> {- let updateFound = false; // Flag to track if any update is found-+ let updateFound = false;try {const fullStack = await getStack(stack.id);if (!fullStack || !fullStack.composeContent) {console.warn(`Stack ${stack.name} (${stack.id}) compose content not found.`);return false;}-- // Extract image references from compose file (simplified parsing)const composeLines = fullStack.composeContent.split('\n');const imageLines = composeLines.filter((line) => line.trim().startsWith('image:') || line.includes(' image:'));-if (imageLines.length === 0) {console.log(`No image references found in stack ${stack.name}.`);return false;}-const imageRefs = imageLines.map((line) => {const imagePart = line.split('image:')[1].trim();- // Handle potential comments or extra content on the linereturn imagePart.replace(/['"]/g, '').split(/[\s#]/)[0];})- .filter((ref) => ref && (ref.includes(':') || ref.includes('/'))); // Filter out invalid/local refs-- const uniqueImageRefs = [...new Set(imageRefs)]; // Check each unique image only once+ .filter((ref) => ref && (ref.includes(':') || ref.includes('/')));+ const uniqueImageRefs = [...new Set(imageRefs)];console.log(`Checking images for stack ${stack.name}: ${uniqueImageRefs.join(', ')}`);-- // Check each unique image for updatesfor (const imageRef of uniqueImageRefs) {try {- // 1. Get current image details (if it exists locally)let currentImageId: string | null = null;try {const currentImage = await getImage(imageRef);if (currentImage) {- currentImageId = currentImage.Id; // Use the full ID (digest)+ currentImageId = currentImage.Id;}- } catch (e: any) {- // Ignore errors if image doesn't exist locally yet- if (e.statusCode !== 404) {+ } catch (e: unknown) {+ if (e instanceof Error && 'statusCode' in e && (e as { statusCode?: number }).statusCode !== 404) {console.warn(`Could not get current details for image ${imageRef}: ${e.message}`);}}-- // 2. Pull the image to get the latest versionconsole.log(`Pulling ${imageRef} to check for updates...`);- await pullImage(imageRef); // This might throw if pull fails-- // 3. Get new image details after pull+ await pullImage(imageRef);let newImageId: string | null = null;try {- const newImage = await getImage(imageRef); // Get details of the potentially updated image+ const newImage = await getImage(imageRef);if (newImage) {newImageId = newImage.Id;} else {console.warn(`Image ${imageRef} not found after pull.`);- continue; // Skip if image disappeared after pull (unlikely)+ continue;}- } catch (e: any) {- console.error(`Could not get details for image ${imageRef} after pull: ${e.message}`);- continue; // Skip this image if we can't get its details+ } catch (e: unknown) {+ console.error(`Could not get details for image ${imageRef} after pull: ${e instanceof Error ? e.message : String(e)}`);+ continue;}-- // 4. Compare IDsif (newImageId && newImageId !== currentImageId) {console.log(`Update found for image ${imageRef} in stack ${stack.name}. New ID: ${newImageId}, Old ID: ${currentImageId}`);updateFound = true;- // Do NOT return early, continue checking other images} else {console.log(`Image ${imageRef} is up-to-date.`);}} catch (error: unknown) {console.error(`Error checking/pulling image update for ${imageRef} in stack ${stack.name}:`, error);- // continue to next image}- } // End of loop through imageRefs-- return updateFound; // Return true only if at least one update was found+ }+ return updateFound;} catch (error: unknown) {console.error(`Error processing stack updates for ${stack.name}:`, error);- return false; // Return false if there's an error processing the stack itself+ return false;}}diff --git a/src/lib/services/docker/container-service.ts b/src/lib/services/docker/container-service.tsindex 33be4b791..17fa49165 100644--- a/src/lib/services/docker/container-service.ts+++ b/src/lib/services/docker/container-service.ts@@ -70,7 +70,7 @@ export async function getContainer(containerId: string) {};} catch (error: unknown) {console.error(`Docker Service: Error getting container ${containerId}:`, error);- if (error instanceof Error && 'statusCode' in error && (error as any).statusCode === 404) {+ if (error instanceof Error && 'statusCode' in error && (error as { statusCode?: number }).statusCode === 404) {return null;}throw new Error(`Failed to get container details for ${containerId} using host "${dockerHost}".`);@@ -157,7 +157,7 @@ export async function removeContainer(containerId: string, force = false): Promi// Type guard and handle custom error typesif (error instanceof Error && 'statusCode' in error) {- const dockerError = error as Error & { statusCode: number };+ const dockerError = error as Error & { statusCode?: number };// Use custom error types for better handling in the API layerif (dockerError.statusCode === 404) {@@ -375,7 +375,7 @@ export async function getContainerStats(containerId: string): Promise<Docker.Contry {await container.inspect();} catch (inspectError: unknown) {- if (inspectError instanceof Error && 'statusCode' in inspectError && (inspectError as any).statusCode === 404) {+ if (inspectError instanceof Error && 'statusCode' in inspectError && (inspectError as { statusCode?: number }).statusCode === 404) {throw new NotFoundError(`Container ${containerId} not found when trying to get stats.`);}// Rethrow other inspect errors@@ -397,7 +397,7 @@ export async function getContainerStats(containerId: string): Promise<Docker.Con} catch (error: unknown) {// Handle cases where stats fails because the container isn't running (often a 404 or 500 from Docker API)if (error instanceof Error && 'statusCode' in error) {- const dockerError = error as Error & { statusCode: number; message?: string };+ const dockerError = error as Error & { statusCode?: number; message?: string };if (dockerError.statusCode === 404) {// Could be container not found OR container not running (Docker API might return 404 for stats on stopped container)@@ -417,7 +417,7 @@ export async function getContainerStats(containerId: string): Promise<Docker.Conconsole.error(`Docker Service: Error getting stats for container ${containerId}:`, error);// Throw a DockerApiError for unexpected issues- const statusCode = error instanceof Error && 'statusCode' in error ? (error as any).statusCode : 500;+ const statusCode = error instanceof Error && 'statusCode' in error ? (error as { statusCode?: number }).statusCode : 500;const message = error instanceof Error ? error.message : String(error);throw new DockerApiError(`Failed to get stats for container ${containerId}: ${message || 'Unknown Docker error'}`, statusCode);}@@ -494,7 +494,7 @@ export async function recreateContainer(containerId: string): Promise<ServiceConawait stopContainer(containerId);} catch (stopError: unknown) {// Ignore "already stopped" errors- if (stopError instanceof Error && 'statusCode' in stopError && (stopError as any).statusCode !== 304 && (stopError as any).statusCode !== 404) {+ if (stopError instanceof Error && 'statusCode' in stopError && (stopError as { statusCode?: number }).statusCode !== 304 && (stopError as { statusCode?: number }).statusCode !== 404) {console.warn(`Could not stop container ${containerId} before removal: ${stopError instanceof Error ? stopError.message : 'Unknown error'}`);}}@@ -525,7 +525,7 @@ export async function recreateContainer(containerId: string): Promise<ServiceCon} catch (error: unknown) {console.error(`Failed to recreate container ${containerId}:`, error);- const statusCode = error instanceof Error && 'statusCode' in error ? (error as any).statusCode : 500;+ const statusCode = error instanceof Error && 'statusCode' in error ? (error as { statusCode?: number }).statusCode : 500;const message = error instanceof Error ? error.message : String(error);throw new DockerApiError(`Failed to recreate container ${originalContainer?.name || containerId}: ${message || 'Unknown error'}`, statusCode);diff --git a/src/lib/services/docker/core.ts b/src/lib/services/docker/core.tsindex d35585d57..d7c095177 100644--- a/src/lib/services/docker/core.ts+++ b/src/lib/services/docker/core.ts@@ -1,27 +1,19 @@import Docker from 'dockerode';import type { DockerConnectionOptions } from '$lib/types/docker';-import { getSettings } from '$lib/services/settings-service'; // Assuming getSettings is async and available here+import { getSettings } from '$lib/services/settings-service';let dockerClient: Docker | null = null;-export let dockerHost = 'unix:///var/run/docker.sock'; // Default and cache for the last used host+export let dockerHost = 'unix:///var/run/docker.sock';-/**- * The function `getDockerInfo` asynchronously retrieves information about the Docker environment.- */export async function getDockerInfo() {- const docker = await getDockerClient(); // Changed: await getDockerClient+ const docker = await getDockerClient();return await docker.info();}-/**- * The function `getDockerClient` initializes and returns a Docker client.- * It fetches Docker host from settings if the client is not already initialized.- */export async function getDockerClient(): Promise<Docker> {- // Changed: now asyncif (!dockerClient) {console.log('Docker client is null, attempting to initialize.');- let hostToUse = dockerHost; // Start with current module-level host (default or last used)+ let hostToUse = dockerHost;try {const currentSettings = await getSettings();if (currentSettings?.dockerHost) {@@ -32,20 +24,19 @@ export async function getDockerClient(): Promise<Docker> {}} catch (err) {console.error('Failed to get settings for Docker client initialization, using fallback:', err);- // hostToUse remains as the current dockerHost or default}console.log(`Initializing Docker client with host: "${hostToUse}".`);const connectionOpts = createConnectionOptions(hostToUse);try {dockerClient = new Docker(connectionOpts);- dockerHost = hostToUse; // Update module-level variable to the host actually used.+ dockerHost = hostToUse;console.log(`Docker client initialized successfully with host: ${dockerHost}`, connectionOpts);} catch (initError) {console.error(`Failed to initialize Docker client with host ${hostToUse}:`, initError);- dockerClient = null; // Ensure client is null if initialization fails- dockerHost = 'unix:///var/run/docker.sock'; // Reset to default on failure to avoid broken state- throw initError; // Re-throw error so caller knows initialization failed+ dockerClient = null;+ dockerHost = 'unix:///var/run/docker.sock';+ throw initError;}}if (!dockerClient) {@@ -55,13 +46,8 @@ export async function getDockerClient(): Promise<Docker> {return dockerClient;}-/**- * The function initializes a Docker connection based on the provided options.- * This function is typically called by createConnectionOptions or directly if needed.- * Note: This function directly mutates dockerClient and dockerHost module variables.- */export function initializeDocker(options: DockerConnectionOptions): Docker {- const connectionOpts: Record<string, any> = {};+ const connectionOpts: Record<string, unknown> = {};if (options.socketPath) {connectionOpts.socketPath = options.socketPath;@@ -82,10 +68,6 @@ export function initializeDocker(options: DockerConnectionOptions): Docker {return dockerClient;}-/**- * The function `updateDockerConnection` establishes a connection to a Docker host based on the- * provided host string. This forces a re-initialization of the client.- */export function updateDockerConnection(newHost: string): void {try {if (!newHost) {@@ -101,23 +83,19 @@ export function updateDockerConnection(newHost: string): void {console.log(`updateDockerConnection called. Forcing connection update to Docker at ${newHost}`);const connectionOpts = createConnectionOptions(newHost);- dockerClient = new Docker(connectionOpts); // Create new client- dockerHost = newHost; // Update module-level variable+ dockerClient = new Docker(connectionOpts);+ dockerHost = newHost;console.log('Docker connection explicitly updated with options:', connectionOpts);} catch (error) {console.error(`Error explicitly updating Docker connection to ${newHost}:`, error);- dockerClient = null; // Ensure client is null if update fails+ dockerClient = null;}}-/**- * The function `testDockerConnection` checks if a connection to Docker can be established.- */export async function testDockerConnection(): Promise<boolean> {- // Changed: now asynctry {- const docker = await getDockerClient(); // Changed: await getDockerClient+ const docker = await getDockerClient();const info = await docker.info();return !!info;} catch (err) {@@ -126,18 +104,8 @@ export async function testDockerConnection(): Promise<boolean> {}}-/**- * The function `createConnectionOptions` parses a host string to create connection options for- * different types of connections such as Unix socket, TCP, and HTTPS.- * @param {string} host - The `createConnectionOptions` function takes a `host` parameter as input and- * based on the format of the host, it constructs connection options for different types of connections- * like Unix socket, TCP, or HTTPS.- * @returns The `createConnectionOptions` function returns a record object containing connection- * options based on the provided `host` parameter. The connection options include `socketPath`, `host`,- * `port`, and `protocol` properties depending on the format of the `host` string.- */-function createConnectionOptions(host: string): Record<string, any> {- const connectionOpts: Record<string, any> = {};+function createConnectionOptions(host: string): Record<string, unknown> {+ const connectionOpts: Record<string, unknown> = {};if (host.startsWith('unix://')) {connectionOpts.socketPath = host.replace('unix://', '');@@ -157,13 +125,8 @@ function createConnectionOptions(host: string): Record<string, any> {return connectionOpts;}-/* The statement `export default getDockerClient;` is exporting the `getDockerClient` function as the-default export of the module. */export default getDockerClient;-/**- * Perform any other necessary cleanup for this module if needed.- */export function cleanup() {console.log('core.ts cleanup called.');}diff --git a/src/lib/services/docker/network-service.ts b/src/lib/services/docker/network-service.tsindex dfece497d..928f2bb50 100644--- a/src/lib/services/docker/network-service.ts+++ b/src/lib/services/docker/network-service.ts@@ -33,7 +33,7 @@ export async function listNetworks(): Promise<ServiceNetwork[]> {created: net.Created ?? ''}));- } catch (error: any) {+ } catch (error: unknown) {console.error('Docker Service: Error listing networks:', error);throw new Error(`Failed to list Docker networks using host "${dockerHost}".`);}@@ -53,16 +53,17 @@ export async function getNetwork(networkId: string): Promise<NetworkInspectInfo>const inspectInfo = await network.inspect();console.log(`Docker Service: Inspected network "${networkId}" successfully.`);return inspectInfo;- } catch (error: any) {+ } catch (error: unknown) {console.error(`Docker Service: Error inspecting network "${networkId}":`, error);- if (error.statusCode === 404) {+ const err = error as { statusCode?: number; message?: string; reason?: string };+ if (err.statusCode === 404) {throw new NotFoundError(`Network "${networkId}" not found.`);}// Docker might return 500 for built-in networks if trying to inspect by name sometimes- if (error.statusCode === 500 && (networkId === 'bridge' || networkId === 'host' || networkId === 'none')) {+ if (err.statusCode === 500 && (networkId === 'bridge' || networkId === 'host' || networkId === 'none')) {throw new NotFoundError(`Cannot inspect built-in network "${networkId}" by name, use ID if available.`);}- throw new DockerApiError(`Failed to inspect network "${networkId}": ${error.message || 'Unknown Docker error'}`, error.statusCode);+ throw new DockerApiError(`Failed to inspect network "${networkId}": ${err.message || 'Unknown Docker error'}`, err.statusCode);}}@@ -85,20 +86,21 @@ export async function removeNetwork(networkId: string): Promise<void> {const network = docker.getNetwork(networkId);await network.remove();console.log(`Docker Service: Network "${networkId}" removed successfully.`);- } catch (error: any) {+ } catch (error: unknown) {console.error(`Docker Service: Error removing network "${networkId}":`, error);- if (error.statusCode === 404) {+ const err = error as { statusCode?: number; message?: string; reason?: string };+ if (err.statusCode === 404) {throw new NotFoundError(`Network "${networkId}" not found.`);}- if (error.statusCode === 409 || (error.reason && error.reason.includes('active endpoints'))) {+ if (err.statusCode === 409 || (err.reason && err.reason.includes('active endpoints'))) {// 409 or specific reason indicates it's likely in usethrow new ConflictError(`Network "${networkId}" has active endpoints (containers connected). Disconnect containers before removal.`);}// Handle removal of predefined networks (usually forbidden)- if (error.statusCode === 403 || (error.reason && error.reason.includes('predefined network'))) {+ if (err.statusCode === 403 || (err.reason && err.reason.includes('predefined network'))) {throw new ConflictError(`Cannot remove predefined network "${networkId}".`);}- throw new DockerApiError(`Failed to remove network "${networkId}": ${error.message || error.reason || 'Unknown Docker error'}`, error.statusCode);+ throw new DockerApiError(`Failed to remove network "${networkId}": ${err.message || err.reason || 'Unknown Docker error'}`, err.statusCode);}}@@ -125,13 +127,13 @@ export async function createNetwork(options: NetworkCreateOptions): Promise<Netwconsole.log(`Docker Service: Network "${options.Name}" (ID: ${inspectInfo.Id}) created successfully.`);return inspectInfo; // Return the detailed inspect info- } catch (error: any) {+ } catch (error: unknown) {console.error(`Docker Service: Error creating network "${options.Name}":`, error);- // Check for specific Docker errors- if (error.statusCode === 409) {+ const err = error as { statusCode?: number; message?: string; reason?: string };+ if (err.statusCode === 409) {// Could be duplicate name if CheckDuplicate was true, or other conflictsthrow new Error(`Network "${options.Name}" may already exist or conflict with an existing configuration.`);}- throw new Error(`Failed to create network "${options.Name}" using host "${dockerHost}". ${error.message || error.reason || ''}`);+ throw new Error(`Failed to create network "${options.Name}" using host "${dockerHost}". ${err.message || err.reason || ''}`);}}diff --git a/src/lib/utils/fs.utils.ts b/src/lib/utils/fs.utils.tsindex 3d984007b..af3cbcf09 100644--- a/src/lib/utils/fs.utils.ts+++ b/src/lib/utils/fs.utils.ts@@ -7,7 +7,7 @@ export async function fileExists(filePath: string): Promise<boolean> {try {const stats = await fs.stat(filePath);return stats.isFile();- } catch (err) {+ } catch {return false;}}@@ -16,7 +16,7 @@ export async function directoryExists(dir: string): Promise<boolean> {try {const stats = await fs.stat(dir);return stats.isDirectory();- } catch (err) {+ } catch {return false;}}diff --git a/src/routes/api/users/+server.ts b/src/routes/api/users/+server.tsindex 8d681e4cc..dcaf0d557 100644--- a/src/routes/api/users/+server.ts+++ b/src/routes/api/users/+server.ts@@ -6,9 +6,7 @@ import { getSettings } from '$lib/services/settings-service';import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';import { tryCatch } from '$lib/utils/try-catch';-// GET users endpointexport const GET: RequestHandler = async ({ locals }) => {- // Only admins can list usersif (!locals.user || !locals.user.roles.includes('admin')) {const response: ApiErrorResponse = {success: false,@@ -39,7 +37,6 @@ export const GET: RequestHandler = async ({ locals }) => {};export const POST: RequestHandler = async ({ request, locals }) => {- // Only admins should be able to create usersconst currentUser = locals.user as User;if (!currentUser || !currentUser.roles.includes('admin')) {@@ -62,7 +59,6 @@ export const POST: RequestHandler = async ({ request, locals }) => {}const { username, password, displayName, email, roles } = userDataResult.data;- // Validate inputif (!username || !password) {const response: ApiErrorResponse = {success: false,@@ -72,7 +68,6 @@ export const POST: RequestHandler = async ({ request, locals }) => {return json(response, { status: 400 });}- // Check if username already existsconst existingUserResult = await tryCatch(getUserByUsername(username));if (existingUserResult.data) {const response: ApiErrorResponse = {@@ -83,12 +78,10 @@ export const POST: RequestHandler = async ({ request, locals }) => {return json(response, { status: 409 });}- // Get password policy from settingsconst settingsResult = await tryCatch(getSettings());const settings = settingsResult.data;const policy = settings?.auth?.passwordPolicy || 'strong';- // Validate password according to policyif (!validatePassword(password, policy)) {const response: ApiErrorResponse = {success: false,@@ -98,7 +91,6 @@ export const POST: RequestHandler = async ({ request, locals }) => {return json(response, { status: 400 });}- // Create the userconst hashResult = await tryCatch(hashPassword(password));if (hashResult.error) {console.error('Error hashing password:', hashResult.error);@@ -112,7 +104,7 @@ export const POST: RequestHandler = async ({ request, locals }) => {}const newUser: User = {- id: '', // Will be generated in saveUser+ id: '',username,passwordHash: hashResult.data,displayName: displayName || username,@@ -133,8 +125,7 @@ export const POST: RequestHandler = async ({ request, locals }) => {return json(response, { status: 500 });}- // Return sanitized user (remove sensitive fields)- const { passwordHash: _, ...sanitizedUser } = saveResult.data;+ const { passwordHash: _unused, ...sanitizedUser } = saveResult.data;return json({success: true,@@ -142,7 +133,6 @@ export const POST: RequestHandler = async ({ request, locals }) => {});};-// Validate password based on policyfunction validatePassword(password: string, policy: 'basic' | 'standard' | 'strong'): boolean {switch (policy) {case 'basic':diff --git a/src/routes/api/users/[id]/+server.ts b/src/routes/api/users/[id]/+server.tsindex d394c5734..c54fd9715 100644--- a/src/routes/api/users/[id]/+server.ts+++ b/src/routes/api/users/[id]/+server.ts@@ -9,12 +9,9 @@ import { BASE_PATH } from '$lib/services/paths-service';import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';import { tryCatch } from '$lib/utils/try-catch';-// Get USER_DIR from base pathconst USER_DIR = path.join(BASE_PATH, 'users');-// PUT endpoint for updating a userexport const PUT: RequestHandler = async ({ params, request, locals }) => {- // Only admins or the user themselves can updateif (!locals.user) {const response: ApiErrorResponse = {success: false,@@ -27,7 +24,6 @@ export const PUT: RequestHandler = async ({ params, request, locals }) => {const userIdToUpdate = params.id;const requestingUser = locals.user as User;- // Check if user is admin or updating their own profileif (!requestingUser.roles.includes('admin') && requestingUser.id !== userIdToUpdate) {const response: ApiErrorResponse = {success: false,@@ -59,22 +55,16 @@ export const PUT: RequestHandler = async ({ params, request, locals }) => {}const { password, displayName, email, roles } = updateDataResult.data;- // Prepare updated user objectconst updatedUser: User = { ...existingUser };if (displayName !== undefined) updatedUser.displayName = displayName;if (email !== undefined) updatedUser.email = email;if (roles !== undefined && requestingUser.roles.includes('admin')) {- // Only admins can change rolesconst ALLOWED = ['admin', 'user', 'viewer'];updatedUser.roles = Array.isArray(roles) ? roles.filter((r) => ALLOWED.includes(r)) : updatedUser.roles;}- // Handle password changeif (password) {- const settingsResult = await tryCatch(getSettings());-- // Password validation can be added here if neededconst hashResult = await tryCatch(hashPassword(password));if (hashResult.error) {const response: ApiErrorResponse = {@@ -101,14 +91,11 @@ export const PUT: RequestHandler = async ({ params, request, locals }) => {return json(response, { status: 500 });}- // Remove passwordHash from returned user object- const { passwordHash, ...sanitizedUser } = saveResult.data;+ const { passwordHash: _unused, ...sanitizedUser } = saveResult.data;return json({ success: true, user: sanitizedUser });};-// DELETE endpointexport const DELETE: RequestHandler = async ({ params, locals }) => {- // Only admins should be able to delete usersif (!locals.user || !locals.user.roles.includes('admin')) {const response: ApiErrorResponse = {success: false,@@ -120,7 +107,6 @@ export const DELETE: RequestHandler = async ({ params, locals }) => {const userId = params.id;- // Don't allow deleting yourselfif (userId === locals.user.id) {const response: ApiErrorResponse = {success: false,