Skip to content

Modern Docker Management, Designed for Everyone

feat: compose and .env template (#231)

Kyle Mendellc47d15f928d5
diff --git a/components.json b/components.json
index 07528ea16..a0ac31937 100644
--- a/components.json
+++ b/components.json
@@ -3,7 +3,7 @@
"style": "default",
"tailwind": {
"css": "src/app.css",
- "baseColor": "gray"
+ "baseColor": "violet"
},
"aliases": {
"components": "$lib/components",
diff --git a/docs/docs/templates/create-a-registry.md b/docs/docs/templates/create-a-registry.md
new file mode 100644
index 000000000..c9feefa74
--- /dev/null
+++ b/docs/docs/templates/create-a-registry.md
@@ -0,0 +1,180 @@
+# Creating a Custom Template Registry
+
+Want to share templates with your team or the community? Create your own template registry!
+
+## Overview
+
+A template registry is simply a JSON file hosted online that describes available templates and where to find them.
+
+## Quick Setup
+
+### 1. Create Registry Structure
+
+Create a JSON manifest file that lists your templates:
+
+```json
+{
+ "name": "My Company Templates",
+ "description": "Docker templates for internal applications",
+ "version": "1.0.0",
+ "author": "Your Team",
+ "url": "https://github.com/yourcompany/docker-templates",
+ "templates": [
+ {
+ "id": "internal-app",
+ "name": "Internal Application",
+ "description": "Company application stack with database",
+ "version": "1.0.0",
+ "author": "DevOps Team",
+ "compose_url": "https://raw.githubusercontent.com/yourcompany/docker-templates/main/internal-app/docker-compose.yml",
+ "env_url": "https://raw.githubusercontent.com/yourcompany/docker-templates/main/internal-app/.env.example",
+ "documentation_url": "https://github.com/yourcompany/docker-templates/tree/main/internal-app",
+ "tags": ["internal", "webapp", "postgres"],
+ "updated_at": "2024-12-01T10:00:00Z"
+ }
+ ]
+}
+```
+
+### 2. Host Your Files
+
+**Option A: GitHub (Recommended)**
+
+1. Create a GitHub repository
+2. Add your registry.json file
+3. Add template directories with docker-compose.yml files
+4. Use raw GitHub URLs for file access
+
+**Option B: Web Server**
+
+- Host registry.json on any web server
+- Ensure HTTPS access
+- Enable CORS if needed
+
+### 3. Template File Structure
+
+For each template, create a directory with:
+
+```
+your-template/
+├── docker-compose.yml # Required: Main compose file
+├── .env.example # Optional: Environment variables
+└── README.md # Optional: Documentation
+```
+
+## Registry JSON Reference
+
+### Required Fields
+
+- `name`: Registry display name
+- `description`: Brief description
+- `version`: Registry version
+- `templates`: Array of template objects
+
+### Template Object Fields
+
+**Required:**
+
+- `id`: Unique identifier (alphanumeric, hyphens, underscores)
+- `name`: Display name
+- `description`: What the template does
+- `compose_url`: Direct URL to docker-compose.yml file
+- `version`: Template version
+- `updated_at`: ISO 8601 timestamp
+
+**Optional:**
+
+- `author`: Template creator
+- `tags`: Array of keywords
+- `env_url`: URL to .env example file
+- `documentation_url`: Link to docs
+- `icon_url`: Template icon
+
+## Example Repository Structure
+
+```
+docker-templates/
+├── registry.json
+├── wordpress/
+│ ├── docker-compose.yml
+│ ├── .env.example
+│ └── README.md
+├── nextcloud/
+│ ├── docker-compose.yml
+│ ├── .env.example
+│ └── README.md
+└── nginx-proxy/
+ ├── docker-compose.yml
+ └── README.md
+```
+
+## Testing Your Registry
+
+1. **Validate JSON**: Use a JSON validator to check syntax
+2. **Test URLs**: Ensure all file URLs are accessible
+3. **Add to Arcane**: Settings → Templates → Add Registry
+4. **Verify**: Check that templates appear and can be downloaded
+
+## Best Practices
+
+### Template Quality
+
+- Use specific image tags (not `latest`)
+- Include health checks
+- Add restart policies
+- Document required environment variables
+- Test templates before publishing
+
+### Registry Management
+
+- Version your templates and registry
+- Keep documentation current
+- Use semantic versioning
+- Regular updates and maintenance
+- Monitor for security updates
+
+### Security
+
+- Use HTTPS for all URLs
+- Validate environment variable examples
+- Don't include sensitive data in examples
+- Consider image security scanning
+
+## GitHub Example
+
+Here's a minimal GitHub setup:
+
+1. **Create repository**: `my-docker-templates`
+2. **Add registry.json**:
+ ```json
+ {
+ "name": "My Templates",
+ "description": "Custom Docker templates",
+ "version": "1.0.0",
+ "templates": [...]
+ }
+ ```
+3. **Registry URL**: `https://raw.githubusercontent.com/username/my-docker-templates/main/registry.json`
+
+## Community Registry
+
+Don't want to maintain your own? Contribute to our community registry:
+
+**GitHub**: [https://github.com/ofkm/arcane-templates](https://github.com/ofkm/arcane-templates)
+
+Submit pull requests to add your templates to the community collection!
+
+## Troubleshooting
+
+**Registry not loading?**
+
+- Check JSON syntax
+- Verify URL accessibility
+- Ensure HTTPS protocol
+- Check CORS headers if using custom domain
+
+**Templates not downloading?**
+
+- Verify file URLs are direct download links
+- Check that files exist at specified URLs
+- Ensure proper file permissions
diff --git a/docs/docs/templates/use-templates.md b/docs/docs/templates/use-templates.md
new file mode 100644
index 000000000..24e4be6cf
--- /dev/null
+++ b/docs/docs/templates/use-templates.md
@@ -0,0 +1,109 @@
+# Using Templates
+
+Templates help you quickly deploy common applications and services with Docker Compose. Arcane supports both local templates and remote registries.
+
+## Quick Start
+
+1. **Create a new stack** → Click "New Stack"
+2. **Choose a template** → Click "Choose Template" button
+3. **Select your template** → Browse local or remote templates
+4. **Configure and deploy** → Customize settings and create your stack
+
+## Template Types
+
+### Local Templates
+
+- Stored on your system in `data/templates/compose/`
+- Always available, even offline
+- Perfect for custom or frequently used configurations
+
+### Remote Templates
+
+- Downloaded from online registries
+- Community-maintained and regularly updated
+- Can be used immediately or downloaded for offline use
+
+## Using the Template Dialog
+
+When you click "Choose Template", you'll see:
+
+- **Local Templates**: Ready to use immediately
+- **Remote Templates**: Two options for each:
+ - **Use Now**: Load template content directly into your stack
+ - **Download**: Save template locally for future offline use
+
+Templates with environment files will show an "ENV" badge and include pre-configured variables.
+
+## Adding Local Templates
+
+1. Navigate to `data/templates/compose/` in your Arcane directory
+2. Add your Docker Compose files (`.yaml` or `.yml`)
+3. Optionally add matching `.env` files for environment variables
+4. Templates appear automatically in the template dialog
+
+### Example Structure
+
+```
+data/templates/compose/
+├── wordpress.yaml
+├── wordpress.env
+├── nextcloud.yaml
+└── postgres.yaml
+```
+
+## Community Registry
+
+Don't want to create your own? Use our community registry with pre-built templates:
+
+**Registry URL:** `https://raw.githubusercontent.com/ofkm/arcane-templates/main/registry.json`
+
+Add this in **Settings → Templates → Add Registry** to get started instantly with popular applications.
+
+## Template Format
+
+Templates use standard Docker Compose format:
+
+```yaml
+# WordPress with MySQL
+version: '3.8'
+
+services:
+ wordpress:
+ image: wordpress:latest
+ ports:
+ - '${WP_PORT:-8080}:80'
+ environment:
+ WORDPRESS_DB_HOST: db
+ WORDPRESS_DB_USER: ${DB_USER}
+ WORDPRESS_DB_PASSWORD: ${DB_PASSWORD}
+
+ db:
+ image: mysql:8.0
+ environment:
+ MYSQL_DATABASE: wordpress
+ MYSQL_USER: ${DB_USER}
+ MYSQL_PASSWORD: ${DB_PASSWORD}
+ MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
+```
+
+## Environment Variables
+
+Create matching `.env` files for default values:
+
+```bash
+# wordpress.env
+DB_USER=wordpress
+DB_PASSWORD=secure_password_here
+DB_ROOT_PASSWORD=root_password_here
+WP_PORT=8080
+```
+
+## Tips
+
+- Use environment variables for configurable values
+- Add comments to describe what the template does
+- Include health checks for production services
+- Use specific image tags instead of `latest` for stability
+- Test templates before sharing with others
+
+Need help? Check out our [community registry examples](https://github.com/arcane-docker/community-templates) for inspiration!
diff --git a/docs/sidebars.ts b/docs/sidebars.ts
index 14b028d2a..86596fe79 100644
--- a/docs/sidebars.ts
+++ b/docs/sidebars.ts
@@ -1,68 +1,82 @@
-import type { SidebarsConfig } from "@docusaurus/plugin-content-docs";
+import type { SidebarsConfig } from '@docusaurus/plugin-content-docs';
/**
* Sidebar configuration for Arcane documentation
*/
const sidebars: SidebarsConfig = {
- docs: [
- // Introduction (homepage)
- "intro",
- // Getting Started section
- {
- type: "category",
- label: "Getting Started",
- collapsible: true,
- collapsed: true,
- items: [
- {
- type: "autogenerated",
- dirName: "getting-started",
- },
- ],
- },
+ docs: [
+ // Introduction (homepage)
+ 'intro',
+ // Getting Started section
+ {
+ type: 'category',
+ label: 'Getting Started',
+ collapsible: true,
+ collapsed: true,
+ items: [
+ {
+ type: 'autogenerated',
+ dirName: 'getting-started'
+ }
+ ]
+ },
- // Features section with nested categories
- {
- type: "category",
- label: "Features",
- collapsible: true,
- collapsed: true,
- items: [
- {
- type: "autogenerated",
- dirName: "features",
- },
- ],
- },
+ // Features section with nested categories
+ {
+ type: 'category',
+ label: 'Features',
+ collapsible: true,
+ collapsed: true,
+ items: [
+ {
+ type: 'autogenerated',
+ dirName: 'features'
+ }
+ ]
+ },
- // How-to Guides
- {
- type: "category",
- label: "Guides",
- collapsible: true,
- collapsed: true,
- items: [
- {
- type: "autogenerated",
- dirName: "guides",
- },
- ],
- },
+ // How-to Guides
+ {
+ type: 'category',
+ label: 'Templates',
+ collapsible: true,
+ collapsed: true,
+ items: [
+ {
+ type: 'autogenerated',
+ dirName: 'templates'
+ }
+ ]
+ },
- // Development/Contributing
- {
- type: "category",
- label: "Development",
- collapsible: true,
- collapsed: true,
- items: [
- {
- type: "autogenerated",
- dirName: "development",
- },
- ],
- },
- ],
+ // How-to Guides
+ {
+ type: 'category',
+ label: 'Guides',
+ collapsible: true,
+ collapsed: true,
+ items: [
+ {
+ type: 'autogenerated',
+ dirName: 'guides'
+ }
+ ]
+ },
+
+ // Development/Contributing
+ {
+ type: 'category',
+ label: 'Development',
+ collapsible: true,
+ collapsed: true,
+ items: [
+ {
+ type: 'autogenerated',
+ dirName: 'development'
+ }
+ ]
+ }
+ ]
};
export default sidebars;
diff --git a/package-lock.json b/package-lock.json
index dfa1ea90f..12fe1fdd8 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "arcane",
- "version": "0.12.0",
+ "version": "0.13.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "arcane",
- "version": "0.12.0",
+ "version": "0.13.1",
"dependencies": {
"@codemirror/lang-yaml": "^6.1.2",
"@codemirror/legacy-modes": "^6.5.1",
@@ -33,6 +33,7 @@
"devDependencies": {
"@eslint/compat": "^1.2.5",
"@eslint/js": "^9.18.0",
+ "@internationalized/date": "^3.8.1",
"@lucide/svelte": "^0.511.0",
"@playwright/test": "^1.52.0",
"@sveltejs/adapter-node": "^5.2.12",
@@ -1000,7 +1001,6 @@
"integrity": "sha512-PgVE6B6eIZtzf9Gu5HvJxRK3ufUFz9DhspELuhW/N0GuMGMTLvPQNRkHP2hTuP9lblOk+f+1xi96sPiPXANXAA==",
"dev": true,
"license": "Apache-2.0",
- "peer": true,
"dependencies": {
"@swc/helpers": "^0.5.0"
}
@@ -1840,7 +1840,6 @@
"integrity": "sha512-5IKx/Y13RsYd+sauPb2x+U/xZikHjolzfuDgTAl/Tdf3Q8rslRvC19NKDLgAJQ6wsqADk10ntlv08nPFw/gO/A==",
"dev": true,
"license": "Apache-2.0",
- "peer": true,
"dependencies": {
"tslib": "^2.8.0"
}
@@ -6360,8 +6359,7 @@
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"dev": true,
- "license": "0BSD",
- "peer": true
+ "license": "0BSD"
},
"node_modules/tw-animate-css": {
"version": "1.3.0",
diff --git a/package.json b/package.json
index 380d1738f..761dd2fa6 100644
--- a/package.json
+++ b/package.json
@@ -1,80 +1,81 @@
{
- "name": "arcane",
- "private": true,
- "version": "0.13.1",
- "type": "module",
- "scripts": {
- "dev": "vite dev --port 3000",
- "build": "vite build",
- "preview": "vite preview --port 3000",
- "prepare": "svelte-kit sync || echo ''",
- "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
- "format": "prettier --write ./src",
- "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
- "lint": "eslint ./src",
- "lint:fix": "eslint ./src --fix",
- "test:init": "APP_ENV=TEST npx tsx scripts/init-test-env.ts",
- "test:setup": "npx tsx scripts/setup-test-images.ts",
- "test:e2e": "APP_ENV=TEST npm run test:init && npm run test:setup && playwright test",
- "test:e2e:ui": "playwright test --ui",
- "test:e2e:report": "playwright show-report"
- },
- "devDependencies": {
- "@eslint/compat": "^1.2.5",
- "@eslint/js": "^9.18.0",
- "@lucide/svelte": "^0.511.0",
- "@playwright/test": "^1.52.0",
- "@sveltejs/adapter-node": "^5.2.12",
- "@sveltejs/kit": "^2.20.8",
- "@sveltejs/vite-plugin-svelte": "^5.0.0",
- "@tailwindcss/vite": "^4.1.7",
- "@types/bcryptjs": "^3.0.0",
- "@types/dockerode": "^3.3.38",
- "@types/dockerode-compose": "^1.4.1",
- "@types/js-yaml": "^4.0.9",
- "@types/proper-lockfile": "^4.1.4",
- "bits-ui": "^2.2.0",
- "clsx": "^2.1.1",
- "eslint": "^9.27.0",
- "eslint-plugin-svelte": "^3.8.1",
- "formsnap": "^2.0.1",
- "globals": "^16.2.0",
- "mode-watcher": "^1.0.7",
- "paneforge": "^1.0.0-next.5",
- "svelte": "5.33.4",
- "svelte-check": "^4.2.1",
- "svelte-sonner": "^1.0.3",
- "sveltekit-superforms": "^2.25.0",
- "tailwind-merge": "^3.3.0",
- "tailwind-variants": "^1.0.0",
- "tailwindcss": "^4.1.7",
- "tw-animate-css": "^1.3.0",
- "typescript": "^5.8.0",
- "typescript-eslint": "^8.33.0",
- "vite": "^6.3.5",
- "zod": "^3.25.32"
- },
- "dependencies": {
- "@codemirror/lang-yaml": "^6.1.2",
- "@codemirror/legacy-modes": "^6.5.1",
- "@swimlane/docker-reference": "^2.0.1",
- "@tanstack/table-core": "^8.21.3",
- "arctic": "^3.7.0",
- "axios": "^1.9.0",
- "bcryptjs": "^3.0.2",
- "codemirror": "^6.0.1",
- "dockerode": "^4.0.6",
- "dockerode-compose": "^1.4.0",
- "js-yaml": "^4.1.0",
- "nanoid": "^5.1.5",
- "prettier": "^3.5.3",
- "prettier-plugin-svelte": "^3.4.0",
- "proper-lockfile": "^4.1.2",
- "runed": "^0.28.0",
- "slugify": "^1.6.6",
- "svelte-codemirror-editor": "^1.4.1",
- "svelte-kit-cookie-session": "^4.1.1",
- "thememirror": "^2.0.1",
- "yaml-env-defaults": "^2.0.5"
- }
+ "name": "arcane",
+ "private": true,
+ "version": "0.13.1",
+ "type": "module",
+ "scripts": {
+ "dev": "vite dev --port 3000",
+ "build": "vite build",
+ "preview": "vite preview --port 3000",
+ "prepare": "svelte-kit sync || echo ''",
+ "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
+ "format": "prettier --write ./src",
+ "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
+ "lint": "eslint ./src",
+ "lint:fix": "eslint ./src --fix",
+ "test:init": "APP_ENV=TEST npx tsx scripts/init-test-env.ts",
+ "test:setup": "npx tsx scripts/setup-test-images.ts",
+ "test:e2e": "APP_ENV=TEST npm run test:init && npm run test:setup && playwright test",
+ "test:e2e:ui": "playwright test --ui",
+ "test:e2e:report": "playwright show-report"
+ },
+ "devDependencies": {
+ "@eslint/compat": "^1.2.5",
+ "@eslint/js": "^9.18.0",
+ "@internationalized/date": "^3.8.1",
+ "@lucide/svelte": "^0.511.0",
+ "@playwright/test": "^1.52.0",
+ "@sveltejs/adapter-node": "^5.2.12",
+ "@sveltejs/kit": "^2.20.8",
+ "@sveltejs/vite-plugin-svelte": "^5.0.0",
+ "@tailwindcss/vite": "^4.1.7",
+ "@types/bcryptjs": "^3.0.0",
+ "@types/dockerode": "^3.3.38",
+ "@types/dockerode-compose": "^1.4.1",
+ "@types/js-yaml": "^4.0.9",
+ "@types/proper-lockfile": "^4.1.4",
+ "bits-ui": "^2.2.0",
+ "clsx": "^2.1.1",
+ "eslint": "^9.27.0",
+ "eslint-plugin-svelte": "^3.8.1",
+ "formsnap": "^2.0.1",
+ "globals": "^16.2.0",
+ "mode-watcher": "^1.0.7",
+ "paneforge": "^1.0.0-next.5",
+ "svelte": "5.33.4",
+ "svelte-check": "^4.2.1",
+ "svelte-sonner": "^1.0.3",
+ "sveltekit-superforms": "^2.25.0",
+ "tailwind-merge": "^3.3.0",
+ "tailwind-variants": "^1.0.0",
+ "tailwindcss": "^4.1.7",
+ "tw-animate-css": "^1.3.0",
+ "typescript": "^5.8.0",
+ "typescript-eslint": "^8.33.0",
+ "vite": "^6.3.5",
+ "zod": "^3.25.32"
+ },
+ "dependencies": {
+ "@codemirror/lang-yaml": "^6.1.2",
+ "@codemirror/legacy-modes": "^6.5.1",
+ "@swimlane/docker-reference": "^2.0.1",
+ "@tanstack/table-core": "^8.21.3",
+ "arctic": "^3.7.0",
+ "axios": "^1.9.0",
+ "bcryptjs": "^3.0.2",
+ "codemirror": "^6.0.1",
+ "dockerode": "^4.0.6",
+ "dockerode-compose": "^1.4.0",
+ "js-yaml": "^4.1.0",
+ "nanoid": "^5.1.5",
+ "prettier": "^3.5.3",
+ "prettier-plugin-svelte": "^3.4.0",
+ "proper-lockfile": "^4.1.2",
+ "runed": "^0.28.0",
+ "slugify": "^1.6.6",
+ "svelte-codemirror-editor": "^1.4.1",
+ "svelte-kit-cookie-session": "^4.1.1",
+ "thememirror": "^2.0.1",
+ "yaml-env-defaults": "^2.0.5"
+ }
}
diff --git a/src/app.css b/src/app.css
index 1e1fb102d..1d37e7a3d 100644
--- a/src/app.css
+++ b/src/app.css
@@ -6,6 +6,24 @@
--font-sans: 'Kantumruy Pro', sans-serif;
}
+/*
+ The default border color has changed to `currentcolor` in Tailwind CSS v4,
+ so we've added these compatibility styles to make sure everything still
+ looks the same as it did with Tailwind CSS v3.
+
+ If we ever want to remove these styles, we need to add an explicit border
+ color utility to any element that depends on these defaults.
+*/
+@layer base {
+ *,
+ ::after,
+ ::before,
+ ::backdrop,
+ ::file-selector-button {
+ border-color: var(--color-gray-200, currentcolor);
+ }
+}
+
:root {
--radius: 0.5rem;
--background: oklch(1 0 0);
@@ -75,83 +93,52 @@
--sidebar-ring: oklch(0.541 0.281 293.009);
}
-/* :root {
- --background: hsl(0 0% 100%);
- --foreground: hsl(224 71.4% 4.1%);
- --card: hsl(0 0% 100%);
- --card-foreground: hsl(224 71.4% 4.1%);
- --popover: hsl(0 0% 100%);
- --popover-foreground: hsl(224 71.4% 4.1%);
- --primary: hsl(262.1 83.3% 57.8%);
- --primary-foreground: hsl(210 20% 98%);
- --secondary: hsl(220 14.3% 95.9%);
- --secondary-foreground: hsl(220.9 39.3% 11%);
- --muted: hsl(220 14.3% 95.9%);
- --muted-foreground: hsl(220 8.9% 46.1%);
- --accent: hsl(220 14.3% 95.9%);
- --accent-foreground: hsl(220.9 39.3% 11%);
- --destructive: hsl(0 72.22% 50.59%);
- --destructive-foreground: hsl(210 20% 98%);
- --border: hsl(220 13% 91%);
- --input: hsl(220 13% 91%);
- --ring: hsl(262.1 83.3% 57.8%);
- --radius: 1rem;
-}
-
-.dark {
- --background: hsl(224 71.4% 4.1%);
- --foreground: hsl(210 20% 98%);
- --card: hsl(224 71.4% 4.1%);
- --card-foreground: hsl(210 20% 98%);
- --popover: hsl(224 71.4% 4.1%);
- --popover-foreground: hsl(210 20% 98%);
- --primary: hsl(263.4 70% 50.4%);
- --primary-foreground: hsl(210 20% 98%);
- --secondary: hsl(215 27.9% 16.9%);
- --secondary-foreground: hsl(210 20% 98%);
- --muted: hsl(215 27.9% 16.9%);
- --muted-foreground: hsl(217.9 10.6% 64.9%);
- --accent: hsl(215 27.9% 16.9%);
- --accent-foreground: hsl(210 20% 98%);
- --destructive: hsl(0 62.8% 30.6%);
- --destructive-foreground: hsl(210 20% 98%);
- --border: hsl(215 27.9% 16.9%);
- --input: hsl(215 27.9% 16.9%);
- --ring: hsl(263.4 70% 50.4%);
-} */
-
-/* Add @theme inline block */
@theme inline {
+ /* Radius (for rounded-*) */
+ --radius-sm: calc(var(--radius) - 4px);
+ --radius-md: calc(var(--radius) - 2px);
+ --radius-lg: var(--radius);
+ --radius-xl: calc(var(--radius) + 4px);
+
+ /* Colors */
--color-background: var(--background);
--color-foreground: var(--foreground);
- --color-card: var(--card);
- --color-card-foreground: var(--card-foreground);
+ --color-muted: var(--muted);
+ --color-muted-foreground: var(--muted-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
+ --color-card: var(--card);
+ --color-card-foreground: var(--card-foreground);
+ --color-border: var(--border);
+ --color-input: var(--input);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
- --color-muted: var(--muted);
- --color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
- --color-border: var(--border);
- --color-input: var(--input);
--color-ring: var(--ring);
- --radius: var(--radius);
+ --color-radius: var(--radius);
+ --color-sidebar: var(--sidebar);
+ --color-sidebar-foreground: var(--sidebar-foreground);
+ --color-sidebar-primary: var(--sidebar-primary);
+ --color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
+ --color-sidebar-accent: var(--sidebar-accent);
+ --color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
+ --color-sidebar-border: var(--sidebar-border);
+ --color-sidebar-ring: var(--sidebar-ring);
}
@layer base {
* {
@apply border-border;
}
+
body {
@apply bg-background text-foreground;
}
-
button {
@apply cursor-pointer;
}
diff --git a/src/lib/components/arcane-button.svelte b/src/lib/components/arcane-button.svelte
index 4424f67df..8393f303b 100644
--- a/src/lib/components/arcane-button.svelte
+++ b/src/lib/components/arcane-button.svelte
@@ -1,8 +1,8 @@
<script lang="ts">
import { Button, type Props as ButtonProps } from '$lib/components/ui/button/index.js';
- import { Play, StopCircle, RotateCcw, Download, Trash2, Loader2, RefreshCcwDot, ScanSearch, FileText, EditIcon as Edit, Check, X, Save, PlusCircle, type Icon as IconType } from '@lucide/svelte';
+ import { Play, StopCircle, RotateCcw, Download, Trash2, Loader2, RefreshCcwDot, ScanSearch, FileText, EditIcon as Edit, Check, X, Save, PlusCircle, type Icon as IconType, LayoutTemplate } from '@lucide/svelte';
- type Action = 'start' | 'deploy' | 'stop' | 'restart' | 'remove' | 'pull' | 'redeploy' | 'inspect' | 'logs' | 'edit' | 'confirm' | 'cancel' | 'save' | 'create';
+ type Action = 'start' | 'deploy' | 'stop' | 'restart' | 'remove' | 'pull' | 'redeploy' | 'inspect' | 'logs' | 'edit' | 'confirm' | 'cancel' | 'save' | 'create' | 'template';
interface Props {
/** The type of action this button represents. Determines icon, default label, and variant. */
@@ -65,7 +65,8 @@
confirm: { defaultLabel: 'Confirm', IconComponent: Check, variant: 'default', loadingLabel: 'Confirming...', customClass: 'arcane-button-confirm' },
cancel: { defaultLabel: 'Cancel', IconComponent: X, variant: 'ghost', loadingLabel: 'Cancelling...', customClass: 'arcane-button-cancel' },
save: { defaultLabel: 'Save', IconComponent: Save, variant: 'default', loadingLabel: 'Saving...', customClass: 'arcane-button-save' },
- create: { defaultLabel: 'Create', IconComponent: PlusCircle, variant: 'default', loadingLabel: 'Creating...', customClass: 'arcane-button-create' }
+ create: { defaultLabel: 'Create', IconComponent: PlusCircle, variant: 'default', loadingLabel: 'Creating...', customClass: 'arcane-button-create' },
+ template: { defaultLabel: 'Use Template', IconComponent: LayoutTemplate, variant: 'secondary', loadingLabel: 'Creating...', customClass: 'arcane-button-restart' }
};
let config = $derived(actionConfigs[action]);
diff --git a/src/lib/components/navbar.svelte b/src/lib/components/sidebar.svelte
similarity index 99%
rename from src/lib/components/navbar.svelte
rename to src/lib/components/sidebar.svelte
index 1681a9f18..d86458773 100644
--- a/src/lib/components/navbar.svelte
+++ b/src/lib/components/sidebar.svelte
@@ -1,5 +1,5 @@
<script lang="ts">
- import { Home, Box, Image, Network, HardDrive, Settings, Menu, X, ChevronRight, ChevronLeft, FileStack, ExternalLink, LogOut, Sun, Moon, ChevronDown, UserIcon, Shield, Bell, Palette, Database, type Icon as IconType, ShieldCheck } from '@lucide/svelte';
+ import { Home, Box, Image, Network, HardDrive, Settings, Menu, X, ChevronRight, ChevronLeft, FileStack, ExternalLink, LogOut, Sun, Moon, ChevronDown, UserIcon, Shield, Bell, Palette, Database, type Icon as IconType, ShieldCheck, LayoutTemplate } from '@lucide/svelte';
import { page } from '$app/state';
import { fly, slide } from 'svelte/transition';
import { Button } from '$lib/components/ui/button/index.js';
@@ -37,9 +37,11 @@
children: [
{ href: '/settings/general', label: 'General', icon: Settings },
{ href: '/settings/docker', label: 'Docker', icon: Database },
+ { href: '/settings/templates', label: 'Templates', icon: LayoutTemplate },
{ href: '/settings/users', label: 'Users', icon: UserIcon },
// { href: '/settings/rbac', label: 'RBAC', icon: ShieldCheck },
{ href: '/settings/security', label: 'Security', icon: Shield }
+
// { href: '/settings/notifications', label: 'Notifications', icon: Bell },
// { href: '/settings/appearance', label: 'Appearance', icon: Palette }
]
diff --git a/src/lib/components/template-selection-dialog.svelte b/src/lib/components/template-selection-dialog.svelte
new file mode 100644
index 000000000..98cedf99c
--- /dev/null
+++ b/src/lib/components/template-selection-dialog.svelte
@@ -0,0 +1,251 @@
+<script lang="ts">
+ import * as Dialog from '$lib/components/ui/dialog/index.js';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import { Card } from '$lib/components/ui/card/index.js';
+ import { Badge } from '$lib/components/ui/badge/index.js';
+ import * as Alert from '$lib/components/ui/alert/index.js';
+ import { FileText, Globe, FolderOpen, Settings, Download, Loader2 } from '@lucide/svelte';
+ import type { ComposeTemplate } from '$lib/services/template-service';
+ import TemplateAPIService from '$lib/services/api/template-api-service';
+ import { toast } from 'svelte-sonner';
+
+ interface Props {
+ open: boolean;
+ templates: ComposeTemplate[];
+ onSelect: (template: ComposeTemplate) => void;
+ }
+
+ let { open = $bindable(), templates, onSelect }: Props = $props();
+
+ const templateAPI = new TemplateAPIService();
+
+ // Loading states for individual templates
+ let loadingStates = $state(new Map<string, boolean>());
+
+ async function handleSelect(template: ComposeTemplate) {
+ // Set loading state
+ loadingStates.set(template.id, true);
+ loadingStates = new Map(loadingStates);
+
+ try {
+ let finalTemplate = template;
+
+ // If it's a remote template, fetch the actual content via API
+ if (template.isRemote) {
+ const templateContent = await templateAPI.getContent(template.id);
+
+ if (!templateContent.content) {
+ toast.error('Failed to load template content');
+ return;
+ }
+
+ // Create the final template with actual content
+ finalTemplate = {
+ ...template,
+ content: templateContent.content,
+ envContent: templateContent.envContent || template.envContent
+ };
+ }
+
+ onSelect(finalTemplate);
+ open = false;
+ toast.success(`Template "${template.name}" loaded successfully!`);
+ } catch (error) {
+ console.error('Error loading template:', error);
+ toast.error('Failed to load template content');
+ } finally {
+ // Clear loading state
+ loadingStates.delete(template.id);
+ loadingStates = new Map(loadingStates);
+ }
+ }
+
+ async function handleDownload(template: ComposeTemplate) {
+ if (!template.isRemote) return;
+
+ const templateId = template.id;
+ loadingStates.set(`download-${templateId}`, true);
+ loadingStates = new Map(loadingStates);
+
+ try {
+ const result = await templateAPI.download(templateId);
+
+ if (result.success) {
+ toast.success(`Template "${template.name}" downloaded successfully!`);
+ } else {
+ toast.error(result.message || 'Failed to download template');
+ }
+ } catch (error) {
+ console.error('Error downloading template:', error);
+
+ // Extract the actual error message from the API response
+ let errorMessage = 'Failed to download template';
+ if (error instanceof Error) {
+ errorMessage = error.message;
+ } else if (error && typeof error === 'object' && 'message' in error) {
+ errorMessage = String(error.message);
+ }
+
+ toast.error(errorMessage);
+ } finally {
+ loadingStates.delete(`download-${templateId}`);
+ loadingStates = new Map(loadingStates);
+ }
+ }
+
+ const localTemplates = $derived(templates.filter((t) => !t.isRemote));
+ const remoteTemplates = $derived(templates.filter((t) => t.isRemote));
+</script>
+
+<Dialog.Root bind:open>
+ <Dialog.Content class="sm:max-w-[900px] max-h-screen overflow-y-auto">
+ <Dialog.Header>
+ <Dialog.Title class="flex items-center gap-2">
+ <FileText class="size-5" />
+ Choose a Template
+ </Dialog.Title>
+ <Dialog.Description>Select a Docker Compose template to get started quickly, or download remote templates for local use.</Dialog.Description>
+ </Dialog.Header>
+
+ <div class="space-y-6 py-4">
+ {#if templates.length === 0}
+ <div class="text-center py-8 text-muted-foreground">
+ <FileText class="size-12 mx-auto mb-4 opacity-50" />
+ <p class="mb-2">No templates available</p>
+ <p class="text-sm">Configure remote registries in <a href="/settings/templates" class="text-primary hover:underline">Template Settings</a> to access community templates</p>
+ </div>
+ {:else}
+ <!-- Local Templates -->
+ {#if localTemplates.length > 0}
+ <div>
+ <h3 class="text-lg font-semibold mb-3 flex items-center gap-2">
+ <FolderOpen class="size-5 text-blue-500" />
+ Local Templates ({localTemplates.length})
+ </h3>
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
+ {#each localTemplates as template}
+ <Card class="cursor-pointer hover:bg-muted/50 transition-colors border-2 hover:border-primary/20">
+ <div class="p-4">
+ <div class="flex items-start justify-between mb-2">
+ <h4 class="font-semibold truncate pr-2">{template.name}</h4>
+ <div class="flex gap-1 ml-2 flex-shrink-0">
+ <Badge variant="outline" class="text-xs">
+ <FolderOpen class="size-3 mr-1" />
+ Local
+ </Badge>
+ {#if template.envContent}
+ <Badge variant="secondary" class="text-xs">
+ <Settings class="size-3 mr-1" />
+ ENV
+ </Badge>
+ {/if}
+ </div>
+ </div>
+ <p class="text-sm text-muted-foreground mb-3 line-clamp-2">
+ {template.description}
+ </p>
+ <div class="flex justify-between items-center">
+ <div class="text-xs text-muted-foreground">
+ {template.envContent ? 'Includes environment variables' : 'Ready to use'}
+ </div>
+ <Button size="sm" onclick={() => handleSelect(template)} disabled={loadingStates.get(template.id)}>
+ {#if loadingStates.get(template.id)}
+ <Loader2 class="size-3 animate-spin mr-1" />
+ Loading...
+ {:else}
+ Use Template
+ {/if}
+ </Button>
+ </div>
+ </div>
+ </Card>
+ {/each}
+ </div>
+ </div>
+ {/if}
+
+ <!-- Remote Templates -->
+ {#if remoteTemplates.length > 0}
+ <div>
+ <h3 class="text-lg font-semibold mb-3 flex items-center gap-2">
+ <Globe class="size-5 text-green-500" />
+ Remote Templates ({remoteTemplates.length})
+ </h3>
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
+ {#each remoteTemplates as template}
+ <Card class="hover:bg-muted/50 transition-colors border-2 hover:border-primary/20">
+ <div class="p-4">
+ <div class="flex items-start justify-between mb-2">
+ <h4 class="font-semibold truncate pr-2">{template.name}</h4>
+ <div class="flex gap-1 ml-2 flex-shrink-0">
+ <Badge variant="secondary" class="text-xs">
+ <Globe class="size-3 mr-1" />
+ {template.metadata?.registry || 'Remote'}
+ </Badge>
+ {#if template.metadata?.envUrl}
+ <Badge variant="secondary" class="text-xs">
+ <Settings class="size-3 mr-1" />
+ ENV
+ </Badge>
+ {/if}
+ </div>
+ </div>
+ <p class="text-sm text-muted-foreground mb-2 line-clamp-2">
+ {template.description}
+ </p>
+ {#if template.metadata?.author}
+ <p class="text-xs text-muted-foreground mb-3">
+ by {template.metadata.author}
+ </p>
+ {/if}
+ <div class="flex justify-between items-center gap-2">
+ <div class="text-xs text-muted-foreground flex-1">
+ {#if template.metadata?.version}
+ <Badge variant="outline" class="text-xs">
+ v{template.metadata.version}
+ </Badge>
+ {/if}
+ </div>
+ <div class="flex gap-2">
+ <Button variant="outline" size="sm" onclick={() => handleDownload(template)} disabled={loadingStates.get(`download-${template.id}`)}>
+ {#if loadingStates.get(`download-${template.id}`)}
+ <Loader2 class="size-3 animate-spin mr-1" />
+ Downloading...
+ {:else}
+ <Download class="size-3 mr-1" />
+ Download
+ {/if}
+ </Button>
+ <Button size="sm" onclick={() => handleSelect(template)} disabled={loadingStates.get(template.id)}>
+ {#if loadingStates.get(template.id)}
+ <Loader2 class="size-3 animate-spin mr-1" />
+ Loading...
+ {:else}
+ Use Now
+ {/if}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </Card>
+ {/each}
+ </div>
+ </div>
+ {/if}
+ {/if}
+ </div>
+
+ <Dialog.Footer>
+ <Button variant="outline" onclick={() => (open = false)}>Cancel</Button>
+ </Dialog.Footer>
+ </Dialog.Content>
+</Dialog.Root>
+
+<style>
+ .line-clamp-2 {
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+ }
+</style>
diff --git a/src/lib/components/ui/dialog/dialog-close.svelte b/src/lib/components/ui/dialog/dialog-close.svelte
new file mode 100644
index 000000000..e8a96a773
--- /dev/null
+++ b/src/lib/components/ui/dialog/dialog-close.svelte
@@ -0,0 +1,7 @@
+<script lang="ts">
+ import { Dialog as DialogPrimitive } from 'bits-ui';
+
+ let { ref = $bindable(null), ...restProps }: DialogPrimitive.CloseProps = $props();
+</script>
+
+<DialogPrimitive.Close bind:ref data-slot="dialog-close" {...restProps} />
diff --git a/src/lib/components/ui/dialog/dialog-content.svelte b/src/lib/components/ui/dialog/dialog-content.svelte
index 0fbe1f5a8..c79b68260 100644
--- a/src/lib/components/ui/dialog/dialog-content.svelte
+++ b/src/lib/components/ui/dialog/dialog-content.svelte
@@ -1,9 +1,9 @@
<script lang="ts">
- import { Dialog as DialogPrimitive, type WithoutChildrenOrChild } from 'bits-ui';
- import X from '@lucide/svelte/icons/x';
+ import { Dialog as DialogPrimitive } from 'bits-ui';
+ import XIcon from '@lucide/svelte/icons/x';
import type { Snippet } from 'svelte';
import * as Dialog from './index.js';
- import { cn } from '$lib/utils.js';
+ import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';
let {
ref = $bindable(null),
@@ -21,15 +21,13 @@
<Dialog.Overlay />
<DialogPrimitive.Content
bind:ref
- class={cn(
- 'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] bg-background fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border p-6 shadow-lg duration-200 sm:rounded-lg',
- className
- )}
+ data-slot="dialog-content"
+ class={cn('bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed left-[50%] top-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg', className)}
{...restProps}
>
{@render children?.()}
- <DialogPrimitive.Close class="ring-offset-background focus:ring-ring absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:pointer-events-none">
- <X class="size-4" />
+ <DialogPrimitive.Close class="ring-offset-background focus:ring-ring rounded-xs focus:outline-hidden absolute right-4 top-4 opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 disabled:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0">
+ <XIcon />
<span class="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
diff --git a/src/lib/components/ui/dialog/dialog-description.svelte b/src/lib/components/ui/dialog/dialog-description.svelte
index a0b3f6b47..a20bc38e8 100644
--- a/src/lib/components/ui/dialog/dialog-description.svelte
+++ b/src/lib/components/ui/dialog/dialog-description.svelte
@@ -5,4 +5,4 @@
let { ref = $bindable(null), class: className, ...restProps }: DialogPrimitive.DescriptionProps = $props();
</script>
-<DialogPrimitive.Description bind:ref class={cn('text-muted-foreground text-sm', className)} {...restProps} />
+<DialogPrimitive.Description bind:ref data-slot="dialog-description" class={cn('text-muted-foreground text-sm', className)} {...restProps} />
diff --git a/src/lib/components/ui/dialog/dialog-footer.svelte b/src/lib/components/ui/dialog/dialog-footer.svelte
index 6857eb5ca..a7789619a 100644
--- a/src/lib/components/ui/dialog/dialog-footer.svelte
+++ b/src/lib/components/ui/dialog/dialog-footer.svelte
@@ -1,11 +1,10 @@
<script lang="ts">
- import type { WithElementRef } from '$lib/utils.js';
+ import { cn, type WithElementRef } from '$lib/utils.js';
import type { HTMLAttributes } from 'svelte/elements';
- import { cn } from '$lib/utils.js';
let { ref = $bindable(null), class: className, children, ...restProps }: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();
</script>
-<div bind:this={ref} class={cn('flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2', className)} {...restProps}>
+<div bind:this={ref} data-slot="dialog-footer" class={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)} {...restProps}>
{@render children?.()}
</div>
diff --git a/src/lib/components/ui/dialog/dialog-header.svelte b/src/lib/components/ui/dialog/dialog-header.svelte
index 6a209be60..f6038a838 100644
--- a/src/lib/components/ui/dialog/dialog-header.svelte
+++ b/src/lib/components/ui/dialog/dialog-header.svelte
@@ -1,11 +1,10 @@
<script lang="ts">
import type { HTMLAttributes } from 'svelte/elements';
- import type { WithElementRef } from '$lib/utils.js';
- import { cn } from '$lib/utils.js';
+ import { cn, type WithElementRef } from '$lib/utils.js';
let { ref = $bindable(null), class: className, children, ...restProps }: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();
</script>
-<div bind:this={ref} class={cn('flex flex-col space-y-1.5 text-center sm:text-left', className)} {...restProps}>
+<div bind:this={ref} data-slot="dialog-header" class={cn('flex flex-col gap-2 text-center sm:text-left', className)} {...restProps}>
{@render children?.()}
</div>
diff --git a/src/lib/components/ui/dialog/dialog-overlay.svelte b/src/lib/components/ui/dialog/dialog-overlay.svelte
index 298afd7e1..8c04b04b2 100644
--- a/src/lib/components/ui/dialog/dialog-overlay.svelte
+++ b/src/lib/components/ui/dialog/dialog-overlay.svelte
@@ -5,4 +5,4 @@
let { ref = $bindable(null), class: className, ...restProps }: DialogPrimitive.OverlayProps = $props();
</script>
-<DialogPrimitive.Overlay bind:ref class={cn('data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/80', className)} {...restProps} />
+<DialogPrimitive.Overlay bind:ref data-slot="dialog-overlay" class={cn('data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50', className)} {...restProps} />
diff --git a/src/lib/components/ui/dialog/dialog-title.svelte b/src/lib/components/ui/dialog/dialog-title.svelte
index ba487298d..71e800c9c 100644
--- a/src/lib/components/ui/dialog/dialog-title.svelte
+++ b/src/lib/components/ui/dialog/dialog-title.svelte
@@ -5,4 +5,4 @@
let { ref = $bindable(null), class: className, ...restProps }: DialogPrimitive.TitleProps = $props();
</script>
-<DialogPrimitive.Title bind:ref class={cn('text-lg font-semibold leading-none tracking-tight', className)} {...restProps} />
+<DialogPrimitive.Title bind:ref data-slot="dialog-title" class={cn('text-lg font-semibold leading-none', className)} {...restProps} />
diff --git a/src/lib/components/ui/dialog/dialog-trigger.svelte b/src/lib/components/ui/dialog/dialog-trigger.svelte
new file mode 100644
index 000000000..ac04d9fe4
--- /dev/null
+++ b/src/lib/components/ui/dialog/dialog-trigger.svelte
@@ -0,0 +1,7 @@
+<script lang="ts">
+ import { Dialog as DialogPrimitive } from 'bits-ui';
+
+ let { ref = $bindable(null), ...restProps }: DialogPrimitive.TriggerProps = $props();
+</script>
+
+<DialogPrimitive.Trigger bind:ref data-slot="dialog-trigger" {...restProps} />
diff --git a/src/lib/components/ui/dialog/index.ts b/src/lib/components/ui/dialog/index.ts
index 3b460fb87..d9e5fb86e 100644
--- a/src/lib/components/ui/dialog/index.ts
+++ b/src/lib/components/ui/dialog/index.ts
@@ -6,10 +6,10 @@ import Header from './dialog-header.svelte';
import Overlay from './dialog-overlay.svelte';
import Content from './dialog-content.svelte';
import Description from './dialog-description.svelte';
+import Trigger from './dialog-trigger.svelte';
+import Close from './dialog-close.svelte';
const Root = DialogPrimitive.Root;
-const Trigger = DialogPrimitive.Trigger;
-const Close = DialogPrimitive.Close;
const Portal = DialogPrimitive.Portal;
export {
diff --git a/src/lib/services/api/template-api-service.ts b/src/lib/services/api/template-api-service.ts
new file mode 100644
index 000000000..f3b08eb87
--- /dev/null
+++ b/src/lib/services/api/template-api-service.ts
@@ -0,0 +1,89 @@
+import BaseAPIService from './api-service';
+import type { ComposeTemplate } from '$lib/services/template-service';
+import type { TemplateRegistryConfig } from '$lib/types/settings.type';
+
+export default class TemplateAPIService extends BaseAPIService {
+ /**
+ * Get all templates (local and remote)
+ */
+ async getAll() {
+ const res = await this.api.get('/templates');
+ return res.data;
+ }
+
+ /**
+ * Get only local templates
+ */
+ async getLocal() {
+ const res = await this.api.get('/templates?type=local');
+ return res.data;
+ }
+
+ /**
+ * Get only remote templates
+ */
+ async getRemote() {
+ const res = await this.api.get('/templates?type=remote');
+ return res.data;
+ }
+
+ /**
+ * Get template content by ID
+ */
+ async getContent(id: string) {
+ const res = await this.api.get(`/templates/${encodeURIComponent(id)}/content`);
+ return res.data;
+ }
+
+ /**
+ * Download and save a remote template locally
+ */
+ async download(id: string, localName?: string) {
+ const res = await this.api.post(`/templates/${encodeURIComponent(id)}/download`, {
+ localName
+ });
+ return res.data;
+ }
+
+ /**
+ * Create a new local template
+ */
+ async create(name: string, content: string, description?: string, envContent?: string) {
+ const res = await this.api.post('/templates', {
+ name,
+ content,
+ description,
+ envContent
+ });
+ return res.data;
+ }
+
+ /**
+ * Update an existing local template
+ */
+ async update(id: string, name: string, content: string, description?: string, envContent?: string) {
+ const res = await this.api.put(`/templates/${encodeURIComponent(id)}`, {
+ name,
+ content,
+ description,
+ envContent
+ });
+ return res.data;
+ }
+
+ /**
+ * Delete a local template
+ */
+ async delete(id: string) {
+ const res = await this.api.delete(`/templates/${encodeURIComponent(id)}`);
+ return res.data;
+ }
+
+ /**
+ * Get template statistics
+ */
+ async getStats() {
+ const res = await this.api.get('/templates/stats');
+ return res.data;
+ }
+}
diff --git a/src/lib/services/settings-service.ts b/src/lib/services/settings-service.ts
index 27925cba9..b12894bdc 100644
--- a/src/lib/services/settings-service.ts
+++ b/src/lib/services/settings-service.ts
@@ -23,6 +23,7 @@ export const DEFAULT_SETTINGS: Settings = {
pruneMode: 'all',
stacksDirectory: STACKS_DIR,
registryCredentials: [],
+ templateRegistries: [],
auth: {
localAuthEnabled: true,
oidcEnabled: false,
@@ -127,6 +128,7 @@ export async function getSettings(): Promise<Settings> {
...(decryptedData.auth || {})
},
registryCredentials: decryptedData.registryCredentials || baseSettings.registryCredentials,
+ templateRegistries: nonSensitiveSettings.templateRegistries || baseSettings.templateRegistries,
onboarding: nonSensitiveSettings.onboarding || baseSettings.onboarding,
baseServerUrl: nonSensitiveSettings.baseServerUrl || baseSettings.baseServerUrl
};
@@ -139,6 +141,7 @@ export async function getSettings(): Promise<Settings> {
...(settingsFromFile.auth || {})
},
registryCredentials: settingsFromFile.registryCredentials || baseSettings.registryCredentials,
+ templateRegistries: settingsFromFile.templateRegistries || baseSettings.templateRegistries,
onboarding: settingsFromFile.onboarding || baseSettings.onboarding,
baseServerUrl: settingsFromFile.baseServerUrl || baseSettings.baseServerUrl
};
diff --git a/src/lib/services/template-registry-service.ts b/src/lib/services/template-registry-service.ts
new file mode 100644
index 000000000..eadcce01b
--- /dev/null
+++ b/src/lib/services/template-registry-service.ts
@@ -0,0 +1,187 @@
+import type { TemplateRegistry, RemoteTemplate } from '$lib/types/template-registry';
+import type { TemplateRegistryConfig } from '$lib/types/settings.type';
+import type { ComposeTemplate } from '$lib/services/template-service';
+import { browser } from '$app/environment';
+
+export class TemplateRegistryService {
+ private cache = new Map<string, { data: TemplateRegistry; timestamp: number }>();
+ private readonly defaultCacheTtl = 3600; // 1 hour
+
+ async fetchRegistry(config: TemplateRegistryConfig): Promise<TemplateRegistry | null> {
+ try {
+ // Check cache first
+ const cached = this.cache.get(config.url);
+ const now = Date.now();
+ const ttl = (config.cache_ttl || this.defaultCacheTtl) * 1000;
+
+ if (cached && now - cached.timestamp < ttl) {
+ return cached.data;
+ }
+
+ let registry: TemplateRegistry;
+
+ if (browser) {
+ const proxyUrl = `/api/templates?url=${encodeURIComponent(config.url)}`;
+ const response = await fetch(proxyUrl);
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({ message: response.statusText }));
+ throw new Error(errorData.message || `Failed to fetch registry: ${response.statusText}`);
+ }
+
+ registry = await response.json();
+ } else {
+ // Direct fetch on server-side
+ const response = await fetch(config.url, {
+ headers: {
+ 'User-Agent': 'Arcane-Template-Registry/1.0',
+ Accept: 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to fetch registry: ${response.statusText}`);
+ }
+
+ registry = await response.json();
+ }
+
+ // Validate registry structure
+ this.validateRegistry(registry);
+
+ // Cache the result
+ this.cache.set(config.url, { data: registry, timestamp: now });
+
+ return registry;
+ } catch (error) {
+ console.error(`Error fetching template registry from ${config.url}:`, error);
+ return null;
+ }
+ }
+
+ async fetchTemplateContent(template: RemoteTemplate): Promise<string | null> {
+ try {
+ if (browser) {
+ // Use unified proxy endpoint in browser
+ const response = await fetch('/api/templates', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ url: template.compose_url,
+ content: true
+ })
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({ message: response.statusText }));
+ throw new Error(errorData.message || `Failed to fetch template content: ${response.statusText}`);
+ }
+
+ const data = await response.json();
+ return data.content;
+ } else {
+ // Direct fetch on server-side
+ const response = await fetch(template.compose_url, {
+ headers: {
+ 'User-Agent': 'Arcane-Template-Registry/1.0',
+ Accept: 'text/plain, application/x-yaml, text/yaml, */*'
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to fetch template content: ${response.statusText}`);
+ }
+
+ return await response.text();
+ }
+ } catch (error) {
+ console.error(`Error fetching template content from ${template.compose_url}:`, error);
+ return null;
+ }
+ }
+
+ async fetchEnvContent(envUrl: string): Promise<string | null> {
+ try {
+ if (browser) {
+ // Use unified proxy endpoint in browser
+ const response = await fetch('/api/templates', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ url: envUrl,
+ content: true
+ })
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({ message: response.statusText }));
+ throw new Error(errorData.message || `Failed to fetch environment content: ${response.statusText}`);
+ }
+
+ const data = await response.json();
+ return data.content;
+ } else {
+ // Direct fetch on server-side
+ const response = await fetch(envUrl, {
+ headers: {
+ 'User-Agent': 'Arcane-Template-Registry/1.0',
+ Accept: 'text/plain, */*'
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to fetch environment content: ${response.statusText}`);
+ }
+
+ return await response.text();
+ }
+ } catch (error) {
+ console.error(`Error fetching environment content from ${envUrl}:`, error);
+ return null;
+ }
+ }
+
+ convertToComposeTemplate(remote: RemoteTemplate, registryName: string): ComposeTemplate {
+ return {
+ id: `${registryName}:${remote.id}`,
+ name: remote.name,
+ description: remote.description,
+ content: '', // Will be loaded on demand
+ isCustom: true,
+ isRemote: true,
+ metadata: {
+ version: remote.version,
+ author: remote.author,
+ tags: remote.tags,
+ registry: registryName,
+ remoteUrl: remote.compose_url,
+ envUrl: remote.env_url,
+ documentationUrl: remote.documentation_url,
+ iconUrl: remote.icon_url,
+ updatedAt: remote.updated_at
+ }
+ };
+ }
+
+ private validateRegistry(registry: TemplateRegistry): void {
+ if (!registry.name || !registry.version || !Array.isArray(registry.templates)) {
+ throw new Error('Invalid registry format');
+ }
+
+ for (const template of registry.templates) {
+ if (!template.id || !template.name || !template.compose_url) {
+ throw new Error(`Invalid template format: ${template.id}`);
+ }
+ }
+ }
+
+ clearCache(): void {
+ this.cache.clear();
+ }
+}
+
+export const templateRegistryService = new TemplateRegistryService();
diff --git a/src/lib/services/template-service.ts b/src/lib/services/template-service.ts
new file mode 100644
index 000000000..94fbe4056
--- /dev/null
+++ b/src/lib/services/template-service.ts
@@ -0,0 +1,564 @@
+import { promises as fs } from 'node:fs';
+import * as path from 'node:path';
+import type { TemplateRegistryConfig } from '$lib/types/settings.type'; // Import from settings
+import { templateRegistryService } from './template-registry-service';
+import { getSettings, saveSettings } from './settings-service';
+
+export interface ComposeTemplate {
+ id: string;
+ name: string;
+ description: string;
+ content: string;
+ envContent?: string; // Optional environment content
+ isCustom: boolean;
+ isRemote?: boolean;
+ metadata?: {
+ version?: string;
+ author?: string;
+ tags?: string[];
+ registry?: string;
+ remoteUrl?: string;
+ envUrl?: string; // Optional environment URL
+ documentationUrl?: string;
+ iconUrl?: string;
+ updatedAt?: string;
+ };
+}
+
+export class TemplateService {
+ private static templatesDir = path.join(process.cwd(), 'data/templates');
+ private static composeTemplatesDir = path.join(this.templatesDir, 'compose');
+ private static envTemplateFile = path.join(this.templatesDir, '.env.template');
+
+ /**
+ * Get all available compose templates from the file system
+ */
+ static async getComposeTemplates(): Promise<ComposeTemplate[]> {
+ try {
+ // Ensure directories exist
+ await this.ensureDirectoriesExist();
+
+ const files = await fs.readdir(this.composeTemplatesDir);
+ const yamlFiles = files.filter((file) => (file.endsWith('.yaml') || file.endsWith('.yml')) && !file.startsWith('.'));
+
+ const templates: ComposeTemplate[] = [];
+
+ for (const file of yamlFiles) {
+ const filePath = path.join(this.composeTemplatesDir, file);
+ const content = await fs.readFile(filePath, 'utf8');
+ const id = path.basename(file, path.extname(file));
+
+ // Try to extract description from comment at top of file
+ const description = this.extractDescriptionFromFile(content);
+
+ // Check for accompanying .env file
+ const envContent = await this.loadTemplateEnvFile(id);
+
+ templates.push({
+ id,
+ name: this.formatTemplateName(id),
+ description: description || 'Custom Docker Compose template',
+ content,
+ envContent,
+ isCustom: true,
+ isRemote: false
+ });
+ }
+
+ return templates.sort((a, b) => a.name.localeCompare(b.name));
+ } catch (error) {
+ console.error('Error loading compose templates:', error);
+ return [];
+ }
+ }
+
+ /**
+ * Load environment file for a specific template
+ */
+ private static async loadTemplateEnvFile(templateId: string): Promise<string | undefined> {
+ const envPath = path.join(this.composeTemplatesDir, `${templateId}.env`);
+ try {
+ return await fs.readFile(envPath, 'utf8');
+ } catch (error) {
+ // No env file found, that's okay
+ return undefined;
+ }
+ }
+
+ /**
+ * Get the .env template content if it exists
+ */
+ static async getEnvTemplate(): Promise<string> {
+ try {
+ await this.ensureDirectoriesExist();
+ return await fs.readFile(this.envTemplateFile, 'utf8');
+ } catch (error) {
+ console.log('No .env template found, using default');
+ return this.getDefaultEnvTemplate();
+ }
+ }
+
+ /**
+ * Create a new template from content
+ */
+ static async createTemplate(name: string, content: string, description?: string, envContent?: string): Promise<void> {
+ // Validate inputs
+ if (!name || name.trim() === '') {
+ throw new Error('Template name cannot be empty');
+ }
+
+ if (!content || content.trim() === '') {
+ throw new Error('Template content cannot be empty');
+ }
+
+ // Basic YAML validation - check if it starts with valid YAML structure
+ const trimmedContent = content.trim();
+ if (!trimmedContent.startsWith('version:') && !trimmedContent.startsWith('services:')) {
+ console.warn('Template content may not be valid Docker Compose YAML - missing version or services section');
+ }
+
+ await this.ensureDirectoriesExist();
+
+ // Improved filename sanitization - convert to lowercase first, then sanitize
+ const sanitizedName = name
+ .toLowerCase()
+ .replace(/[^a-z0-9\s-_]/g, '') // Remove invalid chars, keep spaces, hyphens, underscores
+ .replace(/\s+/g, '-') // Replace spaces with hyphens
+ .replace(/[-_]+/g, '-') // Collapse multiple hyphens/underscores
+ .replace(/^-+|-+$/g, ''); // Remove leading/trailing hyphens
+
+ if (!sanitizedName) {
+ throw new Error('Template name contains no valid characters');
+ }
+
+ // Check for existing files and create unique filename if needed
+ const baseFilename = sanitizedName;
+ let filename = `${baseFilename}.yaml`;
+ let envFilename = `${baseFilename}.env`;
+ let counter = 1;
+
+ // Find unique filenames
+ while (await this.fileExists(path.join(this.composeTemplatesDir, filename))) {
+ filename = `${baseFilename}-${counter}.yaml`;
+ envFilename = `${baseFilename}-${counter}.env`;
+ counter++;
+ }
+
+ const filePath = path.join(this.composeTemplatesDir, filename);
+
+ // Safely add description as YAML comment block
+ let fileContent = content;
+ if (description && description.trim()) {
+ // Ensure description doesn't break YAML by properly formatting as comments
+ const descriptionLines = description.trim().split('\n');
+ const commentBlock = descriptionLines.map((line) => `# ${line}`).join('\n');
+
+ // Add comment block before the content with proper spacing
+ fileContent = `${commentBlock}\n#\n${content}`;
+ }
+
+ await fs.writeFile(filePath, fileContent, 'utf8');
+
+ // Save environment file if provided
+ if (envContent && envContent.trim()) {
+ const envFilePath = path.join(this.composeTemplatesDir, envFilename);
+ // Only create env file if it doesn't exist (since we already checked for compose file uniqueness)
+ if (!(await this.fileExists(envFilePath))) {
+ await fs.writeFile(envFilePath, envContent, 'utf8');
+ }
+ }
+ }
+
+ /**
+ * Helper method to check if a file exists
+ */
+ private static async fileExists(filePath: string): Promise<boolean> {
+ try {
+ await fs.access(filePath);
+ return true;
+ } catch {
+ return false;
+ }
+ }
+
+ /**
+ * Delete a template
+ */
+ static async deleteTemplate(id: string): Promise<void> {
+ const possibleExtensions = ['.yaml', '.yml'];
+ let deleted = false;
+
+ for (const ext of possibleExtensions) {
+ const filePath = path.join(this.composeTemplatesDir, `${id}${ext}`);
+ try {
+ await fs.unlink(filePath);
+ deleted = true;
+ break;
+ } catch (error) {
+ // File doesn't exist with this extension, try next
+ }
+ }
+
+ // Also try to delete the env file
+ try {
+ const envFilePath = path.join(this.composeTemplatesDir, `${id}.env`);
+ await fs.unlink(envFilePath);
+ } catch (error) {
+ // Env file doesn't exist, that's okay
+ }
+
+ if (!deleted) {
+ throw new Error(`Template with id "${id}" not found`);
+ }
+ }
+
+ /**
+ * Get template directory path for users to add their own templates
+ */
+ static getTemplateDirectoryPath(): string {
+ return this.composeTemplatesDir;
+ }
+
+ /**
+ * Get env template file path
+ */
+ static getEnvTemplateFilePath(): string {
+ return this.envTemplateFile;
+ }
+
+ /**
+ * Ensure template directories exist
+ */
+ private static async ensureDirectoriesExist(): Promise<void> {
+ try {
+ await fs.mkdir(this.templatesDir, { recursive: true });
+ await fs.mkdir(this.composeTemplatesDir, { recursive: true });
+
+ // Create README file to help users understand how to add templates
+ const readmePath = path.join(this.templatesDir, 'README.md');
+ try {
+ await fs.access(readmePath);
+ } catch {
+ await this.createReadmeFile();
+ }
+ } catch (error) {
+ console.error('Error ensuring template directories exist:', error);
+ }
+ }
+
+ /**
+ * Create a helpful README file for users
+ */
+ private static async createReadmeFile(): Promise<void> {
+ const readmeContent = `# Arcane Templates
+
+This directory contains templates for creating Docker Compose stacks.
+
+## Directory Structure
+
+- \`compose/\` - Docker Compose template files (.yaml or .yml)
+- \`.env.template\` - Default environment variables template
+
+## Adding Templates
+
+1. **Local Templates**: Place your Docker Compose files in the \`compose/\` directory
+ - Use \`.yaml\` or \`.yml\` extension
+ - Optionally add a matching \`.env\` file with the same name (e.g., \`my-app.yaml\` and \`my-app.env\`)
+ - Add a comment at the top to describe the template:
+ \`\`\`yaml
+ # My Custom Application Stack
+ services:
+ app:
+ image: nginx:alpine
+ # ... rest of your compose file
+ \`\`\`
+
+2. **Template Environment Files**: Create \`.env\` files alongside your templates
+ - File name should match your template: \`wordpress.yaml\` → \`wordpress.env\`
+ - These will be loaded automatically when the template is selected
+ - Example structure:
+ \`\`\`
+ compose/
+ ├── wordpress.yaml
+ ├── wordpress.env
+ ├── nextjs.yaml
+ └── nextjs.env
+ \`\`\`
+
+3. **Remote Templates**: Configure remote registries in the Template Settings page
+ - Access community-maintained templates
+ - Automatically synced from registry sources
+ - Can include both compose and environment files
+
+4. **Environment Template**: Create or edit \`.env.template\` to set default environment variables
+ - This will be used as fallback when templates don't provide their own environment
+ - Use KEY=value format
+
+## Template Naming
+
+- File names will be converted to display names
+- \`my-web-app.yaml\` becomes "My Web App"
+- Use hyphens or underscores to separate words
+
+## Example Templates
+
+You can find example templates in community registries or create your own:
+- wordpress.yaml + wordpress.env - WordPress with MySQL
+- nextjs.yaml + nextjs.env - Next.js application
+- postgres.yaml + postgres.env - PostgreSQL database
+
+All templates added here will automatically appear in the Arcane UI when creating new stacks.
+`;
+
+ await fs.writeFile(path.join(this.templatesDir, 'README.md'), readmeContent, 'utf8');
+ }
+
+ /**
+ * Extract description from file comment
+ */
+ private static extractDescriptionFromFile(content: string): string | null {
+ const lines = content.split('\n');
+ const firstLine = lines[0]?.trim();
+
+ if (firstLine?.startsWith('#')) {
+ return firstLine.substring(1).trim();
+ }
+
+ return null;
+ }
+
+ /**
+ * Format template name for display
+ */
+ private static formatTemplateName(id: string): string {
+ return id
+ .split(/[-_]/)
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
+ .join(' ');
+ }
+
+ /**
+ * Get default .env template content
+ */
+ private static getDefaultEnvTemplate(): string {
+ return `# Environment Variables
+# These variables will be available to your stack services
+# Format: VARIABLE_NAME=value
+
+# Web Server Configuration
+NGINX_HOST=localhost
+NGINX_PORT=80
+
+# Database Configuration
+POSTGRES_DB=myapp
+POSTGRES_USER=myuser
+POSTGRES_PASSWORD=mypassword
+POSTGRES_PORT=5432
+
+# Example Additional Variables
+# API_KEY=your_api_key_here
+# SECRET_KEY=your_secret_key_here
+# DEBUG=false
+`;
+ }
+
+ /**
+ * Load all templates (local and remote)
+ */
+ async loadAllTemplates(): Promise<ComposeTemplate[]> {
+ const templates: ComposeTemplate[] = [];
+
+ // Load local templates
+ templates.push(...(await this.loadLocalTemplates()));
+
+ // Load remote templates
+ templates.push(...(await this.loadRemoteTemplates()));
+
+ return templates;
+ }
+
+ /**
+ * Load local templates from the file system
+ */
+ async loadLocalTemplates(): Promise<ComposeTemplate[]> {
+ try {
+ // Ensure directories exist
+ await TemplateService.ensureDirectoriesExist();
+
+ const files = await fs.readdir(TemplateService.composeTemplatesDir);
+ const yamlFiles = files.filter((file) => (file.endsWith('.yaml') || file.endsWith('.yml')) && !file.startsWith('.'));
+
+ const templates: ComposeTemplate[] = [];
+
+ for (const file of yamlFiles) {
+ const filePath = path.join(TemplateService.composeTemplatesDir, file);
+ const content = await fs.readFile(filePath, 'utf8');
+ const id = path.basename(file, path.extname(file));
+
+ // Try to extract description from comment at top of file
+ const description = TemplateService.extractDescriptionFromFile(content);
+
+ // Check for accompanying .env file
+ const envContent = await TemplateService.loadTemplateEnvFile(id);
+
+ templates.push({
+ id,
+ name: TemplateService.formatTemplateName(id),
+ description: description || 'Custom Docker Compose template',
+ content,
+ envContent,
+ isCustom: true,
+ isRemote: false
+ });
+ }
+
+ return templates.sort((a, b) => a.name.localeCompare(b.name));
+ } catch (error) {
+ console.error('Error loading local templates:', error);
+ return [];
+ }
+ }
+
+ /**
+ * Load remote templates
+ */
+ async loadRemoteTemplates(): Promise<ComposeTemplate[]> {
+ const templates: ComposeTemplate[] = [];
+ const settings = await getSettings();
+ const registryConfigs = settings.templateRegistries || [];
+
+ for (const config of registryConfigs) {
+ if (!config.enabled) continue;
+
+ const registry = await templateRegistryService.fetchRegistry(config);
+ if (!registry) continue;
+
+ for (const remoteTemplate of registry.templates) {
+ const template = templateRegistryService.convertToComposeTemplate(remoteTemplate, config.name);
+ templates.push(template);
+ }
+ }
+
+ return templates;
+ }
+
+ /**
+ * Load template content and environment
+ */
+ async loadTemplateContent(template: ComposeTemplate): Promise<{ content: string; envContent?: string }> {
+ if (template.isRemote && template.metadata?.remoteUrl) {
+ const content = await templateRegistryService.fetchTemplateContent({
+ id: template.id,
+ name: template.name,
+ description: template.description,
+ version: template.metadata.version || '1.0.0',
+ compose_url: template.metadata.remoteUrl,
+ env_url: template.metadata.envUrl,
+ updated_at: template.metadata.updatedAt || new Date().toISOString()
+ });
+
+ let envContent: string | undefined;
+ if (template.metadata.envUrl) {
+ try {
+ envContent = (await templateRegistryService.fetchEnvContent(template.metadata.envUrl)) || undefined;
+ } catch (error) {
+ // Only log if it's not a 404 - missing env files are expected
+ if (error instanceof Error && !error.message.includes('404') && !error.message.includes('Not Found')) {
+ console.error('Error fetching env content:', error);
+ }
+ envContent = undefined;
+ }
+ }
+
+ return {
+ content: content || template.content,
+ envContent: envContent || template.envContent
+ };
+ }
+ return {
+ content: template.content,
+ envContent: template.envContent
+ };
+ }
+
+ /**
+ * Load just the compose content for a template (without env file)
+ */
+ async loadComposeContent(template: ComposeTemplate): Promise<string> {
+ if (!template.isRemote) {
+ return template.content;
+ }
+
+ // For remote templates, fetch the compose content
+ if (!template.metadata?.remoteUrl) {
+ throw new Error('Remote template missing compose URL');
+ }
+
+ const remoteTemplate = {
+ id: template.id,
+ name: template.name,
+ description: template.description,
+ version: template.metadata.version || '1.0.0',
+ compose_url: template.metadata.remoteUrl,
+ env_url: template.metadata.envUrl,
+ updated_at: template.metadata.updatedAt || new Date().toISOString()
+ };
+
+ const content = await templateRegistryService.fetchTemplateContent(remoteTemplate);
+ if (!content) {
+ throw new Error('Failed to fetch template content');
+ }
+
+ return content;
+ }
+
+ /**
+ * Add a registry configuration
+ */
+ async addRegistry(config: TemplateRegistryConfig): Promise<void> {
+ const settings = await getSettings();
+ settings.templateRegistries = settings.templateRegistries || [];
+
+ // Check if registry with same URL already exists
+ const isDuplicate = settings.templateRegistries.some((existingRegistry) => existingRegistry.url === config.url);
+
+ // Only add if not a duplicate
+ if (!isDuplicate) {
+ settings.templateRegistries.push(config);
+ }
+
+ await saveSettings(settings);
+ }
+
+ /**
+ * Remove a registry configuration
+ */
+ async removeRegistry(url: string): Promise<void> {
+ const settings = await getSettings();
+ settings.templateRegistries = (settings.templateRegistries || []).filter((c) => c.url !== url);
+ await saveSettings(settings);
+ }
+
+ /**
+ * Update a registry configuration
+ */
+ async updateRegistry(url: string, updates: Partial<TemplateRegistryConfig>): Promise<void> {
+ const settings = await getSettings();
+ const registryIndex = (settings.templateRegistries || []).findIndex((c) => c.url === url);
+ if (registryIndex !== -1) {
+ settings.templateRegistries[registryIndex] = {
+ ...settings.templateRegistries[registryIndex],
+ ...updates
+ };
+ await saveSettings(settings);
+ }
+ }
+
+ /**
+ * Get all registry configurations
+ */
+ async getRegistries(): Promise<TemplateRegistryConfig[]> {
+ const settings = await getSettings();
+ return settings.templateRegistries || [];
+ }
+}
diff --git a/src/lib/stores/settings-store.ts b/src/lib/stores/settings-store.ts
index a5004af74..9a61bb581 100644
--- a/src/lib/stores/settings-store.ts
+++ b/src/lib/stores/settings-store.ts
@@ -33,6 +33,7 @@ export const settingsStore = writable<Settings>({
pollingInterval: 10,
pruneMode: 'all',
registryCredentials: [],
+ templateRegistries: [],
auth: {
localAuthEnabled: true,
oidcEnabled: false,
diff --git a/src/lib/types/settings.type.ts b/src/lib/types/settings.type.ts
index 05048cb5e..f4b1b5b50 100644
--- a/src/lib/types/settings.type.ts
+++ b/src/lib/types/settings.type.ts
@@ -33,6 +33,14 @@ export interface Onboarding {
};
}
+export interface TemplateRegistryConfig {
+ url: string;
+ name: string;
+ enabled: boolean;
+ last_updated?: string;
+ cache_ttl?: number;
+}
+
export interface Settings {
dockerHost: string;
stacksDirectory: string;
@@ -42,6 +50,7 @@ export interface Settings {
pollingInterval: number;
pruneMode: 'all' | 'dangling' | undefined;
registryCredentials: RegistryCredential[];
+ templateRegistries: TemplateRegistryConfig[]; // Add this new field
auth: AuthSettings;
onboarding?: Onboarding;
baseServerUrl?: string;
diff --git a/src/lib/types/template-registry.ts b/src/lib/types/template-registry.ts
new file mode 100644
index 000000000..82c2a8809
--- /dev/null
+++ b/src/lib/types/template-registry.ts
@@ -0,0 +1,28 @@
+export interface TemplateRegistry {
+ name: string;
+ description: string;
+ version: string;
+ templates: RemoteTemplate[];
+}
+
+export interface RemoteTemplate {
+ id: string;
+ name: string;
+ description: string;
+ version: string;
+ author?: string;
+ tags?: string[];
+ compose_url: string;
+ env_url?: string;
+ documentation_url?: string;
+ icon_url?: string;
+ updated_at: string;
+}
+
+export interface TemplateRegistryConfig {
+ url: string;
+ name: string;
+ enabled: boolean;
+ last_updated?: string;
+ cache_ttl?: number;
+}
diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte
index 412640e02..e5ef6584b 100644
--- a/src/routes/+layout.svelte
+++ b/src/routes/+layout.svelte
@@ -1,7 +1,7 @@
<script lang="ts">
import '../app.css';
import { ModeWatcher } from 'mode-watcher';
- import Nav from '$lib/components/navbar.svelte';
+ import Nav from '$lib/components/sidebar.svelte';
import { Toaster } from '$lib/components/ui/sonner/index.js';
import { navigating, page } from '$app/state';
import ConfirmDialog from '$lib/components/confirm-dialog/confirm-dialog.svelte';
diff --git a/src/routes/api/templates/+server.ts b/src/routes/api/templates/+server.ts
new file mode 100644
index 000000000..be7a629ea
--- /dev/null
+++ b/src/routes/api/templates/+server.ts
@@ -0,0 +1,160 @@
+import { json, error } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { TemplateService } from '$lib/services/template-service';
+
+const templateService = new TemplateService();
+
+export const GET: RequestHandler = async ({ url }) => {
+ // Check if this is a proxy request for external registries
+ const registryUrl = url.searchParams.get('url');
+
+ if (registryUrl) {
+ // Handle proxy request for external registry
+ try {
+ // Validate URL format
+ const urlObj = new URL(registryUrl);
+ if (!['http:', 'https:'].includes(urlObj.protocol)) {
+ return error(400, { message: 'Invalid URL protocol. Only HTTP and HTTPS are allowed.' });
+ }
+
+ console.log(`Proxying template registry request to: ${registryUrl}`);
+
+ const response = await fetch(registryUrl, {
+ headers: {
+ 'User-Agent': 'Arcane-Template-Registry/1.0',
+ Accept: 'application/json, text/plain'
+ },
+ // Add timeout to prevent hanging requests
+ signal: AbortSignal.timeout(30000) // 30 second timeout
+ });
+
+ if (!response.ok) {
+ console.error(`Failed to fetch registry from ${registryUrl}: ${response.status} ${response.statusText}`);
+ return error(response.status, {
+ message: `Failed to fetch registry: ${response.statusText}`
+ });
+ }
+
+ const contentType = response.headers.get('content-type');
+ // GitHub serves JSON files with text/plain content type
+ const allowedHosts = ['raw.githubusercontent.com', 'githubusercontent.com'];
+ const isGitHub = allowedHosts.includes(urlObj.host);
+ const isValidContentType = contentType?.includes('application/json') || contentType?.includes('text/json') || (isGitHub && contentType?.includes('text/plain'));
+
+ if (!isValidContentType) {
+ console.warn(`Registry at ${registryUrl} returned unexpected content type: ${contentType}`);
+ }
+
+ let data;
+ try {
+ data = await response.json();
+ } catch (jsonError) {
+ return error(400, { message: 'Invalid JSON response from registry' });
+ }
+
+ // Add CORS headers to allow client-side access
+ return json(data, {
+ headers: {
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Methods': 'GET',
+ 'Access-Control-Allow-Headers': 'Content-Type'
+ }
+ });
+ } catch (fetchError) {
+ console.error(`Error fetching template registry from ${registryUrl}:`, fetchError);
+
+ if (fetchError instanceof TypeError && fetchError.message.includes('fetch')) {
+ return error(503, { message: 'Unable to reach the registry server. Please check the URL and try again.' });
+ }
+
+ return error(500, {
+ message: fetchError instanceof Error ? fetchError.message : 'Failed to fetch registry'
+ });
+ }
+ }
+
+ // Handle template list requests
+ try {
+ const type = url.searchParams.get('type');
+
+ let templates;
+ switch (type) {
+ case 'local':
+ templates = await templateService.loadLocalTemplates();
+ break;
+ case 'remote':
+ templates = await templateService.loadRemoteTemplates();
+ break;
+ default:
+ templates = await templateService.loadAllTemplates();
+ }
+
+ return json(templates);
+ } catch (err) {
+ console.error('Error fetching templates:', err);
+ return error(500, { message: 'Failed to fetch templates' });
+ }
+};
+
+export const POST: RequestHandler = async ({ request }) => {
+ const body = await request.json();
+
+ // Check if this is a proxy request for content
+ if (body.url && body.content) {
+ try {
+ console.log(`Proxying template content request to: ${body.url}`);
+
+ const response = await fetch(body.url, {
+ headers: {
+ 'User-Agent': 'Arcane-Template-Registry/1.0',
+ Accept: 'text/plain, application/x-yaml, text/yaml, */*'
+ },
+ signal: AbortSignal.timeout(30000)
+ });
+
+ if (!response.ok) {
+ return error(response.status, {
+ message: `Failed to fetch content: ${response.statusText}`
+ });
+ }
+
+ const data = await response.text();
+
+ return json(
+ { content: data },
+ {
+ headers: {
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Methods': 'POST',
+ 'Access-Control-Allow-Headers': 'Content-Type'
+ }
+ }
+ );
+ } catch (fetchError) {
+ console.error(`Error fetching template content from ${body.url}:`, fetchError);
+ return error(500, {
+ message: fetchError instanceof Error ? fetchError.message : 'Failed to fetch content'
+ });
+ }
+ }
+
+ // Handle template creation
+ try {
+ const { name, content, description, envContent } = body;
+
+ if (!name || !content) {
+ return error(400, { message: 'Name and content are required' });
+ }
+
+ await TemplateService.createTemplate(name, content, description, envContent);
+
+ return json({
+ success: true,
+ message: 'Template created successfully',
+ id: name.toLowerCase().replace(/[^a-z0-9-]/g, '-')
+ });
+ } catch (err) {
+ console.error('Error creating template:', err);
+ return error(500, { message: 'Failed to create template' });
+ }
+};
diff --git a/src/routes/api/templates/[id]/+server.ts b/src/routes/api/templates/[id]/+server.ts
new file mode 100644
index 000000000..4694012c2
--- /dev/null
+++ b/src/routes/api/templates/[id]/+server.ts
@@ -0,0 +1,58 @@
+import { json, error } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { TemplateService } from '$lib/services/template-service';
+
+export const GET: RequestHandler = async ({ params }) => {
+ try {
+ const { id } = params;
+ const templates = await TemplateService.getComposeTemplates();
+ const template = templates.find((t) => t.id === id);
+
+ if (!template) {
+ return error(404, { message: 'Template not found' });
+ }
+
+ return json(template);
+ } catch (err) {
+ console.error('Error fetching template:', err);
+ return error(500, { message: 'Failed to fetch template' });
+ }
+};
+
+export const PUT: RequestHandler = async ({ params, request }) => {
+ try {
+ const { id } = params;
+ const { name, content, description, envContent } = await request.json();
+
+ if (!name || !content) {
+ return error(400, { message: 'Name and content are required' });
+ }
+
+ // Delete old template and create new one
+ await TemplateService.deleteTemplate(id);
+ await TemplateService.createTemplate(name, content, description, envContent);
+
+ return json({
+ success: true,
+ message: 'Template updated successfully'
+ });
+ } catch (err) {
+ console.error('Error updating template:', err);
+ return error(500, { message: 'Failed to update template' });
+ }
+};
+
+export const DELETE: RequestHandler = async ({ params }) => {
+ try {
+ const { id } = params;
+ await TemplateService.deleteTemplate(id);
+
+ return json({
+ success: true,
+ message: 'Template deleted successfully'
+ });
+ } catch (err) {
+ console.error('Error deleting template:', err);
+ return error(500, { message: 'Failed to delete template' });
+ }
+};
diff --git a/src/routes/api/templates/[id]/content/+server.ts b/src/routes/api/templates/[id]/content/+server.ts
new file mode 100644
index 000000000..eeb75e8bb
--- /dev/null
+++ b/src/routes/api/templates/[id]/content/+server.ts
@@ -0,0 +1,32 @@
+import { json, error } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { TemplateService } from '$lib/services/template-service';
+
+const templateService = new TemplateService();
+
+export const GET: RequestHandler = async ({ params }) => {
+ try {
+ const { id } = params;
+ const templates = await templateService.loadAllTemplates();
+ const template = templates.find((t) => t.id === id);
+
+ if (!template) {
+ return error(404, { message: 'Template not found' });
+ }
+
+ const templateContent = await templateService.loadTemplateContent(template);
+
+ return json({
+ id: template.id,
+ name: template.name,
+ description: template.description,
+ content: templateContent.content,
+ envContent: templateContent.envContent,
+ isRemote: template.isRemote,
+ metadata: template.metadata
+ });
+ } catch (err) {
+ console.error('Error fetching template content:', err);
+ return error(500, { message: 'Failed to fetch template content' });
+ }
+};
diff --git a/src/routes/api/templates/[id]/download/+server.ts b/src/routes/api/templates/[id]/download/+server.ts
new file mode 100644
index 000000000..37a17e568
--- /dev/null
+++ b/src/routes/api/templates/[id]/download/+server.ts
@@ -0,0 +1,81 @@
+import { json, error } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { TemplateService } from '$lib/services/template-service';
+
+const templateService = new TemplateService();
+
+export const POST: RequestHandler = async ({ params, request }) => {
+ try {
+ const { id } = params;
+ const body = await request.json().catch(() => ({}));
+ const { localName } = body;
+
+ console.log(`Download request for template: ${id}`);
+
+ // Find the remote template
+ const allTemplates = await templateService.loadAllTemplates();
+ const template = allTemplates.find((t) => t.id === id && t.isRemote);
+
+ if (!template || !template.isRemote) {
+ console.error(`Remote template not found: ${id}`);
+ return error(404, { message: 'Remote template not found' });
+ }
+
+ console.log(`Found remote template: ${template.name}`);
+
+ // Load the template content (this handles fetching from remote URLs)
+ let templateContent;
+ try {
+ templateContent = await templateService.loadTemplateContent(template);
+ } catch (contentError) {
+ console.error(`Error loading template content for ${id}:`, contentError);
+
+ // If env file fails but compose succeeds, continue with just compose content
+ if (contentError instanceof Error && contentError.message.includes('environment content')) {
+ console.warn(`Environment file failed for ${template.name}, continuing with compose content only`);
+ // Try to load just the compose content without env
+ try {
+ const composeContent = await templateService.loadComposeContent(template);
+ templateContent = {
+ content: composeContent,
+ envContent: undefined
+ };
+ } catch (composeError) {
+ console.error(`Failed to load compose content for ${id}:`, composeError);
+ return error(500, { message: 'Failed to load template content' });
+ }
+ } else {
+ return error(500, { message: 'Failed to load template content' });
+ }
+ }
+
+ if (!templateContent.content) {
+ return error(500, { message: 'Template content is empty' });
+ }
+
+ // Create local template with downloaded content
+ const savedName = localName || template.name;
+ const localId = savedName.toLowerCase().replace(/[^a-z0-9-]/g, '-');
+
+ try {
+ await TemplateService.createTemplate(savedName, templateContent.content, template.description, templateContent.envContent);
+
+ console.log(`Template saved locally as: ${savedName}`);
+
+ return json({
+ success: true,
+ message: `Template "${savedName}" downloaded and saved locally`,
+ localId,
+ hasEnv: !!templateContent.envContent
+ });
+ } catch (saveError) {
+ console.error(`Error saving template locally:`, saveError);
+ return error(500, { message: 'Failed to save template locally' });
+ }
+ } catch (err) {
+ console.error('Error in download endpoint:', err);
+ return error(500, {
+ message: err instanceof Error ? err.message : 'Failed to download template'
+ });
+ }
+};
diff --git a/src/routes/api/templates/registries/+server.ts b/src/routes/api/templates/registries/+server.ts
new file mode 100644
index 000000000..52dfa90e0
--- /dev/null
+++ b/src/routes/api/templates/registries/+server.ts
@@ -0,0 +1,44 @@
+import { json, error } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { TemplateService } from '$lib/services/template-service';
+import { templateRegistryService } from '$lib/services/template-registry-service';
+import type { TemplateRegistryConfig } from '$lib/types/settings.type';
+
+const templateService = new TemplateService();
+
+export const GET: RequestHandler = async () => {
+ try {
+ const registries = await templateService.getRegistries();
+ return json(registries);
+ } catch (err) {
+ console.error('Error fetching registries:', err);
+ return error(500, { message: 'Failed to fetch registries' });
+ }
+};
+
+export const POST: RequestHandler = async ({ request }) => {
+ try {
+ const config: TemplateRegistryConfig = await request.json();
+
+ if (!config.url || !config.name) {
+ return error(400, { message: 'URL and name are required' });
+ }
+
+ // Test the registry before adding
+ const registry = await templateRegistryService.fetchRegistry(config);
+ if (!registry) {
+ return error(400, { message: 'Failed to fetch registry or invalid format' });
+ }
+
+ await templateService.addRegistry(config);
+
+ return json({
+ success: true,
+ message: 'Registry added successfully',
+ registry: config
+ });
+ } catch (err) {
+ console.error('Error adding registry:', err);
+ return error(500, { message: 'Failed to add registry' });
+ }
+};
diff --git a/src/routes/api/templates/registries/test/+server.ts b/src/routes/api/templates/registries/test/+server.ts
new file mode 100644
index 000000000..895807007
--- /dev/null
+++ b/src/routes/api/templates/registries/test/+server.ts
@@ -0,0 +1,39 @@
+import { json, error } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { templateRegistryService } from '$lib/services/template-registry-service';
+
+export const POST: RequestHandler = async ({ request }) => {
+ try {
+ const { url } = await request.json();
+
+ if (!url) {
+ return error(400, { message: 'URL is required' });
+ }
+
+ const config = {
+ url,
+ name: 'Test Registry',
+ enabled: true
+ };
+
+ const registry = await templateRegistryService.fetchRegistry(config);
+
+ if (!registry) {
+ return error(400, { message: 'Failed to fetch registry or invalid format' });
+ }
+
+ return json({
+ success: true,
+ message: 'Registry is valid and accessible',
+ registry: {
+ name: registry.name,
+ description: registry.description,
+ version: registry.version,
+ templateCount: registry.templates.length
+ }
+ });
+ } catch (err) {
+ console.error('Error testing registry:', err);
+ return error(500, { message: 'Failed to test registry' });
+ }
+};
diff --git a/src/routes/api/templates/stats/+server.ts b/src/routes/api/templates/stats/+server.ts
new file mode 100644
index 000000000..2412b4f77
--- /dev/null
+++ b/src/routes/api/templates/stats/+server.ts
@@ -0,0 +1,28 @@
+import { json, error } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { TemplateService } from '$lib/services/template-service';
+
+const templateService = new TemplateService();
+
+export const GET: RequestHandler = async () => {
+ try {
+ const [allTemplates, registries] = await Promise.all([templateService.loadAllTemplates(), templateService.getRegistries()]);
+
+ const localTemplates = allTemplates.filter((t) => !t.isRemote);
+ const remoteTemplates = allTemplates.filter((t) => t.isRemote);
+
+ const stats = {
+ total: allTemplates.length,
+ local: localTemplates.length,
+ remote: remoteTemplates.length,
+ registries: registries.length,
+ enabledRegistries: registries.filter((r) => r.enabled).length,
+ templatesWithEnv: allTemplates.filter((t) => t.envContent || t.metadata?.envUrl).length
+ };
+
+ return json(stats);
+ } catch (err) {
+ console.error('Error fetching template stats:', err);
+ return error(500, { message: 'Failed to fetch template statistics' });
+ }
+};
diff --git a/src/routes/settings/templates/+page.server.ts b/src/routes/settings/templates/+page.server.ts
new file mode 100644
index 000000000..f5e6cce57
--- /dev/null
+++ b/src/routes/settings/templates/+page.server.ts
@@ -0,0 +1,33 @@
+import { TemplateService } from '$lib/services/template-service';
+import { getSettings } from '$lib/services/settings-service';
+import { templateRegistryService } from '$lib/services/template-registry-service';
+import { fail } from '@sveltejs/kit';
+import type { Actions, PageServerLoad } from './$types';
+import type { TemplateRegistryConfig } from '$lib/types/settings.type';
+
+export const load: PageServerLoad = async () => {
+ try {
+ const templateService = new TemplateService();
+ const settings = await getSettings();
+
+ const templates = await templateService.loadAllTemplates();
+
+ const localTemplateCount = templates.filter((t) => !t.isRemote).length;
+ const remoteTemplateCount = templates.filter((t) => t.isRemote).length;
+
+ return {
+ settings,
+ localTemplateCount,
+ remoteTemplateCount
+ };
+ } catch (error) {
+ console.error('Error loading template settings:', error);
+ const fallbackSettings = await getSettings();
+ return {
+ settings: fallbackSettings,
+ localTemplateCount: 0,
+ remoteTemplateCount: 0,
+ error: error instanceof Error ? error.message : 'Failed to load template data'
+ };
+ }
+};
diff --git a/src/routes/settings/templates/+page.svelte b/src/routes/settings/templates/+page.svelte
new file mode 100644
index 000000000..07aed483e
--- /dev/null
+++ b/src/routes/settings/templates/+page.svelte
@@ -0,0 +1,366 @@
+<script lang="ts">
+ import { Button } from '$lib/components/ui/button/index.js';
+ import { Input } from '$lib/components/ui/input/index.js';
+ import { Label } from '$lib/components/ui/label/index.js';
+ import { Card } from '$lib/components/ui/card/index.js';
+ import { Badge } from '$lib/components/ui/badge/index.js';
+ import * as Alert from '$lib/components/ui/alert/index.js';
+ import { Separator } from '$lib/components/ui/separator/index.js';
+ import { Trash2, Plus, ExternalLink, RefreshCw, FileText, Globe, FolderOpen, Save, Users, Copy } from '@lucide/svelte';
+ import type { PageData } from './$types';
+ import { settingsStore, saveSettingsToServer, updateSettingsStore } from '$lib/stores/settings-store';
+ import { templateRegistryService } from '$lib/services/template-registry-service';
+ import type { TemplateRegistryConfig } from '$lib/types/settings.type';
+ import { toast } from 'svelte-sonner';
+ import { invalidateAll } from '$app/navigation';
+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+
+ let { data }: { data: PageData } = $props();
+
+ // Form state - only need URL now
+ let newRegistryUrl = $state('');
+
+ // Loading states
+ let isLoading = $state({
+ saving: false,
+ addingRegistry: false,
+ refreshing: new Set<string>(),
+ removing: new Set<string>()
+ });
+
+ // Initialize settings from page data
+ $effect(() => {
+ if (data.settings) {
+ updateSettingsStore(data.settings);
+ }
+ });
+
+ // Get template registries from settings store
+ const templateRegistries = $derived($settingsStore.templateRegistries || []);
+
+ // Helper function to save settings and handle result
+ async function saveSettingsAndHandle(successMessage: string) {
+ const result = await tryCatch(saveSettingsToServer());
+ if (result.error) {
+ toast.error(result.error.message || 'Failed to save settings');
+ return false;
+ } else {
+ toast.success(successMessage);
+ await invalidateAll();
+ return true;
+ }
+ }
+
+ // Add registry function
+ async function addRegistry() {
+ if (!newRegistryUrl.trim()) {
+ toast.error('Registry URL is required');
+ return;
+ }
+
+ if (isLoading.addingRegistry) return;
+ isLoading.addingRegistry = true;
+
+ try {
+ // Test the registry first to get its name
+ const testConfig: TemplateRegistryConfig = {
+ url: newRegistryUrl.trim(),
+ name: 'Loading...', // Temporary name
+ enabled: true
+ };
+
+ console.log('Testing registry URL:', testConfig.url);
+ const registry = await templateRegistryService.fetchRegistry(testConfig);
+ if (!registry) {
+ toast.error('Failed to fetch registry or invalid format');
+ return;
+ }
+
+ // Create config with the registry's actual name
+ const config: TemplateRegistryConfig = {
+ url: newRegistryUrl.trim(),
+ name: registry.name, // Use name from registry JSON
+ enabled: true
+ };
+
+ console.log('Registry test successful, adding to store with name:', registry.name);
+
+ // Add to settings store
+ settingsStore.update((settings) => ({
+ ...settings,
+ templateRegistries: [...(settings.templateRegistries || []), config]
+ }));
+
+ // Save immediately
+ const saved = await saveSettingsAndHandle(`Registry "${registry.name}" added and saved successfully`);
+ if (saved) {
+ // Clear form only if save was successful
+ newRegistryUrl = '';
+ }
+ } catch (error) {
+ console.error('Error adding registry:', error);
+ toast.error(error instanceof Error ? error.message : 'Failed to add registry');
+ } finally {
+ isLoading.addingRegistry = false;
+ }
+ }
+
+ // Remove registry function
+ async function removeRegistry(url: string) {
+ if (isLoading.removing.has(url)) return;
+ isLoading.removing.add(url);
+
+ try {
+ settingsStore.update((settings) => ({
+ ...settings,
+ templateRegistries: (settings.templateRegistries || []).filter((r) => r.url !== url)
+ }));
+
+ // Save immediately
+ await saveSettingsAndHandle('Registry removed and saved successfully');
+ } catch (error) {
+ toast.error('Failed to remove registry');
+ } finally {
+ isLoading.removing.delete(url);
+ }
+ }
+
+ // Refresh registry function
+ async function refreshRegistry(url: string) {
+ if (isLoading.refreshing.has(url)) return;
+ isLoading.refreshing.add(url);
+
+ try {
+ const registries = $settingsStore.templateRegistries || [];
+ const config = registries.find((r) => r.url === url);
+
+ if (!config) {
+ toast.error('Registry not found');
+ return;
+ }
+
+ // Clear cache and refetch
+ templateRegistryService.clearCache();
+ const registry = await templateRegistryService.fetchRegistry(config);
+
+ if (!registry) {
+ toast.error('Failed to refresh registry');
+ return;
+ }
+
+ // Update last_updated timestamp and name (in case it changed)
+ settingsStore.update((settings) => ({
+ ...settings,
+ templateRegistries: (settings.templateRegistries || []).map((r) =>
+ r.url === url
+ ? {
+ ...r,
+ name: registry.name, // Update name from registry
+ last_updated: new Date().toISOString()
+ }
+ : r
+ )
+ }));
+
+ // Save immediately
+ await saveSettingsAndHandle('Registry refreshed and saved successfully');
+ } catch (error) {
+ toast.error('Failed to refresh registry');
+ } finally {
+ isLoading.refreshing.delete(url);
+ }
+ }
+
+ // Manual save settings function (for any other changes)
+ async function saveSettings() {
+ if (isLoading.saving) return;
+ isLoading.saving = true;
+
+ console.log('Saving settings to server:', $settingsStore);
+
+ handleApiResultWithCallbacks({
+ result: await tryCatch(saveSettingsToServer()),
+ message: 'Error Saving Settings',
+ setLoadingState: (value) => (isLoading.saving = value),
+ onSuccess: async () => {
+ toast.success('Settings saved successfully');
+ await invalidateAll();
+ }
+ });
+ }
+
+ function copyToClipboard(text: string) {
+ navigator.clipboard
+ .writeText(text)
+ .then(() => {
+ toast.success('Copied to clipboard');
+ })
+ .catch(() => {
+ toast.error('Failed to copy');
+ });
+ }
+</script>
+
+<svelte:head>
+ <title>Template Settings - Arcane</title>
+</svelte:head>
+
+<div class="space-y-6">
+ <div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4">
+ <div>
+ <h1 class="text-3xl font-bold tracking-tight">Template Settings</h1>
+ <p class="text-sm text-muted-foreground mt-1">
+ Manage Docker Compose template sources and registries
+ <a href="https://arcane.ofkm.dev/docs/templates/use-templates" class="text-primary hover:underline ml-1">→ Learn more</a>
+ </p>
+ </div>
+
+ <!-- Keep save button for any future manual settings that might be added -->
+ <Button onclick={saveSettings} disabled={isLoading.saving} class="h-10 arcane-button-save" variant="outline">
+ {#if isLoading.saving}
+ <RefreshCw class="animate-spin size-4" />
+ Saving...
+ {:else}
+ <Save class="size-4" />
+ Save Settings
+ {/if}
+ </Button>
+ </div>
+
+ <!-- Template Statistics -->
+ <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
+ <Card class="p-4">
+ <div class="flex items-center gap-3">
+ <FolderOpen class="size-8 text-blue-500" />
+ <div>
+ <p class="text-2xl font-bold">{data.localTemplateCount}</p>
+ <p class="text-sm text-muted-foreground">Local Templates</p>
+ </div>
+ </div>
+ </Card>
+ <Card class="p-4">
+ <div class="flex items-center gap-3">
+ <Globe class="size-8 text-green-500" />
+ <div>
+ <p class="text-2xl font-bold">{data.remoteTemplateCount}</p>
+ <p class="text-sm text-muted-foreground">Remote Templates</p>
+ </div>
+ </div>
+ </Card>
+ <Card class="p-4">
+ <div class="flex items-center gap-3">
+ <FileText class="size-8 text-purple-500" />
+ <div>
+ <p class="text-2xl font-bold">{templateRegistries.length}</p>
+ <p class="text-sm text-muted-foreground">Registries</p>
+ </div>
+ </div>
+ </Card>
+ </div>
+
+ <Separator />
+
+ <!-- Local Templates Info -->
+ <div class="space-y-4">
+ <h2 class="text-xl font-semibold">Local Templates</h2>
+ <Alert.Root>
+ <FolderOpen class="size-4" />
+ <Alert.Title>Local Template Directory</Alert.Title>
+ <Alert.Description>
+ Place your custom Docker Compose templates in the <code class="bg-muted px-1 rounded text-xs">data/templates/compose/</code> directory. Templates should be YAML files with a descriptive filename. You can also include matching <code class="bg-muted px-1 rounded text-xs">.env</code> files for environment variables.
+ </Alert.Description>
+ </Alert.Root>
+ </div>
+
+ <Separator />
+
+ <!-- Remote Template Registries -->
+ <div class="space-y-4">
+ <div class="flex items-center justify-between">
+ <h2 class="text-xl font-semibold">Remote Template Registries</h2>
+ </div>
+
+ <Alert.Root>
+ <Globe class="size-4" />
+ <Alert.Title>Remote Registries</Alert.Title>
+ <Alert.Description>Add remote template registries to access community templates. Registry names are automatically detected from the JSON manifest. Changes are saved automatically.</Alert.Description>
+ </Alert.Root>
+
+ <Alert.Root class="border-blue-200 bg-blue-50 dark:border-blue-800 dark:bg-blue-950">
+ <Users class="size-4" />
+ <Alert.Title>Community Registry</Alert.Title>
+ <Alert.Description class="space-y-2">
+ <p>Get started quickly with our community registry containing popular templates:</p>
+ <div class="flex items-center gap-2 mt-2">
+ <code class="bg-white dark:bg-gray-800 px-2 py-1 rounded text-xs"> https://raw.githubusercontent.com/ofkm/arcane-templates/main/registry.json </code>
+ <Button size="sm" variant="outline" onclick={() => copyToClipboard('https://raw.githubusercontent.com/ofkm/arcane-templates/main/registry.json')}>
+ <Copy class="size-3 mr-1" />
+ Copy
+ </Button>
+ </div>
+ </Alert.Description>
+ </Alert.Root>
+
+ <!-- Add New Registry Form -->
+ <Card class="p-4">
+ <h3 class="font-medium mb-3">Add Registry</h3>
+ <div class="space-y-3">
+ <div>
+ <Label for="url">Registry URL</Label>
+ <Input id="url" bind:value={newRegistryUrl} type="url" placeholder="https://raw.githubusercontent.com/username/repo/main/registry.json" disabled={isLoading.addingRegistry} required />
+ <p class="text-xs text-muted-foreground mt-1">The registry name will be automatically detected from the JSON file</p>
+ </div>
+ <Button onclick={addRegistry} disabled={isLoading.addingRegistry || !newRegistryUrl.trim()}>
+ <Plus class="size-4 mr-2" />
+ {isLoading.addingRegistry ? 'Testing & Adding...' : 'Add Registry'}
+ </Button>
+ </div>
+ </Card>
+
+ <!-- Registry List -->
+ {#if templateRegistries.length > 0}
+ <div class="space-y-3">
+ {#each templateRegistries as registry}
+ <Card class="p-4">
+ <div class="flex items-center justify-between">
+ <div class="flex-1">
+ <div class="flex items-center gap-2 mb-1">
+ <h4 class="font-medium">{registry.name}</h4>
+ <Badge variant={registry.enabled ? 'default' : 'secondary'}>
+ {registry.enabled ? 'Enabled' : 'Disabled'}
+ </Badge>
+ </div>
+ <p class="text-sm text-muted-foreground break-all">{registry.url}</p>
+ {#if registry.last_updated}
+ <p class="text-xs text-muted-foreground mt-1">
+ Last updated: {new Date(registry.last_updated).toLocaleString()}
+ </p>
+ {/if}
+ </div>
+ <div class="flex items-center gap-2">
+ <Button variant="outline" size="sm" onclick={() => refreshRegistry(registry.url)} disabled={isLoading.refreshing.has(registry.url)}>
+ <RefreshCw class={`size-4 ${isLoading.refreshing.has(registry.url) ? 'animate-spin' : ''}`} />
+ </Button>
+
+ <Button variant="outline" size="sm" onclick={() => window.open(registry.url, '_blank')}>
+ <ExternalLink class="size-4" />
+ </Button>
+
+ <Button variant="destructive" size="sm" onclick={() => removeRegistry(registry.url)} disabled={isLoading.removing.has(registry.url)}>
+ <Trash2 class="size-4" />
+ </Button>
+ </div>
+ </div>
+ </Card>
+ {/each}
+ </div>
+ {:else}
+ <div class="text-center py-6 text-muted-foreground">
+ <Globe class="size-12 mx-auto mb-4 opacity-50" />
+ <p class="mb-2">No registries configured</p>
+ <p class="text-sm">Add a remote template registry to access community templates</p>
+ </div>
+ {/if}
+ </div>
+</div>
diff --git a/src/routes/stacks/new/+page.server.ts b/src/routes/stacks/new/+page.server.ts
index 45fd039dd..e45c73d51 100644
--- a/src/routes/stacks/new/+page.server.ts
+++ b/src/routes/stacks/new/+page.server.ts
@@ -1,5 +1,26 @@
+import { TemplateService } from '$lib/services/template-service';
+import { defaultComposeTemplate } from '$lib/constants';
import type { PageServerLoad } from './$types';
-export const load: PageServerLoad = async () => {
- return {};
-};
+export const load = (async () => {
+ try {
+ const templateService = new TemplateService();
+
+ const [allTemplates, envTemplate] = await Promise.all([templateService.loadAllTemplates(), TemplateService.getEnvTemplate()]);
+
+ return {
+ composeTemplates: allTemplates,
+ envTemplate,
+ defaultTemplate: defaultComposeTemplate
+ };
+ } catch (error) {
+ console.error('Error loading templates:', error);
+
+ // Return fallback data
+ return {
+ composeTemplates: [],
+ envTemplate: defaultComposeTemplate,
+ defaultTemplate: defaultComposeTemplate
+ };
+ }
+}) satisfies PageServerLoad;
diff --git a/src/routes/stacks/new/+page.svelte b/src/routes/stacks/new/+page.svelte
index ff367edd1..654386420 100644
--- a/src/routes/stacks/new/+page.svelte
+++ b/src/routes/stacks/new/+page.svelte
@@ -1,7 +1,7 @@
<script lang="ts">
import * as Card from '$lib/components/ui/card/index.js';
import { Button } from '$lib/components/ui/button/index.js';
- import { ArrowLeft, FileStack, Terminal, Copy, Wand2, Loader2 } from '@lucide/svelte';
+ import { ArrowLeft, FileStack, Terminal, Copy, Loader2, Wand } from '@lucide/svelte';
import * as Breadcrumb from '$lib/components/ui/breadcrumb/index.js';
import { Input } from '$lib/components/ui/input/index.js';
import { Label } from '$lib/components/ui/label/index.js';
@@ -18,16 +18,29 @@
import { Textarea } from '$lib/components/ui/textarea/index.js';
import DropdownCard from '$lib/components/dropdown-card.svelte';
import * as Resizable from '$lib/components/ui/resizable/index.js';
+ import TemplateSelectionDialog from '$lib/components/template-selection-dialog.svelte';
+ import type { ComposeTemplate } from '$lib/services/template-service';
+ import type { PageData } from './$types';
+
+ let { data }: { data: PageData } = $props();
const stackApi = new StackAPIService();
let saving = $state(false);
let converting = $state(false);
+ let showTemplateDialog = $state(false);
let name = $state('');
let composeContent = $state(defaultComposeTemplate);
- let envContent = $state(defaultEnvTemplate);
+ let envContent = $state(data.envTemplate || defaultEnvTemplate);
let dockerRunCommand = $state('');
+ // Initialize with default template if available
+ $effect(() => {
+ if (data.defaultTemplate && !composeContent) {
+ composeContent = data.defaultTemplate;
+ }
+ });
+
async function handleSubmit() {
handleApiResultWithCallbacks({
result: await tryCatch(stackApi.create(name, composeContent, envContent)),
@@ -69,6 +82,22 @@
});
}
+ function handleTemplateSelect(template: ComposeTemplate) {
+ composeContent = template.content;
+
+ // If template has environment content, use it
+ if (template.envContent) {
+ envContent = template.envContent;
+ }
+
+ // Auto-populate name if empty
+ if (!name.trim()) {
+ name = template.name.toLowerCase().replace(/[^a-z0-9-]/g, '-');
+ }
+
+ toast.success(`Template "${template.name}" loaded successfully!`);
+ }
+
const exampleCommands = ['docker run -d --name nginx -p 8080:80 -v nginx_data:/usr/share/nginx/html nginx:alpine', 'docker run -d --name postgres -e POSTGRES_DB=mydb -e POSTGRES_USER=user -e POSTGRES_PASSWORD=pass -v postgres_data:/var/lib/postgresql/data postgres:15', 'docker run -d --name redis -p 6379:6379 --restart unless-stopped redis:alpine'];
function useExample(command: string) {
@@ -113,7 +142,7 @@
<Loader2 class="mr-2 size-4 animate-spin" />
Converting...
{:else}
- <Wand2 class="mr-2 size-4" />
+ <Wand class="mr-2 size-4" />
Convert to Compose
{/if}
</Button>
@@ -146,7 +175,10 @@
<Card.Description>Create a new Docker Compose stack with environment variables</Card.Description>
</div>
</div>
- <ArcaneButton action="create" onClick={handleSubmit} loading={saving} disabled={!name || !composeContent} />
+ <div class="flex items-center gap-2">
+ <ArcaneButton action="template" onClick={() => (showTemplateDialog = true)} loading={saving} disabled={saving || converting} />
+ <ArcaneButton action="create" onClick={handleSubmit} loading={saving} disabled={!name || !composeContent} />
+ </div>
</div>
</Card.Header>
<Card.Content>
@@ -163,7 +195,7 @@
<div class="border rounded-md overflow-hidden mt-2 h-[550px]">
<YamlEditor bind:value={composeContent} readOnly={saving} />
</div>
- <p class="text-xs text-muted-foreground">Enter a valid compose.yaml file.</p>
+ <p class="text-xs text-muted-foreground">Enter a valid compose.yaml file or choose from templates using the "Use Template" button above.</p>
</div>
</Resizable.Pane>
<Resizable.Handle />
@@ -173,7 +205,13 @@
<div class="border rounded-md overflow-hidden mt-2 h-[550px]">
<EnvEditor bind:value={envContent} readOnly={saving} />
</div>
- <p class="text-xs text-muted-foreground">Define environment variables in KEY=value format. These will be saved as a .env file in the stack directory.</p>
+ <p class="text-xs text-muted-foreground">
+ {#if data.envTemplate}
+ Environment variables loaded from template. Modify as needed.
+ {:else}
+ Define environment variables in KEY=value format. These will be saved as a .env file in the stack directory.
+ {/if}
+ </p>
</div>
</Resizable.Pane>
</Resizable.PaneGroup>
@@ -188,3 +226,6 @@
</Card.Root>
</form>
</div>
+
+<!-- Template Selection Dialog -->
+<TemplateSelectionDialog bind:open={showTemplateDialog} templates={data.composeTemplates || []} onSelect={handleTemplateSelect} />
diff --git a/template-registry.json b/template-registry.json
new file mode 100644
index 000000000..ed7b84512
--- /dev/null
+++ b/template-registry.json
@@ -0,0 +1,32 @@
+{
+ "name": "Community Docker Templates",
+ "description": "A collection of popular Docker Compose templates",
+ "version": "1.0.0",
+ "templates": [
+ {
+ "id": "wordpress-mysql",
+ "name": "WordPress + MySQL",
+ "description": "WordPress blog with MySQL database",
+ "version": "1.0.0",
+ "author": "Community",
+ "tags": ["cms", "blog", "php", "mysql"],
+ "compose_url": "https://raw.githubusercontent.com/example/templates/main/wordpress/docker-compose.yml",
+ "env_url": "https://raw.githubusercontent.com/example/templates/main/wordpress/.env.example",
+ "documentation_url": "https://github.com/example/templates/tree/main/wordpress",
+ "icon_url": "https://example.com/icons/wordpress.svg",
+ "updated_at": "2025-05-28T10:00:00Z"
+ },
+ {
+ "id": "nextjs-postgres",
+ "name": "Next.js + PostgreSQL",
+ "description": "Next.js application with PostgreSQL database",
+ "version": "1.0.0",
+ "author": "Community",
+ "tags": ["react", "nextjs", "postgresql", "frontend"],
+ "compose_url": "https://raw.githubusercontent.com/example/templates/main/nextjs/docker-compose.yml",
+ "env_url": "https://raw.githubusercontent.com/example/templates/main/nextjs/.env.example",
+ "documentation_url": "https://github.com/example/templates/tree/main/nextjs",
+ "updated_at": "2025-05-28T09:30:00Z"
+ }
+ ]
+}