weeee💃

This commit is contained in:
VN 2024-10-15 08:35:05 +02:00
commit 143dac75ba
24 changed files with 6024 additions and 0 deletions

21
.gitignore vendored Normal file
View File

@ -0,0 +1,21 @@
node_modules
# Output
.output
.vercel
/.svelte-kit
/build
# OS
.DS_Store
Thumbs.db
# Env
.env
.env.*
!.env.example
!.env.test
# Vite
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

1
.npmrc Normal file
View File

@ -0,0 +1 @@
engine-strict=true

4
.prettierignore Normal file
View File

@ -0,0 +1,4 @@
# Package Managers
package-lock.json
pnpm-lock.yaml
yarn.lock

15
.prettierrc Normal file
View File

@ -0,0 +1,15 @@
{
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
"plugins": ["prettier-plugin-svelte", "prettier-plugin-tailwindcss"],
"overrides": [
{
"files": "*.svelte",
"options": {
"parser": "svelte"
}
}
]
}

38
README.md Normal file
View File

@ -0,0 +1,38 @@
# create-svelte
Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/main/packages/create-svelte).
## Creating a project
If you're seeing this, you've probably already done this step. Congrats!
```bash
# create a new project in the current directory
npm create svelte@latest
# create a new project in my-app
npm create svelte@latest my-app
```
## Developing
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
```bash
npm run dev
# or start the server and open the app in a new browser tab
npm run dev -- --open
```
## Building
To create a production version of your app:
```bash
npm run build
```
You can preview the production build with `npm run preview`.
> To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.

33
eslint.config.js Normal file
View File

@ -0,0 +1,33 @@
import js from '@eslint/js';
import ts from 'typescript-eslint';
import svelte from 'eslint-plugin-svelte';
import prettier from 'eslint-config-prettier';
import globals from 'globals';
/** @type {import('eslint').Linter.Config[]} */
export default [
js.configs.recommended,
...ts.configs.recommended,
...svelte.configs['flat/recommended'],
prettier,
...svelte.configs['flat/prettier'],
{
languageOptions: {
globals: {
...globals.browser,
...globals.node
}
}
},
{
files: ['**/*.svelte'],
languageOptions: {
parserOptions: {
parser: ts.parser
}
}
},
{
ignores: ['build/', '.svelte-kit/', 'dist/']
}
];

5315
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

47
package.json Normal file
View File

@ -0,0 +1,47 @@
{
"name": "caddyui",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"test": "npm run test:integration && npm run test:unit",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"lint": "prettier --check . && eslint .",
"format": "prettier --write .",
"test:integration": "playwright test",
"test:unit": "vitest"
},
"devDependencies": {
"@playwright/test": "^1.28.1",
"@sveltejs/adapter-auto": "^3.0.0",
"@sveltejs/kit": "^2.0.0",
"@sveltejs/vite-plugin-svelte": "^3.0.0",
"@tailwindcss/typography": "^0.5.14",
"@types/eslint": "^9.6.0",
"autoprefixer": "^10.4.20",
"eslint": "^9.0.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-svelte": "^2.36.0",
"flowbite": "^2.5.2",
"flowbite-svelte": "^0.46.23",
"flowbite-svelte-icons": "^1.6.2",
"globals": "^15.0.0",
"prettier": "^3.1.1",
"prettier-plugin-svelte": "^3.1.2",
"prettier-plugin-tailwindcss": "^0.6.5",
"svelte": "^4.2.7",
"svelte-check": "^4.0.0",
"tailwindcss": "^3.4.9",
"typescript": "^5.0.0",
"typescript-eslint": "^8.0.0",
"vite": "^5.0.3",
"vitest": "^2.0.0"
},
"type": "module",
"dependencies": {
"lucide-svelte": "^0.452.0"
}
}

12
playwright.config.ts Normal file
View File

@ -0,0 +1,12 @@
import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
webServer: {
command: 'npm run build && npm run preview',
port: 4173
},
testDir: 'tests',
testMatch: /(.+\.)?(test|spec)\.[jt]s/
};
export default config;

6
postcss.config.js Normal file
View File

@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {}
}
};

3
src/app.css Normal file
View File

@ -0,0 +1,3 @@
@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';

13
src/app.d.ts vendored Normal file
View File

@ -0,0 +1,13 @@
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};

12
src/app.html Normal file
View File

@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

7
src/index.test.ts Normal file
View File

@ -0,0 +1,7 @@
import { describe, it, expect } from 'vitest';
describe('sum test', () => {
it('adds 1 + 2 to equal 3', () => {
expect(1 + 2).toBe(3);
});
});

1
src/lib/index.ts Normal file
View File

@ -0,0 +1 @@
// place files you want to import through the `$lib` alias in this folder.

View File

@ -0,0 +1,5 @@
<script>
import '../app.css';
</script>
<slot></slot>

281
src/routes/+page.svelte Normal file
View File

@ -0,0 +1,281 @@
<script lang="ts">
import { onMount } from 'svelte';
import { CaddyService, configStore, upstreamsStore } from './CaddyService';
import {
Button,
Card,
Tabs,
TabItem,
Table,
TableBody,
TableBodyCell,
TableBodyRow,
TableHead,
TableHeadCell,
Modal,
Input,
Textarea,
Spinner
} from 'flowbite-svelte';
import { fly, fade } from 'svelte/transition';
import type { Upstream, CAInfo } from './CaddyService';
let config: Record<string, any> = {};
let upstreams: Upstream[] = [];
let caInfo: CAInfo | null = null;
let caCertificates: string = '';
let showConfigModal: boolean = false;
let showCAModal: boolean = false;
let loadingConfig: boolean = false;
let loadingUpstreams: boolean = false;
let newConfig: string = '';
let configPath: string = '';
let caId: string = 'local';
let activeTab: string = 'config';
configStore.subscribe((value) => (config = value));
upstreamsStore.subscribe((value) => (upstreams = value));
onMount(async () => {
await refreshData();
});
async function refreshData(): Promise<void> {
try {
loadingConfig = true;
await CaddyService.getConfig();
await CaddyService.getUpstreams();
} catch (error) {
alert(`Failed to refresh data: ${(error as Error).message}`);
} finally {
loadingConfig = false;
loadingUpstreams = false;
}
}
async function handleUpdateConfig(): Promise<void> {
try {
loadingConfig = true;
await CaddyService.updateConfig(configPath, JSON.parse(newConfig));
await refreshData();
showConfigModal = false;
} catch (error) {
alert(`Failed to update config: ${(error as Error).message}`);
} finally {
loadingConfig = false;
}
}
async function handleLoadConfig(): Promise<void> {
try {
loadingConfig = true;
await CaddyService.loadConfig(JSON.parse(newConfig));
await refreshData();
showConfigModal = false;
} catch (error) {
alert(`Failed to load config: ${(error as Error).message}`);
} finally {
loadingConfig = false;
}
}
async function handleStopServer(): Promise<void> {
if (confirm('Are you sure you want to stop the Caddy server?')) {
try {
await CaddyService.stopServer();
alert('Caddy server stopped successfully');
} catch (error) {
alert(`Failed to stop server: ${(error as Error).message}`);
}
}
}
async function handleGetCAInfo(): Promise<void> {
try {
caInfo = await CaddyService.getCAInfo(caId);
caCertificates = await CaddyService.getCACertificates(caId);
showCAModal = true;
} catch (error) {
alert(`Failed to get CA info: ${(error as Error).message}`);
}
}
function handleTabChange(tab: string) {
activeTab = tab;
}
import { Cog, ServerCrash, Shield, RefreshCw } from 'lucide-svelte';
</script>
<main class="container mx-auto p-4 bg-gray-50 min-h-screen">
<h1 class="text-4xl font-bold mb-6 text-caddy-green">Caddy UI</h1>
<Tabs style="pills">
<!-- Removed bind:active -->
<TabItem
open={activeTab === 'config'}
on:click={() => handleTabChange('config')}
title="Configuration"
class="flex items-center gap-2"
></TabItem>
<TabItem
open={activeTab === 'upstreams'}
on:click={() => handleTabChange('upstreams')}
title="Upstreams"
class="flex items-center gap-2"
></TabItem>
<TabItem
open={activeTab === 'ca_management'}
on:click={() => handleTabChange('ca_management')}
title="CA Management"
class="flex items-center gap-2"
></TabItem>
</Tabs>
<!-- Display content based on the activeTab -->
{#if activeTab === 'config'}
<div class="mt-6">
<Card class="shadow-lg">
<div class="flex justify-between items-center mb-4">
<h2 class="text-2xl font-semibold text-caddy-blue">Current Configuration</h2>
<Button
color="green"
on:click={() => (showConfigModal = true)}
class="flex items-center gap-2"
>
<RefreshCw size="16" />
Update Configuration
</Button>
</div>
{#if loadingConfig}
<div class="flex justify-center p-4">
<Spinner size="xl" color="blue" />
</div>
{:else}
<pre class="bg-gray-100 p-4 rounded-lg overflow-x-auto text-sm">{JSON.stringify(
config,
null,
2
)}</pre>
{/if}
</Card>
</div>
{/if}
{#if activeTab === 'upstreams'}
<div class="mt-6">
<Card class="shadow-lg">
<h2 class="text-2xl font-semibold mb-4 text-caddy-blue">Upstreams</h2>
{#if loadingUpstreams}
<div class="flex justify-center p-4">
<Spinner size="xl" color="blue" />
</div>
{:else}
<div class="overflow-x-auto">
<Table striped={true} hoverable={true}>
<TableHead>
<TableHeadCell>Address</TableHeadCell>
<TableHeadCell>Requests</TableHeadCell>
<TableHeadCell>Fails</TableHeadCell>
</TableHead>
<TableBody>
{#each upstreams as upstream}
<TableBodyRow>
<TableBodyCell>{upstream.address}</TableBodyCell>
<TableBodyCell>{upstream.num_requests}</TableBodyCell>
<TableBodyCell>{upstream.fails}</TableBodyCell>
</TableBodyRow>
{/each}
</TableBody>
</Table>
</div>
{/if}
</Card>
</div>
{/if}
{#if activeTab === 'ca_management'}
<div class="mt-6">
<Card class="shadow-lg">
<h2 class="text-2xl font-semibold mb-4 text-caddy-blue">CA Management</h2>
<div class="flex items-center gap-2">
<Input type="text" placeholder="CA ID (e.g., local)" bind:value={caId} />
<Button color="green" on:click={handleGetCAInfo}>Get CA Info</Button>
</div>
</Card>
</div>
{/if}
</main>
<div class="mt-6 flex justify-end">
<Button color="red" on:click={handleStopServer} class="flex items-center gap-2">
<ServerCrash size="16" />
Stop Caddy Server
</Button>
</div>
<Modal bind:open={showConfigModal} size="xl" autoclose={false} class="w-full max-w-4xl">
<h2 class="text-2xl font-semibold mb-4 text-caddy-blue">Update Configuration</h2>
<Input
type="text"
placeholder="Config path (e.g., apps/http/servers/myserver/listen)"
class="mb-4"
bind:value={configPath}
/>
<Textarea
rows={10}
placeholder="Enter new configuration (JSON format)"
bind:value={newConfig}
class="mb-4"
/>
<div class="flex justify-end gap-2">
<Button color="light" on:click={() => (showConfigModal = false)}>Cancel</Button>
<Button color="green" on:click={handleUpdateConfig}>Update Config</Button>
<Button color="blue" on:click={handleLoadConfig}>Load Full Config</Button>
</div>
</Modal>
<Modal bind:open={showCAModal} size="xl" autoclose={false}>
<h2 class="text-2xl font-semibold mb-4 text-caddy-blue">CA Information</h2>
{#if caInfo}
<div class="mb-4 space-y-2">
<p><strong class="text-caddy-green">ID:</strong> {caInfo.id}</p>
<p><strong class="text-caddy-green">Name:</strong> {caInfo.name}</p>
<p><strong class="text-caddy-green">Root CN:</strong> {caInfo.root_common_name}</p>
<p>
<strong class="text-caddy-green">Intermediate CN:</strong>
{caInfo.intermediate_common_name}
</p>
</div>
<h3 class="text-lg font-semibold mb-2 text-caddy-blue">Certificates</h3>
<Textarea rows={10} readonly value={caCertificates} class="mb-4" />
{:else}
<p class="text-gray-600">No CA information available.</p>
{/if}
<div class="flex justify-end">
<Button color="blue" on:click={() => (showCAModal = false)}>Close</Button>
</div>
</Modal>
<style>
:global(body) {
background-color: #f3f4f6;
}
:global(.text-caddy-green) {
color: #00add8;
}
:global(.text-caddy-blue) {
color: #0097b7;
}
:global(.bg-caddy-green) {
background-color: #00add8;
}
:global(.bg-caddy-blue) {
background-color: #0097b7;
}
</style>

147
src/routes/CaddyService.ts Normal file
View File

@ -0,0 +1,147 @@
// CaddyService.ts
import { writable, type Writable } from 'svelte/store';
const API_BASE_URL = 'http://localhost:2019'; // Adjust this to your Caddy API endpoint
export interface Upstream {
address: string;
num_requests: number;
fails: number;
}
export interface CAInfo {
id: string;
name: string;
root_common_name: string;
intermediate_common_name: string;
root_certificate: string;
intermediate_certificate: string;
}
export const configStore: Writable<Record<string, any>> = writable({});
export const upstreamsStore: Writable<Upstream[]> = writable([]);
export const CaddyService = {
async loadConfig(
config: Record<string, any>,
contentType: string = 'application/json'
): Promise<Record<string, any>> {
try {
const response = await fetch(`${API_BASE_URL}/load`, {
method: 'POST',
headers: {
'Content-Type': contentType
},
body: JSON.stringify(config)
});
if (!response.ok) throw new Error('Failed to load configuration');
return await response.json();
} catch (error) {
console.error('Error loading config:', error);
throw error;
}
},
async stopServer(): Promise<boolean> {
try {
const response = await fetch(`${API_BASE_URL}/stop`, { method: 'POST' });
if (!response.ok) throw new Error('Failed to stop server');
return true;
} catch (error) {
console.error('Error stopping server:', error);
throw error;
}
},
async getConfig(path: string = ''): Promise<Record<string, any>> {
try {
const response = await fetch(`${API_BASE_URL}/config/${path}`);
if (!response.ok) throw new Error('Failed to get configuration');
const config = await response.json();
configStore.set(config);
return config;
} catch (error) {
console.error('Error getting config:', error);
throw error;
}
},
async updateConfig(
path: string,
data: any,
method: 'POST' | 'PUT' | 'PATCH' | 'DELETE' = 'POST'
): Promise<Record<string, any>> {
try {
const response = await fetch(`${API_BASE_URL}/config/${path}`, {
method,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if (!response.ok) throw new Error(`Failed to ${method} configuration`);
await this.getConfig(); // Refresh the config store
return await response.json();
} catch (error) {
console.error(`Error ${method}ing config:`, error);
throw error;
}
},
async deleteConfig(path: string): Promise<Record<string, any>> {
return this.updateConfig(path, null, 'DELETE');
},
async adaptConfig(config: string, contentType: string): Promise<Record<string, any>> {
try {
const response = await fetch(`${API_BASE_URL}/adapt`, {
method: 'POST',
headers: {
'Content-Type': contentType
},
body: config
});
if (!response.ok) throw new Error('Failed to adapt configuration');
return await response.json();
} catch (error) {
console.error('Error adapting config:', error);
throw error;
}
},
async getCAInfo(id: string): Promise<CAInfo> {
try {
const response = await fetch(`${API_BASE_URL}/pki/ca/${id}`);
if (!response.ok) throw new Error('Failed to get CA information');
return await response.json();
} catch (error) {
console.error('Error getting CA info:', error);
throw error;
}
},
async getCACertificates(id: string): Promise<string> {
try {
const response = await fetch(`${API_BASE_URL}/pki/ca/${id}/certificates`);
if (!response.ok) throw new Error('Failed to get CA certificates');
return await response.text();
} catch (error) {
console.error('Error getting CA certificates:', error);
throw error;
}
},
async getUpstreams(): Promise<Upstream[]> {
try {
const response = await fetch(`${API_BASE_URL}/reverse_proxy/upstreams`);
if (!response.ok) throw new Error('Failed to get upstreams');
const upstreams = await response.json();
upstreamsStore.set(upstreams);
return upstreams;
} catch (error) {
console.error('Error getting upstreams:', error);
throw error;
}
}
};

BIN
static/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

18
svelte.config.js Normal file
View File

@ -0,0 +1,18 @@
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
/** @type {import('@sveltejs/kit').Config} */
const config = {
// Consult https://kit.svelte.dev/docs/integrations#preprocessors
// for more information about preprocessors
preprocess: vitePreprocess(),
kit: {
// adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list.
// If your environment is not supported, or you settled on a specific environment, switch out the adapter.
// See https://kit.svelte.dev/docs/adapters for more information about adapters.
adapter: adapter()
}
};
export default config;

11
tailwind.config.ts Normal file
View File

@ -0,0 +1,11 @@
import type { Config } from 'tailwindcss';
export default {
content: ['./src/**/*.{html,js,svelte,ts}'],
theme: {
extend: {}
},
plugins: [require('@tailwindcss/typography')]
} as Config;

6
tests/test.ts Normal file
View File

@ -0,0 +1,6 @@
import { expect, test } from '@playwright/test';
test('home page has expected h1', async ({ page }) => {
await page.goto('/');
await expect(page.locator('h1')).toBeVisible();
});

19
tsconfig.json Normal file
View File

@ -0,0 +1,19 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
// except $lib which is handled by https://kit.svelte.dev/docs/configuration#files
//
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in
}

9
vite.config.ts Normal file
View File

@ -0,0 +1,9 @@
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vitest/config';
export default defineConfig({
plugins: [sveltekit()],
test: {
include: ['src/**/*.{test,spec}.{js,ts}']
}
});