Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: show error messages in toasts (#148)
Kyle Mendellc5d6b9069fc9
diff --git a/package-lock.json b/package-lock.jsonindex ec356e2e9..337b72d4e 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "arcane",- "version": "0.6.0",+ "version": "0.7.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "arcane",- "version": "0.6.0",+ "version": "0.7.0","dependencies": {"@codemirror/lang-yaml": "^6.1.2","@codemirror/legacy-modes": "^6.5.1",diff --git a/src/lib/components/action-buttons.svelte b/src/lib/components/action-buttons.svelteindex 3c2600039..f25802f14 100644--- a/src/lib/components/action-buttons.svelte+++ b/src/lib/components/action-buttons.svelte@@ -8,7 +8,7 @@import ContainerAPIService from '$lib/services/api/container-api-service';import StackAPIService from '$lib/services/api/stack-api-service';import { tryCatch } from '$lib/utils/try-catch';- import { handleApiReponse } from '$lib/utils/api.util';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';const containerApi = new ContainerAPIService();const stackApi = new StackAPIService();@@ -59,16 +59,16 @@destructive: true,action: async () => {isLoading.remove = true;- handleApiReponse(- await tryCatch(type === 'container' ? containerApi.remove(id) : stackApi.remove(id)),- `Failed to Remove ${type}`,- (value) => (isLoading.remove = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(type === 'container' ? containerApi.remove(id) : stackApi.remove(id)),+ message: `Failed to Remove ${type}`,+ setLoadingState: (value) => (isLoading.remove = value),+ onSuccess: async () => {toast.success(`${type.charAt(0).toUpperCase() + type.slice(1)} Removed Successfully`);await invalidateAll();goto(`/${type}s`);}- );+ });}}});@@ -80,15 +80,15 @@label: 'Redeploy',action: async () => {isLoading.redeploy = true;- handleApiReponse(- await tryCatch(stackApi.redeploy(id)),- `Failed to Redeploy ${type}`,- (value) => (isLoading.redeploy = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(stackApi.redeploy(id)),+ message: `Failed to Redeploy ${type}`,+ setLoadingState: (value) => (isLoading.redeploy = value),+ onSuccess: async () => {toast.success(`${type.charAt(0).toUpperCase() + type.slice(1)} Redeployed Successfully`);await invalidateAll();}- );+ });}}});@@ -97,54 +97,54 @@async function handleStart() {isLoading.start = true;- handleApiReponse(- await tryCatch(type === 'container' ? containerApi.start(id) : stackApi.start(id)),- `Failed to Start ${type}`,- (value) => (isLoading.start = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(type === 'container' ? containerApi.start(id) : stackApi.start(id)),+ message: `Failed to Start ${type}`,+ setLoadingState: (value) => (isLoading.start = value),+ onSuccess: async () => {toast.success(`${type.charAt(0).toUpperCase() + type.slice(1)} Started Successfully`);await invalidateAll();}- );+ });}async function handleStop() {isLoading.stop = true;- handleApiReponse(- await tryCatch(type === 'container' ? containerApi.stop(id) : stackApi.stop(id)),- `Failed to Stop ${type}`,- (value) => (isLoading.stop = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(type === 'container' ? containerApi.stop(id) : stackApi.stop(id)),+ message: `Failed to Stop ${type}`,+ setLoadingState: (value) => (isLoading.stop = value),+ onSuccess: async () => {toast.success(`${type.charAt(0).toUpperCase() + type.slice(1)} Stopped Successfully`);await invalidateAll();}- );+ });}async function handleRestart() {isLoading.restart = true;- handleApiReponse(- await tryCatch(type === 'container' ? containerApi.restart(id) : stackApi.restart(id)),- `Failed to Restart ${type}`,- (value) => (isLoading.restart = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(type === 'container' ? containerApi.restart(id) : stackApi.restart(id)),+ message: `Failed to Restart ${type}`,+ setLoadingState: (value) => (isLoading.restart = value),+ onSuccess: async () => {toast.success(`${type.charAt(0).toUpperCase() + type.slice(1)} Restarted Successfully`);await invalidateAll();}- );+ });}async function handlePull() {isLoading.pulling = true;- handleApiReponse(- await tryCatch(type === 'container' ? containerApi.pull(id) : stackApi.pull(id)),- 'Failed to Pull Image(s)',- (value) => (isLoading.pulling = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(type === 'container' ? containerApi.pull(id) : stackApi.pull(id)),+ message: 'Failed to Pull Image(s)',+ setLoadingState: (value) => (isLoading.pulling = value),+ onSuccess: async () => {toast.success('Image(s) Pulled Successfully.');await invalidateAll();}- );+ });}</script>diff --git a/src/lib/services/docker/scheduler-service.ts b/src/lib/services/docker/scheduler-service.tsindex 5adf3b22d..3ed18d10d 100644--- a/src/lib/services/docker/scheduler-service.ts+++ b/src/lib/services/docker/scheduler-service.ts@@ -56,7 +56,7 @@ async function runAutoUpdateChecks(): Promise<void> {/*** Stop the auto-update scheduler*/-export function stopAutoUpdateScheduler(): void {+export async function stopAutoUpdateScheduler(): Promise<void> {if (autoUpdateTimer) {clearInterval(autoUpdateTimer);autoUpdateTimer = null;diff --git a/src/lib/types/errors.type.ts b/src/lib/types/errors.type.tsnew file mode 100644index 000000000..3ab1bac1b--- /dev/null+++ b/src/lib/types/errors.type.ts@@ -0,0 +1,19 @@+//This file replaces errors.ts++export enum ApiErrorCode {+ VALIDATION_ERROR = 'VALIDATION_ERROR',+ NOT_FOUND = 'NOT_FOUND',+ DOCKER_API_ERROR = 'DOCKER_API_ERROR',+ CONFLICT = 'CONFLICT',+ BAD_REQUEST = 'BAD_REQUEST',+ INTERNAL_SERVER_ERROR = 'INTERNAL_SERVER_ERROR',+ UNAUTHORIZED = 'UNAUTHORIZED',+ FORBIDDEN = 'FORBIDDEN'+}++export interface ApiErrorResponse {+ success: false;+ error: string;+ code: ApiErrorCode;+ details?: unknown;+}diff --git a/src/lib/utils/api.util.ts b/src/lib/utils/api.util.tsindex 615c6369c..0f1d44326 100644--- a/src/lib/utils/api.util.ts+++ b/src/lib/utils/api.util.ts@@ -1,22 +1,18 @@import type { Result } from './try-catch';import { toast } from 'svelte-sonner';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';-/**- * Handles the result of an API call, showing errors or executing a success callback.- * Optionally sets a loading state to false on error.- * @param result The result object from a try-catch utility.- * @param errorMessage The base error message for logging and toast if an error occurs.- * @param setLoadingState Optional setter function to set a boolean loading state to false specifically on error.- * @param onSuccess Optional callback function to execute if there is no error. Receives the data from the result.- */-export function handleApiReponse<T>(result: Result<T, Error>, message: string, setLoadingState: (value: boolean) => void, onSuccess: (data: T) => void) {+export function handleApiResultWithCallbacks<T>({ result, message, setLoadingState = () => {}, onSuccess, onError = () => {} }: { result: Result<T, Error>; message: string; setLoadingState?: (value: boolean) => void; onSuccess: (result: Result<T, Error>) => void; onError?: (result: Result<T, Error>) => void }) {+ setLoadingState(true);if (result.error) {- console.error(message + ':', result.error);- toast.error(`${message}: ${result.error.message}`);+ const dockerMsg = extractDockerErrorMessage(result.error);+ console.error(`onErrorCallback: ${message}:`, result.error);+ toast.error(`${message}: ${dockerMsg}`);setLoadingState(false);+ onError(result);return;} else if (result.data) {- onSuccess(result.data);+ onSuccess(result);setLoadingState(false);}}diff --git a/src/lib/utils/errors.util.ts b/src/lib/utils/errors.util.tsnew file mode 100644index 000000000..7aadaeb6b--- /dev/null+++ b/src/lib/utils/errors.util.ts@@ -0,0 +1,16 @@+export function extractDockerErrorMessage(error: any): string {+ if (!error) return 'Unknown error';++ if (error.response && error.response.data) {+ if (typeof error.response.data === 'string') return error.response.data;+ if (error.response.data.error) return error.response.data.error;+ }++ if (error.body && error.body.error) return error.body.error;+ if (error.error) return error.error;+ if (error.reason) return error.reason;+ if (error.stderr) return error.stderr;+ if (error.data && typeof error.data === 'string') return error.data;+ if (error.message) return error.message;+ return JSON.stringify(error);+}diff --git a/src/routes/+page.svelte b/src/routes/+page.svelteindex 4806d5c73..f79113690 100644--- a/src/routes/+page.svelte+++ b/src/routes/+page.svelte@@ -15,7 +15,7 @@import * as Table from '$lib/components/ui/table';import { statusVariantMap } from '$lib/types/statuses';import { shortId } from '$lib/utils/string.utils';- import { handleApiReponse } from '$lib/utils/api.util';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';import ContainerAPIService from '$lib/services/api/container-api-service';import SystemAPIService from '$lib/services/api/system-api-service';@@ -71,16 +71,16 @@async function handleStartAll() {if (isLoading.starting || !dashboardStates.dockerInfo || stoppedContainers === 0) return;isLoading.starting = true;- handleApiReponse(- await tryCatch(containerApi.startAll()),- `Failed to Start All Containers`,- (value) => (isLoading.starting = value),- async () => {- toast.success(`All Containers Started Successfully.`);+ handleApiResultWithCallbacks({+ result: await tryCatch(containerApi.startAll()),+ message: 'Failed to Start All Containers',+ setLoadingState: (value) => (isLoading.starting = value),+ onSuccess: async () => {+ toast.success('All Containers Started Successfully.');await invalidateAll();isLoading.starting = false;}- );+ });}async function handleStopAll() {@@ -93,16 +93,16 @@label: 'Confirm',destructive: false,action: async () => {- handleApiReponse(- await tryCatch(containerApi.stopAll()),- `Failed to Stop All Running Containers`,- (value) => (isLoading.starting = value),- async () => {- toast.success(`All Containers Stopped Successfully.`);+ handleApiResultWithCallbacks({+ result: await tryCatch(containerApi.stopAll()),+ message: 'Failed to Stop All Running Containers',+ setLoadingState: (value) => (isLoading.stopping = value),+ onSuccess: async () => {+ toast.success('All Containers Stopped Successfully.');await invalidateAll();isLoading.stopping = false;}- );+ });}}});@@ -111,18 +111,18 @@async function confirmPrune(selectedTypes: string[]) {if (isLoading.pruning || selectedTypes.length === 0) return;isLoading.pruning = true;- handleApiReponse(- await tryCatch(systemApi.prune(['containers', 'images'])),- `Failed to Prune ${selectedTypes}`,- (value) => (isLoading.pruning = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(systemApi.prune(['containers', 'images'])),+ message: `Failed to Prune ${selectedTypes}`,+ setLoadingState: (value) => (isLoading.pruning = value),+ onSuccess: async () => {dashboardStates.isPruneDialogOpen = false;const formattedTypes = selectedTypes.map((type) => capitalizeFirstLetter(type)).join(', ');toast.success(`${formattedTypes} ${selectedTypes.length > 1 ? 'were' : 'was'} pruned successfully.`);await invalidateAll();isLoading.pruning = false;}- );+ });}</script>diff --git a/src/routes/api/containers/+server.ts b/src/routes/api/containers/+server.tsindex 3ff7ae9d6..5f4545b3f 100644--- a/src/routes/api/containers/+server.ts+++ b/src/routes/api/containers/+server.ts@@ -2,29 +2,38 @@ import { json } from '@sveltejs/kit';import type { RequestHandler } from './$types';import { createContainer } from '$lib/services/docker/container-service';import type { ContainerConfig } from '$lib/types/docker';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';+import { tryCatch } from '$lib/utils/try-catch';export const POST: RequestHandler = async ({ request }) => {- try {- const config = (await request.json()) as ContainerConfig;+ const config = (await request.json()) as ContainerConfig;- if (!config.name || !config.image) {- return json({ success: false, error: 'Container name and image are required' }, { status: 400 });- }+ if (!config.name || !config.image) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Container name and image are required',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }++ const result = await tryCatch(createContainer(config));- const container = await createContainer(config);+ if (result.error) {+ console.error('Error creating container:', result.error);- return json({- success: true,- container- });- } catch (error: any) {- console.error('Error creating container:', error);- return json(- {- success: false,- error: error.message || 'Failed to create container'- },- { status: 500 }- );+ const response: ApiErrorResponse = {+ success: false,+ error: extractDockerErrorMessage(result.error),+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });}++ return json({+ success: true,+ container: result.data+ });};diff --git a/src/routes/api/containers/[containerId]/+server.ts b/src/routes/api/containers/[containerId]/+server.tsindex fc102a08a..1faa29671 100644--- a/src/routes/api/containers/[containerId]/+server.ts+++ b/src/routes/api/containers/[containerId]/+server.ts@@ -1,26 +1,36 @@import { json } from '@sveltejs/kit';import type { RequestHandler } from './$types';import { getContainer } from '$lib/services/docker/container-service';+import { tryCatch } from '$lib/utils/try-catch';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';export const GET: RequestHandler = async ({ params }) => {const containerId = params.containerId;- try {- const container = await getContainer(containerId);+ const result = await tryCatch(getContainer(containerId));- if (!container) {- return json({ success: false, error: 'Container not found' }, { status: 404 });- }+ if (result.error) {+ console.error(`API Error getting container ${containerId}:`, result.error);- return json(container);- } catch (error: any) {- console.error(`API Error getting container ${containerId}:`, error);- return json(- {- success: false,- error: error.message || 'Failed to get container information'- },- { status: 500 }- );+ const response: ApiErrorResponse = {+ success: false,+ error: extractDockerErrorMessage(result.error),+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: result.error+ };++ return json(response, { status: 500 });+ }++ if (!result.data) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Container not found',+ code: ApiErrorCode.NOT_FOUND+ };+ return json(response, { status: 404 });}++ return json(result.data);};diff --git a/src/routes/api/containers/[containerId]/logs/stream/+server.ts b/src/routes/api/containers/[containerId]/logs/stream/+server.tsnew file mode 100644index 000000000..3203409e3--- /dev/null+++ b/src/routes/api/containers/[containerId]/logs/stream/+server.ts@@ -0,0 +1,82 @@+import { getDockerClient } from '$lib/services/docker/core';+import { json } from '@sveltejs/kit';+import type { RequestHandler } from './$types';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';+import { tryCatch } from '$lib/utils/try-catch';++export const GET: RequestHandler = async ({ params }) => {+ const { containerId } = params;+ const docker = getDockerClient();++ const result = await tryCatch(+ (async () => {+ const container = docker.getContainer(containerId);++ // Check if container exists+ const containerInfo = await container.inspect();+ const hasTty = containerInfo.Config.Tty === true;++ // Create a stream for Server-Sent Events (SSE)+ const encoder = new TextEncoder();+ const stream = new ReadableStream({+ async start(controller) {+ try {+ const logStream = await container.logs({+ follow: true,+ stdout: true,+ stderr: true,+ timestamps: false,+ tail: 300+ });++ logStream.on('data', (chunk) => {+ let log;+ if (!hasTty) {+ log = chunk.slice(8).toString('utf8');+ } else {+ log = chunk.toString('utf8');+ }+ controller.enqueue(encoder.encode(`data: ${log}\n\n`));+ });++ logStream.on('end', () => {+ controller.close();+ });++ logStream.on('error', (err) => {+ console.error('Log stream error:', err);+ controller.error(err);+ });+ } catch (err) {+ console.error('Error setting up log stream:', err);+ controller.error(err);+ }+ }+ });++ return stream;+ })()+ );++ if (result.error) {+ console.error('Error streaming container logs:', result.error);++ const response: ApiErrorResponse = {+ success: false,+ error: extractDockerErrorMessage(result.error),+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: result.error+ };++ return json(response, { status: 500 });+ }++ return new Response(result.data, {+ headers: {+ 'Content-Type': 'text/event-stream',+ 'Cache-Control': 'no-cache',+ Connection: 'keep-alive'+ }+ });+};diff --git a/src/routes/api/containers/[containerId]/pull/+server.ts b/src/routes/api/containers/[containerId]/pull/+server.tsindex 2b86f62cb..f22a137ca 100644--- a/src/routes/api/containers/[containerId]/pull/+server.ts+++ b/src/routes/api/containers/[containerId]/pull/+server.ts@@ -2,52 +2,56 @@ import type { RequestHandler } from './$types';import { json } from '@sveltejs/kit';import { getContainer } from '$lib/services/docker/container-service';import { pullImage } from '$lib/services/docker/image-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';+import { tryCatch } from '$lib/utils/try-catch';-/**- * This TypeScript function handles a POST request to pull an image associated with a container and- * returns success or error messages accordingly.- * @param - The code snippet you provided is a TypeScript function that handles a POST request. It- * takes a containerId from the request parameters, retrieves the container information using the- * containerId, extracts the image name from the container, and then pulls the image. If successful, it- * returns a success message with the pulled image- * @returns The code snippet is an asynchronous function that handles a POST request. It attempts to- * pull an image associated with a container identified by `containerId`. Here is what is being- * returned based on the execution flow:- */export const POST: RequestHandler = async ({ params }) => {const containerId = params.containerId;- try {- // Get the container to find its image- const container = await getContainer(containerId);- if (!container) {- return json(- {- success: false,- error: `Container not found`- },- { status: 404 }- );- }-- // Extract the image name- const imageName = container.image;-- // Pull the image- await pullImage(imageName);-- return json({- success: true,- message: `Container image ${imageName} pulled successfully`- });- } catch (error: any) {- console.error(`API Error pulling container image for ${containerId}:`, error);- return json(- {- success: false,- error: error.message || 'Failed to pull container image'- },- { status: 500 }- );+ // Try to get the container+ const getResult = await tryCatch(getContainer(containerId));+ if (getResult.error) {+ console.error(`API Error pulling image for container ${containerId}:`, getResult.error);++ const response: ApiErrorResponse = {+ success: false,+ error: extractDockerErrorMessage(getResult.error),+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: getResult.error+ };++ return json(response, { status: 500 });+ }++ if (!getResult.data) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Container not found',+ code: ApiErrorCode.NOT_FOUND+ };+ return json(response, { status: 404 });+ }++ const imageName = getResult.data.image;++ // Try to pull the image+ const pullResult = await tryCatch(pullImage(imageName));+ if (pullResult.error) {+ console.error(`API Error pulling image ${imageName} for container ${containerId}:`, pullResult.error);++ const response: ApiErrorResponse = {+ success: false,+ error: extractDockerErrorMessage(pullResult.error),+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: pullResult.error+ };++ return json(response, { status: 500 });}++ return json({+ success: true,+ message: `Container image ${imageName} pulled successfully`+ });};diff --git a/src/routes/api/containers/[containerId]/remove/+server.ts b/src/routes/api/containers/[containerId]/remove/+server.tsindex c70a0a524..35ac35d1a 100644--- a/src/routes/api/containers/[containerId]/remove/+server.ts+++ b/src/routes/api/containers/[containerId]/remove/+server.ts@@ -1,36 +1,31 @@import type { RequestHandler } from './$types';import { json } from '@sveltejs/kit';import { removeContainer } from '$lib/services/docker/container-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';+import { tryCatch } from '$lib/utils/try-catch';-/**- * This TypeScript function handles the deletion of a container with optional force parameter and- * returns success or error messages accordingly.- * @param - The code snippet you provided is an example of a DELETE request handler function in- * JavaScript using an asynchronous function. Here's a breakdown of the key components:- * @returns The DELETE request handler is returning a JSON response with either a success message if- * the container was removed successfully or an error message if there was a failure in removing the- * container. The response includes a `success` key indicating the operation's success status and a- * `message` key with a corresponding message. If an error occurs, the response includes a `success`- * key set to false, an `error`- */export const DELETE: RequestHandler = async ({ params, url }) => {const containerId = params.containerId;const force = url.searchParams.has('force') ? url.searchParams.get('force') === 'true' : false;- try {- await removeContainer(containerId, force);- return json({- success: true,- message: `Container removed successfully`- });- } catch (error: any) {- console.error(`API Error removing container ${containerId}:`, error);- return json(- {- success: false,- error: error.message || 'Failed to remove container'- },- { status: 409 }- );+ const result = await tryCatch(removeContainer(containerId, force));++ if (result.error) {+ console.error(`API Error Deleting container ${containerId}:`, result.error);++ const response: ApiErrorResponse = {+ success: false,+ error: extractDockerErrorMessage(result.error),+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: result.error+ };++ return json(response, { status: 500 });}++ return json({+ success: true,+ message: `Container Deleted Successfully`+ });};diff --git a/src/routes/api/containers/[containerId]/restart/+server.ts b/src/routes/api/containers/[containerId]/restart/+server.tsindex 555ad058e..6f36f11a7 100644--- a/src/routes/api/containers/[containerId]/restart/+server.ts+++ b/src/routes/api/containers/[containerId]/restart/+server.ts@@ -1,36 +1,30 @@import type { RequestHandler } from './$types';import { json } from '@sveltejs/kit';import { restartContainer } from '$lib/services/docker/container-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';+import { tryCatch } from '$lib/utils/try-catch';-/**- * The POST request handler restarts a container based on the provided containerId and returns a- * success message or an error message if the restart fails.- * @param - The code snippet you provided is a TypeScript function that handles a POST request. It- * takes a `containerId` from the request parameters, attempts to restart a container with that ID- * using the `restartContainer` function, and then returns a success message if the restart is- * successful. If an error occurs during- * @returns The code snippet is defining a POST request handler function that restarts a container- * based on the provided `containerId`. If the container restart is successful, it returns a JSON- * response with a success message. If an error occurs during the restart process, it logs the error- * and returns a JSON response indicating the failure along with an error message.- */export const POST: RequestHandler = async ({ params }) => {const containerId = params.containerId;- try {- await restartContainer(containerId);- return json({- success: true,- message: `Container restarted successfully`- });- } catch (error: any) {- console.error(`API Error restarting container ${containerId}:`, error);- return json(- {- success: false,- error: error.message || 'Failed to restart container'- },- { status: 500 }- );+ const result = await tryCatch(restartContainer(containerId));++ if (result.error) {+ console.error(`API Error restarting container ${containerId}:`, result.error);++ const response: ApiErrorResponse = {+ success: false,+ error: extractDockerErrorMessage(result.error),+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: result.error+ };++ return json(response, { status: 500 });}++ return json({+ success: true,+ message: `Container restarted successfully`+ });};diff --git a/src/routes/api/containers/[containerId]/start/+server.ts b/src/routes/api/containers/[containerId]/start/+server.tsindex 49f1bbbba..5ad527019 100644--- a/src/routes/api/containers/[containerId]/start/+server.ts+++ b/src/routes/api/containers/[containerId]/start/+server.ts@@ -1,34 +1,30 @@import type { RequestHandler } from './$types';import { json } from '@sveltejs/kit';import { startContainer } from '$lib/services/docker/container-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';+import { tryCatch } from '$lib/utils/try-catch';-/**- * This TypeScript function handles a POST request to start a container and returns a success message- * or an error message with appropriate status code.- * @param - The code snippet you provided is a TypeScript function that handles a POST request. It- * expects a parameter object with a `containerId` property. Inside the function, it attempts to start- * a container using the `startContainer` function with the provided `containerId`. If the operation is- * successful, it returns- * @returns The code snippet is a TypeScript function that handles a POST request to start a container- * based on the provided `containerId`.- */export const POST: RequestHandler = async ({ params }) => {const containerId = params.containerId;- try {- await startContainer(containerId);- return json({- success: true,- message: `Container started successfully`- });- } catch (error: any) {- console.error(`API Error starting container ${containerId}:`, error);- return json(- {- success: false,- error: error.message || 'Failed to start container'- },- { status: 500 }- );+ const result = await tryCatch(startContainer(containerId));++ if (result.error) {+ console.error(`API Error starting container ${containerId}:`, result.error);++ const response: ApiErrorResponse = {+ success: false,+ error: extractDockerErrorMessage(result.error),+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: result.error+ };++ return json(response, { status: 500 });}++ return json({+ success: true,+ message: `Container started successfully`+ });};diff --git a/src/routes/api/containers/[containerId]/stats/stream/+server.ts b/src/routes/api/containers/[containerId]/stats/stream/+server.tsnew file mode 100644index 000000000..90f4836fe--- /dev/null+++ b/src/routes/api/containers/[containerId]/stats/stream/+server.ts@@ -0,0 +1,105 @@+import { getDockerClient } from '$lib/services/docker/core';+import { json } from '@sveltejs/kit';+import type { RequestHandler } from './$types';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';+import { tryCatch } from '$lib/utils/try-catch';++export const GET: RequestHandler = async ({ params, request }) => {+ const { containerId } = params;+ const docker = getDockerClient();++ const result = await tryCatch(+ (async () => {+ const container = docker.getContainer(containerId);+ const encoder = new TextEncoder();++ const stream = new ReadableStream({+ start(controller) {+ let isActive = true;+ let pollInterval: ReturnType<typeof setInterval>;+ let pingInterval: ReturnType<typeof setInterval>;++ const cleanup = () => {+ isActive = false;+ clearInterval(pollInterval);+ clearInterval(pingInterval);+ };++ request.signal.addEventListener('abort', cleanup);++ pollInterval = setInterval(async () => {+ if (!isActive) return;++ try {+ const stats = await container.stats({ stream: false });+ if (!isActive) return;+ try {+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(stats)}\n\n`));+ } catch (err) {+ if (err && typeof err === 'object' && 'code' in err && (err as any).code === 'ERR_INVALID_STATE') {+ cleanup();+ } else {+ console.error('Enqueue error:', err);+ }+ }+ } catch (err) {+ if (!isActive) return;++ if ((err as any).statusCode === 404) {+ try {+ controller.enqueue(encoder.encode(`data: ${JSON.stringify({ removed: true })}\n\n`));+ cleanup();+ controller.close();+ } catch (e) {+ cleanup();+ }+ } else {+ console.error('Container stats error:', err);+ }+ }+ }, 2000);++ pingInterval = setInterval(() => {+ if (!isActive) return;+ try {+ controller.enqueue(encoder.encode(':\n\n'));+ } catch (err) {+ if (err && typeof err === 'object' && 'code' in err && (err as any).code === 'ERR_INVALID_STATE') {+ cleanup();+ }+ }+ }, 15000);++ return cleanup;+ },+ cancel() {+ // Cleanup handled by return function from start()+ }+ });++ return stream;+ })()+ );++ if (result.error) {+ console.error('Error streaming container stats:', result.error);++ const response: ApiErrorResponse = {+ success: false,+ error: extractDockerErrorMessage(result.error),+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: result.error+ };++ return json(response, { status: 500 });+ }++ return new Response(result.data, {+ headers: {+ 'Content-Type': 'text/event-stream',+ 'Cache-Control': 'no-cache',+ Connection: 'keep-alive'+ }+ });+};diff --git a/src/routes/api/containers/[containerId]/stop/+server.ts b/src/routes/api/containers/[containerId]/stop/+server.tsindex 63a5fcb08..6982023a2 100644--- a/src/routes/api/containers/[containerId]/stop/+server.ts+++ b/src/routes/api/containers/[containerId]/stop/+server.ts@@ -1,24 +1,30 @@import type { RequestHandler } from './$types';import { json } from '@sveltejs/kit';import { stopContainer } from '$lib/services/docker/container-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';+import { tryCatch } from '$lib/utils/try-catch';export const POST: RequestHandler = async ({ params }) => {const containerId = params.containerId;- try {- await stopContainer(containerId);- return json({- success: true,- message: `Container stopped successfully`- });- } catch (error: any) {- console.error(`API Error stopping container ${containerId}:`, error);- return json(- {- success: false,- error: error.message || 'Failed to stop container'- },- { status: 500 }- );+ const result = await tryCatch(stopContainer(containerId));++ if (result.error) {+ console.error(`API Error stopping container ${containerId}:`, result.error);++ const response: ApiErrorResponse = {+ success: false,+ error: extractDockerErrorMessage(result.error),+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: result.error+ };++ return json(response, { status: 500 });}++ return json({+ success: true,+ message: `Container stopped successfully`+ });};diff --git a/src/routes/api/containers/[id]/logs/stream/+server.ts b/src/routes/api/containers/[id]/logs/stream/+server.tsdeleted file mode 100644index 506e5bc7e..000000000--- a/src/routes/api/containers/[id]/logs/stream/+server.ts+++ /dev/null@@ -1,74 +0,0 @@-import { getDockerClient } from '$lib/services/docker/core';-import { error } from '@sveltejs/kit';-import type { RequestHandler } from './$types';--export const GET: RequestHandler = async ({ params }) => {- const { id } = params;- const docker = getDockerClient();-- try {- const container = docker.getContainer(id);-- // Check if container exists- const containerInfo = await container.inspect();- const hasTty = containerInfo.Config.Tty === true;-- // Create a stream for Server-Sent Events (SSE)- const encoder = new TextEncoder();- const stream = new ReadableStream({- async start(controller) {- try {- // Get log stream from Docker- const logStream = await container.logs({- follow: true, // Follow logs (stream)- stdout: true, // Get stdout stream- stderr: true, // Get stderr stream- timestamps: false, // Don't include timestamps (we'll format in frontend)- tail: 300 // Start with most recent logs- });-- // Handle data chunks- logStream.on('data', (chunk) => {- let log;- // Remove Docker header (first 8 bytes)- if (!hasTty) {- // Remove Docker header (first 8 bytes)- log = chunk.slice(8).toString('utf8');- } else {- // For TTY-enabled containers, use the chunk as-is- log = chunk.toString('utf8');- }-- // Format as SSE message- controller.enqueue(encoder.encode(`data: ${log}\n\n`));- });-- // Handle end of stream- logStream.on('end', () => {- controller.close();- });-- // Handle errors- logStream.on('error', (err) => {- console.error('Log stream error:', err);- controller.error(err);- });- } catch (err) {- console.error('Error setting up log stream:', err);- controller.error(err);- }- }- });-- return new Response(stream, {- headers: {- 'Content-Type': 'text/event-stream',- 'Cache-Control': 'no-cache',- Connection: 'keep-alive'- }- });- } catch (err) {- console.error('Error streaming container logs:', err);- throw error(500, 'Failed to stream container logs');- }-};diff --git a/src/routes/api/containers/[id]/stats/stream/+server.ts b/src/routes/api/containers/[id]/stats/stream/+server.tsdeleted file mode 100644index 0aa748e63..000000000--- a/src/routes/api/containers/[id]/stats/stream/+server.ts+++ /dev/null@@ -1,103 +0,0 @@-import { getDockerClient } from '$lib/services/docker/core';-import { error } from '@sveltejs/kit';-import type { RequestHandler } from './$types';--export const GET: RequestHandler = async ({ params, request }) => {- const { id } = params;- const docker = getDockerClient();-- try {- const container = docker.getContainer(id);- const encoder = new TextEncoder();-- const stream = new ReadableStream({- start(controller) {- // Track if the controller is still active- let isActive = true;- let pollInterval: ReturnType<typeof setInterval>;- let pingInterval: ReturnType<typeof setInterval>;-- // Clean up function to handle all interval clearing- const cleanup = () => {- isActive = false;- clearInterval(pollInterval);- clearInterval(pingInterval);- };-- // Listen for client disconnects- request.signal.addEventListener('abort', cleanup);-- // Poll container stats- pollInterval = setInterval(async () => {- if (!isActive) return;-- try {- // Get container stats- const stats = await container.stats({ stream: false });-- // Check if still active before sending- if (!isActive) return;-- try {- controller.enqueue(encoder.encode(`data: ${JSON.stringify(stats)}\n\n`));- } catch (err) {- // Controller is closed- if (err && typeof err === 'object' && 'code' in err && (err as any).code === 'ERR_INVALID_STATE') {- cleanup();- } else {- console.error('Enqueue error:', err);- }- }- } catch (err) {- if (!isActive) return;-- if ((err as any).statusCode === 404) {- try {- controller.enqueue(encoder.encode(`data: ${JSON.stringify({ removed: true })}\n\n`));- cleanup();- controller.close();- } catch (e) {- // Ignore errors if controller is already closed- cleanup();- }- } else {- console.error('Container stats error:', err);- }- }- }, 2000);-- // Keep-alive ping- pingInterval = setInterval(() => {- if (!isActive) return;-- try {- controller.enqueue(encoder.encode(':\n\n'));- } catch (err) {- if (err && typeof err === 'object' && 'code' in err && (err as any).code === 'ERR_INVALID_STATE') {- cleanup();- }- }- }, 15000);-- // Return cleanup function- return cleanup;- },-- cancel() {- // This is called when the client disconnects- // Cleanup is handled by the return function from start()- }- });-- return new Response(stream, {- headers: {- 'Content-Type': 'text/event-stream',- 'Cache-Control': 'no-cache',- Connection: 'keep-alive'- }- });- } catch (err) {- console.error('Error streaming container stats:', err);- throw error(500, 'Failed to stream container stats');- }-};diff --git a/src/routes/api/containers/start-all/+server.ts b/src/routes/api/containers/start-all/+server.tsindex 83f3555ed..c8acf0810 100644--- a/src/routes/api/containers/start-all/+server.ts+++ b/src/routes/api/containers/start-all/+server.ts@@ -1,20 +1,38 @@-import { json, error as serverError } from '@sveltejs/kit';+import { json } from '@sveltejs/kit';import { listContainers, startContainer } from '$lib/services/docker/container-service';import type { RequestHandler } from './$types';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';+import { tryCatch } from '$lib/utils/try-catch';export const POST: RequestHandler = async () => {- console.log('API: POST /api/containers/start-all');- try {- const containers = await listContainers(true); // Fetch all containers- const stopped = containers.filter((c) => c.state === 'exited');- if (stopped.length === 0) {- return json({ success: true, count: 0, message: 'No stopped containers to start.' });- }- await Promise.all(stopped.map((c) => startContainer(c.id)));- console.log(`API: Started ${stopped.length} containers.`);- return json({ success: true, count: stopped.length, message: `Successfully started ${stopped.length} container(s).` });- } catch (err: any) {- console.error('API Error (startAllStopped):', err);- throw serverError(500, err.message || 'Failed to start stopped containers.');+ const result = await tryCatch(+ (async () => {+ const containers = await listContainers(true);+ const stopped = containers.filter((c) => c.state === 'exited');+ if (stopped.length === 0) {+ return { count: 0, message: 'No stopped containers to start.' };+ }+ await Promise.all(stopped.map((c) => startContainer(c.id)));+ return { count: stopped.length, message: `Successfully started ${stopped.length} container(s).` };+ })()+ );++ if (result.error) {+ console.error('API Error (startAllStopped):', result.error);++ const response: ApiErrorResponse = {+ success: false,+ error: extractDockerErrorMessage(result.error),+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });}++ return json({+ success: true,+ count: result.data.count,+ message: result.data.message+ });};diff --git a/src/routes/api/containers/stop-all/+server.ts b/src/routes/api/containers/stop-all/+server.tsindex aabe23835..43ca5df1c 100644--- a/src/routes/api/containers/stop-all/+server.ts+++ b/src/routes/api/containers/stop-all/+server.ts@@ -1,20 +1,39 @@-import { json, error as serverError } from '@sveltejs/kit';+import { json } from '@sveltejs/kit';import { listContainers, stopContainer } from '$lib/services/docker/container-service';import type { RequestHandler } from './$types';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';+import { tryCatch } from '$lib/utils/try-catch';export const POST: RequestHandler = async () => {- console.log('API: POST /api/containers/stop-all');- try {- const containers = await listContainers(true); // Fetch all containers- const running = containers.filter((c) => c.state === 'running');- if (running.length === 0) {- return json({ success: true, count: 0, message: 'No running containers to stop.' });- }- await Promise.all(running.map((c) => stopContainer(c.id)));- console.log(`API: Stopped ${running.length} containers.`);- return json({ success: true, count: running.length, message: `Successfully stopped ${running.length} container(s).` });- } catch (err: any) {- console.error('API Error (stopAllRunning):', err);- throw serverError(500, err.message || 'Failed to stop running containers.');+ const result = await tryCatch(+ (async () => {+ const containers = await listContainers(true);+ const running = containers.filter((c) => c.state === 'running');+ if (running.length === 0) {+ return { count: 0, message: 'No running containers to stop.' };+ }+ await Promise.all(running.map((c) => stopContainer(c.id)));+ console.log(`API: Stopped ${running.length} containers.`);+ return { count: running.length, message: `Successfully stopped ${running.length} container(s).` };+ })()+ );++ if (result.error) {+ console.error('API Error (stopAllRunning):', result.error);++ const response: ApiErrorResponse = {+ success: false,+ error: extractDockerErrorMessage(result.error),+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });}++ return json({+ success: true,+ count: result.data.count,+ message: result.data.message+ });};diff --git a/src/routes/api/images/[id]/+server.ts b/src/routes/api/images/[id]/+server.tsindex 73c2742cf..e6455e7c7 100644--- a/src/routes/api/images/[id]/+server.ts+++ b/src/routes/api/images/[id]/+server.ts@@ -1,16 +1,38 @@import { json } from '@sveltejs/kit';import type { RequestHandler } from './$types';import { removeImage } from '$lib/services/docker/image-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';+import { tryCatch } from '$lib/utils/try-catch';export const DELETE: RequestHandler = async ({ params, url }) => {const { id } = params;const force = url.searchParams.get('force') === 'true';- try {- await removeImage(id, force);- return json({ success: true });- } catch (error: any) {- console.error('API Error removing image:', error);- return json({ error: `Failed to remove image: ${error.message || 'Unknown error'}` }, { status: 500 });+ if (!id) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Image ID is required',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });}++ const result = await tryCatch(removeImage(id, force));++ if (result.error) {+ console.error('Error removing image:', result.error);++ const response: ApiErrorResponse = {+ success: false,+ error: extractDockerErrorMessage(result.error),+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });+ }++ return json({+ success: true+ });};diff --git a/src/routes/api/images/prune/+server.ts b/src/routes/api/images/prune/+server.tsindex 9afe863aa..a197388b8 100644--- a/src/routes/api/images/prune/+server.ts+++ b/src/routes/api/images/prune/+server.ts@@ -1,26 +1,51 @@-import { json, error } from '@sveltejs/kit';+import { json } from '@sveltejs/kit';import type { RequestHandler } from './$types';import { pruneImages } from '$lib/services/docker/image-service';import { getSettings } from '$lib/services/settings-service';import { formatBytes } from '$lib/utils';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';+import { tryCatch } from '$lib/utils/try-catch';export const POST: RequestHandler = async () => {- try {- const settings = await getSettings();- const pruneMode = settings.pruneMode;-- const result = await pruneImages(pruneMode);- const spaceReclaimedFormatted = formatBytes(result.SpaceReclaimed || 0);- const message = result.ImagesDeleted && result.ImagesDeleted.length > 0 ? `Successfully pruned ${result.ImagesDeleted.length} image(s). Space reclaimed: ${spaceReclaimedFormatted}.` : `No unused images found to prune. Space reclaimed: ${spaceReclaimedFormatted}.`;-- return json({- success: true,- message: message,- spaceReclaimed: result.SpaceReclaimed,- imagesDeletedCount: result.ImagesDeleted?.length || 0- });- } catch (err: any) {- console.error('API Error pruning images:', err);- throw error(500, err.message || 'Failed to prune images');+ const settingsResult = await tryCatch(getSettings());++ if (settingsResult.error) {+ console.error('Error getting settings:', settingsResult.error);++ const response: ApiErrorResponse = {+ success: false,+ error: 'Failed to retrieve settings',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: settingsResult.error+ };+ return json(response, { status: 500 });}++ const pruneMode = settingsResult.data.pruneMode;++ const pruneResult = await tryCatch(pruneImages(pruneMode));++ if (pruneResult.error) {+ console.error('Error pruning images:', pruneResult.error);++ const response: ApiErrorResponse = {+ success: false,+ error: extractDockerErrorMessage(pruneResult.error),+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: pruneResult.error+ };+ return json(response, { status: 500 });+ }++ const result = pruneResult.data;+ const spaceReclaimedFormatted = formatBytes(result.SpaceReclaimed || 0);+ const message = result.ImagesDeleted && result.ImagesDeleted.length > 0 ? `Successfully pruned ${result.ImagesDeleted.length} image(s). Space reclaimed: ${spaceReclaimedFormatted}.` : `No unused images found to prune. Space reclaimed: ${spaceReclaimedFormatted}.`;++ return json({+ success: true,+ message: message,+ spaceReclaimed: result.SpaceReclaimed,+ imagesDeletedCount: result.ImagesDeleted?.length || 0+ });};diff --git a/src/routes/api/images/pull-stream/[...name]/+server.ts b/src/routes/api/images/pull-stream/[...name]/+server.tsindex f6531d2e2..960fba711 100644--- a/src/routes/api/images/pull-stream/[...name]/+server.ts+++ b/src/routes/api/images/pull-stream/[...name]/+server.ts@@ -1,9 +1,22 @@import type { RequestHandler } from './$types';import { getDockerClient } from '$lib/services/docker/core';import { URL } from 'url';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';+import { json } from '@sveltejs/kit';export const GET: RequestHandler = async ({ params, request }) => {const imageName = params.name;++ if (!imageName) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Image name is required',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }+const url = new URL(request.url);const tag = url.searchParams.get('tag') || 'latest';const platform = url.searchParams.get('platform');@@ -46,9 +59,19 @@ export const GET: RequestHandler = async ({ params, request }) => {(err: Error | null, output: any[]) => {// Pull completeif (err) {- send({ error: err.message });+ const errorResponse: ApiErrorResponse = {+ success: false,+ error: extractDockerErrorMessage(err),+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: err+ };+ send(errorResponse);} else {- send({ complete: true, progress: 100 });+ send({+ success: true,+ complete: true,+ progress: 100+ });}controller.close();},@@ -75,25 +98,36 @@ export const GET: RequestHandler = async ({ params, request }) => {if (totalSize > 0) {totalProgress = Math.min(99, Math.floor((currentProgress / totalSize) * 100));- send({ progress: totalProgress, status: event.status });+ send({+ success: true,+ progress: totalProgress,+ status: event.status+ });} else {// Send initial status even if progress can't be calculated yet- send({ progress: 0, status: event.status });+ send({+ success: true,+ progress: 0,+ status: event.status+ });}} else if (event.status) {// Send status updates that don't have layer progress- send({ status: event.status });+ send({+ success: true,+ status: event.status+ });}});} catch (error: any) {- controller.enqueue(- new TextEncoder().encode(- `data: ${JSON.stringify({- error: error.message || 'Unknown error pulling image'- })}\n\n`- )- );+ const errorResponse: ApiErrorResponse = {+ success: false,+ error: error.message || 'Unknown error pulling image',+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: error+ };+ controller.enqueue(new TextEncoder().encode(`data: ${JSON.stringify(errorResponse)}\n\n`));controller.close();}}diff --git a/src/routes/api/images/pull/[...name]/+server.ts b/src/routes/api/images/pull/[...name]/+server.tsindex 3bc3a6eee..b4114c9b4 100644--- a/src/routes/api/images/pull/[...name]/+server.ts+++ b/src/routes/api/images/pull/[...name]/+server.ts@@ -1,33 +1,55 @@import { json } from '@sveltejs/kit';import type { RequestHandler } from '@sveltejs/kit';import { pullImage } from '$lib/services/docker/image-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';+import { tryCatch } from '$lib/utils/try-catch';export const POST: RequestHandler = async ({ params, request }) => {+ const fullPath = params.name;++ if (!fullPath) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Image reference is required',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }++ let body;try {- const fullPath = params.name;-- if (!fullPath) {- return json({ error: 'Image reference is required.' }, { status: 400 });- }-- const body = await request.json();- const platform = body?.platform;- const tag = body?.tag || 'latest';-- const imageRef = fullPath.includes(':') ? fullPath : `${fullPath}:${tag}`;-- console.log(`API: Pulling image "${imageRef}"...`);- await pullImage(imageRef, platform);-- return json(- {- success: true,- message: `Image "${imageRef}" pulled successfully.`- },- { status: 200 }- );- } catch (error: any) {- console.error('API Error pulling image:', error);- return json({ error: `Failed to pull image: ${error.message || 'Unknown error'}` }, { status: 500 });+ body = await request.json();+ } catch (error) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Invalid request body',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });}++ const platform = body?.platform;+ const tag = body?.tag || 'latest';+ const imageRef = fullPath.includes(':') ? fullPath : `${fullPath}:${tag}`;++ console.log(`API: Pulling image "${imageRef}"...`);+ const result = await tryCatch(pullImage(imageRef, platform));++ if (result.error) {+ console.error('Error pulling image:', result.error);++ const response: ApiErrorResponse = {+ success: false,+ error: extractDockerErrorMessage(result.error),+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });+ }++ return json({+ success: true,+ message: `Image "${imageRef}" pulled successfully.`+ });};diff --git a/src/routes/api/networks/[id]/+server.ts b/src/routes/api/networks/[id]/+server.tsindex 1a93de95c..ec9212dd5 100644--- a/src/routes/api/networks/[id]/+server.ts+++ b/src/routes/api/networks/[id]/+server.ts@@ -1,26 +1,59 @@-import { json, error } from '@sveltejs/kit';+import { json } from '@sveltejs/kit';import type { RequestHandler } from './$types';import { removeNetwork } from '$lib/services/docker/network-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';+import { tryCatch } from '$lib/utils/try-catch';export const DELETE: RequestHandler = async ({ params }) => {const networkId = params.id;if (!networkId) {- throw error(400, 'Network ID is required');+ const response: ApiErrorResponse = {+ success: false,+ error: 'Network ID is required',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });}- try {- await removeNetwork(networkId);- return json({ success: true, message: `Network ${networkId} deleted.` });- } catch (err: any) {- console.error(`API Error removing network ${networkId}:`, err);- // Pass specific error messages from the service- if (err.message.includes('not found')) {- throw error(404, err.message);+ const result = await tryCatch(removeNetwork(networkId));++ if (result.error) {+ console.error(`API Error removing network ${networkId}:`, result.error);++ // Handle specific error cases with appropriate status codes+ if (result.error.message?.includes('not found')) {+ const response: ApiErrorResponse = {+ success: false,+ error: result.error.message,+ code: ApiErrorCode.NOT_FOUND,+ details: result.error+ };+ return json(response, { status: 404 });}- if (err.message.includes('cannot be removed')) {- throw error(409, err.message); // 409 Conflict++ if (result.error.message?.includes('cannot be removed')) {+ const response: ApiErrorResponse = {+ success: false,+ error: result.error.message,+ code: ApiErrorCode.CONFLICT,+ details: result.error+ };+ return json(response, { status: 409 });}- throw error(500, err.message || 'Failed to remove network');++ const response: ApiErrorResponse = {+ success: false,+ error: extractDockerErrorMessage(result.error),+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });}++ return json({+ success: true,+ message: `Network ${networkId} deleted.`+ });};diff --git a/src/routes/api/networks/create/+server.ts b/src/routes/api/networks/create/+server.tsindex 341b1911d..940fdc6e5 100644--- a/src/routes/api/networks/create/+server.ts+++ b/src/routes/api/networks/create/+server.ts@@ -1,47 +1,77 @@-import { json, error } from '@sveltejs/kit';+import { json } from '@sveltejs/kit';import type { RequestHandler } from './$types';import { createNetwork } from '$lib/services/docker/network-service';import type { NetworkCreateOptions } from 'dockerode';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';+import { tryCatch } from '$lib/utils/try-catch';export const POST: RequestHandler = async ({ request }) => {- try {- const options: NetworkCreateOptions = await request.json();+ let options: NetworkCreateOptions;- if (!options.Name) {- throw error(400, 'Network name (Name) is required');- }+ const requestBodyResult = await tryCatch(request.json());- // Add default CheckDuplicate if not provided, common use case- if (options.CheckDuplicate === undefined) {- options.CheckDuplicate = true;- }+ if (requestBodyResult.error) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Invalid JSON payload',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }++ options = requestBodyResult.data;- // Call the service function- const networkInfo = await createNetwork(options);-- // Return the details of the created network- return json({- success: true,- network: {- // Map inspectInfo to ServiceNetwork shape if needed, or return full info- id: networkInfo.Id,- name: networkInfo.Name,- driver: networkInfo.Driver,- scope: networkInfo.Scope,- subnet: networkInfo.IPAM?.Config?.[0]?.Subnet ?? null,- gateway: networkInfo.IPAM?.Config?.[0]?.Gateway ?? null,- created: networkInfo.Created- // Add other relevant fields from NetworkInspectInfo if desired- },- message: `Network "${networkInfo.Name}" created successfully.`- });- } catch (err: any) {- // Handle specific SvelteKit errors or re-throw them- if (err.status >= 400 && err.status < 600) {- throw err;+ if (!options.Name) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Network name (Name) is required',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }++ if (options.CheckDuplicate === undefined) {+ options.CheckDuplicate = true;+ }++ const result = await tryCatch(createNetwork(options));++ if (result.error) {+ console.error('API Error creating network:', result.error);++ if (result.error.message?.includes('already exists')) {+ const response: ApiErrorResponse = {+ success: false,+ error: `Network with name "${options.Name}" already exists`,+ code: ApiErrorCode.CONFLICT,+ details: result.error+ };+ return json(response, { status: 409 });}- // Handle errors from createNetwork- console.error('API Error creating network:', err);- throw error(500, err.message || 'Failed to create network');++ const response: ApiErrorResponse = {+ success: false,+ error: extractDockerErrorMessage(result.error),+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });}++ const networkInfo = result.data;++ return json({+ success: true,+ network: {+ id: networkInfo.Id,+ name: networkInfo.Name,+ driver: networkInfo.Driver,+ scope: networkInfo.Scope,+ subnet: networkInfo.IPAM?.Config?.[0]?.Subnet ?? null,+ gateway: networkInfo.IPAM?.Config?.[0]?.Gateway ?? null,+ created: networkInfo.Created+ },+ message: `Network "${networkInfo.Name}" created successfully.`+ });};diff --git a/src/routes/api/settings/+server.ts b/src/routes/api/settings/+server.tsindex 2b4ef9786..e62e84ee8 100644--- a/src/routes/api/settings/+server.ts+++ b/src/routes/api/settings/+server.ts@@ -4,202 +4,203 @@ import { getSettings, saveSettings } from '$lib/services/settings-service';import type { Settings } from '$lib/types/settings.type';import { initComposeService } from '$lib/services/docker/stack-service';import { initAutoUpdateScheduler, stopAutoUpdateScheduler } from '$lib/services/docker/scheduler-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { tryCatch } from '$lib/utils/try-catch';export const GET: RequestHandler = async () => {- try {- const settings = await getSettings();- return json({ success: true, settings });- } catch (error: any) {- console.error('API Error fetching settings:', error);- return json(- {- success: false,- error: error.message || 'Failed to fetch settings'- },- { status: 500 }- );+ const result = await tryCatch(getSettings());+ if (result.error) {+ console.error('API Error fetching settings:', result.error);+ const response: ApiErrorResponse = {+ success: false,+ error: result.error.message || 'Failed to fetch settings',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });}+ return json({ success: true, settings: result.data });};export const PUT: RequestHandler = async ({ request }) => {- try {- const body = await request.json();- const currentSettings = await getSettings();-- // Validate required fields- if (!body.dockerHost) {- return json(- {- success: false,- error: 'Docker host cannot be empty.'- },- { status: 400 }- );- }+ const bodyResult = await tryCatch(request.json());+ if (bodyResult.error) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Invalid JSON payload',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }+ const body = bodyResult.data;++ const currentSettingsResult = await tryCatch(getSettings());+ if (currentSettingsResult.error) {+ console.error('API Error fetching current settings:', currentSettingsResult.error);+ const response: ApiErrorResponse = {+ success: false,+ error: currentSettingsResult.error.message || 'Failed to fetch current settings',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: currentSettingsResult.error+ };+ return json(response, { status: 500 });+ }+ const currentSettings = currentSettingsResult.data;++ // Validate required fields+ if (!body.dockerHost) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Docker host cannot be empty.',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }+ if (!body.stacksDirectory) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Stacks directory cannot be empty.',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }- if (!body.stacksDirectory) {- return json(- {- success: false,- error: 'Stacks directory cannot be empty.'- },- { status: 400 }- );+ // Normalize boolean values (handle string representation from form data)+ const booleanFields = ['autoUpdate', 'pollingEnabled'];+ const nestedAuthBooleanFields = ['localAuthEnabled', 'rbacEnabled'];+ booleanFields.forEach((field) => {+ if (field in body && typeof body[field] === 'string') {+ body[field] = body[field] === 'true';}-- // Normalize boolean values (handle string representation from form data)- const booleanFields = ['autoUpdate', 'pollingEnabled'];- const nestedAuthBooleanFields = ['localAuthEnabled', 'rbacEnabled'];-- // Handle top-level boolean fields- booleanFields.forEach((field) => {- if (field in body) {- // Convert string "true"/"false" to actual boolean if needed- if (typeof body[field] === 'string') {- body[field] = body[field] === 'true';- }+ });+ if (body.auth) {+ nestedAuthBooleanFields.forEach((field) => {+ if (field in body.auth && typeof body.auth[field] === 'string') {+ body.auth[field] = body.auth[field] === 'true';}});+ }- // Handle nested auth boolean fields- if (body.auth) {- nestedAuthBooleanFields.forEach((field) => {- if (field in body.auth) {- // Convert string "true"/"false" to actual boolean if needed- if (typeof body.auth[field] === 'string') {- body.auth[field] = body.auth[field] === 'true';- }- }- });- }-- // Validate polling interval if polling is enabled- if (body.pollingEnabled) {- const pollingInterval = parseInt(body.pollingInterval, 10);- if (isNaN(pollingInterval) || pollingInterval < 5 || pollingInterval > 60) {- return json(- {- success: false,- error: 'Polling interval must be between 5 and 60 minutes.'- },- { status: 400 }- );- }- body.pollingInterval = pollingInterval; // Ensure it's a number- }-- // Validate auto-update interval if enabled- if (body.autoUpdate) {- const autoUpdateInterval = parseInt(body.autoUpdateInterval, 10);- if (isNaN(autoUpdateInterval) || autoUpdateInterval < 5) {- body.autoUpdateInterval = 60; // Default to 60 minutes- } else {- const validatedAutoUpdateInterval = Math.min(Math.max(autoUpdateInterval, 5), 1440);- body.autoUpdateInterval = validatedAutoUpdateInterval;- }- }-- // Ensure nested objects exist if they are partially updated- if (!body.externalServices) body.externalServices = {};- if (!body.auth) body.auth = {};-- // Handle registry credentials- if (body.registryCredentials && typeof body.registryCredentials === 'string') {- try {- body.registryCredentials = JSON.parse(body.registryCredentials);- } catch (e) {- console.error('Error parsing registry credentials', e);- // Use current registry credentials- body.registryCredentials = currentSettings.registryCredentials;- }+ // Validate polling interval if polling is enabled+ if (body.pollingEnabled) {+ const pollingInterval = parseInt(body.pollingInterval, 10);+ if (isNaN(pollingInterval) || pollingInterval < 5 || pollingInterval > 60) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Polling interval must be between 5 and 60 minutes.',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });}+ body.pollingInterval = pollingInterval;+ }- // Handle authentication settings- if (body.authentication && typeof body.authentication === 'string') {- try {- body.authentication = JSON.parse(body.authentication);- } catch (e) {- console.error('Error parsing authentication settings', e);- // Use current authentication settings- body.authentication = currentSettings.auth;- }+ // Validate auto-update interval if enabled+ if (body.autoUpdate) {+ const autoUpdateInterval = parseInt(body.autoUpdateInterval, 10);+ if (isNaN(autoUpdateInterval) || autoUpdateInterval < 5) {+ body.autoUpdateInterval = 60;+ } else {+ const validatedAutoUpdateInterval = Math.min(Math.max(autoUpdateInterval, 5), 1440);+ body.autoUpdateInterval = validatedAutoUpdateInterval;}+ }- // Handle Auth settings- if (body.auth !== undefined) {- body.auth = {- localAuthEnabled: body.auth.localAuthEnabled ?? currentSettings.auth?.localAuthEnabled ?? true,- sessionTimeout: body.auth.sessionTimeout ?? currentSettings.auth?.sessionTimeout ?? 60,- passwordPolicy: body.auth.passwordPolicy ?? currentSettings.auth?.passwordPolicy ?? 'strong'- };- } else if (currentSettings.auth) {- // Keep current auth settings if not provided in update- body.auth = currentSettings.auth;+ // Ensure nested objects exist if they are partially updated+ if (!body.externalServices) body.externalServices = {};+ if (!body.auth) body.auth = {};++ // Handle registry credentials+ if (body.registryCredentials && typeof body.registryCredentials === 'string') {+ try {+ body.registryCredentials = JSON.parse(body.registryCredentials);+ } catch (e) {+ console.error('Error parsing registry credentials', e);+ body.registryCredentials = currentSettings.registryCredentials;}+ }- // Add onboarding to accepted fields- // Validate and normalize onboarding status- if (body.onboarding) {- if (typeof body.onboarding.completed === 'string') {- body.onboarding.completed = body.onboarding.completed === 'true';- }-- // Ensure completedAt is a valid date string- if (!body.onboarding.completedAt) {- body.onboarding.completedAt = new Date().toISOString();- }+ // Handle authentication settings+ if (body.authentication && typeof body.authentication === 'string') {+ try {+ body.authentication = JSON.parse(body.authentication);+ } catch (e) {+ console.error('Error parsing authentication settings', e);+ body.authentication = currentSettings.auth;}+ }- // Merge settings- const updatedSettings: Settings = {- ...currentSettings,- ...body+ // Handle Auth settings+ if (body.auth !== undefined) {+ body.auth = {+ localAuthEnabled: body.auth.localAuthEnabled ?? currentSettings.auth?.localAuthEnabled ?? true,+ sessionTimeout: body.auth.sessionTimeout ?? currentSettings.auth?.sessionTimeout ?? 60,+ passwordPolicy: body.auth.passwordPolicy ?? currentSettings.auth?.passwordPolicy ?? 'strong'};+ } else if (currentSettings.auth) {+ body.auth = currentSettings.auth;+ }- // Handle special cases for pruning settings- if (body.pruneMode) {- updatedSettings.pruneMode = body.pruneMode as 'all' | 'dangling';+ // Add onboarding to accepted fields+ if (body.onboarding) {+ if (typeof body.onboarding.completed === 'string') {+ body.onboarding.completed = body.onboarding.completed === 'true';+ }+ if (!body.onboarding.completedAt) {+ body.onboarding.completedAt = new Date().toISOString();}+ }- // Save updated settings- await saveSettings(updatedSettings);+ // Merge settings+ const updatedSettings: Settings = {+ ...currentSettings,+ ...body+ };+ if (body.pruneMode) {+ updatedSettings.pruneMode = body.pruneMode as 'all' | 'dangling';+ }- // Handle Docker connection changes- const dockerHostChanged = currentSettings.dockerHost !== updatedSettings.dockerHost;- const stacksDirChanged = currentSettings.stacksDirectory !== updatedSettings.stacksDirectory;+ // Save updated settings+ const saveResult = await tryCatch(saveSettings(updatedSettings));+ if (saveResult.error) {+ console.error('API Error saving settings:', saveResult.error);+ const response: ApiErrorResponse = {+ success: false,+ error: saveResult.error.message || 'Failed to save settings',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: saveResult.error+ };+ return json(response, { status: 500 });+ }- if (dockerHostChanged || stacksDirChanged) {- // Reinitialize compose service with new settings- await initComposeService();+ // Handle Docker connection changes+ const dockerHostChanged = currentSettings.dockerHost !== updatedSettings.dockerHost;+ const stacksDirChanged = currentSettings.stacksDirectory !== updatedSettings.stacksDirectory;+ if (dockerHostChanged || stacksDirChanged) {+ const initResult = await tryCatch(initComposeService());+ if (initResult.error) {+ console.error('API Error initializing compose service:', initResult.error);+ // Not returning error since settings were saved successfully}+ }- // Handle auto-update changes- const autoUpdateChanged = currentSettings.autoUpdate !== updatedSettings.autoUpdate || currentSettings.autoUpdateInterval !== updatedSettings.autoUpdateInterval;-- if (autoUpdateChanged) {- if (updatedSettings.autoUpdate) {- // Stop any existing scheduler and start with new settings- await stopAutoUpdateScheduler();- await initAutoUpdateScheduler();- } else {- // Stop the auto-update scheduler if disabled- await stopAutoUpdateScheduler();+ // Handle auto-update changes+ const autoUpdateChanged = currentSettings.autoUpdate !== updatedSettings.autoUpdate || currentSettings.autoUpdateInterval !== updatedSettings.autoUpdateInterval;+ if (autoUpdateChanged) {+ if (updatedSettings.autoUpdate) {+ await tryCatch(stopAutoUpdateScheduler());+ const schedulerResult = await tryCatch(initAutoUpdateScheduler());+ if (schedulerResult.error) {+ console.error('API Error initializing auto-update scheduler:', schedulerResult.error);}+ } else {+ await tryCatch(stopAutoUpdateScheduler());}-- return json({- success: true,- message: 'Settings updated successfully',- settings: updatedSettings- });- } catch (error: any) {- console.error('API Error updating settings:', error);- return json(- {- success: false,- error: error.message || 'Failed to update settings'- },- { status: 500 }- );}++ return json({+ success: true,+ message: 'Settings updated successfully',+ settings: updatedSettings+ });};diff --git a/src/routes/api/stacks/[stackId]/+server.ts b/src/routes/api/stacks/[stackId]/+server.tsindex 465de0819..155199ad6 100644--- a/src/routes/api/stacks/[stackId]/+server.ts+++ b/src/routes/api/stacks/[stackId]/+server.ts@@ -1,17 +1,28 @@import type { RequestHandler } from './$types';import { json } from '@sveltejs/kit';import { updateStack } from '$lib/services/docker/stack-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { tryCatch } from '$lib/utils/try-catch';export const PUT: RequestHandler = async ({ params, request }) => {const { stackId } = params;const { name, composeContent, autoUpdate, envContent } = await request.json();- try {- // From your API endpoint- await updateStack(stackId, { name, composeContent, autoUpdate, envContent });- return json({ success: true, message: 'Stack updated successfully' });- } catch (error: any) {- console.error('Error updating stack:', error);- return json({ success: false, error: error.message || 'Failed to update stack' }, { status: 500 });+ const result = await tryCatch(updateStack(stackId, { name, composeContent, autoUpdate, envContent }));++ if (result.error) {+ console.error('Error updating stack:', result.error);+ const response: ApiErrorResponse = {+ success: false,+ error: result.error.message || 'Failed to update stack',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });}++ return json({+ success: true,+ message: 'Stack updated successfully'+ });};diff --git a/src/routes/api/stacks/[stackId]/migrate/+server.ts b/src/routes/api/stacks/[stackId]/migrate/+server.tsindex 4e58dddd2..02208de41 100644--- a/src/routes/api/stacks/[stackId]/migrate/+server.ts+++ b/src/routes/api/stacks/[stackId]/migrate/+server.ts@@ -1,19 +1,36 @@import type { RequestHandler } from '@sveltejs/kit';-import { error, json } from '@sveltejs/kit';+import { json } from '@sveltejs/kit';import { migrateStackToNameFolder } from '$lib/services/docker/stack-migration-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { tryCatch } from '$lib/utils/try-catch';export const POST: RequestHandler = async ({ params }) => {const { stackId } = params;if (!stackId) {- throw error(400, 'Missing stackId');+ const response: ApiErrorResponse = {+ success: false,+ error: 'Missing stackId',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });}- try {- await migrateStackToNameFolder(stackId);- return json({ success: true, message: `Stack "${stackId}" migrated successfully.` });- } catch (err: any) {- console.error(err);- throw error(500, err?.message || 'Failed to migrate stack');+ const result = await tryCatch(migrateStackToNameFolder(stackId));++ if (result.error) {+ console.error('Error migrating stack:', result.error);+ const response: ApiErrorResponse = {+ success: false,+ error: result.error.message || 'Failed to migrate stack',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });}++ return json({+ success: true,+ message: `Stack "${stackId}" migrated successfully.`+ });};diff --git a/src/routes/api/stacks/[stackId]/pull/+server.ts b/src/routes/api/stacks/[stackId]/pull/+server.tsindex e89ba5c86..0fe7699f8 100644--- a/src/routes/api/stacks/[stackId]/pull/+server.ts+++ b/src/routes/api/stacks/[stackId]/pull/+server.ts@@ -2,85 +2,89 @@ import type { RequestHandler } from './$types';import { json } from '@sveltejs/kit';import { getStack } from '$lib/services/docker/stack-service';import Docker from 'dockerode';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { tryCatch } from '$lib/utils/try-catch';export const POST: RequestHandler = async ({ params }) => {const id = params.stackId;const docker = new Docker();- try {- // Get the stack to access its compose content- const stack = await getStack(id);- if (!stack || !stack.composeContent) {- return json({ success: false, error: 'Stack not found or has no compose content' }, { status: 404 });- }-- // Parse the compose file to extract image names- // This is a simplified approach - you might need more robust parsing- const composeLines = stack.composeContent.split('\n');- const imageLines = composeLines.filter((line) => line.trim().startsWith('image:') || line.includes(' image:'));+ // Get the stack to access its compose content+ const stackResult = await tryCatch(getStack(id));+ if (stackResult.error || !stackResult.data || !stackResult.data.composeContent) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Stack not found or has no compose content',+ code: ApiErrorCode.NOT_FOUND,+ details: stackResult.error+ };+ return json(response, { status: 404 });+ }+ const stack = stackResult.data;- if (imageLines.length === 0) {- return json({ success: false, error: 'No images found in stack compose file' }, { status: 400 });- }+ // Parse the compose file to extract image names+ const composeLines = stack.composeContent!.split('\n');+ const imageLines = composeLines.filter((line) => line.trim().startsWith('image:') || line.includes(' image:'));- // Extract image names- const imageNames = imageLines.map((line) => {- const imagePart = line.split('image:')[1].trim();- // Remove any quotes or trailing characters- return imagePart.replace(/['"]/g, '').split(' ')[0];- });+ if (imageLines.length === 0) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'No images found in stack compose file',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }- // Pull each image- const pullResults = await Promise.all(- imageNames.map(async (imageName) => {- try {- const stream = await docker.pull(imageName);+ // Extract image names+ const imageNames = imageLines.map((line) => {+ const imagePart = line.split('image:')[1].trim();+ return imagePart.replace(/['"]/g, '').split(' ')[0];+ });- // Process the stream- return new Promise((resolve, reject) => {- docker.modem.followProgress(- stream,- (err: any, output: any[]) => {- if (err) {- reject(err);- } else {- resolve({ image: imageName, success: true });- }- },- (event: any) => {- // Optional: handle progress events- console.log(`Pull progress for ${imageName}:`, event);- }- );- });- } catch (error) {- console.error(`Error pulling image ${imageName}:`, error);- return { image: imageName, success: false, error };- }- })- );+ // Pull each image using tryCatch for each pull+ const pullResults = await Promise.all(+ imageNames.map(async (imageName) => {+ const pullResult = await tryCatch(docker.pull(imageName));+ if (pullResult.error) {+ console.error(`Error pulling image ${imageName}:`, pullResult.error);+ return { image: imageName, success: false, error: pullResult.error.message || pullResult.error };+ }+ // Process the stream+ return new Promise((resolve) => {+ docker.modem.followProgress(+ pullResult.data,+ (err: any) => {+ if (err) {+ console.error(`Error in followProgress for ${imageName}:`, err);+ resolve({ image: imageName, success: false, error: err.message || err });+ } else {+ resolve({ image: imageName, success: true });+ }+ },+ (event: any) => {+ // Optional: handle progress events+ console.log(`Pull progress for ${imageName}:`, event);+ }+ );+ });+ })+ );- // Check if all pulls were successful- const allSuccessful = pullResults.every((result: any) => result.success);+ const allSuccessful = pullResults.every((result: any) => result.success);- if (allSuccessful) {- return json({- success: true,- message: `All images for stack pulled successfully`,- details: pullResults- });- } else {- return json(- {- success: false,- error: 'Some images failed to pull',- details: pullResults- },- { status: 500 }- );- }- } catch (error: any) {- console.error(`API Error pulling images for stack ${id}:`, error);- return json({ success: false, error: error.message || 'Failed to pull stack images' }, { status: 500 });+ if (allSuccessful) {+ return json({+ success: true,+ message: `All images for stack pulled successfully`,+ details: pullResults+ });+ } else {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Some images failed to pull',+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: pullResults+ };+ return json(response, { status: 500 });}};diff --git a/src/routes/api/stacks/[stackId]/redeploy/+server.ts b/src/routes/api/stacks/[stackId]/redeploy/+server.tsindex 1172b57d0..12628a5d6 100644--- a/src/routes/api/stacks/[stackId]/redeploy/+server.ts+++ b/src/routes/api/stacks/[stackId]/redeploy/+server.ts@@ -1,19 +1,36 @@import type { RequestHandler } from './$types';import { json } from '@sveltejs/kit';import { fullyRedeployStack } from '$lib/services/docker/stack-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { tryCatch } from '$lib/utils/try-catch';export const POST: RequestHandler = async ({ params }) => {const id = params.stackId;- try {- const success = await fullyRedeployStack(id);- if (success) {- return json({ success: true, message: `Stack redeployed successfully` });- } else {- return json({ success: false, error: 'Failed to redeploy stack' }, { status: 500 });- }- } catch (error: any) {- console.error(`API Error redeploying stack ${id}:`, error);- return json({ success: false, error: error.message || 'Failed to redeploy stack' }, { status: 500 });+ const result = await tryCatch(fullyRedeployStack(id));++ if (result.error) {+ console.error(`API Error redeploying stack ${id}:`, result.error);+ const response: ApiErrorResponse = {+ success: false,+ error: result.error.message || 'Failed to redeploy stack',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });+ }++ if (result.data) {+ return json({+ success: true,+ message: `Stack redeployed successfully`+ });+ } else {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Failed to redeploy stack',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR+ };+ return json(response, { status: 500 });}};diff --git a/src/routes/api/stacks/[stackId]/remove/+server.ts b/src/routes/api/stacks/[stackId]/remove/+server.tsindex d2db6a40d..acfb893b1 100644--- a/src/routes/api/stacks/[stackId]/remove/+server.ts+++ b/src/routes/api/stacks/[stackId]/remove/+server.ts@@ -1,23 +1,45 @@import type { RequestHandler } from './$types';import { json } from '@sveltejs/kit';import { removeStack } from '$lib/services/docker/stack-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { tryCatch } from '$lib/utils/try-catch';export const DELETE: RequestHandler = async ({ params }) => {const id = params.stackId;if (!id) {- return json({ success: false, error: 'Stack ID is required' }, { status: 400 });+ const response: ApiErrorResponse = {+ success: false,+ error: 'Stack ID is required',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });}- try {- const success = await removeStack(id);- if (success) {- return json({ success: true, message: `Stack removed successfully` });- } else {- return json({ success: false, error: 'Failed to remove stack' }, { status: 400 });- }- } catch (error: any) {- console.error(`API Error removing stack ${id}:`, error);- return json({ success: false, error: error.message || 'Failed to remove stack' }, { status: 409 });+ const result = await tryCatch(removeStack(id));++ if (result.error) {+ console.error(`API Error removing stack ${id}:`, result.error);+ const response: ApiErrorResponse = {+ success: false,+ error: result.error.message || 'Failed to remove stack',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: result.error+ };+ return json(response, { status: 409 });+ }++ if (result.data) {+ return json({+ success: true,+ message: `Stack removed successfully`+ });+ } else {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Failed to remove stack',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });}};diff --git a/src/routes/api/stacks/[stackId]/restart/+server.ts b/src/routes/api/stacks/[stackId]/restart/+server.tsindex bcc2c5b9d..dadde257b 100644--- a/src/routes/api/stacks/[stackId]/restart/+server.ts+++ b/src/routes/api/stacks/[stackId]/restart/+server.ts@@ -1,19 +1,36 @@import type { RequestHandler } from './$types';import { json } from '@sveltejs/kit';import { restartStack } from '$lib/services/docker/stack-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { tryCatch } from '$lib/utils/try-catch';export const POST: RequestHandler = async ({ params }) => {const id = params.stackId;- try {- const success = await restartStack(id);- if (success) {- return json({ success: true, message: `Stack restarted successfully` });- } else {- return json({ success: false, error: 'Failed to restart stack' }, { status: 500 });- }- } catch (error: any) {- console.error(`API Error restarting stack ${id}:`, error);- return json({ success: false, error: error.message || 'Failed to restart stack' }, { status: 500 });+ const result = await tryCatch(restartStack(id));++ if (result.error) {+ console.error(`API Error restarting stack ${id}:`, result.error);+ const response: ApiErrorResponse = {+ success: false,+ error: result.error.message || 'Failed to restart stack',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });+ }++ if (result.data) {+ return json({+ success: true,+ message: `Stack restarted successfully`+ });+ } else {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Failed to restart stack',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR+ };+ return json(response, { status: 500 });}};diff --git a/src/routes/api/stacks/[stackId]/start/+server.ts b/src/routes/api/stacks/[stackId]/start/+server.tsindex dde9e1d63..30a3a5dfc 100644--- a/src/routes/api/stacks/[stackId]/start/+server.ts+++ b/src/routes/api/stacks/[stackId]/start/+server.ts@@ -1,15 +1,27 @@import { startStack } from '$lib/services/docker/stack-service';import type { RequestHandler } from './$types';import { json } from '@sveltejs/kit';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { tryCatch } from '$lib/utils/try-catch';export const POST: RequestHandler = async ({ params }) => {const id = params.stackId;- try {- await startStack(id);- return json({ success: true, message: `Stack started successfully` });- } catch (error: any) {- console.error(`API Error starting stack ${id}:`, error);- return json({ success: false, error: error.message || 'Failed to start stack' }, { status: 500 });+ const result = await tryCatch(startStack(id));++ if (result.error) {+ console.error(`API Error starting stack ${id}:`, result.error);+ const response: ApiErrorResponse = {+ success: false,+ error: result.error.message || 'Failed to start stack',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });}++ return json({+ success: true,+ message: `Stack started successfully`+ });};diff --git a/src/routes/api/stacks/[stackId]/stop/+server.ts b/src/routes/api/stacks/[stackId]/stop/+server.tsindex 11f0d03b6..ce4354a68 100644--- a/src/routes/api/stacks/[stackId]/stop/+server.ts+++ b/src/routes/api/stacks/[stackId]/stop/+server.ts@@ -1,19 +1,36 @@import type { RequestHandler } from './$types';import { json } from '@sveltejs/kit';import { stopStack } from '$lib/services/docker/stack-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { tryCatch } from '$lib/utils/try-catch';export const POST: RequestHandler = async ({ params }) => {const id = params.stackId;- try {- const success = await stopStack(id);- if (success) {- return json({ success: true, message: `Stack stopped successfully` });- } else {- return json({ success: false, error: 'Failed to stop stack' }, { status: 500 });- }- } catch (error: any) {- console.error(`API Error stopping stack ${id}:`, error);- return json({ success: false, error: error.message || 'Failed to stop stack' }, { status: 500 });+ const result = await tryCatch(stopStack(id));++ if (result.error) {+ console.error(`API Error stopping stack ${id}:`, result.error);+ const response: ApiErrorResponse = {+ success: false,+ error: result.error.message || 'Failed to stop stack',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });+ }++ if (result.data) {+ return json({+ success: true,+ message: `Stack stopped successfully`+ });+ } else {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Failed to stop stack',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR+ };+ return json(response, { status: 500 });}};diff --git a/src/routes/api/stacks/create/+server.ts b/src/routes/api/stacks/create/+server.tsindex ed8b20463..de9784b60 100644--- a/src/routes/api/stacks/create/+server.ts+++ b/src/routes/api/stacks/create/+server.ts@@ -1,36 +1,58 @@-import { json, error } from '@sveltejs/kit';+import { json } from '@sveltejs/kit';import type { RequestHandler } from './$types';import { createStack } from '$lib/services/docker/stack-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { tryCatch } from '$lib/utils/try-catch';export const POST: RequestHandler = async ({ request }) => {- try {- const body = await request.json();- const name = body.name?.toString();- const composeContent = body.composeContent?.toString();- const envContent = body.envContent?.toString();-- if (!name) {- throw error(502, 'Stack name is required');- }+ const bodyResult = await tryCatch(request.json());+ if (bodyResult.error) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Invalid JSON payload',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }+ const body = bodyResult.data;+ const name = body.name?.toString();+ const composeContent = body.composeContent?.toString();+ const envContent = body.envContent?.toString();- if (!composeContent) {- throw error(503, 'Compose file content is required');- }+ if (!name) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Stack name is required',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }- const newStack = await createStack(name, composeContent, envContent);+ if (!composeContent) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Compose file content is required',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }- return json({- success: true,- stack: newStack,- message: `Stack "${newStack.name}" created successfully.`- });- } catch (err: any) {- // Handle specific SvelteKit errors or re-throw them- if (err.status >= 400 && err.status < 600) {- throw err;- }- // Handle errors from createStack- console.error('API Error creating stack:', err);- throw error(500, err.message || 'Failed to create stack');+ const result = await tryCatch(createStack(name, composeContent, envContent));+ if (result.error) {+ console.error('API Error creating stack:', result.error);+ const response: ApiErrorResponse = {+ success: false,+ error: result.error.message || 'Failed to create stack',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });}++ const newStack = result.data;+ return json({+ success: true,+ stack: newStack,+ message: `Stack "${newStack.name}" created successfully.`+ });};diff --git a/src/routes/api/stacks/import/+server.ts b/src/routes/api/stacks/import/+server.tsindex 0320322f1..b92830317 100644--- a/src/routes/api/stacks/import/+server.ts+++ b/src/routes/api/stacks/import/+server.ts@@ -1,32 +1,49 @@import { json } from '@sveltejs/kit';import type { RequestHandler } from './$types';import { importExternalStack } from '$lib/services/docker/stack-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { tryCatch } from '$lib/utils/try-catch';export const POST: RequestHandler = async ({ request }) => {- const { stackId, stackName } = await request.json();+ const bodyResult = await tryCatch(request.json());+ if (bodyResult.error) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Invalid JSON payload',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }+ const { stackId, stackName } = bodyResult.data;if (!stackId) {- return json({ success: false, error: 'Stack ID is required' }, { status: 400 });+ const response: ApiErrorResponse = {+ success: false,+ error: 'Stack ID is required',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });}- try {- const importedStack = await importExternalStack(stackId);-- console.log(`Successfully imported stack: ${stackId} (${stackName || importedStack.name})`);+ const result = await tryCatch(importExternalStack(stackId));- return json({- success: true,- stack: importedStack,- message: `Successfully imported stack ${importedStack.name}`- });- } catch (err) {- console.error(`Error importing stack ${stackId}:`, err);- return json(- {- success: false,- error: err instanceof Error ? err.message : 'Failed to import stack'- },- { status: 500 }- );+ if (result.error) {+ console.error(`Error importing stack ${stackId}:`, result.error);+ const response: ApiErrorResponse = {+ success: false,+ error: result.error.message || 'Failed to import stack',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });}++ const importedStack = result.data;+ console.log(`Successfully imported stack: ${stackId} (${stackName || importedStack.name})`);++ return json({+ success: true,+ stack: importedStack,+ message: `Successfully imported stack ${importedStack.name}`+ });};diff --git a/src/routes/api/system/auto-update/+server.ts b/src/routes/api/system/auto-update/+server.tsindex e18ed8add..384d28ea5 100644--- a/src/routes/api/system/auto-update/+server.ts+++ b/src/routes/api/system/auto-update/+server.ts@@ -2,45 +2,50 @@ import type { RequestHandler } from './$types';import { json } from '@sveltejs/kit';import { getSettings } from '$lib/services/settings-service';import { checkAndUpdateContainers, checkAndUpdateStacks } from '$lib/services/docker/auto-update-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { tryCatch } from '$lib/utils/try-catch';export const GET: RequestHandler = async () => {- try {- const settings = await getSettings();+ const settingsResult = await tryCatch(getSettings());- return json({- enabled: settings.autoUpdate,- interval: settings.autoUpdateInterval || 60,- message: settings.autoUpdate ? `Auto-update is enabled and checks every ${settings.autoUpdateInterval || 60} minutes` : 'Auto-update is disabled'- });- } catch (error: any) {- console.error('Error getting auto-update status:', error);- return json(- {- error: error.message || 'Failed to get auto-update status',- enabled: false- },- { status: 500 }- );+ if (settingsResult.error) {+ console.error('Error getting auto-update status:', settingsResult.error);+ const response: ApiErrorResponse = {+ success: false,+ error: settingsResult.error.message || 'Failed to get auto-update status',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: settingsResult.error+ };+ return json(response, { status: 500 });}++ const settings = settingsResult.data;+ return json({+ success: true,+ enabled: settings.autoUpdate,+ interval: settings.autoUpdateInterval || 60,+ message: settings.autoUpdate ? `Auto-update is enabled and checks every ${settings.autoUpdateInterval || 60} minutes` : 'Auto-update is disabled'+ });};export const POST: RequestHandler = async () => {- try {- const [containerResults, stackResults] = await Promise.all([checkAndUpdateContainers(), checkAndUpdateStacks()]);+ const containerResult = await tryCatch(checkAndUpdateContainers());+ const stackResult = await tryCatch(checkAndUpdateStacks());- return json({- success: true,- containers: containerResults,- stacks: stackResults- });- } catch (error: any) {- console.error('Error running manual update check:', error);- return json(- {- success: false,- error: error.message || 'Failed to run update check'- },- { status: 500 }- );+ if (containerResult.error || stackResult.error) {+ console.error('Error running manual update check:', containerResult.error || stackResult.error);+ const response: ApiErrorResponse = {+ success: false,+ error: containerResult.error?.message || stackResult.error?.message || 'Failed to run update check',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: containerResult.error || stackResult.error+ };+ return json(response, { status: 500 });}++ return json({+ success: true,+ containers: containerResult.data,+ stacks: stackResult.data+ });};diff --git a/src/routes/api/system/prune/+server.ts b/src/routes/api/system/prune/+server.tsindex 4e39940ff..9850faa76 100644--- a/src/routes/api/system/prune/+server.ts+++ b/src/routes/api/system/prune/+server.ts@@ -1,69 +1,80 @@-import { json, error as serverError } from '@sveltejs/kit';+import { json } from '@sveltejs/kit';import { pruneSystem } from '$lib/services/docker/system-service';import type { RequestHandler } from './$types';-import { formatBytes } from '$lib/utils'; // Import formatBytes+import { formatBytes } from '$lib/utils';import type { PruneType } from '$lib/types/actions.type';--// Define allowed types+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { tryCatch } from '$lib/utils/try-catch';const allowedPruneTypes: PruneType[] = ['containers', 'images', 'networks', 'volumes'];export const POST: RequestHandler = async ({ url }) => {- // Get types from query parameters, e.g., /api/docker/system/prune?types=containers,imagesconst typesParam = url.searchParams.get('types');if (!typesParam) {- throw serverError(400, 'Missing required query parameter: types');+ const response: ApiErrorResponse = {+ success: false,+ error: 'Missing required query parameter: types',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });}- // Validate and parse typesconst requestedTypes = typesParam.split(',').map((t) => t.trim().toLowerCase()) as PruneType[];const validTypes = requestedTypes.filter((t) => allowedPruneTypes.includes(t));if (validTypes.length === 0) {- throw serverError(400, `No valid resource types provided for pruning. Allowed types: ${allowedPruneTypes.join(', ')}`);+ const response: ApiErrorResponse = {+ success: false,+ error: `No valid resource types provided for pruning. Allowed types: ${allowedPruneTypes.join(', ')}`,+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });}console.log(`API: POST /api/system/prune - Pruning types: ${validTypes.join(', ')}`);- try {- const results = await pruneSystem(validTypes); // Pass validated types to service+ const result = await tryCatch(pruneSystem(validTypes));++ if (result.error) {+ console.error('API Error (pruneSystem):', result.error);+ const response: ApiErrorResponse = {+ success: false,+ error: result.error.message || 'Failed to prune system.',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });+ }- // Calculate total space reclaimed and check for errors- let totalSpaceReclaimed = 0;- let hasErrors = false;- const errorMessages: string[] = [];+ const results = result.data;+ let totalSpaceReclaimed = 0;+ let hasErrors = false;+ const errorMessages: string[] = [];- if (Array.isArray(results)) {- results.forEach((res) => {- if (res) {- if (typeof res.SpaceReclaimed === 'number') {- totalSpaceReclaimed += res.SpaceReclaimed;- }- if (res.error) {- hasErrors = true;- errorMessages.push(`${res.type || 'Unknown'}: ${res.error}`);- }+ if (Array.isArray(results)) {+ results.forEach((res) => {+ if (res) {+ if (typeof res.SpaceReclaimed === 'number') {+ totalSpaceReclaimed += res.SpaceReclaimed;}- });- }-- let message = `System prune completed for: ${validTypes.join(', ')}.`;- if (totalSpaceReclaimed > 0) {- message += ` Reclaimed ${formatBytes(totalSpaceReclaimed)}.`;- }- if (hasErrors) {- message += ` Errors occurred: ${errorMessages.join('; ')}`;- // Decide if partial success should still return 200 or a different status- console.warn('Prune completed with errors:', errorMessages);- // Return 207 Multi-Status might be appropriate, but 200 with error details is often simpler- return json({ success: false, results, spaceReclaimed: totalSpaceReclaimed, message }, { status: 200 }); // Indicate partial failure in payload- }+ if (res.error) {+ hasErrors = true;+ errorMessages.push(`${res.type || 'Unknown'}: ${res.error}`);+ }+ }+ });+ }- console.log('API: System prune completed successfully.');- return json({ success: true, results, spaceReclaimed: totalSpaceReclaimed, message });- } catch (err: any) {- console.error('API Error (pruneSystem):', err);- // Handle errors from pruneSystem setup or unexpected issues- throw serverError(err.status || 500, err.body?.message || err.message || 'Failed to prune system.');+ let message = `System prune completed for: ${validTypes.join(', ')}.`;+ if (totalSpaceReclaimed > 0) {+ message += ` Reclaimed ${formatBytes(totalSpaceReclaimed)}.`;}+ if (hasErrors) {+ message += ` Errors occurred: ${errorMessages.join('; ')}`;+ console.warn('Prune completed with errors:', errorMessages);+ return json({ success: false, results, spaceReclaimed: totalSpaceReclaimed, message }, { status: 200 });+ }++ console.log('API: System prune completed successfully.');+ return json({ success: true, results, spaceReclaimed: totalSpaceReclaimed, message });};diff --git a/src/routes/api/users/+server.ts b/src/routes/api/users/+server.tsindex 1bc959309..8d681e4cc 100644--- a/src/routes/api/users/+server.ts+++ b/src/routes/api/users/+server.ts@@ -3,89 +3,143 @@ import type { RequestHandler } from './$types';import { getUserByUsername, hashPassword, saveUser, listUsers } from '$lib/services/user-service';import type { User } from '$lib/types/user.type';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 }) => {- try {- // Check authentication - only admins can list users- if (!locals.user || !locals.user.roles.includes('admin')) {- return json({ error: 'Unauthorized' }, { status: 403 });- }-- const users = await listUsers();-- // Remove sensitive data before sending- const sanitizedUsers = users.map((user) => {- const { passwordHash, ...rest } = user;- return rest;- });-- return json({ users: sanitizedUsers });- } catch (error) {- console.error('Error listing users:', error);- return json({ error: 'Failed to list users' }, { status: 500 });+ // Only admins can list users+ if (!locals.user || !locals.user.roles.includes('admin')) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Unauthorized',+ code: ApiErrorCode.FORBIDDEN+ };+ return json(response, { status: 403 });+ }++ const usersResult = await tryCatch(listUsers());+ if (usersResult.error) {+ console.error('Error listing users:', usersResult.error);+ const response: ApiErrorResponse = {+ success: false,+ error: 'Failed to list users',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: usersResult.error+ };+ return json(response, { status: 500 });}++ const sanitizedUsers = usersResult.data.map((user: User) => {+ const { passwordHash, ...rest } = user;+ return rest;+ });++ return json({ success: true, users: sanitizedUsers });};export const POST: RequestHandler = async ({ request, locals }) => {- try {- // Only admins should be able to create users- const currentUser = locals.user as User;-- if (!currentUser || !currentUser.roles.includes('admin')) {- return json({ error: 'Unauthorized' }, { status: 403 });- }-- const userData = await request.json();- const { username, password, displayName, email, roles } = userData;-- // Validate input- if (!username || !password) {- return json({ error: 'Username and password are required' }, { status: 400 });- }-- // Check if username already exists- const existingUser = await getUserByUsername(username);-- if (existingUser) {- return json({ error: 'Username already exists' }, { status: 409 });- }-- // Get password policy from settings- const settings = await getSettings();- const policy = settings.auth?.passwordPolicy || 'strong';-- // Validate password according to policy- if (!validatePassword(password, policy)) {- return json({ error: 'Password does not meet requirements' }, { status: 400 });- }-- // Create the user- const passwordHash = await hashPassword(password);-- const newUser: User = {- id: '', // Will be generated in saveUser- username,- passwordHash,- displayName: displayName || username,- email,- roles: roles || ['user'],- createdAt: new Date().toISOString()+ // Only admins should be able to create users+ const currentUser = locals.user as User;++ if (!currentUser || !currentUser.roles.includes('admin')) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Unauthorized',+ code: ApiErrorCode.FORBIDDEN+ };+ return json(response, { status: 403 });+ }++ const userDataResult = await tryCatch(request.json());+ if (userDataResult.error) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Invalid JSON payload',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }+ const { username, password, displayName, email, roles } = userDataResult.data;++ // Validate input+ if (!username || !password) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Username and password are required',+ code: ApiErrorCode.BAD_REQUEST};+ return json(response, { status: 400 });+ }- const savedUser = await saveUser(newUser);+ // Check if username already exists+ const existingUserResult = await tryCatch(getUserByUsername(username));+ if (existingUserResult.data) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Username already exists',+ code: ApiErrorCode.CONFLICT+ };+ return json(response, { status: 409 });+ }- // Return sanitized user (remove sensitive fields)- const { passwordHash: _, ...sanitizedUser } = savedUser;+ // Get password policy from settings+ const settingsResult = await tryCatch(getSettings());+ const settings = settingsResult.data;+ const policy = settings?.auth?.passwordPolicy || 'strong';++ // Validate password according to policy+ if (!validatePassword(password, policy)) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Password does not meet requirements',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }- return json({- success: true,- user: sanitizedUser- });- } catch (error) {- console.error('Error creating user:', error);- return json({ error: 'Failed to create user' }, { status: 500 });+ // Create the user+ const hashResult = await tryCatch(hashPassword(password));+ if (hashResult.error) {+ console.error('Error hashing password:', hashResult.error);+ const response: ApiErrorResponse = {+ success: false,+ error: 'Failed to hash password',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: hashResult.error+ };+ return json(response, { status: 500 });}++ const newUser: User = {+ id: '', // Will be generated in saveUser+ username,+ passwordHash: hashResult.data,+ displayName: displayName || username,+ email,+ roles: roles || ['user'],+ createdAt: new Date().toISOString()+ };++ const saveResult = await tryCatch(saveUser(newUser));+ if (saveResult.error) {+ console.error('Error saving user:', saveResult.error);+ const response: ApiErrorResponse = {+ success: false,+ error: 'Failed to create user',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: saveResult.error+ };+ return json(response, { status: 500 });+ }++ // Return sanitized user (remove sensitive fields)+ const { passwordHash: _, ...sanitizedUser } = saveResult.data;++ return json({+ success: true,+ user: sanitizedUser+ });};// Validate password based on policydiff --git a/src/routes/api/users/[id]/+server.ts b/src/routes/api/users/[id]/+server.tsindex f9103949b..a213f6593 100644--- a/src/routes/api/users/[id]/+server.ts+++ b/src/routes/api/users/[id]/+server.ts@@ -6,99 +6,154 @@ import { getSettings } from '$lib/services/settings-service';import fs from 'fs/promises';import path from 'node:path';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 }) => {- try {- // Only admins or the user themselves can update- if (!locals.user) {- return json({ error: 'Unauthorized' }, { status: 401 });- }-- const userIdToUpdate = params.id;- const requestingUser = locals.user as User;-- // Check if user is admin or updating their own profile- if (!requestingUser.roles.includes('admin') && requestingUser.id !== userIdToUpdate) {- return json({ error: 'Forbidden' }, { status: 403 });- }+ // Only admins or the user themselves can update+ if (!locals.user) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Unauthorized',+ code: ApiErrorCode.UNAUTHORIZED+ };+ return json(response, { status: 401 });+ }- const existingUser = await getUserById(userIdToUpdate);- if (!existingUser) {- return json({ error: 'User not found' }, { status: 404 });- }+ const userIdToUpdate = params.id;+ const requestingUser = locals.user as User;++ // Check if user is admin or updating their own profile+ if (!requestingUser.roles.includes('admin') && requestingUser.id !== userIdToUpdate) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Forbidden',+ code: ApiErrorCode.FORBIDDEN+ };+ return json(response, { status: 403 });+ }- const updateData = await request.json();- const { password, displayName, email, roles } = updateData;+ const existingUserResult = await tryCatch(getUserById(userIdToUpdate));+ if (existingUserResult.error || !existingUserResult.data) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'User not found',+ code: ApiErrorCode.NOT_FOUND+ };+ return json(response, { status: 404 });+ }+ const existingUser = existingUserResult.data;++ const updateDataResult = await tryCatch(request.json());+ if (updateDataResult.error) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Invalid JSON payload',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }+ const { password, displayName, email, roles } = updateDataResult.data;- // Prepare updated user object- const updatedUser: User = { ...existingUser };+ // Prepare updated user object+ const 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 roles- const ALLOWED = ['admin', 'user', 'viewer'];- updatedUser.roles = Array.isArray(roles) ? roles.filter((r) => ALLOWED.includes(r)) : updatedUser.roles;- }+ if (displayName !== undefined) updatedUser.displayName = displayName;+ if (email !== undefined) updatedUser.email = email;+ if (roles !== undefined && requestingUser.roles.includes('admin')) {+ // Only admins can change roles+ const ALLOWED = ['admin', 'user', 'viewer'];+ updatedUser.roles = Array.isArray(roles) ? roles.filter((r) => ALLOWED.includes(r)) : updatedUser.roles;+ }- // Handle password change- if (password) {- // Get password policy from settings- const settings = await getSettings();- const policy = settings.auth?.passwordPolicy || 'medium';-- // Validate password according to policy- // if (!validatePassword(password, policy)) {- // return json({ error: 'Password does not meet requirements' }, { status: 400 });- // }- updatedUser.passwordHash = await hashPassword(password);- updatedUser.requirePasswordChange = false; // Reset flag if password is changed+ // Handle password change+ if (password) {+ const settingsResult = await tryCatch(getSettings());+ const settings = settingsResult.data;+ const policy = settings?.auth?.passwordPolicy || 'medium';++ // Password validation can be added here if needed+ const hashResult = await tryCatch(hashPassword(password));+ if (hashResult.error) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Failed to hash password',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: hashResult.error+ };+ return json(response, { status: 500 });}+ updatedUser.passwordHash = hashResult.data;+ updatedUser.requirePasswordChange = false;+ }- const savedUser = await saveUser(updatedUser);-- // Return sanitized user- const { passwordHash: _, ...sanitizedUser } = savedUser;- return json({ success: true, user: sanitizedUser });- } catch (error) {- console.error('Error updating user:', error);- return json({ error: 'Failed to update user' }, { status: 500 });+ const saveResult = await tryCatch(saveUser(updatedUser));+ if (saveResult.error) {+ console.error('Error saving user:', saveResult.error);+ const response: ApiErrorResponse = {+ success: false,+ error: 'Failed to update user',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: saveResult.error+ };+ return json(response, { status: 500 });}++ const { passwordHash: _, ...sanitizedUser } = saveResult.data;+ return json({ success: true, user: sanitizedUser });};// DELETE endpointexport const DELETE: RequestHandler = async ({ params, locals }) => {- try {- // Only admins should be able to delete users- if (!locals.user || !locals.user.roles.includes('admin')) {- return json({ error: 'Unauthorized' }, { status: 403 });- }+ // Only admins should be able to delete users+ if (!locals.user || !locals.user.roles.includes('admin')) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Unauthorized',+ code: ApiErrorCode.FORBIDDEN+ };+ return json(response, { status: 403 });+ }- const userId = params.id;+ const userId = params.id;- // Don't allow deleting yourself- if (userId === locals.user.id) {- return json({ error: 'Cannot delete your own account' }, { status: 400 });- }-- const userFile = path.join(USER_DIR, `${userId}.dat`);+ // Don't allow deleting yourself+ if (userId === locals.user.id) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Cannot delete your own account',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }- try {- await fs.access(userFile);- } catch {- return json({ error: 'User not found' }, { status: 404 });- }+ const userFile = path.join(USER_DIR, `${userId}.dat`);- // Delete the user file- await fs.unlink(userFile);+ const accessResult = await tryCatch(fs.access(userFile));+ if (accessResult.error) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'User not found',+ code: ApiErrorCode.NOT_FOUND+ };+ return json(response, { status: 404 });+ }- return json({ success: true });- } catch (error) {- console.error('Error deleting user:', error);- return json({ error: 'Failed to delete user' }, { status: 500 });+ const unlinkResult = await tryCatch(fs.unlink(userFile));+ if (unlinkResult.error) {+ console.error('Error deleting user:', unlinkResult.error);+ const response: ApiErrorResponse = {+ success: false,+ error: 'Failed to delete user',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: unlinkResult.error+ };+ return json(response, { status: 500 });}++ return json({ success: true });};diff --git a/src/routes/api/users/password/+server.ts b/src/routes/api/users/password/+server.tsindex 48ed53445..9be2bae9b 100644--- a/src/routes/api/users/password/+server.ts+++ b/src/routes/api/users/password/+server.ts@@ -2,48 +2,91 @@ import { json } from '@sveltejs/kit';import type { RequestHandler } from './$types';import { getUserByUsername, saveUser } from '$lib/services/user-service';import { verifyPassword, hashPassword } from '$lib/services/user-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { tryCatch } from '$lib/utils/try-catch';export const POST: RequestHandler = async ({ request, locals }) => {- try {- const currentUser = locals.user;+ const currentUser = locals.user;- if (!currentUser) {- return json({ error: 'Not authenticated' }, { status: 401 });- }-- const { currentPassword, newPassword } = await request.json();-- if (!currentPassword || !newPassword) {- return json({ error: 'Both current and new passwords are required' }, { status: 400 });- }+ if (!currentUser) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Not authenticated',+ code: ApiErrorCode.UNAUTHORIZED+ };+ return json(response, { status: 401 });+ }- // Get fresh user data- const user = await getUserByUsername(currentUser.username);+ const bodyResult = await tryCatch(request.json());+ if (bodyResult.error) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Invalid JSON payload',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }+ const { currentPassword, newPassword } = bodyResult.data;- if (!user) {- return json({ error: 'User not found' }, { status: 404 });- }+ if (!currentPassword || !newPassword) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Both current and new passwords are required',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }- // Verify current password- const validPassword = await verifyPassword(user, currentPassword);+ const userResult = await tryCatch(getUserByUsername(currentUser.username));+ if (userResult.error || !userResult.data) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'User not found',+ code: ApiErrorCode.NOT_FOUND+ };+ return json(response, { status: 404 });+ }+ const user = userResult.data;- if (!validPassword) {- return json({ error: 'Current password is incorrect' }, { status: 400 });- }+ const verifyResult = await tryCatch(verifyPassword(user, currentPassword));+ if (verifyResult.error || !verifyResult.data) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Current password is incorrect',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }- // Hash new password- const passwordHash = await hashPassword(newPassword);+ const hashResult = await tryCatch(hashPassword(newPassword));+ if (hashResult.error) {+ console.error('Error hashing new password:', hashResult.error);+ const response: ApiErrorResponse = {+ success: false,+ error: 'Failed to hash new password',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: hashResult.error+ };+ return json(response, { status: 500 });+ }- // Update user with new password hash- await saveUser({+ const saveResult = await tryCatch(+ saveUser({...user,- passwordHash,+ passwordHash: hashResult.data,updatedAt: new Date().toISOString()- });-- return json({ success: true });- } catch (error) {- console.error('Error changing password:', error);- return json({ error: 'Failed to change password' }, { status: 500 });+ })+ );+ if (saveResult.error) {+ console.error('Error saving user with new password:', saveResult.error);+ const response: ApiErrorResponse = {+ success: false,+ error: 'Failed to change password',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: saveResult.error+ };+ return json(response, { status: 500 });}++ return json({ success: true });};diff --git a/src/routes/api/volumes/+server.ts b/src/routes/api/volumes/+server.tsindex 45428f88c..f418995d0 100644--- a/src/routes/api/volumes/+server.ts+++ b/src/routes/api/volumes/+server.ts@@ -2,29 +2,51 @@ import { json } from '@sveltejs/kit';import type { RequestHandler } from './$types';import { createVolume } from '$lib/services/docker/volume-service';import type { VolumeCreateOptions } from 'dockerode';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { tryCatch } from '$lib/utils/try-catch';export const POST: RequestHandler = async ({ request }) => {- try {- const body: VolumeCreateOptions = await request.json();-- if (!body.Name) {- return json({ error: 'Volume name is required.' }, { status: 409 });- }+ const bodyResult = await tryCatch(request.json());+ if (bodyResult.error) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Invalid JSON payload',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }+ const body: VolumeCreateOptions = bodyResult.data;- const volumeInfo = await createVolume(body);+ if (!body.Name) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Volume name is required.',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }- return json(- {- success: true,- volume: {- ...volumeInfo,- Name: volumeInfo.name- }- },- { status: 201 }- );- } catch (error: any) {- console.error('API Error creating volume:', error);- return json({ error: `Failed to create volume: ${error.message || 'Unknown error'}` }, { status: 500 });+ const volumeResult = await tryCatch(createVolume(body));+ if (volumeResult.error) {+ console.error('API Error creating volume:', volumeResult.error);+ const response: ApiErrorResponse = {+ success: false,+ error: volumeResult.error.message || 'Failed to create volume',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: volumeResult.error+ };+ return json(response, { status: 500 });}++ const volumeInfo = volumeResult.data;+ return json(+ {+ success: true,+ volume: {+ ...volumeInfo,+ Name: volumeInfo.name+ }+ },+ { status: 201 }+ );};diff --git a/src/routes/api/volumes/[name]/+server.ts b/src/routes/api/volumes/[name]/+server.tsindex ce0fc8bbe..f69cc130a 100644--- a/src/routes/api/volumes/[name]/+server.ts+++ b/src/routes/api/volumes/[name]/+server.ts@@ -1,16 +1,25 @@import { json } from '@sveltejs/kit';import type { RequestHandler } from './$types';import { removeVolume } from '$lib/services/docker/volume-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { tryCatch } from '$lib/utils/try-catch';export const DELETE: RequestHandler = async ({ params, url }) => {const { name } = params;const force = url.searchParams.get('force') === 'true';- try {- await removeVolume(name, force);- return json({ success: true });- } catch (error: any) {- console.error('API Error removing volume:', error);- return json({ error: `Failed to remove volume: ${error.message || 'Unknown error'}` }, { status: 500 });+ const result = await tryCatch(removeVolume(name, force));++ if (result.error) {+ console.error('API Error removing volume:', result.error);+ const response: ApiErrorResponse = {+ success: false,+ error: result.error.message || 'Failed to remove volume',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });}++ return json({ success: true });};diff --git a/src/routes/containers/+page.svelte b/src/routes/containers/+page.svelteindex 09bd330c0..6ddae6461 100644--- a/src/routes/containers/+page.svelte+++ b/src/routes/containers/+page.svelte@@ -15,7 +15,7 @@import StatusBadge from '$lib/components/badges/status-badge.svelte';import { statusVariantMap } from '$lib/types/statuses';import { capitalizeFirstLetter } from '$lib/utils/string.utils';- import { handleApiReponse } from '$lib/utils/api.util';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { shortId } from '$lib/utils/string.utils';const containerApi = new ContainerAPIService();@@ -60,7 +60,6 @@}async function handleRemoveContainer(id: string) {- // const endpoint = `/api/containers/${id}/remove${force ? '?force=true' : ''}`;openConfirmDialog({title: 'Delete Container',message: 'Are you sure you want to delete this container? This action cannot be undone.',@@ -68,15 +67,15 @@label: 'Delete',destructive: true,action: async () => {- handleApiReponse(- await tryCatch(containerApi.remove(id)),- 'Failed to Remove Container',- (value) => (isLoading.remove = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(containerApi.remove(id)),+ message: 'Failed to Remove Container',+ setLoadingState: (value) => (isLoading.remove = value),+ onSuccess: async () => {toast.success('Container Removed Successfully.');await invalidateAll();}- );+ });}}});@@ -86,35 +85,35 @@isLoading[action] = true;if (action === 'start') {- handleApiReponse(- await tryCatch(containerApi.start(id)),- 'Failed to Start Container',- (value) => (isLoading.start = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(containerApi.start(id)),+ message: 'Failed to Start Container',+ setLoadingState: (value) => (isLoading.start = value),+ async onSuccess() {toast.success('Container Started Successfully.');await invalidateAll();}- );+ });} else if (action === 'stop') {- handleApiReponse(- await tryCatch(containerApi.stop(id)),- 'Failed to Stop Container',- (value) => (isLoading.stop = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(containerApi.stop(id)),+ message: 'Failed to Stop Container',+ setLoadingState: (value) => (isLoading.stop = value),+ async onSuccess() {toast.success('Container Stopped Successfully.');await invalidateAll();}- );+ });} else if (action === 'restart') {- handleApiReponse(- await tryCatch(containerApi.restart(id)),- 'Failed to Restart Container',- (value) => (isLoading.stop = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(containerApi.restart(id)),+ message: 'Failed to Restart Container',+ setLoadingState: (value) => (isLoading.restart = value),+ async onSuccess() {toast.success('Container Restarted Successfully.');await invalidateAll();}- );+ });} else {console.error('An Unknown Error Occurred');toast.error('An Unknown Error Occurred');diff --git a/src/routes/containers/create-container-dialog.svelte b/src/routes/containers/create-container-dialog.svelteindex 24309beb5..37200fa9a 100644--- a/src/routes/containers/create-container-dialog.svelte+++ b/src/routes/containers/create-container-dialog.svelte@@ -12,7 +12,7 @@import { toast } from 'svelte-sonner';import { invalidateAll } from '$app/navigation';import Switch from '$lib/components/ui/switch/switch.svelte';- import { handleApiReponse } from '$lib/utils/api.util';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';import ContainerAPIService from '$lib/services/api/container-api-service';@@ -263,16 +263,16 @@isCreating = true;- handleApiReponse(- await tryCatch(containerApi.create(containerConfig)),- 'Failed to Create Container',- (value) => (isCreating = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(containerApi.create(containerConfig)),+ message: 'Failed to Create Container',+ setLoadingState: (value) => (isCreating = value),+ onSuccess: async () => {toast.success(`Container "${containerConfig.name}" created successfully!`);await invalidateAll();handleClose();}- );+ });}</script>diff --git a/src/routes/images/+page.svelte b/src/routes/images/+page.svelteindex 887db713e..94c8b80fd 100644--- a/src/routes/images/+page.svelte+++ b/src/routes/images/+page.svelte@@ -16,7 +16,7 @@import * as Dialog from '$lib/components/ui/dialog/index.js';import StatusBadge from '$lib/components/badges/status-badge.svelte';import ImageAPIService from '$lib/services/api/image-api-service';- import { handleApiReponse } from '$lib/utils/api.util';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';let { data }: { data: PageData } = $props();@@ -114,20 +114,15 @@continue;}- const result = await tryCatch(imageApi.remove(id));- handleApiReponse(- result,- `Failed to delete image "${imageIdentifier}"`,- (value) => (isLoading.removing = value),- async () => {+ await handleApiResultWithCallbacks({+ result: await tryCatch(imageApi.remove(id)),+ message: `Failed to delete image "${imageIdentifier}"`,+ setLoadingState: (value) => (isLoading.removing = value),+ onSuccess: async () => {toast.success(`Image "${imageIdentifier}" deleted successfully.`);successCount++;}- );-- if (result.error) {- failureCount++;- }+ });}console.log(`Finished deleting. Success: ${successCount}, Failed: ${failureCount}`);@@ -145,16 +140,16 @@}async function handlePruneImages() {- handleApiReponse(- await tryCatch(imageApi.prune()),- 'Failed to Prune Images',- (value) => (isLoading.pruning = value),- async (result) => {+ await handleApiResultWithCallbacks({+ result: await tryCatch(imageApi.prune()),+ message: 'Failed to Prune Images',+ setLoadingState: (value) => (isLoading.pruning = value),+ onSuccess: async (result: any) => {isConfirmPruneDialogOpen = false;- toast.success(result.message);+ toast.success(result?.message ?? 'Images pruned successfully.');await invalidateAll();}- );+ });}async function pullImageByRepoTag(repoTag: string | undefined) {@@ -166,15 +161,15 @@let [imageRef, tag] = repoTag.split(':');tag = tag || 'latest';- handleApiReponse(- await tryCatch(imageApi.pull(imageRef, tag)),- `Failed to pull image "${repoTag}"`,- (value) => (isLoading.pulling = value),- async () => {+ await handleApiResultWithCallbacks({+ result: await tryCatch(imageApi.pull(imageRef, tag)),+ message: `Failed to pull image "${repoTag}"`,+ setLoadingState: (value) => (isLoading.pulling = value),+ onSuccess: async () => {toast.success(`Image "${repoTag}" pulled successfully.`);await invalidateAll();}- );+ });}async function handleImageRemove(id: string) {@@ -188,15 +183,15 @@label: 'Delete',destructive: true,action: async () => {- handleApiReponse(- await tryCatch(imageApi.remove(id)),- 'Failed to Remove Image',- (value) => (isLoading.removing = value),- async () => {+ await handleApiResultWithCallbacks({+ result: await tryCatch(imageApi.remove(id)),+ message: 'Failed to Remove Image',+ setLoadingState: (value) => (isLoading.removing = value),+ onSuccess: async () => {toast.success(`Image "${imageIdentifier}" deleted successfully.`);await invalidateAll();}- );+ });}}});diff --git a/src/routes/images/[imageId]/+page.svelte b/src/routes/images/[imageId]/+page.svelteindex 6c06d6018..3db0b3baf 100644--- a/src/routes/images/[imageId]/+page.svelte+++ b/src/routes/images/[imageId]/+page.svelte@@ -9,7 +9,7 @@import { Badge } from '$lib/components/ui/badge/index.js';import { formatDate, formatBytes } from '$lib/utils';import { openConfirmDialog } from '$lib/components/confirm-dialog';- import { handleApiReponse } from '$lib/utils/api.util';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';import ImageAPIService from '$lib/services/api/image-api-service';import { toast } from 'svelte-sonner';@@ -36,15 +36,15 @@label: 'Delete',destructive: true,action: async () => {- handleApiReponse(- await tryCatch(imageApi.remove(id)),- 'Failed to Remove Image',- (value) => (isLoading.removing = value),- async () => {+ await handleApiResultWithCallbacks({+ result: await tryCatch(imageApi.remove(id)),+ message: 'Failed to Remove Image',+ setLoadingState: (value) => (isLoading.removing = value),+ onSuccess: async () => {toast.success('Image Removed Successfully.');goto('/images');}- );+ });}}});diff --git a/src/routes/networks/+page.svelte b/src/routes/networks/+page.svelteindex c2c884580..397337c37 100644--- a/src/routes/networks/+page.svelte+++ b/src/routes/networks/+page.svelte@@ -12,7 +12,7 @@import CreateNetworkDialog from './CreateNetworkDialog.svelte';import * as Table from '$lib/components/ui/table';import type { NetworkCreateOptions } from 'dockerode';- import { handleApiReponse } from '$lib/utils/api.util';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';import { openConfirmDialog } from '$lib/components/confirm-dialog';import NetworkAPIService from '$lib/services/api/network-api-service';@@ -46,16 +46,16 @@const networkApi = new NetworkAPIService();async function handleCreateNetworkSubmit(options: NetworkCreateOptions) {- handleApiReponse(- await tryCatch(networkApi.create(options)),- 'Failed to Create Network',- (value) => (isLoading.create = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(networkApi.create(options)),+ message: 'Failed to Create Network',+ setLoadingState: (value) => (isLoading.create = value),+ onSuccess: async () => {toast.success('Network Created Successfully.');await invalidateAll();networkPageStates.isCreateDialogOpen = false;}- );+ });}async function handleDeleteNetwork(id: string) {@@ -66,15 +66,15 @@label: 'Delete',destructive: true,action: async () => {- handleApiReponse(- await tryCatch(networkApi.remove(encodeURIComponent(id))),- 'Failed to Remove Container',- (value) => (isLoading.remove = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(networkApi.remove(encodeURIComponent(id))),+ message: 'Failed to Remove Network',+ setLoadingState: (value) => (isLoading.remove = value),+ onSuccess: async () => {toast.success('Network Removed Successfully.');await invalidateAll();}- );+ });}}});@@ -113,15 +113,15 @@for (const network of selectedNetworks) {const result = await tryCatch(networkApi.remove(encodeURIComponent(network.id)));- handleApiReponse(+ handleApiResultWithCallbacks({result,- `Failed to delete network "${network.name}"`,- (value) => (isLoading.remove = value),- async () => {+ message: `Failed to delete network "${network.name}"`,+ setLoadingState: (value) => (isLoading.remove = value),+ onSuccess: async () => {toast.success(`Network "${network.name}" deleted successfully.`);successCount++;}- );+ });if (result.error) {failureCount++;diff --git a/src/routes/networks/[networkId]/+page.svelte b/src/routes/networks/[networkId]/+page.svelteindex bb301eed5..038a402f5 100644--- a/src/routes/networks/[networkId]/+page.svelte+++ b/src/routes/networks/[networkId]/+page.svelte@@ -2,63 +2,38 @@import type { PageData, ActionData } from './$types';import * as Card from '$lib/components/ui/card/index.js';import { Button } from '$lib/components/ui/button/index.js';- import { ArrowLeft, AlertCircle, RefreshCw, HardDrive, Clock, Tag, Layers, Hash, Trash2, Loader2, Network, Globe, Settings, ListTree, Container } from '@lucide/svelte';+ import { ArrowLeft, AlertCircle, HardDrive, Clock, Tag, Layers, Hash, Trash2, Loader2, Network, Globe, Settings, ListTree, Container } from '@lucide/svelte';import * as Breadcrumb from '$lib/components/ui/breadcrumb/index.js';import { enhance } from '$app/forms';- import { invalidateAll } from '$app/navigation';import * as Alert from '$lib/components/ui/alert/index.js';import { Separator } from '$lib/components/ui/separator/index.js';import { Badge } from '$lib/components/ui/badge/index.js';import { formatDate } from '$lib/utils';- // import ConfirmDialog from '$lib/components/confirm-dialog/confirm-dialog-old.svelte';import type { NetworkInspectInfo } from 'dockerode';+ import { toast } from 'svelte-sonner';let { data, form }: { data: PageData; form: ActionData } = $props();let { network }: { network: NetworkInspectInfo | null | undefined } = $derived(data);- let isRefreshing = $state(false);let isRemoving = $state(false);let showRemoveConfirm = $state(false);const shortId = $derived(network?.Id?.substring(0, 12) || 'N/A');const createdDate = $derived(network?.Created ? formatDate(network.Created) : 'N/A');const connectedContainers = $derived(network?.Containers ? Object.values(network.Containers) : []);- // Determine if network is potentially in use (basic check)const inUse = $derived(connectedContainers.length > 0);- // Determine if network is predefined (cannot be removed)const isPredefined = $derived(network?.Name === 'bridge' || network?.Name === 'host' || network?.Name === 'none');- async function refreshData() {- isRefreshing = true;- try {- await invalidateAll();- } finally {- isRefreshing = false;- }- }-function triggerRemove() {if (isPredefined) {- // Optionally show a toast or alert instead of the dialog+ toast.error('Cannot Remove Predefined Networks');console.warn('Cannot remove predefined network');return;}showRemoveConfirm = true;}-- // This function is called by the ConfirmDialog- function handleRemoveConfirm() {- // No 'force' option for network removal in standard Docker API- const removeForm = document.getElementById('remove-network-form') as HTMLFormElement;- if (removeForm) {- removeForm.submit();- }- }</script>-<!-- Confirmation Dialog for Remove -->-<!-- <ConfirmDialog bind:open={showRemoveConfirm} title="Confirm Network Removal" description={`Are you sure you want to remove network "${network?.Name}" (${shortId})? This action cannot be undone. Ensure no containers are connected.`} confirmLabel="Remove" variant="destructive" onConfirm={handleRemoveConfirm} itemType="network" isRunning={inUse} /> -->-<div class="space-y-6 pb-8"><!-- Breadcrumb Navigation --><div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4">diff --git a/src/routes/settings/+page.svelte b/src/routes/settings/+page.svelteindex 39693c28d..8effa75dc 100644--- a/src/routes/settings/+page.svelte+++ b/src/routes/settings/+page.svelte@@ -9,7 +9,7 @@import UserManagement from './tabs/user-management.svelte';import Authentication from './tabs/authentication.svelte';import { saveSettingsToServer, updateSettingsStore } from '$lib/stores/settings-store';- import { handleApiReponse } from '$lib/utils/api.util';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';let { data } = $props<{ data: PageData }>();@@ -41,15 +41,15 @@isLoading.saving = true;settingsPageStates.error = null;- handleApiReponse(- await tryCatch(saveSettingsToServer()),- 'Error Saving Settings',- (value) => (isLoading.saving = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(saveSettingsToServer()),+ message: 'Error Saving Settings',+ setLoadingState: (value) => (isLoading.saving = value),+ onSuccess: async () => {toast.success(`Settings Saved Successfully`);await invalidateAll();}- );+ });}</script>@@ -82,7 +82,7 @@<div id="settings-container"><input type="hidden" id="csrf_token" value={data.csrf} />- {#each tabs as tab, i (tab.id)}+ {#each tabs as tab (tab.id)}<Tabs.Content value={tab.id} class="space-y-4"><tab.component {data} /></Tabs.Content>diff --git a/src/routes/settings/tabs/user-management.svelte b/src/routes/settings/tabs/user-management.svelteindex 969c75af2..a2a727f44 100644--- a/src/routes/settings/tabs/user-management.svelte+++ b/src/routes/settings/tabs/user-management.svelte@@ -9,7 +9,7 @@import UserFormDialog from '$lib/components/dialogs/user-form-dialog.svelte';import * as Table from '$lib/components/ui/table';import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';- import { handleApiReponse } from '$lib/utils/api.util';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';import UserAPIService from '$lib/services/api/user-api-service';import { invalidateAll } from '$app/navigation';@@ -55,17 +55,17 @@async function handleDialogSubmit({ user: userData, isEditMode, userId }: { user: Partial<User> & { password?: string }; isEditMode: boolean; userId?: string }) {isLoading.saving = true;- handleApiReponse(- await tryCatch(isEditMode ? userApi.update(userId || '', userData as User) : userApi.create(userData as User)),- isEditMode ? 'Error Updating User' : 'Error Creating User',- (value) => (isLoading.saving = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(isEditMode ? userApi.update(userId || '', userData as User) : userApi.create(userData as User)),+ message: isEditMode ? 'Error Updating User' : 'Error Creating User',+ setLoadingState: (value) => (isLoading.saving = value),+ onSuccess: async () => {userPageStates.isUserDialogOpen = false;toast.success(isEditMode ? 'User Updated Successfully' : 'User Created Successfully');await invalidateAll();isLoading.saving = false;}- );+ });}async function handleRemoveUser(userId: string) {@@ -76,15 +76,15 @@label: 'Delete',destructive: true,action: async () => {- handleApiReponse(- await tryCatch(userApi.delete(userId)),- 'Failed to Delete User',- (value) => (isLoading.saving = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(userApi.delete(userId)),+ message: 'Failed to Delete User',+ setLoadingState: (value) => (isLoading.saving = value),+ onSuccess: async () => {toast.success('User Deleted Successfully.');await invalidateAll();}- );+ });}}});diff --git a/src/routes/stacks/+page.server.ts b/src/routes/stacks/+page.server.tsindex 61b4e316b..926095284 100644--- a/src/routes/stacks/+page.server.ts+++ b/src/routes/stacks/+page.server.ts@@ -1,27 +1,31 @@import { loadComposeStacks, discoverExternalStacks } from '$lib/services/docker/stack-service';import type { PageServerLoad } from './$types';+import { tryCatch } from '$lib/utils/try-catch';export const load: PageServerLoad = async () => {- try {- const managedStacks = await loadComposeStacks();- const externalStacks = await discoverExternalStacks();- const combinedStacks = [...managedStacks];-- for (const externalStack of externalStacks) {- if (!combinedStacks.some((stack) => stack.id === externalStack.id)) {- combinedStacks.push(externalStack);- }- }+ const managedResult = await tryCatch(loadComposeStacks());+ const externalResult = await tryCatch(discoverExternalStacks());- return {- stacks: combinedStacks- };- } catch (err: unknown) {- console.error('Failed to load stacks:', err);- const errorMessage = err instanceof Error ? err.message : String(err);+ if (managedResult.error || externalResult.error) {+ console.error('Failed to load stacks:', managedResult.error || externalResult.error);+ const errorMessage = (managedResult.error?.message || externalResult.error?.message) ?? 'Unknown error';return {stacks: [],error: 'Failed to load Docker Compose stacks: ' + errorMessage};}++ const managedStacks = managedResult.data;+ const externalStacks = externalResult.data;+ const combinedStacks = [...managedStacks];++ for (const externalStack of externalStacks) {+ if (!combinedStacks.some((stack) => stack.id === externalStack.id)) {+ combinedStacks.push(externalStack);+ }+ }++ return {+ stacks: combinedStacks+ };};diff --git a/src/routes/stacks/+page.svelte b/src/routes/stacks/+page.svelteindex 1d58a140a..14fd18bb2 100644--- a/src/routes/stacks/+page.svelte+++ b/src/routes/stacks/+page.svelte@@ -15,7 +15,7 @@import { toast } from 'svelte-sonner';import { tryCatch } from '$lib/utils/try-catch';import StackAPIService from '$lib/services/api/stack-api-service';- import { handleApiReponse } from '$lib/utils/api.util';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import type { StackActions } from '$lib/types/actions.type';let { data }: { data: PageData } = $props();@@ -44,55 +44,55 @@isLoading[action] = true;if (action === 'start') {- handleApiReponse(- await tryCatch(stackApi.start(id)),- 'Failed to Start Stack',- (value) => (isLoading.start = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(stackApi.start(id)),+ message: 'Failed to Start Stack',+ setLoadingState: (value) => (isLoading.start = value),+ onSuccess: async () => {toast.success('Stack Started Successfully.');await invalidateAll();}- );+ });} else if (action === 'stop') {- handleApiReponse(- await tryCatch(stackApi.stop(id)),- 'Failed to Stop Stack',- (value) => (isLoading.stop = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(stackApi.stop(id)),+ message: 'Failed to Stop Stack',+ setLoadingState: (value) => (isLoading.stop = value),+ onSuccess: async () => {toast.success('Stack Stopped Successfully.');await invalidateAll();}- );+ });} else if (action === 'restart') {- handleApiReponse(- await tryCatch(stackApi.restart(id)),- 'Failed to Restart Stack',- (value) => (isLoading.restart = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(stackApi.restart(id)),+ message: 'Failed to Restart Stack',+ setLoadingState: (value) => (isLoading.restart = value),+ onSuccess: async () => {toast.success('Stack Restarted Successfully.');await invalidateAll();}- );+ });} else if (action === 'redeploy') {- handleApiReponse(- await tryCatch(stackApi.redeploy(id)),- 'Failed to Redeploy Stack',- (value) => (isLoading.redeploy = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(stackApi.redeploy(id)),+ message: 'Failed to Redeploy Stack',+ setLoadingState: (value) => (isLoading.redeploy = value),+ onSuccess: async () => {toast.success('Stack redeployed successfully.');await invalidateAll();}- );+ });} else if (action === 'pull') {- handleApiReponse(- await tryCatch(stackApi.pull(id)),- 'Failed to pull Stack',- (value) => (isLoading.pull = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(stackApi.pull(id)),+ message: 'Failed to pull Stack',+ setLoadingState: (value) => (isLoading.pull = value),+ onSuccess: async () => {toast.success('Stack Pulled successfully.');await invalidateAll();}- );+ });} else if (action === 'destroy') {openConfirmDialog({title: `Confirm Removal`,@@ -101,28 +101,28 @@label: 'Remove',destructive: true,action: async () => {- handleApiReponse(- await tryCatch(stackApi.remove(id)),- 'Failed to Remove Stack',- (value) => (isLoading.destroy = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(stackApi.remove(id)),+ message: 'Failed to Remove Stack',+ setLoadingState: (value) => (isLoading.destroy = value),+ onSuccess: async () => {toast.success('Stack Removed Successfully');await invalidateAll();}- );+ });}}});} else if (action === 'migrate') {- handleApiReponse(- await tryCatch(stackApi.migrate(id)),- 'Failed to Migrate Stack',- (value) => (isLoading.migrate = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(stackApi.migrate(id)),+ message: 'Failed to Migrate Stack',+ setLoadingState: (value) => (isLoading.migrate = value),+ onSuccess: async () => {toast.success('Stack Migrated Successfully.');await invalidateAll();}- );+ });} else {console.error('An Unknown Error Occurred');toast.error('An Unknown Error Occurred');diff --git a/src/routes/stacks/[stackId]/+page.server.ts b/src/routes/stacks/[stackId]/+page.server.tsindex 70408bdfe..649a328f7 100644--- a/src/routes/stacks/[stackId]/+page.server.ts+++ b/src/routes/stacks/[stackId]/+page.server.ts@@ -2,81 +2,81 @@ import { getStack, updateStack, startStack, stopStack, restartStack, removeStackimport { getSettings } from '$lib/services/settings-service';import { getContainer } from '$lib/services/docker/container-service';import type { PageServerLoad, Actions } from './$types';+import { tryCatch } from '$lib/utils/try-catch';export const load: PageServerLoad = async ({ params }) => {const { stackId } = params;- try {- const stack = await getStack(stackId);-- const editorState = {- name: stack.name,- composeContent: stack.composeContent || '',- envContent: stack.envContent || '',- autoUpdate: stack.meta?.autoUpdate || false,- originalName: stack.name,- originalComposeContent: stack.composeContent || '',- originalEnvContent: stack.envContent || ''- };-- const settings = await getSettings();-- const servicePorts: Record<string, string[]> = {};- if (stack.services) {- for (const service of stack.services) {- if (service.id) {- try {- const containerData = await getContainer(service.id);- if (containerData && containerData.networkSettings?.Ports) {- const portBindings = containerData.networkSettings.Ports;- const parsedPorts: string[] = [];-- for (const containerPort in portBindings) {- if (portBindings.hasOwnProperty(containerPort)) {- const bindings = portBindings[containerPort];- if (bindings && Array.isArray(bindings) && bindings.length > 0) {- bindings.forEach((binding: any) => {- if (binding.HostPort) {- const portType = containerPort.split('/')[1] || 'tcp';- parsedPorts.push(`${binding.HostPort}:${containerPort.split('/')[0]}/${portType}`);- }- });- }- }- }-- servicePorts[service.id] = parsedPorts;- }- } catch (error) {- console.error(`Failed to fetch ports for service ${service.id}:`, error);- }- }- }- }-- return {- stack,- servicePorts,- editorState,- settings- };- } catch (err: unknown) {- console.error(`Error loading stack ${stackId}:`, err);- const errorMessage = err instanceof Error ? err.message : String(err);+ const stackResult = await tryCatch(getStack(stackId));+ if (stackResult.error || !stackResult.data) {+ console.error(`Error loading stack ${stackId}:`, stackResult.error);+ const errorMessage = stackResult.error?.message ?? 'Stack not found or failed to load';return {stack: null,error: `Stack not found or failed to load: ${errorMessage}`,editorState: {name: '',composeContent: '',- envContent: '', // Include env content+ envContent: '',originalName: '',originalComposeContent: '',- originalEnvContent: '', // Include original env content+ originalEnvContent: '',autoUpdate: false}};}+ const stack = stackResult.data;++ const editorState = {+ name: stack.name,+ composeContent: stack.composeContent || '',+ envContent: stack.envContent || '',+ autoUpdate: stack.meta?.autoUpdate || false,+ originalName: stack.name,+ originalComposeContent: stack.composeContent || '',+ originalEnvContent: stack.envContent || ''+ };++ const settingsResult = await tryCatch(getSettings());+ const settings = settingsResult.data;++ const servicePorts: Record<string, string[]> = {};+ if (stack.services) {+ for (const service of stack.services) {+ if (service.id) {+ const containerResult = await tryCatch(getContainer(service.id));+ if (!containerResult.error && containerResult.data && containerResult.data.networkSettings?.Ports) {+ const portBindings = containerResult.data.networkSettings.Ports;+ const parsedPorts: string[] = [];++ for (const containerPort in portBindings) {+ if (portBindings.hasOwnProperty(containerPort)) {+ const bindings = portBindings[containerPort];+ if (bindings && Array.isArray(bindings) && bindings.length > 0) {+ bindings.forEach((binding: any) => {+ if (binding.HostPort) {+ const portType = containerPort.split('/')[1] || 'tcp';+ parsedPorts.push(`${binding.HostPort}:${containerPort.split('/')[0]}/${portType}`);+ }+ });+ }+ }+ }++ servicePorts[service.id] = parsedPorts;+ } else if (containerResult.error) {+ console.error(`Failed to fetch ports for service ${service.id}:`, containerResult.error);+ }+ }+ }+ }++ return {+ stack,+ servicePorts,+ editorState,+ settings+ };};export const actions: Actions = {@@ -88,85 +88,82 @@ export const actions: Actions = {const composeContent = formData.get('composeContent')?.toString() || '';const autoUpdate = formData.get('autoUpdate') === 'on';- try {- await updateStack(stackId, { name, composeContent, autoUpdate });+ const result = await tryCatch(updateStack(stackId, { name, composeContent, autoUpdate }));+ if (!result.error) {return {success: true,message: 'Stack updated successfully'};- } catch (err: unknown) {- console.error('Error updating stack:', err);+ } else {+ console.error('Error updating stack:', result.error);return {success: false,- error: err instanceof Error ? err.message : 'Failed to update stack'+ error: result.error instanceof Error ? result.error.message : 'Failed to update stack'};}},start: async ({ params }) => {- try {- await startStack(params.stackId);+ const result = await tryCatch(startStack(params.stackId));+ if (!result.error) {return { success: true };- } catch (err: unknown) {- console.error('Error starting stack:', err);+ } else {+ console.error('Error starting stack:', result.error);return {success: false,- error: err instanceof Error ? err.message : 'Failed to start stack'+ error: result.error instanceof Error ? result.error.message : 'Failed to start stack'};}},stop: async ({ params }) => {- try {- await stopStack(params.stackId);+ const result = await tryCatch(stopStack(params.stackId));+ if (!result.error) {return { success: true };- } catch (err: unknown) {- console.error('Error stopping stack:', err);+ } else {+ console.error('Error stopping stack:', result.error);return {success: false,- error: err instanceof Error ? err.message : 'Failed to stop stack'+ error: result.error instanceof Error ? result.error.message : 'Failed to stop stack'};}},restart: async ({ params }) => {- try {- await restartStack(params.stackId);+ const result = await tryCatch(restartStack(params.stackId));+ if (!result.error) {return { success: true };- } catch (err: unknown) {- console.error('Error restarting stack:', err);+ } else {+ console.error('Error restarting stack:', result.error);return {success: false,- error: err instanceof Error ? err.message : 'Failed to restart stack'+ error: result.error instanceof Error ? result.error.message : 'Failed to restart stack'};}},remove: async ({ params }) => {- try {- const success = await removeStack(params.stackId);- if (success) {- return { success: true, message: 'Stack removal initiated' };- }- return { success: false, error: 'Failed to remove stack' };- } catch (err: unknown) {- console.error('Error removing stack:', err);+ const result = await tryCatch(removeStack(params.stackId));+ if (!result.error && result.data) {+ return { success: true, message: 'Stack removal initiated' };+ } else {+ console.error('Error removing stack:', result.error);return {success: false,- error: err instanceof Error ? err.message : 'Failed to remove stack'+ error: result.error instanceof Error ? result.error.message : 'Failed to remove stack'};}},redeploy: async ({ params }) => {- try {- await fullyRedeployStack(params.stackId);+ const result = await tryCatch(fullyRedeployStack(params.stackId));+ if (!result.error) {return { success: true, message: 'Stack redeployment initiated' };- } catch (err: unknown) {- console.error('Error redeploying stack:', err);+ } else {+ console.error('Error redeploying stack:', result.error);return {success: false,- error: err instanceof Error ? err.message : 'Failed to redeploy stack'+ error: result.error instanceof Error ? result.error.message : 'Failed to redeploy stack'};}}diff --git a/src/routes/stacks/[stackId]/+page.svelte b/src/routes/stacks/[stackId]/+page.svelteindex 86aee99b5..f9f868a84 100644--- a/src/routes/stacks/[stackId]/+page.svelte+++ b/src/routes/stacks/[stackId]/+page.svelte@@ -18,7 +18,7 @@import { Switch } from '$lib/components/ui/switch/index.js';import { tryCatch } from '$lib/utils/try-catch';import StackAPIService from '$lib/services/api/stack-api-service';- import { handleApiReponse } from '$lib/utils/api.util';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';const stackApi = new StackAPIService();@@ -61,23 +61,22 @@async function handleSaveChanges() {if (!stack || !hasChanges) return;- handleApiReponse(- await tryCatch(stackApi.save(stack.id, name, composeContent, autoUpdate, envContent)),- 'Failed to Save Stack',- (value) => (isLoading.saving = value),- async (data) => {+ handleApiResultWithCallbacks({+ result: await tryCatch(stackApi.save(stack.id, name, composeContent, autoUpdate, envContent)),+ message: 'Failed to Save Stack',+ setLoadingState: (value) => (isLoading.saving = value),+ onSuccess: async () => {originalName = name;originalComposeContent = composeContent;originalEnvContent = envContent;originalAutoUpdate = autoUpdate;- console.log('Stack save successful:', data);+ console.log('Stack save successful');toast.success('Stack updated successfully!');-await new Promise((resolve) => setTimeout(resolve, 200));await invalidateAll();}- );+ });}function getHostForService(service: any): string {diff --git a/src/routes/stacks/new/+page.svelte b/src/routes/stacks/new/+page.svelteindex ab373a0e6..e13a59fcc 100644--- a/src/routes/stacks/new/+page.svelte+++ b/src/routes/stacks/new/+page.svelte@@ -11,7 +11,7 @@import StackAPIService from '$lib/services/api/stack-api-service';import { preventDefault } from '$lib/utils/form.utils';import { tryCatch } from '$lib/utils/try-catch';- import { handleApiReponse } from '$lib/utils/api.util';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import EnvEditor from '$lib/components/env-editor.svelte';import { defaultEnvTemplate, defaultComposeTemplate } from '$lib/constants';@@ -23,18 +23,16 @@let envContent = $state(defaultEnvTemplate);async function handleSubmit() {- saving = true;-- handleApiReponse(- await tryCatch(stackApi.create(name, composeContent, envContent)),- 'Failed to Create Stack',- (value) => (saving = value),- async (data) => {- toast.success(`Stack "${data.stack.name}" created with environment file.`);+ handleApiResultWithCallbacks({+ result: await tryCatch(stackApi.create(name, composeContent, envContent)),+ message: 'Failed to Create Stack',+ setLoadingState: (value) => (saving = value),+ onSuccess: async () => {+ toast.success(`Stack "${name}" created with environment file.`);await invalidateAll();- goto(`/stacks/${data.stack.name}`);+ goto(`/stacks/${name}`);}- );+ });}</script>diff --git a/src/routes/volumes/+page.svelte b/src/routes/volumes/+page.svelteindex 22be090e4..c041dd773 100644--- a/src/routes/volumes/+page.svelte+++ b/src/routes/volumes/+page.svelte@@ -11,7 +11,7 @@import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';import * as Table from '$lib/components/ui/table';import { openConfirmDialog } from '$lib/components/confirm-dialog';- import { handleApiReponse } from '$lib/utils/api.util';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';import VolumeAPIService from '$lib/services/api/volume-api-service';import StatusBadge from '$lib/components/badges/status-badge.svelte';@@ -47,69 +47,32 @@label: 'Delete',destructive: true,action: async () => {- handleApiReponse(- await tryCatch(volumeApi.remove(volumeName)),- 'Failed to Remove Volume',- (value) => (isLoading.remove = value),- async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(volumeApi.remove(volumeName)),+ message: 'Failed to Remove Volume',+ setLoadingState: (value) => (isLoading.remove = value),+ onSuccess: async () => {toast.success('Volume Removed Successfully.');await invalidateAll();}- );+ });}}});}async function handleCreateVolume(volumeCreate: VolumeCreateOptions) {- handleApiReponse(- await tryCatch(volumeApi.create(volumeCreate)),- `Failed to Create Volume "${volumeCreate.Name}"`,- (value) => (isLoading.creating = value),- async () => {- toast.success(`Volume "${volumeCreate.Name}" Create successfully.`);+ handleApiResultWithCallbacks({+ result: await tryCatch(volumeApi.create(volumeCreate)),+ message: `Failed to Create Volume "${volumeCreate.Name}"`,+ setLoadingState: (value) => (isLoading.creating = value),+ onSuccess: async () => {+ toast.success(`Volume "${volumeCreate.Name}" created successfully.`);await invalidateAll();}- );+ });}- // async function handleCreateVolumeSubmit(event: { name: string; driver?: string; driverOpts?: Record<string, string>; labels?: Record<string, string> }) {- // const { name, driver, driverOpts, labels } = event;-- // isLoading.creating = true;- // try {- // const response = await fetch('/api/volumes', {- // method: 'POST',- // headers: {- // 'Content-Type': 'application/json'- // },- // body: JSON.stringify({- // name,- // driver,- // driverOpts,- // labels- // })- // });-- // const result = await response.json();-- // if (!response.ok) {- // throw new Error(result.error || `HTTP error! status: ${response.status}`);- // }-- // toast.success(`Volume "${result.volume.Name}" created successfully.`);- // isDialogOpen.create = false;-- // await refreshData();- // } catch (err: unknown) {- // console.error('Failed to create volume:', err);- // const message = err instanceof Error ? err.message : String(err);- // toast.error(`Failed to create volume: ${message}`);- // } finally {- // isLoading.creating = false;- // }- // }-async function handleDeleteSelected() {openConfirmDialog({title: 'Delete Selected Volumes',@@ -135,15 +98,15 @@if (!volume?.name) continue;const result = await tryCatch(volumeApi.remove(volume.name));- handleApiReponse(+ handleApiResultWithCallbacks({result,- `Failed to delete image "${volume.name}"`,- (value) => (isLoading.remove = value),- async () => {+ message: `Failed to delete image "${volume.name}"`,+ setLoadingState: (value) => (isLoading.remove = value),+ onSuccess: async () => {toast.success(`Volume "${volume.name}" deleted successfully.`);successCount++;}- );+ });if (result.error) {failureCount++;diff --git a/src/routes/volumes/[volumeName]/+page.svelte b/src/routes/volumes/[volumeName]/+page.svelteindex 75c6cb98a..19c1f0a2a 100644--- a/src/routes/volumes/[volumeName]/+page.svelte+++ b/src/routes/volumes/[volumeName]/+page.svelte@@ -10,7 +10,6 @@import { Separator } from '$lib/components/ui/separator/index.js';import { Badge } from '$lib/components/ui/badge/index.js';import { formatDate } from '$lib/utils';- // import ConfirmDialog from '$lib/components/confirm-dialog/confirm-dialog-old.svelte';let { data, form }: { data: PageData; form: ActionData } = $props();let { volume, inUse } = $derived(data);@@ -33,19 +32,8 @@forceRemove = false;showRemoveConfirm = true;}-- function handleRemoveConfirm(forceConfirm: boolean) {- forceRemove = forceConfirm;- const removeForm = document.getElementById('remove-volume-form') as HTMLFormElement;- if (removeForm) {- removeForm.action = `?/remove${forceRemove ? '&force=true' : ''}`;- removeForm.submit();- }- }</script>-<!-- <ConfirmDialog bind:open={showRemoveConfirm} title="Confirm Volume Removal" description={`Are you sure you want to remove volume "${volume?.Name}"? This action cannot be undone.`} confirmLabel="Remove" variant="destructive" onConfirm={handleRemoveConfirm} itemType="volume" isRunning={inUse} /> -->-<div class="space-y-6 pb-8"><div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4"><div>diff --git a/src/routes/volumes/create-volume-dialog.svelte b/src/routes/volumes/create-volume-dialog.svelteindex 24f303646..288133c4f 100644--- a/src/routes/volumes/create-volume-dialog.svelte+++ b/src/routes/volumes/create-volume-dialog.svelte@@ -16,7 +16,7 @@onSubmit?: (data: VolumeCreateOptions) => void;}- let { open = $bindable(false), isCreating = false, onSubmit = (_data: VolumeCreateOptions) => {} }: Props = $props();+ let { open = $bindable(false), isCreating = false, onSubmit = () => {} }: Props = $props();let volumeCreateStates = $state({volumeName: '',