Conversation
Reviewer's GuideDocumentation-only PR that refreshes DockStat API/frontend docs (lists source files, normalizes tables, bullet formatting, and headings), adds a startup animation GIF to the API README, adjusts one example base URL, tweaks example error handling code in actions docs, and introduces a dedicated dev script for the API service in the monorepo package.json. Flow diagram for dev:dockstat/api development scriptflowchart TD
developer[Developer] --> npm_script[Run dev:dockstat/api]
npm_script --> docker_up[bun run docker-up]
docker_up --> compose_stack[docker compose -f docker-compose.dev.yaml up]
compose_stack --> turbo_dev_api[bun run dev --filter=@dockstat/api]
turbo_dev_api --> api_running[DockStatAPI dev server running on /api/v2]
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 1 issue, and left some high level feedback:
- In
frontend-plugin-apiREADME the base URL link text and href now differ (localhost:3000vslocalhost:9876); align them so users don’t get confused about which port to use. - The DockStatAPI startup GIF in
apps/api/README.mdpoints at a specific branch (DockStatAPI-readme-update); consider referencingmainor a stable asset path so the image doesn’t break when branches are cleaned up.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- In `frontend-plugin-api` README the base URL link text and href now differ (`localhost:3000` vs `localhost:9876`); align them so users don’t get confused about which port to use.
- The DockStatAPI startup GIF in `apps/api/README.md` points at a specific branch (`DockStatAPI-readme-update`); consider referencing `main` or a stable asset path so the image doesn’t break when branches are cleaned up.
## Individual Comments
### Comment 1
<location> `apps/docs/dockstat/api-reference/frontend-plugin-api-(plugins-frontend)/README.md:18` </location>
<code_context>
Base URL (development)
-- [http://localhost:3000/api/v2/plugins/frontend](http://localhost:3000/api/v2/plugins/frontend)
+* [http://localhost:3000/api/v2/plugins/frontend](http://localhost:9876/api/v2/plugins/frontend)
Overview
</code_context>
<issue_to_address>
**issue (bug_risk):** The Base URL link text and actual href use different ports; consider making them consistent or clarifying the intended URL.
Here the link label shows `localhost:3000`, but the actual href goes to `localhost:9876`. Please either align both to the correct port or add a note explaining why the display URL and target differ, so readers know which port to use for the frontend plugin API.
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
| Base URL (development) | ||
|
|
||
| - [http://localhost:3000/api/v2/plugins/frontend](http://localhost:3000/api/v2/plugins/frontend) | ||
| * [http://localhost:3000/api/v2/plugins/frontend](http://localhost:9876/api/v2/plugins/frontend) |
There was a problem hiding this comment.
issue (bug_risk): The Base URL link text and actual href use different ports; consider making them consistent or clarifying the intended URL.
Here the link label shows localhost:3000, but the actual href goes to localhost:9876. Please either align both to the correct port or add a note explaining why the display URL and target differ, so readers know which port to use for the frontend plugin API.
* chore(api): Add startup animation, logger config, and API dev script (#63) (#64) * chore(api): Add startup animation, logger config, and API dev script (#63) * docs: sync from Outline * 66 logger x docker client the current workers do not forward their logs (#67) * refactor(logging): Standardize cross-process log handling and improve UI Introduces a centralized logging mechanism to forward log entries generated by workers to the main process. This ensures all application logs are consistently processed and displayed. - **Logger:** Made `Logger.emitLogEntry` public and enhanced it to accept metadata for accurate log re-emission from various sources. Added a visual indicator for log hooks in formatted messages. - **Docker Client:** - Implemented `WorkerLogger` in `docker-client` workers to proxy log entries via a new `__log__` event. - The `docker-client` manager now listens for and re-emits `__log__` events through the main logger. - Refactored worker-related types (`InboundMessage`, `InitMessage`, `MetricsMessage`) and utility functions (`tryBuildFromProxy`) into dedicated shared files for better organization. - **Typings:** Defined `LogLevel`, `LogEntry` types, and added the `__log__` event to the `EVENTS` interface to support structured log forwarding. - **UI:** Updated the `Sidebar` to display the unified log stream with improved formatting, including colored log levels, badges for logger names/request IDs, and a new `log` timestamp format. - **Utils:** Added a new `log` format to `formatDate` and standardized the default locale for date formatting to `de-DE`. - **Dependencies:** Upgraded `@dockstat/docker-client` to `2.0.0` and numerous other dependencies (e.g., `framer-motion`, `react-router`, `@types/node`) to their latest patch/minor versions. - **Cleanup:** Removed a debug `console.log` statement from `plugin-handler`. * refactor(logging, client): improve logging detail and worker robustness Update .env.example with refined default logger configurations to reduce noise and focus on `PluginHandler` messages. Forward `requestId` within `__log__` events to enhance log correlation. Strengthen worker initialization checks by explicitly verifying `message.success`. Streamline event typings by removing `workerLoggerResponse`. Includes minor import reordering and variable name correction for consistency. * [ImgBot] Optimize images (#65) * chore(api): Add startup animation, logger config, and API dev script (#63) * docs: sync from Outline * [ImgBot] Optimize images *Total -- 389.34kb -> 261.94kb (32.72%) /.github/assets/logos/square.png -- 81.10kb -> 20.42kb (74.82%) /.github/assets/gifs/DockStatAPI-startup.gif -- 306.82kb -> 240.10kb (21.74%) /packages/ui/public/vite.svg -- 1.42kb -> 1.42kb (0.07%) Signed-off-by: ImgBotApp <ImgBotHelp@gmail.com> * chore(assets): Add and organize GitHub assets, update README logo --------- Signed-off-by: ImgBotApp <ImgBotHelp@gmail.com> Co-authored-by: ItsNik <info@itsnik.de> Co-authored-by: Its4Nik <106100177+Its4Nik@users.noreply.github.com> Co-authored-by: ImgBotApp <ImgBotHelp@gmail.com> * chore(gifs): Add .gitignore to ignore YML files --------- Signed-off-by: ImgBotApp <ImgBotHelp@gmail.com> Co-authored-by: imgbot[bot] <31301654+imgbot[bot]@users.noreply.github.com> Co-authored-by: ImgBotApp <ImgBotHelp@gmail.com>
* chore(api): Add startup animation, logger config, and API dev script (#63) (#64)
* chore(api): Add startup animation, logger config, and API dev script (#63)
* docs: sync from Outline
* 66 logger x docker client the current workers do not forward their logs (#67)
* refactor(logging): Standardize cross-process log handling and improve UI
Introduces a centralized logging mechanism to forward log entries generated by workers to the main process. This ensures all application logs are consistently processed and displayed.
- **Logger:** Made `Logger.emitLogEntry` public and enhanced it to accept metadata for accurate log re-emission from various sources. Added a visual indicator for log hooks in formatted messages.
- **Docker Client:**
- Implemented `WorkerLogger` in `docker-client` workers to proxy log entries via a new `__log__` event.
- The `docker-client` manager now listens for and re-emits `__log__` events through the main logger.
- Refactored worker-related types (`InboundMessage`, `InitMessage`, `MetricsMessage`) and utility functions (`tryBuildFromProxy`) into dedicated shared files for better organization.
- **Typings:** Defined `LogLevel`, `LogEntry` types, and added the `__log__` event to the `EVENTS` interface to support structured log forwarding.
- **UI:** Updated the `Sidebar` to display the unified log stream with improved formatting, including colored log levels, badges for logger names/request IDs, and a new `log` timestamp format.
- **Utils:** Added a new `log` format to `formatDate` and standardized the default locale for date formatting to `de-DE`.
- **Dependencies:** Upgraded `@dockstat/docker-client` to `2.0.0` and numerous other dependencies (e.g., `framer-motion`, `react-router`, `@types/node`) to their latest patch/minor versions.
- **Cleanup:** Removed a debug `console.log` statement from `plugin-handler`.
* refactor(logging, client): improve logging detail and worker robustness
Update .env.example with refined default logger configurations to reduce noise and focus on `PluginHandler` messages. Forward `requestId` within `__log__` events to enhance log correlation. Strengthen worker initialization checks by explicitly verifying `message.success`. Streamline event typings by removing `workerLoggerResponse`. Includes minor import reordering and variable name correction for consistency.
* [ImgBot] Optimize images (#65)
* chore(api): Add startup animation, logger config, and API dev script (#63)
* docs: sync from Outline
* [ImgBot] Optimize images
*Total -- 389.34kb -> 261.94kb (32.72%)
/.github/assets/logos/square.png -- 81.10kb -> 20.42kb (74.82%)
/.github/assets/gifs/DockStatAPI-startup.gif -- 306.82kb -> 240.10kb (21.74%)
/packages/ui/public/vite.svg -- 1.42kb -> 1.42kb (0.07%)
Signed-off-by: ImgBotApp <ImgBotHelp@gmail.com>
* chore(assets): Add and organize GitHub assets, update README logo
---------
Signed-off-by: ImgBotApp <ImgBotHelp@gmail.com>
Co-authored-by: ItsNik <info@itsnik.de>
Co-authored-by: Its4Nik <106100177+Its4Nik@users.noreply.github.com>
Co-authored-by: ImgBotApp <ImgBotHelp@gmail.com>
* chore(gifs): Add .gitignore to ignore YML files
* 43 feat uiux add management of repositories (#71)
* refactor(data): Implement useEdenQuery/Mutation hooks for data fetching
- Introduced `useEdenQuery` and `useEdenMutation` to streamline API interaction with `@elysiajs/eden`.
- Centralized common data fetching patterns including error handling, automatic query invalidation, and toast notifications.
- Removed deprecated `lib/actions` and `lib/queries` directories; their functionalities are now integrated into the new hooks.
- Refactored all major components and pages (`AddClient`, `AddHost`, `PluginBrowser`, `Layout`, client and extension pages) to utilize the new data hooks.
- Consolidated `AdditionalSettingsContext` into a unified `ConfigProviderContext` for better state management.
- Enhanced `PluginHandler` to improve plugin security verification, including explicit checks for DVA connectivity.
- Added `RepoCard` component and `RepoIcons` for improved repository UI.
- Updated `installPluginBody` schema to omit the `plugin` field.
- Extended `parseFromDBToRepoLink` to support generating raw file links or repository tree/branch links.
* refactor(frontend): Remove redundant lib/actions pattern and aliases
The `lib/actions` directory and its associated pattern have been removed, as the `useEdenMutation` hook provides a more direct and integrated way to handle client-side API mutations.
This refactoring includes:
* Deleting `apps/dockstat/src/lib/actions` directory, including `README.md`, `executePluginAction.ts`, and `executePluginLoader.ts`.
* Updating `apps/dockstat/src/hooks/usePluginPage.ts` to directly use `useEdenMutation` for executing plugin loaders and actions, replacing the previously used helper functions.
* Removing `@Actions` and `@Queries` path aliases from `apps/dockstat/tsconfig.json` and `apps/dockstat/vite.config.ts`.
* Reorganizing import statements across various files in `apps/dockstat` for consistency.
This change simplifies the codebase by reducing unnecessary abstraction layers for API interactions.
* refactor(api): Remove redundant 'api.v2' prefix from route calls
The Eden API client in the frontend previously required routes to be accessed with a verbose `api.api.v2.<route>` prefix. This commit refactors the `src/lib/api.ts` file to directly export the `api.v2` namespace from the `treaty` client.
Consequently, all API calls throughout the frontend (`apps/dockstat/`) and documentation (`apps/docs/`) are updated to use the simplified `api.<route>` syntax. This change improves code readability, reduces verbosity, and streamlines interaction with the backend API.
Additionally, the environment variable for the API base URL was updated from `VITE_API_URL` to `DOCKSTAT_API_PORT` in `src/lib/api.ts`. Minor formatting adjustments were also applied in the integration guide README.
* feat(ui): Enhance repository management and introduce Select component
Refactor repository management in the frontend and introduce a reusable
Select component to improve form interactions.
- **apps/api**:
- Truncate error details in the metrics middleware for more concise logging.
- **apps/dockstat**:
- Redesign `RepoCard` component to include detailed security badges (Strict, Relaxed, No Verification),
display source and verification API clearly, and provide direct links.
- Implement a dedicated "Add Repository" form on the extensions page, replacing the previous placeholder,
with state management and validation.
- Integrate the new `Select` component for repository filtering in the plugin browser.
- **packages/ui**:
- Introduce a new generic `Select` component with support for different sizes, variants (default, filled, underline),
and styling options.
- Add corresponding CSS variables for the `Select` component.
- Extend `RepoIcons` component with a `size` prop for scalable icon rendering.
- Simplify verification badge logic within the `Repo` component.
- Update rendering keys in `Modal`, `RepoPluginSlide`, and `RepoList` for improved stability.
- **packages/utils**:
- Add handling for the `default` repository type in `parseFromDBToRepoLink` function.
* chore(ci): Lint [skip ci]
* feat(plugins): Refactor plugin page logic and introduce dedicated UI states
Splits the monolithic `usePluginPage` hook into modular, specialized hooks: `usePluginTemplate`, `usePluginState`, `usePluginLoaders`, and `usePluginActions`. This enhances maintainability and separation of concerns for plugin page management.
Introduces a new component file, `PluginPageStates.tsx`, to centralize UI rendering for various plugin page states, including loading, error, not found, and missing templates. This improves the user experience with clearer feedback.
Updates the `useEdenMutation` hook to support a `routeBuilder` pattern, enabling dynamic construction of API endpoints for plugin actions and loaders based on runtime parameters.
Performs minor cleanup by replacing unstable `key` props (e.g., using `Date` or `Math.random()`) with stable, deterministic values in several UI components for improved React reconciliation.
* chore: lint
* refactor(hooks): Split useEdenMutation into specialized hooks
The monolithic `useEdenMutation` hook has been refactored and split into several specialized components to improve modularity, clarify API usage, and enhance maintainability.
The changes include:
- **`apps/dockstat/src/hooks/eden/types.ts`**: Introduced to centralize shared types for Eden-related hooks.
- **`apps/dockstat/src/hooks/eden/useBaseEdenMutation.ts`**: Extracts the core `useMutation` logic, toast handling, and query invalidation into a reusable base hook.
- **`apps/dockstat/src/hooks/eden/useEdenMutation.ts`**: Provides a simplified interface for direct Eden API routes that do not require a route builder with dynamic parameters.
- **`apps/dockstat/src/hooks/eden/useEdenRouteMutation.ts`**: Provides an interface for Eden API routes that require parameters to build the route function at the time of mutation.
- **Removed `apps/dockstat/src/hooks/useEdenMutation.ts`**: The old, overloaded hook has been removed.
All existing consumers of the previous `useEdenMutation` have been updated to use the appropriate new specialized hook (`useEdenMutation` or `useEdenRouteMutation`) and their new import paths.
Additionally, corrected query invalidation keys for `pinNavLink` and `unpinNavLink` mutations in `layout.tsx` from `fetchNavLinks` to `fetchAdditionalSettings` to ensure proper cache updates.
* refactor(plugins): Extract plugin template logic to utils and address UI issues
Moved plugin page data normalization, template parsing, and fragment mapping from `usePluginTemplate` hook to a new utility file `src/utils/normalizePluginPageData.ts`. This centralizes complex data processing logic and simplifies the `usePluginTemplate` hook.
Also includes the following improvements:
- Corrected the import path for `useEdenMutation` in `usePluginTemplate.ts`.
- Fixed an issue in the plugin browser (`plugins.tsx`) where the repository `Select` component did not display the currently selected repository.
- Adjusted how the `isBusy` prop is passed to the `TopNav` component in `layout.tsx`.
- Reordered a `toast` import statement in `useBaseEdenMutation.ts` for consistency.
* deps(bun.lock): Update various package dependencies
---------
Co-authored-by: actions-user <its4nik@users.noreply.github.com>
* refactor(eden-hooks): Rename useEdenMutation to useEdenRouteMutation
* 70 dockstore refactor into dockstat repository (#72)
* feat(repo-cli): Introduce repository CLI for managing DockStat repos
This commit introduces a new `@dockstat/repo-cli` package, providing a command-line interface to assist with managing DockStat repositories.
Key functionalities include:
- `init`: Initialize a new repository configuration file.
- `bundle`: Bundle plugins within the repository and update the manifest.
- `badges`: Generate SVG badges based on repository content and configuration.
Additionally, a new `isRepoType` utility is added to `@dockstat/utils` for validating repository types.
* feat(repo-cli): Introduce local serving and consolidated repository config
Deprecate and remove the internal `apps/dockstore` tooling responsible for plugin bundling, README generation, and schema management. This includes `bundler.ts`, `generate-readme.ts`, `.schemas/plugin-meta.schema.json`, and related `package.json` scripts and config files.
Replaced the decentralized plugin metadata and manifest generation with a new, centralized `apps/dockstore/repo.json` file. This file now defines the repository's configuration (name, policy, verification_api, content directories) and serves as the single source of truth for repository content metadata (plugins, themes, stacks).
The `dockstat-repo-cli`'s `bundle` command has been updated to populate this new `repo.json` file with plugin metadata.
Added a new `serve` command to `dockstat-repo-cli`, enabling simple local serving of the repository's static files via `Bun.serve`. This is intended for development, testing, or use behind a reverse proxy.
Introduced `packages/dockstat-repo-cli/src/utils/contentType.ts` to support the new `serve` command by providing appropriate `Content-Type` headers.
* feat(repo-cli): introduce repository management CLI
* chore: bump versions in bun.lock
* chore(repo-config): Remove 'content/' prefix from module paths
* build(repo-cli): Configure package for publishing and metadata
Add .npmignore to exclude source files and build artifacts from published package.
Update package.json with version, description, and 'files' array for explicit publication control.
Correct the CLI executable name in the 'bin' field from 'dockstore-repo-cli' to 'dockstat-repo-cli'.
* fix(repo-cli): Correct CLI binary output filename
* fix(repo-cli): Sanitize served paths and refactor badge generation
refactor(repo-cli/badges): Consolidate badge creation logic
- Replaced repetitive conditional blocks for plugins, themes, and stacks with a configurable array and a loop.
- Improves code maintainability and extensibility for future badge types.
fix(repo-cli/serve): Prevent directory traversal attacks
- Added `filePath.replaceAll("../", "/")` to sanitize requested file paths.
- Mitigates a potential security vulnerability allowing access to files outside the intended content directory.
refactor(typings, utils): Remove 'default' repo type
- Removed "default" from the `Repo.type` union enum in `db.ts`.
- Removed "default" from the `REPO_TYPES` array in `isRepoType.ts`.
- Aligns type definitions and utility functions with current supported repository types.
* feat(repo): Implement manifest-based repository registration
This commit significantly overhauls the repository registration process, moving towards a manifest-driven approach.
**Key Changes:**
* **API (`apps/api`)**:
* The `POST /repositories` endpoint now accepts a single `link_to_manifest` (URL) instead of individual fields like name, source, type, and policy.
* The API fetches the manifest from the provided link, utilizes new utility functions to parse its content, and extracts the repository configuration for storage.
* Adds `@dockstat/repo-cli` dependency to facilitate manifest parsing.
* **Core Logic (`packages/utils/repo`)**:
* Introduces `parseRawToDB` to intelligently convert raw manifest URLs (GitHub, GitLab, Gitea, HTTP) into structured database `type` and `source` strings.
* Enhances `parseFromDBToRepoLink` for more robust URL reconstruction based on repository type and source.
* Adds helper functions `parseRepoParts` and `splitDomain` for robust URL decomposition.
* **Database (`packages/db`)**:
* Updates the `repositories_table` schema to include a `paths` column (JSON type) for storing manifest-defined paths for themes, plugins, and stacks.
* Enables automatic database backup functionality with configurable intervals, compression, and maximum backups. Backups are stored in a `.backups` directory.
* **Frontend (`apps/dockstat`)**:
* The "Add Repository" form in the Extensions page is simplified to a single input field for the raw manifest or repository link.
* Removes previously individual fields for name, source, type, policy, and verification API.
* **Typings**:
* `Repo` and `CreateRepo` types updated to include the new `paths` field and remove the "default" option from the `type` enum.
* `RepoFile` interface in `@dockstat/repo-cli` is extended for flexibility.
* **.gitignore**: Updated to exclude the `.backups` directory.
This refactor streamlines the user experience for adding new repositories and prepares the system for richer manifest-based capabilities.
* chore(ci): Lint [skip ci]
* feat(plugins, api, build): Introduce DockStacks plugin and standardize publishing
- Introduce the new `DockStacks` plugin for managing Docker container stacks. This includes its initial project setup, definition using `@dockstat/plugin-builder`, and configuration types.
- Update the API route (`apps/api/src/routes/db.ts`) to store specific `paths` (plugins, stacks, themes) in the repository configuration upon creation. This allows repositories to define structured locations for different asset types.
- Standardize the package publishing process across core utility packages (`@dockstat/plugin-builder`, `@dockstat/repo-cli`, `@dockstat/sqlite-wrapper`, `@dockstat/typings`, `@dockstat/utils`) by adding a dedicated `publish` script to each `package.json`.
- Add root-level `publish` and `pub` commands to the monorepo `package.json` for simplified execution of package publishing.
- Bump versions for `@dockstat/plugin-builder` and `@dockstat/typings`.
* merge
* merge
* feat(docknode): Initial application setup with Bun and Elysia
Replaces the previous subproject entry with a new implementation of the DockNode application.
This commit establishes the foundational structure for DockNode, leveraging Bun runtime and the Elysia web framework.
Key components include:
- Integration with @dockstat/sqlite-wrapper for local database management.
- A StackHandler for dynamic creation, configuration, and orchestration of Docker Compose stacks.
- Essential project configuration such as .gitignore, tsconfig, and package.json.
* style(fmt): Standardize TS and TSConfig formatting
Reordered import statements in `apps/docknode/src/stacks/index.ts`.
Standardized comment placement and property delimiters (commas vs. semicolons) in `apps/docknode/tsconfig.json` and `packages/typings/src/v2/extensions/stacks/compose.d.ts`.
These changes improve code consistency and readability.
* feat(dev-env): Introduce Dockerized local development environment
Adds a comprehensive Docker Compose setup for consistent local development, coupled with significant ecosystem and dependency updates.
- **Docker Development Environment:**
- Introduced `docker-compose.dev.yaml` to provide isolated services:
- `socket-proxy`: For secure Docker socket access.
- `sqlite-web`: Two instances for inspecting `dockstat.sqlite` and `verification.db`.
- `prometheus`: For collecting application metrics.
- Added `dockstat-dev.prometheus.yml` to configure Prometheus to scrape metrics from the API.
- Updated `package.json` scripts (`docker-up`, `docker-up:quiet`, `dev:dockstat`) to integrate with the new Docker setup.
- **Bun and Dependency Updates:**
- Upgraded Bun runtime from `1.3.1` to `1.3.6`.
- Migrated core dependencies (`elysia`, `@elysiajs/eden`) to Bun's package catalog for enhanced dependency management and resolution.
- Performed various dependency updates across the monorepo, including `turbo`, `typescript`, `@types/bun`, `@types/react`, `js-yaml`, `@elysiajs/openapi`, `rollup`, `@sinclair/typebox`, `docker-compose`, `framer-motion`, `storybook`, and `@typescript-eslint` packages.
* Update packages/repo-cli/src/types.ts
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
Signed-off-by: ItsNik <info@itsnik.de>
* chore(docknode): update gitignore to exclude local environment files [DOCK-123]
Added patterns for local backup directories, stack configurations, and database files to prevent them from being tracked in version control. Updated the formatting for the bun lockfile entry.
* build(deps): bump dependencies in bun.lock
Update various project dependencies to their latest versions, including Babel, ESLint, Storybook, Tailwind CSS, TypeScript, and Rollup components.
---------
Signed-off-by: ItsNik <info@itsnik.de>
Co-authored-by: actions-user <its4nik@users.noreply.github.com>
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
* 88 refactor themesidebarcontext to separate UI state remove themeprops bag and avoid no op defaults (#94)
* feat(repo-cli): Introduce repository CLI for managing DockStat repos
This commit introduces a new `@dockstat/repo-cli` package, providing a command-line interface to assist with managing DockStat repositories.
Key functionalities include:
- `init`: Initialize a new repository configuration file.
- `bundle`: Bundle plugins within the repository and update the manifest.
- `badges`: Generate SVG badges based on repository content and configuration.
Additionally, a new `isRepoType` utility is added to `@dockstat/utils` for validating repository types.
* feat(repo-cli): Introduce local serving and consolidated repository config
Deprecate and remove the internal `apps/dockstore` tooling responsible for plugin bundling, README generation, and schema management. This includes `bundler.ts`, `generate-readme.ts`, `.schemas/plugin-meta.schema.json`, and related `package.json` scripts and config files.
Replaced the decentralized plugin metadata and manifest generation with a new, centralized `apps/dockstore/repo.json` file. This file now defines the repository's configuration (name, policy, verification_api, content directories) and serves as the single source of truth for repository content metadata (plugins, themes, stacks).
The `dockstat-repo-cli`'s `bundle` command has been updated to populate this new `repo.json` file with plugin metadata.
Added a new `serve` command to `dockstat-repo-cli`, enabling simple local serving of the repository's static files via `Bun.serve`. This is intended for development, testing, or use behind a reverse proxy.
Introduced `packages/dockstat-repo-cli/src/utils/contentType.ts` to support the new `serve` command by providing appropriate `Content-Type` headers.
* feat(repo-cli): introduce repository management CLI
* chore: bump versions in bun.lock
* chore(repo-config): Remove 'content/' prefix from module paths
* build(repo-cli): Configure package for publishing and metadata
Add .npmignore to exclude source files and build artifacts from published package.
Update package.json with version, description, and 'files' array for explicit publication control.
Correct the CLI executable name in the 'bin' field from 'dockstore-repo-cli' to 'dockstat-repo-cli'.
* fix(repo-cli): Correct CLI binary output filename
* fix(repo-cli): Sanitize served paths and refactor badge generation
refactor(repo-cli/badges): Consolidate badge creation logic
- Replaced repetitive conditional blocks for plugins, themes, and stacks with a configurable array and a loop.
- Improves code maintainability and extensibility for future badge types.
fix(repo-cli/serve): Prevent directory traversal attacks
- Added `filePath.replaceAll("../", "/")` to sanitize requested file paths.
- Mitigates a potential security vulnerability allowing access to files outside the intended content directory.
refactor(typings, utils): Remove 'default' repo type
- Removed "default" from the `Repo.type` union enum in `db.ts`.
- Removed "default" from the `REPO_TYPES` array in `isRepoType.ts`.
- Aligns type definitions and utility functions with current supported repository types.
* feat(repo): Implement manifest-based repository registration
This commit significantly overhauls the repository registration process, moving towards a manifest-driven approach.
**Key Changes:**
* **API (`apps/api`)**:
* The `POST /repositories` endpoint now accepts a single `link_to_manifest` (URL) instead of individual fields like name, source, type, and policy.
* The API fetches the manifest from the provided link, utilizes new utility functions to parse its content, and extracts the repository configuration for storage.
* Adds `@dockstat/repo-cli` dependency to facilitate manifest parsing.
* **Core Logic (`packages/utils/repo`)**:
* Introduces `parseRawToDB` to intelligently convert raw manifest URLs (GitHub, GitLab, Gitea, HTTP) into structured database `type` and `source` strings.
* Enhances `parseFromDBToRepoLink` for more robust URL reconstruction based on repository type and source.
* Adds helper functions `parseRepoParts` and `splitDomain` for robust URL decomposition.
* **Database (`packages/db`)**:
* Updates the `repositories_table` schema to include a `paths` column (JSON type) for storing manifest-defined paths for themes, plugins, and stacks.
* Enables automatic database backup functionality with configurable intervals, compression, and maximum backups. Backups are stored in a `.backups` directory.
* **Frontend (`apps/dockstat`)**:
* The "Add Repository" form in the Extensions page is simplified to a single input field for the raw manifest or repository link.
* Removes previously individual fields for name, source, type, policy, and verification API.
* **Typings**:
* `Repo` and `CreateRepo` types updated to include the new `paths` field and remove the "default" option from the `type` enum.
* `RepoFile` interface in `@dockstat/repo-cli` is extended for flexibility.
* **.gitignore**: Updated to exclude the `.backups` directory.
This refactor streamlines the user experience for adding new repositories and prepares the system for richer manifest-based capabilities.
* chore(ci): Lint [skip ci]
* feat(plugins, api, build): Introduce DockStacks plugin and standardize publishing
- Introduce the new `DockStacks` plugin for managing Docker container stacks. This includes its initial project setup, definition using `@dockstat/plugin-builder`, and configuration types.
- Update the API route (`apps/api/src/routes/db.ts`) to store specific `paths` (plugins, stacks, themes) in the repository configuration upon creation. This allows repositories to define structured locations for different asset types.
- Standardize the package publishing process across core utility packages (`@dockstat/plugin-builder`, `@dockstat/repo-cli`, `@dockstat/sqlite-wrapper`, `@dockstat/typings`, `@dockstat/utils`) by adding a dedicated `publish` script to each `package.json`.
- Add root-level `publish` and `pub` commands to the monorepo `package.json` for simplified execution of package publishing.
- Bump versions for `@dockstat/plugin-builder` and `@dockstat/typings`.
* merge
* merge
* feat(docknode): Initial application setup with Bun and Elysia
Replaces the previous subproject entry with a new implementation of the DockNode application.
This commit establishes the foundational structure for DockNode, leveraging Bun runtime and the Elysia web framework.
Key components include:
- Integration with @dockstat/sqlite-wrapper for local database management.
- A StackHandler for dynamic creation, configuration, and orchestration of Docker Compose stacks.
- Essential project configuration such as .gitignore, tsconfig, and package.json.
* style(fmt): Standardize TS and TSConfig formatting
Reordered import statements in `apps/docknode/src/stacks/index.ts`.
Standardized comment placement and property delimiters (commas vs. semicolons) in `apps/docknode/tsconfig.json` and `packages/typings/src/v2/extensions/stacks/compose.d.ts`.
These changes improve code consistency and readability.
* feat(dev-env): Introduce Dockerized local development environment
Adds a comprehensive Docker Compose setup for consistent local development, coupled with significant ecosystem and dependency updates.
- **Docker Development Environment:**
- Introduced `docker-compose.dev.yaml` to provide isolated services:
- `socket-proxy`: For secure Docker socket access.
- `sqlite-web`: Two instances for inspecting `dockstat.sqlite` and `verification.db`.
- `prometheus`: For collecting application metrics.
- Added `dockstat-dev.prometheus.yml` to configure Prometheus to scrape metrics from the API.
- Updated `package.json` scripts (`docker-up`, `docker-up:quiet`, `dev:dockstat`) to integrate with the new Docker setup.
- **Bun and Dependency Updates:**
- Upgraded Bun runtime from `1.3.1` to `1.3.6`.
- Migrated core dependencies (`elysia`, `@elysiajs/eden`) to Bun's package catalog for enhanced dependency management and resolution.
- Performed various dependency updates across the monorepo, including `turbo`, `typescript`, `@types/bun`, `@types/react`, `js-yaml`, `@elysiajs/openapi`, `rollup`, `@sinclair/typebox`, `docker-compose`, `framer-motion`, `storybook`, and `@typescript-eslint` packages.
* feat(docknode): Implement core DockNode features and Docker stack management
- Introduce Dockerfile for containerizing the DockNode application.
- Develop a comprehensive StackHandler for Docker Compose stack management, including:
- CRUD operations (create, get, list, update, delete, rename, export).
- Lifecycle commands (up, down, stop, restart, pull).
- Information commands (ps, logs, config, network stats, version).
- Execution commands (exec, run, rm, kill, port).
- Expose stack management functionalities via new `/api/stacks` endpoints.
- Integrate `docker-compose` for orchestration and `dockerode` for Docker API interaction.
- Add `.dockerignore`, `.npmignore`, and update `.gitignore` for relevant file exclusions.
- Update `README.md` with DockNode description and API examples.
- Introduce application-specific logger and utility functions.
- Configure `tsconfig.json` for ESNext and bundler module resolution.
- Add necessary dependencies for Docker client, logger, typings, utilities, and OpenAPI.
* build(dockstacks): Add @dockstat/logger dependency
* feat(docker-client): Export core DockerClient directly and refine constructor options
The `DockerClient` class is now directly exportable and importable via `@dockstat/docker-client/client`, allowing for more flexible usage without needing to instantiate the `DockerClientManager`.
Additionally, the `options` parameter in the `DockerClientBase` constructor has been made required, ensuring explicit configuration for client instances.
The package version has been incremented to `2.0.1`.
* feat(docknode): Integrate shared docker client and update dependencies
* refactor(sqlite-wrapper): Restructure source code and modularize DB class
Moved all source files into a dedicated 'src/' directory to improve project structure and maintainability. This refactor also includes a significant modularization of the 'DB' class.
Key changes include:
* All core logic previously in 'index.ts' has been moved to 'src/index.ts'.
* Extracted various concerns from the 'DB' class into new helper modules under 'src/lib':
* Backup and restore operations moved to 'src/lib/backup'.
* Index creation and dropping moved to 'src/lib/index'.
* SQL helper functions like 'isSQLFunction' moved to 'src/lib/sql'.
* Table creation logic ('buildColumnSQL', 'buildTableConstraints', 'isTableSchema', 'setTableComment', 'getTableComment') moved to 'src/lib/table'.
* Updated all relative imports in test files to point to the new 'src/' paths.
* Adjusted 'package.json' and 'tsconfig.json' to reflect the new file structure and module resolution.
* Bumped package version to 1.3.3.
* feat(repo-cli): overhaul README documentation and rename package
- Renamed package from 'dockstore-cli' to '@dockstat/repo-cli' for consistent branding.
- Completely rewrote the README to provide comprehensive usage documentation:
- Added detailed installation instructions.
- Documented 'init', 'bundle', 'badges', and 'serve' commands with their options, descriptions, and requirement status.
- Included license information.
- Bumped package version to 1.0.4.
* feat(query-builder): Add detailed info-level logging to query execution and WHERE methods
- Introduce `safeStringify` utility in `WhereQueryBuilder` to robustly serialize complex values (including RegExp) for logging.
- Add info-level logs to `SelectQueryBuilder` execution methods (`all`, `get`, `count`, `exists`, `value`, `pluck`) to display built queries, parameters, and results.
- Add info-level logs to `WhereQueryBuilder` methods (`where`, `whereRgx`, `whereExpr`, `whereIn`, `whereOp`, `whereBetween`, `whereNull`, etc.) to track the construction of WHERE clauses and their parameters.
- Remove duplicate `safeStringify` implementation from `SelectQueryBuilder` to utilize the new base class helper.
- Bump package version to 1.3.4.
* formatting
* Feat theme handler (#73)
* feat(query-builder): Add detailed info-level logging to query execution and WHERE methods
- Introduce `safeStringify` utility in `WhereQueryBuilder` to robustly serialize complex values (including RegExp) for logging.
- Add info-level logs to `SelectQueryBuilder` execution methods (`all`, `get`, `count`, `exists`, `value`, `pluck`) to display built queries, parameters, and results.
- Add info-level logs to `WhereQueryBuilder` methods (`where`, `whereRgx`, `whereExpr`, `whereIn`, `whereOp`, `whereBetween`, `whereNull`, etc.) to track the construction of WHERE clauses and their parameters.
- Remove duplicate `safeStringify` implementation from `SelectQueryBuilder` to utilize the new base class helper.
- Bump package version to 1.3.4.
* formatting
* feat(theme-handler): Introduce theme-handler package for managing UI themes
This commit introduces the new `@dockstat/theme-handler` package, providing a comprehensive solution for managing UI themes across the application.
Key features include:
- **Client-side utilities**:
- React context (`ThemeContext`) for easily accessing theme data.
- Functions to dynamically apply theme variables (CSS custom properties) to the document.
- Local storage integration for persisting user theme preferences.
- **Server-side management**:
- `ThemeDB` class for robust SQLite database integration to store, retrieve, update, and delete themes.
- Elysia-based API routes (`/themes`) offering full CRUD capabilities for themes, including fetching by name or ID.
- **Default themes**:
- Ships with pre-defined "DockStat-Dark", "DockStat-Light", "DockStat-OLED", and "DockStat-UltraDark" themes, including their CSS variables and animation properties.
- **Bun & Elysia integration**:
- The package is set up with Bun for efficient dependency management and runtime, and Elysia for building high-performance API routes.
This package centralizes theme logic, making it easier to manage and apply consistent styling throughout the application.
* feat(ui): Add theme browser and selection functionality
This commit introduces a user interface for browsing and selecting application themes.
- **New `ThemeBrowser` Component**: A dedicated component is added to display available themes, each with a preview of its key color variables (background, primary text, accent, etc.). Users can select a theme from this browser.
- **Sidebar Integration**: The `Sidebar` component now includes a new 'Palette' icon button that opens a modal containing the `ThemeBrowser`.
- **`ThemeProps` Interface**: A `ThemeProps` interface is defined to facilitate passing theme-related data (list of themes, current theme ID, selection handler, open callback) from parent components to the `Sidebar` and subsequently to the `ThemeBrowser`.
- **Navbar Update**: The `Navbar` component is updated to accept and forward `themeProps` to the `Sidebar`, ensuring theme management can be controlled from higher up the component tree.
- Refactored the loading state check for pinned items in the Sidebar to use `mutationFn.isBusy` for a cleaner approach.
- Exports `ThemeBrowser` components for broader use within the `ui` package.
* refactor(sqlite-wrapper): Truncate excessively long stringified condition values
Introduce a `truncate` utility function to limit the length of strings.
Apply this utility within the `WhereQueryBuilder.safeStringify` method to prevent excessively long stringified values (e.g., from `JSON.stringify` or `String()`) from being returned. This improves readability in debugging logs or contexts where these values might be displayed, ensuring they don't consume too much space. The maximum length for truncated strings is set to 100 characters.
* feat(dockstat): Implement client-side theme management and provider
Introduce `ThemeProvider` to manage and apply themes within the DockStat UI. This includes:
- Adding `@dockstat/theme-handler` dependency.
- Creating `ThemeProviderContext` and `useTheme` hook for global theme state and access.
- Implementing `ThemeProvider` to handle theme fetching (by name/ID) from the API, applying themes to the document using `@dockstat/theme-handler/client` functions (`applyThemeToDocument`), and persisting user preferences (`saveThemePreference`, `loadThemePreference`).
- Integrating the `ThemeProvider` at the application root in `src/providers/index.tsx`.
- Updating `layout.tsx` to consume theme data and functions from `useTheme`, enabling theme selection capabilities in the sidebar.
- Adding a new `/stacks` route and a placeholder `StacksIndex` page.
* feat(api): Add theme management endpoints
* feat(docknode): Implement API key authentication
Introduces API key-based authentication to the docknode application. This implementation leverages the 'better-auth' library, configured to accept API keys via the 'x-docknode-key' header.
Key changes include:
- Addition of the 'better-auth' dependency to apps/docknode.
- Creation of 'src/auth/index.ts' to define the authentication setup.
- Updates to '.env.example' for `BETTER_AUTH_SECRET` and `BETTER_AUTH_URL` configuration.
- Minor updates to `bun.lock` and import reordering across various packages (e.g., `dockstat`, `sqlite-wrapper`, `theme-handler`) for consistency and dependency management.
* docs(all): Standardize formatting and add new content
- Refactored RSS feed websocket subscription path to `api.api.v2.misc.stats.rss` in `apps/dockstat/src/lib/websocketEffects/README.md`.
- Introduced a new documentation page for `Eden Query & Mutation Hooks` under `apps/docs/dockstat/patterns`, detailing `useEdenQuery` and `useEdenMutation` with code examples and type inference.
- Documented the `createIndex` method in `@dockstat/sqlite-wrapper`, providing comprehensive usage, options, and examples for index creation.
- Standardized Markdown table formatting across all documentation files for improved readability and consistency.
- Addressed minor formatting issues, including trailing commas in code snippets and ensuring all Markdown files end with a newline.
* Update apps/dockstat/src/providers/theme.tsx
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
Signed-off-by: ItsNik <info@itsnik.de>
* fix(db): Remove incomplete createIndex call
* refactor(dockstat/theme): Simplify API calls in theme provider
Remove `useEdenQuery` hooks from `ThemeProvider` and replace them with direct calls to the `api` client. This streamlines data fetching for themes (by name, by ID, and all themes) by eliminating an intermediate hook layer.
Consolidate theme application and persistence logic into a new `applyAndPersistTheme` callback for improved code reuse and clarity.
The `useTheme` hook also removes its explicit error throw for usage outside `ThemeProvider`, relying on `useContext` to return `undefined` when the context is not available.
* refactor(theme-handler): modularize server API routes and models
The `theme-handler` server API has been refactored into a more modular and organized structure.
Previously, all theme API routes and associated response models were defined in a single large file (`src/server/api.ts`). This commit breaks down this monolithic file into a clear directory structure:
* **`src/server/api/models/`**: Contains schema definitions for theme data (`themeModel.ts`), mutation payloads (`themePost.ts`), and standardized API responses (`themeResponses.ts`).
* **`src/server/api/routes/`**: Contains individual files for each set of API operations: `queries.ts` (GET), `mutations.ts` (POST), `update.ts` (PUT), and `delete.ts` (DELETE).
The main `createThemeRoutes` function now composes these smaller, focused route modules, improving maintainability and readability.
Additionally, the top-level `src/index.ts` has been updated to re-export `client` and `server` modules as namespaces (`export * as client from "./client"`), providing a clearer and more explicit import structure for consumers of the package.
This refactoring aims to improve code organization, reusability of API models, and overall maintainability of the `theme-handler` package.
* refactor(query-builder/logging): Centralize logging in Select and Where builders
Refactor logging logic within `SelectQueryBuilder` and `WhereQueryBuilder` by introducing dedicated private/protected helper methods.
This change:
- Consolidates common logging patterns for query initiation and results in `SelectQueryBuilder` into `logSelectStart` and `logSelectReturn`.
- Introduces `logColumnReturn` for consistent logging in `pluck` and `value` methods.
- Centralizes logging of `where` conditions and internal state in `WhereQueryBuilder` using `logWhere` and `logWhereState`.
- Improves consistency and readability of log messages across different query execution and condition building methods.
- Reduces code duplication for logging statements, making the code more maintainable.
* feat(ui, api, theme-handler): Implement user feedback toasts and enhance theme preview
- **`dockstat`**: Added toast notifications for successful pin/unpin operations and theme selection, providing immediate user feedback.
- **`ui`**: Overhauled the `ThemeBrowser` component to display a more dynamic and accurate color preview using validated theme variables. Extracted color constants and created a `getValidColors` utility.
- **`theme-handler`**:
- Introduced `onFinish` callback to `applyThemeToDocument` for client-side feedback integration.
- Corrected the logic in the theme creation route to prevent creating themes with duplicate names (bug fix).
- Updated theme response models to use `ThemeModel` consistently and refined the delete route's response type.
- **`api`**: Improved request completion logging by including the request URL path, enhancing observability.
* Update apps/docs/dockstat/patterns/eden-query-&-mutation-hooks/README.md
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
Signed-off-by: ItsNik <info@itsnik.de>
* refactor(components): Remove unused props and refine component types
Omit 'paths' from `RepoCard` props definition to align with actual usage.
Remove 'isLoading' from `ThemeProps` in `Sidebar` as it is no longer required.
Perform minor whitespace cleanup in the `WhereQueryBuilder`.
---------
Signed-off-by: ItsNik <info@itsnik.de>
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
* feat(hotkeys, node, ui): Introduce configurable hotkeys and DockNode pages
This commit brings significant updates including configurable hotkeys, a new DockNode section, and various UI enhancements.
**Hotkeys:**
- Add `hotkeys` field to the global configuration schema (`DockStatConfigTable`) and context (`ConfigProviderData`).
- Define `HotkeyAction` type for better type safety of configurable hotkey actions (e.g., "open:quicklinks").
- Set a default hotkey `k` for opening quick links in the database defaults.
- Integrate configurable hotkeys into the `Navbar` and `LinkLookup` components, allowing customization of the quick links modal hotkey.
**DockNode & Stacks:**
- Create new pages for `/node` (DockNode overview) and `/node/stacks` (Stacks within a DockNode).
- Refactor and move the existing `/stacks` functionality to the new `/node/stacks` route, deleting the old `/stacks` page.
- Update the application router and sidebar navigation to reflect the new DockNode structure.
**UI & Accessibility:**
- Enhance the `Card` component with a `tabIndex` prop to improve keyboard navigation and focus management.
- Adjust tab indexing within the `LinkLookup` modal for better accessibility.
- Apply minor styling and structure adjustments to sidebar items, including child item formatting.
**Refactoring:**
- Streamline theme loading state management in the main layout by removing unnecessary `isLoading` prop from `useTheme` consumer.
* feat(hotkeys): Introduce `useHotkey` hook and add sidebar toggle
Create a new `useHotkey` React hook in `@dockstat/utils/react` to provide a centralized and declarative way for components to manage keyboard shortcuts.
- Migrate existing hotkey handling logic in `LinkLookup` component (for quick links modal) to utilize the new `useHotkey` hook.
- Integrate the `useHotkey` hook into the `Navbar` component to manage sidebar `open`, `close`, and `toggle` actions, making hotkey management consistent.
- Add `toggle:sidebar` hotkey (`b` by default) to the default application configuration in `packages/db`.
- Refactor utility imports across `apps/api` and `packages/plugin-handler` to use barrel exports from `@dockstat/utils` (e.g., `import { repo } from "@dockstat/utils"` instead of direct path imports).
- Update various project dependencies.
* fix(formatting): adjusted imports
* feat(docknode-management): Introduce API, UI, and backend for DockNode registration
This commit introduces a comprehensive system for managing DockNode instances from the main DockStat API and frontend. Users can now register, monitor, and remove external DockNode servers, enhancing distributed management capabilities.
**Key Changes:**
* **API (`apps/api`):**
* Added `@dockstat/docknode` and `@elysiajs/eden` dependencies.
* Implemented `DockNodeHandler` to manage DockNode registration within a new `docknode-register` SQLite table. This includes functionality for checking node reachability, creating, and deleting entries.
* Exposed new `/api/v2/node` endpoints (`GET`, `POST`, `DELETE`) for performing CRUD operations on DockNode registrations.
* Defined Elysia TypeBox models for robust API request validation.
* **DockNode (`apps/docknode`):**
* Added a `GET /api/status` endpoint, allowing the main API to perform health checks and determine if a registered DockNode is online.
* Configured the SQLite database to use Write-Ahead Logging (WAL) journal mode for improved performance and data integrity.
* **Frontend (`apps/dockstat`):**
* Created a new "DockNodes" page (`src/pages/node/index.tsx`) in the UI to list, create, and delete DockNode registrations.
* Developed the `DockNodeCard` React component to visually represent each registered node, displaying its status, host, port, SSL usage, and providing options for interaction.
* Integrated new `useEdenQuery` and `useEdenMutation` hooks for seamless interaction with the API.
* **Database & Typings (`packages/db`, `packages/typings`):**
* Refactored the `tls_certs_and_keys` field in the main `config` table to a more generic `keys` object.
* Extended the `keys` object to include a dedicated slot for `docknode` specific API keys, enabling future secure communication.
* Improved type definitions for foreign keys in `packages/sqlite-wrapper`.
* **Utilities (`packages/utils`):**
* Introduced a new set of React Query-based utility hooks (`useEdenQuery`, `useEdenMutation`, `useEdenRouteMutation`) for `elysia/eden` clients. These hooks simplify data fetching and mutations, providing standardized error handling, loading states, and automatic query invalidation.
* Added `@tanstack/react-query` as a dependency.
* **Build & Development:**
* Updated the `dev:dockstat` script to include `--filter=@dockstat/docknode` for integrated development.
* Updated various dependencies across the monorepo.
This feature lays the groundwork for centralized management of distributed DockNode services.
* chore(ci): Lint [skip ci]
* refactor(ui): Enhance Slides animation and DockNodeCard UI
Refactor the `Slides` component in `@packages/ui` to dynamically measure and animate content height. This change leverages `ResizeObserver` to ensure that slides with dynamic content automatically adjust their height during transitions, resulting in a smoother and more responsive user experience. The previous `collapseVariants` animation logic is replaced with direct height and opacity animations. Additionally, the `overflow-hidden` class is removed from the `Slides` `CardBody` as `SlideContent` now manages its own overflow for animation.
Redesign the `DockNodeCard` component in the `dockstat` application, introducing significant visual and structural improvements:
- Updated layout and spacing for better readability.
- Refined typography and enhanced status badges.
- Improved presentation of connection details.
- Restyled `CardFooter` with updated action button presentation and text ("Visit" changed to "Open").
- Minor adjustments to event handling for the delete action, including explicit `e.stopPropagation()`.
* Feat settings page (#76)
* feat(hotkeys): Implement configurable hotkey management
Introduce a comprehensive hotkey management system within the application settings.
- **API:** Added a new `POST /config/hotkey` endpoint to allow users to update and persist their hotkey preferences in the database.
- **Frontend (DockStat):**
- Created a new `SettingsPage` with a dedicated "Hotkeys" slide.
- The `HotkeysSlide` provides an intuitive UI for users to configure global hotkeys, including support for `CTRL + SHIFT + <key>` combinations.
- Integrates with the new API endpoint to save changes and provides immediate feedback.
- **Hotkeys Utility:** Enhanced the `useHotkey` hook to support `shift+key` combinations and a generic `toggle` function, making hotkey handling more flexible.
- **Configuration:** Updated default hotkey configurations to include new actions such as `open:sidebar` and `close:sidebar`.
- **UI Integration:** Adapted components like `Navbar` and `LinkLookup` to consume dynamic hotkey configurations.
- **Database/Typings:** Updated database models and type definitions (`DatabaseModel.hotkeyRes`, `DatabaseModel.hotkeyBody`, `HotkeyAction`) to reflect the new hotkey structure.
* refactor(codebase): Reorder imports and remove unused declarations
* feat(settings): Introduce General Settings page and API config management
This commit introduces a new "General Settings" page in the DockStat frontend and expands the backend API for configuration management.
Key changes include:
* **API & Database (`apps/api`, `packages/db`, `packages/typings`):**
* **Fix(config):** Corrected a widespread typo from `addtionalSettings` to `additionalSettings` in database schemas, typings, default configurations, and API models. This ensures consistency and correctness of the configuration object.
* Added `GET /db/details` and `GET /db/details/:tableName/all` endpoints for database introspection, providing schema information and raw table data.
* Implemented `POST /db/config/additionalSettings` for updating application-wide settings such as `showBackendRamUsageInNavbar`.
* Added TypeBox schemas for `additionalSettingsBody` and `additionalSettingsRes`.
* **Frontend (`apps/dockstat`):**
* Introduced the `GeneralSettingsSlide` component as the main entry point for general settings.
* Implemented `PinnedNavSection` to manage user-pinned navigation links.
* Developed `PinnableLinksSection` to allow users to discover and pin available dashboard links, including those provided by plugins.
* Added `PluginLinksSection` to display all detected plugin-provided routes.
* Created `AdditionalSettingsSection` to control specific application behaviors, starting with the option to display backend RAM usage in the navbar.
* Updated the `/settings` page to integrate the new `GeneralSettingsSlide`.
* Refactored the `ConfigProvider` to correctly handle `additionalSettings` and provide it to the application context.
* Minor UI adjustments in `HostsList` and `ClientsPage` for improved layout and consistency.
* Fixed hotkey display to correctly replace both `_` and `:` with spaces.
* **UI Library (`packages/ui`):**
* Expanded `Badge` component with an `xs` size option.
* Adjusted `Divider` vertical orientation to use `min-h-full` for better responsiveness.
* Enhanced `Slides` component with improved content transition animations and a `ResizeObserver` for dynamic height adjustments.
* Exported `SidebarPaths` and `PathItem` from Navbar for broader use in navigation.
* **Other:**
* Updated `apps/docknode/.gitignore` to include `docknode.db*` for better exclusion of database files and backups.
This comprehensive update streamlines configuration management and provides users with more control over their DockStat experience.
* chore(ci): Lint [skip ci]
* fix(formatting): adjusted imports
* fix(remove unwanted): remove database file from git tree
* feat(ui, api): Enhance UI components and streamline API error responses
Refactor:
- API: Removed redundant 'error' field from additional settings update error response in `db.ts` to ensure consistent error payload with `message`.
Dockstat App:
- UI/Hosts: Simplified the display for "no hosts configured" by removing an unnecessary card and icon.
- UI/Settings: Enhanced pinned navigation section with a fixed height, vertical resizing, and scroll functionality for improved usability.
UI Package:
- Badges: Corrected `xs` badge padding from `py-.5` to `py-0.5` for consistent styling.
- Slides: Fixed `useSlideState` by adding `activeSlide` to `useEffect` dependencies, ensuring proper re-measurement on slide changes.
- Theme Browser: Added `m-1` margin to `ThemePreviewCard` for improved visual spacing between theme previews.
* feat(db:migration): Implement automatic schema migration (#78)
* feat(db:migration): Implement automatic schema migration
This commit introduces automatic schema migration capabilities to the `sqlite-wrapper`.
The `db.createTable()` method now automatically detects schema changes when a table already exists and performs an atomic migration if differences are found. This process ensures smooth schema evolution without manual intervention, including:
- Creating a temporary table with the new schema.
- Copying existing data, mapping common columns and applying defaults for new ones.
- Recreating indexes, triggers, and foreign key constraints.
- Swapping the tables safely within a transaction.
**Key Migration Features & Options:**
- **Schema Detection**: Automatically identifies additions, removals, and changes in column constraints (NOT NULL, UNIQUE, Primary Key status) and types.
- **Data Preservation**: Data is preserved by default (`preserveData: true`), with options to control how constraint violations are handled (`onConflict: 'fail' | 'ignore' | 'replace'`).
- **Customization**: Supports `dropMissingColumns` and `tempTableSuffix` for fine-grained control.
- **Disabling Migration**: Migration can be explicitly disabled per table using `migrate: false` in `TableOptions`.
- **Type Handling**: Correctly migrates JSON and Boolean columns.
This feature significantly simplifies schema management for applications using `sqlite-wrapper`.
A new test suite (`__test__/migration.test.ts`) has been added to thoroughly validate various migration scenarios.
The `README.md` has been updated to document the new "Automatic Schema Migration" feature in detail, including usage examples and best practices. The package version is bumped to `1.3.5`.
* deps(bun): update @types/bun to 1.3.9
* fix(migration): improve migration robustness and add comprehensive tests
Migration robustness:
- Foreign key `PRAGMA` statements are now correctly handled outside the migration transaction, ensuring proper disabling and re-enabling of FK constraints for reliable table alterations.
- Improved logging in `schemasAreDifferent` to provide more detail on column count differences.
- The `currentSchema` is now passed to `migrateTable` from `checkAndMigrate` to avoid redundant database calls.
New migration tests:
- Added a test to verify that migration fails with the default `onConflict` strategy when constraints (e.g., `NOT NULL`) are violated.
- Added tests to confirm that no actual migration (ALTER TABLE) occurs when switching between type aliases (e.g., `TEXT` to `JSON`, `INTEGER` to `BOOLEAN`), ensuring data is preserved and correctly interpreted.
Type centralization:
- Moved `TableColumn`, `IndexInfo`, `ForeignKeyInfo`, and `ForeignKeyStatus` interfaces to `src/types.ts` for better organization and reusability.
Minor fixes and improvements:
- Corrected the in-memory database name check from `:memory` to `:memory:` in the `DB` class.
- Updated README.md to fix a typo from "Wrong packing" to "incorrect packaging".
- Removed the `dropMissingColumns` option from `MigrationOptions` as it was never implemented.
* Sqlite wrapper automatic table migration on schema change (#79)
* feat(db:migration): Implement automatic schema migration
This commit introduces automatic schema migration capabilities to the `sqlite-wrapper`.
The `db.createTable()` method now automatically detects schema changes when a table already exists and performs an atomic migration if differences are found. This process ensures smooth schema evolution without manual intervention, including:
- Creating a temporary table with the new schema.
- Copying existing data, mapping common columns and applying defaults for new ones.
- Recreating indexes, triggers, and foreign key constraints.
- Swapping the tables safely within a transaction.
**Key Migration Features & Options:**
- **Schema Detection**: Automatically identifies additions, removals, and changes in column constraints (NOT NULL, UNIQUE, Primary Key status) and types.
- **Data Preservation**: Data is preserved by default (`preserveData: true`), with options to control how constraint violations are handled (`onConflict: 'fail' | 'ignore' | 'replace'`).
- **Customization**: Supports `dropMissingColumns` and `tempTableSuffix` for fine-grained control.
- **Disabling Migration**: Migration can be explicitly disabled per table using `migrate: false` in `TableOptions`.
- **Type Handling**: Correctly migrates JSON and Boolean columns.
This feature significantly simplifies schema management for applications using `sqlite-wrapper`.
A new test suite (`__test__/migration.test.ts`) has been added to thoroughly validate various migration scenarios.
The `README.md` has been updated to document the new "Automatic Schema Migration" feature in detail, including usage examples and best practices. The package version is bumped to `1.3.5`.
* deps(bun): update @types/bun to 1.3.9
* fix(migration): improve migration robustness and add comprehensive tests
Migration robustness:
- Foreign key `PRAGMA` statements are now correctly handled outside the migration transaction, ensuring proper disabling and re-enabling of FK constraints for reliable table alterations.
- Improved logging in `schemasAreDifferent` to provide more detail on column count differences.
- The `currentSchema` is now passed to `migrateTable` from `checkAndMigrate` to avoid redundant database calls.
New migration tests:
- Added a test to verify that migration fails with the default `onConflict` strategy when constraints (e.g., `NOT NULL`) are violated.
- Added tests to confirm that no actual migration (ALTER TABLE) occurs when switching between type aliases (e.g., `TEXT` to `JSON`, `INTEGER` to `BOOLEAN`), ensuring data is preserved and correctly interpreted.
Type centralization:
- Moved `TableColumn`, `IndexInfo`, `ForeignKeyInfo`, and `ForeignKeyStatus` interfaces to `src/types.ts` for better organization and reusability.
Minor fixes and improvements:
- Corrected the in-memory database name check from `:memory` to `:memory:` in the `DB` class.
- Updated README.md to fix a typo from "Wrong packing" to "incorrect packaging".
- Removed the `dropMissingColumns` option from `MigrationOptions` as it was never implemented.
* refactor(sqlite-wrapper): Extract createTable helper methods
Introduces `normalizeMigrationOptions` to centralize the parsing of the `migrate` option into a standardized `{ enabled, options }` object.
Adds `shouldCheckExistingTable` to encapsulate the conditions for checking if a table already exists (e.g., excluding temporary or in-memory tables).
These private helper methods refactor the `createTable` method, improving its readability and maintainability by extracting complex conditional logic. This makes the `createTable` method more focused on its primary responsibility.
* feat(sqlite-wrapper): Introduce migration onConflict options and SQL-based schema comparison
**Migration Conflict Resolution:** Adds `onConflict` options (`ignore` and `replace`) to schema migration, allowing users to define how existing data is handled when new unique constraints are introduced during a migration.
**Robust Schema Comparison:** Reworks the `schemasAreDifferent` logic to compare the full `CREATE TABLE` SQL statements. This provides a more precise and comprehensive detection of schema changes, including intricate column definitions, constraints, and default values, greatly improving migration reliability.
**SQL Generation Refactoring:** Extracts the `CREATE TABLE` SQL generation into a new `buildTableSQL` utility function, enhancing modularity and reusability.
**Standardized Migration Options:** Normalizes the `migrate` option in `TableOptions` to always be a `MigrationOptions` object, providing a consistent API for configuring migration behavior.
Updates internal schema retrieval mechanisms and tests to leverage the full `CREATE TABLE` SQL for migration decisions.
* fix(sqlite-wrapper): Correct handling of 'migrate' option in migrateTable
* refactor(types): Relax column definition type constraints
The `InferTableSchema` type in `plugin-builder` and `PluginConfig['table']['columns']` (along with `DBPlugin`'s generic type) in `typings` were previously constrained to `Record<string, ColumnDefinition>`.
This commit relaxes these constraints to `Record<string, unknown>`. This change offers greater flexibility for defining columns within plugin configurations and during table schema inference, reducing tight coupling to the `ColumnDefinition` type from `@dockstat/sqlite-wrapper`. It allows for more generic or custom column definitions without needing to strictly conform to `ColumnDefinition` at the interface level.
Additionally, this commit includes minor import reordering in `sqlite-wrapper` and `migration` for consistency.
* feat(sqlite-wrapper): Prevent auto-migration for temporary and in-memory tables
The `createTable` method will no longer automatically apply schema migrations to certain types of tables.
This change introduces an `allowMigration` utility that determines if a table is eligible for automatic schema migration based on its properties and name. Migrations are now explicitly denied for:
- Tables created with the `temporary: true` option.
- In-memory tables (identified by the name `":memory:"`).
- Tables prefixed with `temp_` (which SQLite uses for internal temporary objects).
- Tables used internally by the migration process (matching `_migration_temp` suffix).
This ensures that only persistent, user-managed tables are subject to schema changes, preventing unintended modifications to ephemeral table structures.
Additionally, the `createTable` method now includes a `try...catch` block to handle `SQLiteError` with `errno === 1` (table already exists). This allows the method to gracefully proceed and return the `QueryBuilder` for an existing table even if a `CREATE TABLE` statement fails because the table already exists, ensuring robust behavior in various scenarios.
New tests have been added to validate that temporary and in-memory tables do not trigger automatic schema migrations.
---------
Signed-off-by: ItsNik <info@itsnik.de>
* 80 migrations always run when ifnotexists is true (#81)
* feat(migration): Implement automatic table schema migration and refactor logging
This release introduces robust automatic schema migration capabilities for tables managed by `sqlite-wrapper`, alongside a comprehensive refactor of the internal logging system.
**Automatic Schema Migration:**
* **Intelligent Detection**: `createTable` now automatically detects schema differences (column additions, removals, constraint changes, default values) between the existing table and the desired schema.
* **Data Preservation**: Migrations are performed without data loss by creating a temporary table, copying data, and re-creating the original table.
* **Flexible Conflict Handling**: Supports `onConflict` strategies (`ignore`, `replace`) during migration when adding unique constraints that might conflict with existing data.
* **Index and Foreign Key Preservation**: Ensures that existing indexes and foreign key constraints are re-established after migration.
* **Alias-Aware Type Handling**: Correctly identifies column type aliases (e.g., `JSON` as `TEXT`, `BOOLEAN` as `INTEGER`) to prevent unnecessary migrations.
* **Migration Control**: Introduces `migrate` options to explicitly enable/disable migration or customize the temporary table suffix.
* **Exclusion for Special Tables**: Automatically skips migration for `:memory:` databases and `TEMPORARY` tables.
* **Enhanced Comparison**: The `schemasAreDifferent` logic has been improved to normalize `CREATE TABLE` statements (removing …
* chore(api): Add startup animation, logger config, and API dev script (#63) (#64)
* chore(api): Add startup animation, logger config, and API dev script (#63)
* docs: sync from Outline
* 66 logger x docker client the current workers do not forward their logs (#67)
* refactor(logging): Standardize cross-process log handling and improve UI
Introduces a centralized logging mechanism to forward log entries generated by workers to the main process. This ensures all application logs are consistently processed and displayed.
- **Logger:** Made `Logger.emitLogEntry` public and enhanced it to accept metadata for accurate log re-emission from various sources. Added a visual indicator for log hooks in formatted messages.
- **Docker Client:**
- Implemented `WorkerLogger` in `docker-client` workers to proxy log entries via a new `__log__` event.
- The `docker-client` manager now listens for and re-emits `__log__` events through the main logger.
- Refactored worker-related types (`InboundMessage`, `InitMessage`, `MetricsMessage`) and utility functions (`tryBuildFromProxy`) into dedicated shared files for better organization.
- **Typings:** Defined `LogLevel`, `LogEntry` types, and added the `__log__` event to the `EVENTS` interface to support structured log forwarding.
- **UI:** Updated the `Sidebar` to display the unified log stream with improved formatting, including colored log levels, badges for logger names/request IDs, and a new `log` timestamp format.
- **Utils:** Added a new `log` format to `formatDate` and standardized the default locale for date formatting to `de-DE`.
- **Dependencies:** Upgraded `@dockstat/docker-client` to `2.0.0` and numerous other dependencies (e.g., `framer-motion`, `react-router`, `@types/node`) to their latest patch/minor versions.
- **Cleanup:** Removed a debug `console.log` statement from `plugin-handler`.
* refactor(logging, client): improve logging detail and worker robustness
Update .env.example with refined default logger configurations to reduce noise and focus on `PluginHandler` messages. Forward `requestId` within `__log__` events to enhance log correlation. Strengthen worker initialization checks by explicitly verifying `message.success`. Streamline event typings by removing `workerLoggerResponse`. Includes minor import reordering and variable name correction for consistency.
* [ImgBot] Optimize images (#65)
* chore(api): Add startup animation, logger config, and API dev script (#63)
* docs: sync from Outline
* [ImgBot] Optimize images
*Total -- 389.34kb -> 261.94kb (32.72%)
/.github/assets/logos/square.png -- 81.10kb -> 20.42kb (74.82%)
/.github/assets/gifs/DockStatAPI-startup.gif -- 306.82kb -> 240.10kb (21.74%)
/packages/ui/public/vite.svg -- 1.42kb -> 1.42kb (0.07%)
Signed-off-by: ImgBotApp <ImgBotHelp@gmail.com>
* chore(assets): Add and organize GitHub assets, update README logo
---------
Signed-off-by: ImgBotApp <ImgBotHelp@gmail.com>
Co-authored-by: ItsNik <info@itsnik.de>
Co-authored-by: Its4Nik <106100177+Its4Nik@users.noreply.github.com>
Co-authored-by: ImgBotApp <ImgBotHelp@gmail.com>
* chore(gifs): Add .gitignore to ignore YML files
* 43 feat uiux add management of repositories (#71)
* refactor(data): Implement useEdenQuery/Mutation hooks for data fetching
- Introduced `useEdenQuery` and `useEdenMutation` to streamline API interaction with `@elysiajs/eden`.
- Centralized common data fetching patterns including error handling, automatic query invalidation, and toast notifications.
- Removed deprecated `lib/actions` and `lib/queries` directories; their functionalities are now integrated into the new hooks.
- Refactored all major components and pages (`AddClient`, `AddHost`, `PluginBrowser`, `Layout`, client and extension pages) to utilize the new data hooks.
- Consolidated `AdditionalSettingsContext` into a unified `ConfigProviderContext` for better state management.
- Enhanced `PluginHandler` to improve plugin security verification, including explicit checks for DVA connectivity.
- Added `RepoCard` component and `RepoIcons` for improved repository UI.
- Updated `installPluginBody` schema to omit the `plugin` field.
- Extended `parseFromDBToRepoLink` to support generating raw file links or repository tree/branch links.
* refactor(frontend): Remove redundant lib/actions pattern and aliases
The `lib/actions` directory and its associated pattern have been removed, as the `useEdenMutation` hook provides a more direct and integrated way to handle client-side API mutations.
This refactoring includes:
* Deleting `apps/dockstat/src/lib/actions` directory, including `README.md`, `executePluginAction.ts`, and `executePluginLoader.ts`.
* Updating `apps/dockstat/src/hooks/usePluginPage.ts` to directly use `useEdenMutation` for executing plugin loaders and actions, replacing the previously used helper functions.
* Removing `@Actions` and `@Queries` path aliases from `apps/dockstat/tsconfig.json` and `apps/dockstat/vite.config.ts`.
* Reorganizing import statements across various files in `apps/dockstat` for consistency.
This change simplifies the codebase by reducing unnecessary abstraction layers for API interactions.
* refactor(api): Remove redundant 'api.v2' prefix from route calls
The Eden API client in the frontend previously required routes to be accessed with a verbose `api.api.v2.<route>` prefix. This commit refactors the `src/lib/api.ts` file to directly export the `api.v2` namespace from the `treaty` client.
Consequently, all API calls throughout the frontend (`apps/dockstat/`) and documentation (`apps/docs/`) are updated to use the simplified `api.<route>` syntax. This change improves code readability, reduces verbosity, and streamlines interaction with the backend API.
Additionally, the environment variable for the API base URL was updated from `VITE_API_URL` to `DOCKSTAT_API_PORT` in `src/lib/api.ts`. Minor formatting adjustments were also applied in the integration guide README.
* feat(ui): Enhance repository management and introduce Select component
Refactor repository management in the frontend and introduce a reusable
Select component to improve form interactions.
- **apps/api**:
- Truncate error details in the metrics middleware for more concise logging.
- **apps/dockstat**:
- Redesign `RepoCard` component to include detailed security badges (Strict, Relaxed, No Verification),
display source and verification API clearly, and provide direct links.
- Implement a dedicated "Add Repository" form on the extensions page, replacing the previous placeholder,
with state management and validation.
- Integrate the new `Select` component for repository filtering in the plugin browser.
- **packages/ui**:
- Introduce a new generic `Select` component with support for different sizes, variants (default, filled, underline),
and styling options.
- Add corresponding CSS variables for the `Select` component.
- Extend `RepoIcons` component with a `size` prop for scalable icon rendering.
- Simplify verification badge logic within the `Repo` component.
- Update rendering keys in `Modal`, `RepoPluginSlide`, and `RepoList` for improved stability.
- **packages/utils**:
- Add handling for the `default` repository type in `parseFromDBToRepoLink` function.
* chore(ci): Lint [skip ci]
* feat(plugins): Refactor plugin page logic and introduce dedicated UI states
Splits the monolithic `usePluginPage` hook into modular, specialized hooks: `usePluginTemplate`, `usePluginState`, `usePluginLoaders`, and `usePluginActions`. This enhances maintainability and separation of concerns for plugin page management.
Introduces a new component file, `PluginPageStates.tsx`, to centralize UI rendering for various plugin page states, including loading, error, not found, and missing templates. This improves the user experience with clearer feedback.
Updates the `useEdenMutation` hook to support a `routeBuilder` pattern, enabling dynamic construction of API endpoints for plugin actions and loaders based on runtime parameters.
Performs minor cleanup by replacing unstable `key` props (e.g., using `Date` or `Math.random()`) with stable, deterministic values in several UI components for improved React reconciliation.
* chore: lint
* refactor(hooks): Split useEdenMutation into specialized hooks
The monolithic `useEdenMutation` hook has been refactored and split into several specialized components to improve modularity, clarify API usage, and enhance maintainability.
The changes include:
- **`apps/dockstat/src/hooks/eden/types.ts`**: Introduced to centralize shared types for Eden-related hooks.
- **`apps/dockstat/src/hooks/eden/useBaseEdenMutation.ts`**: Extracts the core `useMutation` logic, toast handling, and query invalidation into a reusable base hook.
- **`apps/dockstat/src/hooks/eden/useEdenMutation.ts`**: Provides a simplified interface for direct Eden API routes that do not require a route builder with dynamic parameters.
- **`apps/dockstat/src/hooks/eden/useEdenRouteMutation.ts`**: Provides an interface for Eden API routes that require parameters to build the route function at the time of mutation.
- **Removed `apps/dockstat/src/hooks/useEdenMutation.ts`**: The old, overloaded hook has been removed.
All existing consumers of the previous `useEdenMutation` have been updated to use the appropriate new specialized hook (`useEdenMutation` or `useEdenRouteMutation`) and their new import paths.
Additionally, corrected query invalidation keys for `pinNavLink` and `unpinNavLink` mutations in `layout.tsx` from `fetchNavLinks` to `fetchAdditionalSettings` to ensure proper cache updates.
* refactor(plugins): Extract plugin template logic to utils and address UI issues
Moved plugin page data normalization, template parsing, and fragment mapping from `usePluginTemplate` hook to a new utility file `src/utils/normalizePluginPageData.ts`. This centralizes complex data processing logic and simplifies the `usePluginTemplate` hook.
Also includes the following improvements:
- Corrected the import path for `useEdenMutation` in `usePluginTemplate.ts`.
- Fixed an issue in the plugin browser (`plugins.tsx`) where the repository `Select` component did not display the currently selected repository.
- Adjusted how the `isBusy` prop is passed to the `TopNav` component in `layout.tsx`.
- Reordered a `toast` import statement in `useBaseEdenMutation.ts` for consistency.
* deps(bun.lock): Update various package dependencies
---------
Co-authored-by: actions-user <its4nik@users.noreply.github.com>
* refactor(eden-hooks): Rename useEdenMutation to useEdenRouteMutation
* 70 dockstore refactor into dockstat repository (#72)
* feat(repo-cli): Introduce repository CLI for managing DockStat repos
This commit introduces a new `@dockstat/repo-cli` package, providing a command-line interface to assist with managing DockStat repositories.
Key functionalities include:
- `init`: Initialize a new repository configuration file.
- `bundle`: Bundle plugins within the repository and update the manifest.
- `badges`: Generate SVG badges based on repository content and configuration.
Additionally, a new `isRepoType` utility is added to `@dockstat/utils` for validating repository types.
* feat(repo-cli): Introduce local serving and consolidated repository config
Deprecate and remove the internal `apps/dockstore` tooling responsible for plugin bundling, README generation, and schema management. This includes `bundler.ts`, `generate-readme.ts`, `.schemas/plugin-meta.schema.json`, and related `package.json` scripts and config files.
Replaced the decentralized plugin metadata and manifest generation with a new, centralized `apps/dockstore/repo.json` file. This file now defines the repository's configuration (name, policy, verification_api, content directories) and serves as the single source of truth for repository content metadata (plugins, themes, stacks).
The `dockstat-repo-cli`'s `bundle` command has been updated to populate this new `repo.json` file with plugin metadata.
Added a new `serve` command to `dockstat-repo-cli`, enabling simple local serving of the repository's static files via `Bun.serve`. This is intended for development, testing, or use behind a reverse proxy.
Introduced `packages/dockstat-repo-cli/src/utils/contentType.ts` to support the new `serve` command by providing appropriate `Content-Type` headers.
* feat(repo-cli): introduce repository management CLI
* chore: bump versions in bun.lock
* chore(repo-config): Remove 'content/' prefix from module paths
* build(repo-cli): Configure package for publishing and metadata
Add .npmignore to exclude source files and build artifacts from published package.
Update package.json with version, description, and 'files' array for explicit publication control.
Correct the CLI executable name in the 'bin' field from 'dockstore-repo-cli' to 'dockstat-repo-cli'.
* fix(repo-cli): Correct CLI binary output filename
* fix(repo-cli): Sanitize served paths and refactor badge generation
refactor(repo-cli/badges): Consolidate badge creation logic
- Replaced repetitive conditional blocks for plugins, themes, and stacks with a configurable array and a loop.
- Improves code maintainability and extensibility for future badge types.
fix(repo-cli/serve): Prevent directory traversal attacks
- Added `filePath.replaceAll("../", "/")` to sanitize requested file paths.
- Mitigates a potential security vulnerability allowing access to files outside the intended content directory.
refactor(typings, utils): Remove 'default' repo type
- Removed "default" from the `Repo.type` union enum in `db.ts`.
- Removed "default" from the `REPO_TYPES` array in `isRepoType.ts`.
- Aligns type definitions and utility functions with current supported repository types.
* feat(repo): Implement manifest-based repository registration
This commit significantly overhauls the repository registration process, moving towards a manifest-driven approach.
**Key Changes:**
* **API (`apps/api`)**:
* The `POST /repositories` endpoint now accepts a single `link_to_manifest` (URL) instead of individual fields like name, source, type, and policy.
* The API fetches the manifest from the provided link, utilizes new utility functions to parse its content, and extracts the repository configuration for storage.
* Adds `@dockstat/repo-cli` dependency to facilitate manifest parsing.
* **Core Logic (`packages/utils/repo`)**:
* Introduces `parseRawToDB` to intelligently convert raw manifest URLs (GitHub, GitLab, Gitea, HTTP) into structured database `type` and `source` strings.
* Enhances `parseFromDBToRepoLink` for more robust URL reconstruction based on repository type and source.
* Adds helper functions `parseRepoParts` and `splitDomain` for robust URL decomposition.
* **Database (`packages/db`)**:
* Updates the `repositories_table` schema to include a `paths` column (JSON type) for storing manifest-defined paths for themes, plugins, and stacks.
* Enables automatic database backup functionality with configurable intervals, compression, and maximum backups. Backups are stored in a `.backups` directory.
* **Frontend (`apps/dockstat`)**:
* The "Add Repository" form in the Extensions page is simplified to a single input field for the raw manifest or repository link.
* Removes previously individual fields for name, source, type, policy, and verification API.
* **Typings**:
* `Repo` and `CreateRepo` types updated to include the new `paths` field and remove the "default" option from the `type` enum.
* `RepoFile` interface in `@dockstat/repo-cli` is extended for flexibility.
* **.gitignore**: Updated to exclude the `.backups` directory.
This refactor streamlines the user experience for adding new repositories and prepares the system for richer manifest-based capabilities.
* chore(ci): Lint [skip ci]
* feat(plugins, api, build): Introduce DockStacks plugin and standardize publishing
- Introduce the new `DockStacks` plugin for managing Docker container stacks. This includes its initial project setup, definition using `@dockstat/plugin-builder`, and configuration types.
- Update the API route (`apps/api/src/routes/db.ts`) to store specific `paths` (plugins, stacks, themes) in the repository configuration upon creation. This allows repositories to define structured locations for different asset types.
- Standardize the package publishing process across core utility packages (`@dockstat/plugin-builder`, `@dockstat/repo-cli`, `@dockstat/sqlite-wrapper`, `@dockstat/typings`, `@dockstat/utils`) by adding a dedicated `publish` script to each `package.json`.
- Add root-level `publish` and `pub` commands to the monorepo `package.json` for simplified execution of package publishing.
- Bump versions for `@dockstat/plugin-builder` and `@dockstat/typings`.
* merge
* merge
* feat(docknode): Initial application setup with Bun and Elysia
Replaces the previous subproject entry with a new implementation of the DockNode application.
This commit establishes the foundational structure for DockNode, leveraging Bun runtime and the Elysia web framework.
Key components include:
- Integration with @dockstat/sqlite-wrapper for local database management.
- A StackHandler for dynamic creation, configuration, and orchestration of Docker Compose stacks.
- Essential project configuration such as .gitignore, tsconfig, and package.json.
* style(fmt): Standardize TS and TSConfig formatting
Reordered import statements in `apps/docknode/src/stacks/index.ts`.
Standardized comment placement and property delimiters (commas vs. semicolons) in `apps/docknode/tsconfig.json` and `packages/typings/src/v2/extensions/stacks/compose.d.ts`.
These changes improve code consistency and readability.
* feat(dev-env): Introduce Dockerized local development environment
Adds a comprehensive Docker Compose setup for consistent local development, coupled with significant ecosystem and dependency updates.
- **Docker Development Environment:**
- Introduced `docker-compose.dev.yaml` to provide isolated services:
- `socket-proxy`: For secure Docker socket access.
- `sqlite-web`: Two instances for inspecting `dockstat.sqlite` and `verification.db`.
- `prometheus`: For collecting application metrics.
- Added `dockstat-dev.prometheus.yml` to configure Prometheus to scrape metrics from the API.
- Updated `package.json` scripts (`docker-up`, `docker-up:quiet`, `dev:dockstat`) to integrate with the new Docker setup.
- **Bun and Dependency Updates:**
- Upgraded Bun runtime from `1.3.1` to `1.3.6`.
- Migrated core dependencies (`elysia`, `@elysiajs/eden`) to Bun's package catalog for enhanced dependency management and resolution.
- Performed various dependency updates across the monorepo, including `turbo`, `typescript`, `@types/bun`, `@types/react`, `js-yaml`, `@elysiajs/openapi`, `rollup`, `@sinclair/typebox`, `docker-compose`, `framer-motion`, `storybook`, and `@typescript-eslint` packages.
* Update packages/repo-cli/src/types.ts
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
Signed-off-by: ItsNik <info@itsnik.de>
* chore(docknode): update gitignore to exclude local environment files [DOCK-123]
Added patterns for local backup directories, stack configurations, and database files to prevent them from being tracked in version control. Updated the formatting for the bun lockfile entry.
* build(deps): bump dependencies in bun.lock
Update various project dependencies to their latest versions, including Babel, ESLint, Storybook, Tailwind CSS, TypeScript, and Rollup components.
---------
Signed-off-by: ItsNik <info@itsnik.de>
Co-authored-by: actions-user <its4nik@users.noreply.github.com>
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
* 88 refactor themesidebarcontext to separate UI state remove themeprops bag and avoid no op defaults (#94)
* feat(repo-cli): Introduce repository CLI for managing DockStat repos
This commit introduces a new `@dockstat/repo-cli` package, providing a command-line interface to assist with managing DockStat repositories.
Key functionalities include:
- `init`: Initialize a new repository configuration file.
- `bundle`: Bundle plugins within the repository and update the manifest.
- `badges`: Generate SVG badges based on repository content and configuration.
Additionally, a new `isRepoType` utility is added to `@dockstat/utils` for validating repository types.
* feat(repo-cli): Introduce local serving and consolidated repository config
Deprecate and remove the internal `apps/dockstore` tooling responsible for plugin bundling, README generation, and schema management. This includes `bundler.ts`, `generate-readme.ts`, `.schemas/plugin-meta.schema.json`, and related `package.json` scripts and config files.
Replaced the decentralized plugin metadata and manifest generation with a new, centralized `apps/dockstore/repo.json` file. This file now defines the repository's configuration (name, policy, verification_api, content directories) and serves as the single source of truth for repository content metadata (plugins, themes, stacks).
The `dockstat-repo-cli`'s `bundle` command has been updated to populate this new `repo.json` file with plugin metadata.
Added a new `serve` command to `dockstat-repo-cli`, enabling simple local serving of the repository's static files via `Bun.serve`. This is intended for development, testing, or use behind a reverse proxy.
Introduced `packages/dockstat-repo-cli/src/utils/contentType.ts` to support the new `serve` command by providing appropriate `Content-Type` headers.
* feat(repo-cli): introduce repository management CLI
* chore: bump versions in bun.lock
* chore(repo-config): Remove 'content/' prefix from module paths
* build(repo-cli): Configure package for publishing and metadata
Add .npmignore to exclude source files and build artifacts from published package.
Update package.json with version, description, and 'files' array for explicit publication control.
Correct the CLI executable name in the 'bin' field from 'dockstore-repo-cli' to 'dockstat-repo-cli'.
* fix(repo-cli): Correct CLI binary output filename
* fix(repo-cli): Sanitize served paths and refactor badge generation
refactor(repo-cli/badges): Consolidate badge creation logic
- Replaced repetitive conditional blocks for plugins, themes, and stacks with a configurable array and a loop.
- Improves code maintainability and extensibility for future badge types.
fix(repo-cli/serve): Prevent directory traversal attacks
- Added `filePath.replaceAll("../", "/")` to sanitize requested file paths.
- Mitigates a potential security vulnerability allowing access to files outside the intended content directory.
refactor(typings, utils): Remove 'default' repo type
- Removed "default" from the `Repo.type` union enum in `db.ts`.
- Removed "default" from the `REPO_TYPES` array in `isRepoType.ts`.
- Aligns type definitions and utility functions with current supported repository types.
* feat(repo): Implement manifest-based repository registration
This commit significantly overhauls the repository registration process, moving towards a manifest-driven approach.
**Key Changes:**
* **API (`apps/api`)**:
* The `POST /repositories` endpoint now accepts a single `link_to_manifest` (URL) instead of individual fields like name, source, type, and policy.
* The API fetches the manifest from the provided link, utilizes new utility functions to parse its content, and extracts the repository configuration for storage.
* Adds `@dockstat/repo-cli` dependency to facilitate manifest parsing.
* **Core Logic (`packages/utils/repo`)**:
* Introduces `parseRawToDB` to intelligently convert raw manifest URLs (GitHub, GitLab, Gitea, HTTP) into structured database `type` and `source` strings.
* Enhances `parseFromDBToRepoLink` for more robust URL reconstruction based on repository type and source.
* Adds helper functions `parseRepoParts` and `splitDomain` for robust URL decomposition.
* **Database (`packages/db`)**:
* Updates the `repositories_table` schema to include a `paths` column (JSON type) for storing manifest-defined paths for themes, plugins, and stacks.
* Enables automatic database backup functionality with configurable intervals, compression, and maximum backups. Backups are stored in a `.backups` directory.
* **Frontend (`apps/dockstat`)**:
* The "Add Repository" form in the Extensions page is simplified to a single input field for the raw manifest or repository link.
* Removes previously individual fields for name, source, type, policy, and verification API.
* **Typings**:
* `Repo` and `CreateRepo` types updated to include the new `paths` field and remove the "default" option from the `type` enum.
* `RepoFile` interface in `@dockstat/repo-cli` is extended for flexibility.
* **.gitignore**: Updated to exclude the `.backups` directory.
This refactor streamlines the user experience for adding new repositories and prepares the system for richer manifest-based capabilities.
* chore(ci): Lint [skip ci]
* feat(plugins, api, build): Introduce DockStacks plugin and standardize publishing
- Introduce the new `DockStacks` plugin for managing Docker container stacks. This includes its initial project setup, definition using `@dockstat/plugin-builder`, and configuration types.
- Update the API route (`apps/api/src/routes/db.ts`) to store specific `paths` (plugins, stacks, themes) in the repository configuration upon creation. This allows repositories to define structured locations for different asset types.
- Standardize the package publishing process across core utility packages (`@dockstat/plugin-builder`, `@dockstat/repo-cli`, `@dockstat/sqlite-wrapper`, `@dockstat/typings`, `@dockstat/utils`) by adding a dedicated `publish` script to each `package.json`.
- Add root-level `publish` and `pub` commands to the monorepo `package.json` for simplified execution of package publishing.
- Bump versions for `@dockstat/plugin-builder` and `@dockstat/typings`.
* merge
* merge
* feat(docknode): Initial application setup with Bun and Elysia
Replaces the previous subproject entry with a new implementation of the DockNode application.
This commit establishes the foundational structure for DockNode, leveraging Bun runtime and the Elysia web framework.
Key components include:
- Integration with @dockstat/sqlite-wrapper for local database management.
- A StackHandler for dynamic creation, configuration, and orchestration of Docker Compose stacks.
- Essential project configuration such as .gitignore, tsconfig, and package.json.
* style(fmt): Standardize TS and TSConfig formatting
Reordered import statements in `apps/docknode/src/stacks/index.ts`.
Standardized comment placement and property delimiters (commas vs. semicolons) in `apps/docknode/tsconfig.json` and `packages/typings/src/v2/extensions/stacks/compose.d.ts`.
These changes improve code consistency and readability.
* feat(dev-env): Introduce Dockerized local development environment
Adds a comprehensive Docker Compose setup for consistent local development, coupled with significant ecosystem and dependency updates.
- **Docker Development Environment:**
- Introduced `docker-compose.dev.yaml` to provide isolated services:
- `socket-proxy`: For secure Docker socket access.
- `sqlite-web`: Two instances for inspecting `dockstat.sqlite` and `verification.db`.
- `prometheus`: For collecting application metrics.
- Added `dockstat-dev.prometheus.yml` to configure Prometheus to scrape metrics from the API.
- Updated `package.json` scripts (`docker-up`, `docker-up:quiet`, `dev:dockstat`) to integrate with the new Docker setup.
- **Bun and Dependency Updates:**
- Upgraded Bun runtime from `1.3.1` to `1.3.6`.
- Migrated core dependencies (`elysia`, `@elysiajs/eden`) to Bun's package catalog for enhanced dependency management and resolution.
- Performed various dependency updates across the monorepo, including `turbo`, `typescript`, `@types/bun`, `@types/react`, `js-yaml`, `@elysiajs/openapi`, `rollup`, `@sinclair/typebox`, `docker-compose`, `framer-motion`, `storybook`, and `@typescript-eslint` packages.
* feat(docknode): Implement core DockNode features and Docker stack management
- Introduce Dockerfile for containerizing the DockNode application.
- Develop a comprehensive StackHandler for Docker Compose stack management, including:
- CRUD operations (create, get, list, update, delete, rename, export).
- Lifecycle commands (up, down, stop, restart, pull).
- Information commands (ps, logs, config, network stats, version).
- Execution commands (exec, run, rm, kill, port).
- Expose stack management functionalities via new `/api/stacks` endpoints.
- Integrate `docker-compose` for orchestration and `dockerode` for Docker API interaction.
- Add `.dockerignore`, `.npmignore`, and update `.gitignore` for relevant file exclusions.
- Update `README.md` with DockNode description and API examples.
- Introduce application-specific logger and utility functions.
- Configure `tsconfig.json` for ESNext and bundler module resolution.
- Add necessary dependencies for Docker client, logger, typings, utilities, and OpenAPI.
* build(dockstacks): Add @dockstat/logger dependency
* feat(docker-client): Export core DockerClient directly and refine constructor options
The `DockerClient` class is now directly exportable and importable via `@dockstat/docker-client/client`, allowing for more flexible usage without needing to instantiate the `DockerClientManager`.
Additionally, the `options` parameter in the `DockerClientBase` constructor has been made required, ensuring explicit configuration for client instances.
The package version has been incremented to `2.0.1`.
* feat(docknode): Integrate shared docker client and update dependencies
* refactor(sqlite-wrapper): Restructure source code and modularize DB class
Moved all source files into a dedicated 'src/' directory to improve project structure and maintainability. This refactor also includes a significant modularization of the 'DB' class.
Key changes include:
* All core logic previously in 'index.ts' has been moved to 'src/index.ts'.
* Extracted various concerns from the 'DB' class into new helper modules under 'src/lib':
* Backup and restore operations moved to 'src/lib/backup'.
* Index creation and dropping moved to 'src/lib/index'.
* SQL helper functions like 'isSQLFunction' moved to 'src/lib/sql'.
* Table creation logic ('buildColumnSQL', 'buildTableConstraints', 'isTableSchema', 'setTableComment', 'getTableComment') moved to 'src/lib/table'.
* Updated all relative imports in test files to point to the new 'src/' paths.
* Adjusted 'package.json' and 'tsconfig.json' to reflect the new file structure and module resolution.
* Bumped package version to 1.3.3.
* feat(repo-cli): overhaul README documentation and rename package
- Renamed package from 'dockstore-cli' to '@dockstat/repo-cli' for consistent branding.
- Completely rewrote the README to provide comprehensive usage documentation:
- Added detailed installation instructions.
- Documented 'init', 'bundle', 'badges', and 'serve' commands with their options, descriptions, and requirement status.
- Included license information.
- Bumped package version to 1.0.4.
* feat(query-builder): Add detailed info-level logging to query execution and WHERE methods
- Introduce `safeStringify` utility in `WhereQueryBuilder` to robustly serialize complex values (including RegExp) for logging.
- Add info-level logs to `SelectQueryBuilder` execution methods (`all`, `get`, `count`, `exists`, `value`, `pluck`) to display built queries, parameters, and results.
- Add info-level logs to `WhereQueryBuilder` methods (`where`, `whereRgx`, `whereExpr`, `whereIn`, `whereOp`, `whereBetween`, `whereNull`, etc.) to track the construction of WHERE clauses and their parameters.
- Remove duplicate `safeStringify` implementation from `SelectQueryBuilder` to utilize the new base class helper.
- Bump package version to 1.3.4.
* formatting
* Feat theme handler (#73)
* feat(query-builder): Add detailed info-level logging to query execution and WHERE methods
- Introduce `safeStringify` utility in `WhereQueryBuilder` to robustly serialize complex values (including RegExp) for logging.
- Add info-level logs to `SelectQueryBuilder` execution methods (`all`, `get`, `count`, `exists`, `value`, `pluck`) to display built queries, parameters, and results.
- Add info-level logs to `WhereQueryBuilder` methods (`where`, `whereRgx`, `whereExpr`, `whereIn`, `whereOp`, `whereBetween`, `whereNull`, etc.) to track the construction of WHERE clauses and their parameters.
- Remove duplicate `safeStringify` implementation from `SelectQueryBuilder` to utilize the new base class helper.
- Bump package version to 1.3.4.
* formatting
* feat(theme-handler): Introduce theme-handler package for managing UI themes
This commit introduces the new `@dockstat/theme-handler` package, providing a comprehensive solution for managing UI themes across the application.
Key features include:
- **Client-side utilities**:
- React context (`ThemeContext`) for easily accessing theme data.
- Functions to dynamically apply theme variables (CSS custom properties) to the document.
- Local storage integration for persisting user theme preferences.
- **Server-side management**:
- `ThemeDB` class for robust SQLite database integration to store, retrieve, update, and delete themes.
- Elysia-based API routes (`/themes`) offering full CRUD capabilities for themes, including fetching by name or ID.
- **Default themes**:
- Ships with pre-defined "DockStat-Dark", "DockStat-Light", "DockStat-OLED", and "DockStat-UltraDark" themes, including their CSS variables and animation properties.
- **Bun & Elysia integration**:
- The package is set up with Bun for efficient dependency management and runtime, and Elysia for building high-performance API routes.
This package centralizes theme logic, making it easier to manage and apply consistent styling throughout the application.
* feat(ui): Add theme browser and selection functionality
This commit introduces a user interface for browsing and selecting application themes.
- **New `ThemeBrowser` Component**: A dedicated component is added to display available themes, each with a preview of its key color variables (background, primary text, accent, etc.). Users can select a theme from this browser.
- **Sidebar Integration**: The `Sidebar` component now includes a new 'Palette' icon button that opens a modal containing the `ThemeBrowser`.
- **`ThemeProps` Interface**: A `ThemeProps` interface is defined to facilitate passing theme-related data (list of themes, current theme ID, selection handler, open callback) from parent components to the `Sidebar` and subsequently to the `ThemeBrowser`.
- **Navbar Update**: The `Navbar` component is updated to accept and forward `themeProps` to the `Sidebar`, ensuring theme management can be controlled from higher up the component tree.
- Refactored the loading state check for pinned items in the Sidebar to use `mutationFn.isBusy` for a cleaner approach.
- Exports `ThemeBrowser` components for broader use within the `ui` package.
* refactor(sqlite-wrapper): Truncate excessively long stringified condition values
Introduce a `truncate` utility function to limit the length of strings.
Apply this utility within the `WhereQueryBuilder.safeStringify` method to prevent excessively long stringified values (e.g., from `JSON.stringify` or `String()`) from being returned. This improves readability in debugging logs or contexts where these values might be displayed, ensuring they don't consume too much space. The maximum length for truncated strings is set to 100 characters.
* feat(dockstat): Implement client-side theme management and provider
Introduce `ThemeProvider` to manage and apply themes within the DockStat UI. This includes:
- Adding `@dockstat/theme-handler` dependency.
- Creating `ThemeProviderContext` and `useTheme` hook for global theme state and access.
- Implementing `ThemeProvider` to handle theme fetching (by name/ID) from the API, applying themes to the document using `@dockstat/theme-handler/client` functions (`applyThemeToDocument`), and persisting user preferences (`saveThemePreference`, `loadThemePreference`).
- Integrating the `ThemeProvider` at the application root in `src/providers/index.tsx`.
- Updating `layout.tsx` to consume theme data and functions from `useTheme`, enabling theme selection capabilities in the sidebar.
- Adding a new `/stacks` route and a placeholder `StacksIndex` page.
* feat(api): Add theme management endpoints
* feat(docknode): Implement API key authentication
Introduces API key-based authentication to the docknode application. This implementation leverages the 'better-auth' library, configured to accept API keys via the 'x-docknode-key' header.
Key changes include:
- Addition of the 'better-auth' dependency to apps/docknode.
- Creation of 'src/auth/index.ts' to define the authentication setup.
- Updates to '.env.example' for `BETTER_AUTH_SECRET` and `BETTER_AUTH_URL` configuration.
- Minor updates to `bun.lock` and import reordering across various packages (e.g., `dockstat`, `sqlite-wrapper`, `theme-handler`) for consistency and dependency management.
* docs(all): Standardize formatting and add new content
- Refactored RSS feed websocket subscription path to `api.api.v2.misc.stats.rss` in `apps/dockstat/src/lib/websocketEffects/README.md`.
- Introduced a new documentation page for `Eden Query & Mutation Hooks` under `apps/docs/dockstat/patterns`, detailing `useEdenQuery` and `useEdenMutation` with code examples and type inference.
- Documented the `createIndex` method in `@dockstat/sqlite-wrapper`, providing comprehensive usage, options, and examples for index creation.
- Standardized Markdown table formatting across all documentation files for improved readability and consistency.
- Addressed minor formatting issues, including trailing commas in code snippets and ensuring all Markdown files end with a newline.
* Update apps/dockstat/src/providers/theme.tsx
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
Signed-off-by: ItsNik <info@itsnik.de>
* fix(db): Remove incomplete createIndex call
* refactor(dockstat/theme): Simplify API calls in theme provider
Remove `useEdenQuery` hooks from `ThemeProvider` and replace them with direct calls to the `api` client. This streamlines data fetching for themes (by name, by ID, and all themes) by eliminating an intermediate hook layer.
Consolidate theme application and persistence logic into a new `applyAndPersistTheme` callback for improved code reuse and clarity.
The `useTheme` hook also removes its explicit error throw for usage outside `ThemeProvider`, relying on `useContext` to return `undefined` when the context is not available.
* refactor(theme-handler): modularize server API routes and models
The `theme-handler` server API has been refactored into a more modular and organized structure.
Previously, all theme API routes and associated response models were defined in a single large file (`src/server/api.ts`). This commit breaks down this monolithic file into a clear directory structure:
* **`src/server/api/models/`**: Contains schema definitions for theme data (`themeModel.ts`), mutation payloads (`themePost.ts`), and standardized API responses (`themeResponses.ts`).
* **`src/server/api/routes/`**: Contains individual files for each set of API operations: `queries.ts` (GET), `mutations.ts` (POST), `update.ts` (PUT), and `delete.ts` (DELETE).
The main `createThemeRoutes` function now composes these smaller, focused route modules, improving maintainability and readability.
Additionally, the top-level `src/index.ts` has been updated to re-export `client` and `server` modules as namespaces (`export * as client from "./client"`), providing a clearer and more explicit import structure for consumers of the package.
This refactoring aims to improve code organization, reusability of API models, and overall maintainability of the `theme-handler` package.
* refactor(query-builder/logging): Centralize logging in Select and Where builders
Refactor logging logic within `SelectQueryBuilder` and `WhereQueryBuilder` by introducing dedicated private/protected helper methods.
This change:
- Consolidates common logging patterns for query initiation and results in `SelectQueryBuilder` into `logSelectStart` and `logSelectReturn`.
- Introduces `logColumnReturn` for consistent logging in `pluck` and `value` methods.
- Centralizes logging of `where` conditions and internal state in `WhereQueryBuilder` using `logWhere` and `logWhereState`.
- Improves consistency and readability of log messages across different query execution and condition building methods.
- Reduces code duplication for logging statements, making the code more maintainable.
* feat(ui, api, theme-handler): Implement user feedback toasts and enhance theme preview
- **`dockstat`**: Added toast notifications for successful pin/unpin operations and theme selection, providing immediate user feedback.
- **`ui`**: Overhauled the `ThemeBrowser` component to display a more dynamic and accurate color preview using validated theme variables. Extracted color constants and created a `getValidColors` utility.
- **`theme-handler`**:
- Introduced `onFinish` callback to `applyThemeToDocument` for client-side feedback integration.
- Corrected the logic in the theme creation route to prevent creating themes with duplicate names (bug fix).
- Updated theme response models to use `ThemeModel` consistently and refined the delete route's response type.
- **`api`**: Improved request completion logging by including the request URL path, enhancing observability.
* Update apps/docs/dockstat/patterns/eden-query-&-mutation-hooks/README.md
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
Signed-off-by: ItsNik <info@itsnik.de>
* refactor(components): Remove unused props and refine component types
Omit 'paths' from `RepoCard` props definition to align with actual usage.
Remove 'isLoading' from `ThemeProps` in `Sidebar` as it is no longer required.
Perform minor whitespace cleanup in the `WhereQueryBuilder`.
---------
Signed-off-by: ItsNik <info@itsnik.de>
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
* feat(hotkeys, node, ui): Introduce configurable hotkeys and DockNode pages
This commit brings significant updates including configurable hotkeys, a new DockNode section, and various UI enhancements.
**Hotkeys:**
- Add `hotkeys` field to the global configuration schema (`DockStatConfigTable`) and context (`ConfigProviderData`).
- Define `HotkeyAction` type for better type safety of configurable hotkey actions (e.g., "open:quicklinks").
- Set a default hotkey `k` for opening quick links in the database defaults.
- Integrate configurable hotkeys into the `Navbar` and `LinkLookup` components, allowing customization of the quick links modal hotkey.
**DockNode & Stacks:**
- Create new pages for `/node` (DockNode overview) and `/node/stacks` (Stacks within a DockNode).
- Refactor and move the existing `/stacks` functionality to the new `/node/stacks` route, deleting the old `/stacks` page.
- Update the application router and sidebar navigation to reflect the new DockNode structure.
**UI & Accessibility:**
- Enhance the `Card` component with a `tabIndex` prop to improve keyboard navigation and focus management.
- Adjust tab indexing within the `LinkLookup` modal for better accessibility.
- Apply minor styling and structure adjustments to sidebar items, including child item formatting.
**Refactoring:**
- Streamline theme loading state management in the main layout by removing unnecessary `isLoading` prop from `useTheme` consumer.
* feat(hotkeys): Introduce `useHotkey` hook and add sidebar toggle
Create a new `useHotkey` React hook in `@dockstat/utils/react` to provide a centralized and declarative way for components to manage keyboard shortcuts.
- Migrate existing hotkey handling logic in `LinkLookup` component (for quick links modal) to utilize the new `useHotkey` hook.
- Integrate the `useHotkey` hook into the `Navbar` component to manage sidebar `open`, `close`, and `toggle` actions, making hotkey management consistent.
- Add `toggle:sidebar` hotkey (`b` by default) to the default application configuration in `packages/db`.
- Refactor utility imports across `apps/api` and `packages/plugin-handler` to use barrel exports from `@dockstat/utils` (e.g., `import { repo } from "@dockstat/utils"` instead of direct path imports).
- Update various project dependencies.
* fix(formatting): adjusted imports
* feat(docknode-management): Introduce API, UI, and backend for DockNode registration
This commit introduces a comprehensive system for managing DockNode instances from the main DockStat API and frontend. Users can now register, monitor, and remove external DockNode servers, enhancing distributed management capabilities.
**Key Changes:**
* **API (`apps/api`):**
* Added `@dockstat/docknode` and `@elysiajs/eden` dependencies.
* Implemented `DockNodeHandler` to manage DockNode registration within a new `docknode-register` SQLite table. This includes functionality for checking node reachability, creating, and deleting entries.
* Exposed new `/api/v2/node` endpoints (`GET`, `POST`, `DELETE`) for performing CRUD operations on DockNode registrations.
* Defined Elysia TypeBox models for robust API request validation.
* **DockNode (`apps/docknode`):**
* Added a `GET /api/status` endpoint, allowing the main API to perform health checks and determine if a registered DockNode is online.
* Configured the SQLite database to use Write-Ahead Logging (WAL) journal mode for improved performance and data integrity.
* **Frontend (`apps/dockstat`):**
* Created a new "DockNodes" page (`src/pages/node/index.tsx`) in the UI to list, create, and delete DockNode registrations.
* Developed the `DockNodeCard` React component to visually represent each registered node, displaying its status, host, port, SSL usage, and providing options for interaction.
* Integrated new `useEdenQuery` and `useEdenMutation` hooks for seamless interaction with the API.
* **Database & Typings (`packages/db`, `packages/typings`):**
* Refactored the `tls_certs_and_keys` field in the main `config` table to a more generic `keys` object.
* Extended the `keys` object to include a dedicated slot for `docknode` specific API keys, enabling future secure communication.
* Improved type definitions for foreign keys in `packages/sqlite-wrapper`.
* **Utilities (`packages/utils`):**
* Introduced a new set of React Query-based utility hooks (`useEdenQuery`, `useEdenMutation`, `useEdenRouteMutation`) for `elysia/eden` clients. These hooks simplify data fetching and mutations, providing standardized error handling, loading states, and automatic query invalidation.
* Added `@tanstack/react-query` as a dependency.
* **Build & Development:**
* Updated the `dev:dockstat` script to include `--filter=@dockstat/docknode` for integrated development.
* Updated various dependencies across the monorepo.
This feature lays the groundwork for centralized management of distributed DockNode services.
* chore(ci): Lint [skip ci]
* refactor(ui): Enhance Slides animation and DockNodeCard UI
Refactor the `Slides` component in `@packages/ui` to dynamically measure and animate content height. This change leverages `ResizeObserver` to ensure that slides with dynamic content automatically adjust their height during transitions, resulting in a smoother and more responsive user experience. The previous `collapseVariants` animation logic is replaced with direct height and opacity animations. Additionally, the `overflow-hidden` class is removed from the `Slides` `CardBody` as `SlideContent` now manages its own overflow for animation.
Redesign the `DockNodeCard` component in the `dockstat` application, introducing significant visual and structural improvements:
- Updated layout and spacing for better readability.
- Refined typography and enhanced status badges.
- Improved presentation of connection details.
- Restyled `CardFooter` with updated action button presentation and text ("Visit" changed to "Open").
- Minor adjustments to event handling for the delete action, including explicit `e.stopPropagation()`.
* Feat settings page (#76)
* feat(hotkeys): Implement configurable hotkey management
Introduce a comprehensive hotkey management system within the application settings.
- **API:** Added a new `POST /config/hotkey` endpoint to allow users to update and persist their hotkey preferences in the database.
- **Frontend (DockStat):**
- Created a new `SettingsPage` with a dedicated "Hotkeys" slide.
- The `HotkeysSlide` provides an intuitive UI for users to configure global hotkeys, including support for `CTRL + SHIFT + <key>` combinations.
- Integrates with the new API endpoint to save changes and provides immediate feedback.
- **Hotkeys Utility:** Enhanced the `useHotkey` hook to support `shift+key` combinations and a generic `toggle` function, making hotkey handling more flexible.
- **Configuration:** Updated default hotkey configurations to include new actions such as `open:sidebar` and `close:sidebar`.
- **UI Integration:** Adapted components like `Navbar` and `LinkLookup` to consume dynamic hotkey configurations.
- **Database/Typings:** Updated database models and type definitions (`DatabaseModel.hotkeyRes`, `DatabaseModel.hotkeyBody`, `HotkeyAction`) to reflect the new hotkey structure.
* refactor(codebase): Reorder imports and remove unused declarations
* feat(settings): Introduce General Settings page and API config management
This commit introduces a new "General Settings" page in the DockStat frontend and expands the backend API for configuration management.
Key changes include:
* **API & Database (`apps/api`, `packages/db`, `packages/typings`):**
* **Fix(config):** Corrected a widespread typo from `addtionalSettings` to `additionalSettings` in database schemas, typings, default configurations, and API models. This ensures consistency and correctness of the configuration object.
* Added `GET /db/details` and `GET /db/details/:tableName/all` endpoints for database introspection, providing schema information and raw table data.
* Implemented `POST /db/config/additionalSettings` for updating application-wide settings such as `showBackendRamUsageInNavbar`.
* Added TypeBox schemas for `additionalSettingsBody` and `additionalSettingsRes`.
* **Frontend (`apps/dockstat`):**
* Introduced the `GeneralSettingsSlide` component as the main entry point for general settings.
* Implemented `PinnedNavSection` to manage user-pinned navigation links.
* Developed `PinnableLinksSection` to allow users to discover and pin available dashboard links, including those provided by plugins.
* Added `PluginLinksSection` to display all detected plugin-provided routes.
* Created `AdditionalSettingsSection` to control specific application behaviors, starting with the option to display backend RAM usage in the navbar.
* Updated the `/settings` page to integrate the new `GeneralSettingsSlide`.
* Refactored the `ConfigProvider` to correctly handle `additionalSettings` and provide it to the application context.
* Minor UI adjustments in `HostsList` and `ClientsPage` for improved layout and consistency.
* Fixed hotkey display to correctly replace both `_` and `:` with spaces.
* **UI Library (`packages/ui`):**
* Expanded `Badge` component with an `xs` size option.
* Adjusted `Divider` vertical orientation to use `min-h-full` for better responsiveness.
* Enhanced `Slides` component with improved content transition animations and a `ResizeObserver` for dynamic height adjustments.
* Exported `SidebarPaths` and `PathItem` from Navbar for broader use in navigation.
* **Other:**
* Updated `apps/docknode/.gitignore` to include `docknode.db*` for better exclusion of database files and backups.
This comprehensive update streamlines configuration management and provides users with more control over their DockStat experience.
* chore(ci): Lint [skip ci]
* fix(formatting): adjusted imports
* fix(remove unwanted): remove database file from git tree
* feat(ui, api): Enhance UI components and streamline API error responses
Refactor:
- API: Removed redundant 'error' field from additional settings update error response in `db.ts` to ensure consistent error payload with `message`.
Dockstat App:
- UI/Hosts: Simplified the display for "no hosts configured" by removing an unnecessary card and icon.
- UI/Settings: Enhanced pinned navigation section with a fixed height, vertical resizing, and scroll functionality for improved usability.
UI Package:
- Badges: Corrected `xs` badge padding from `py-.5` to `py-0.5` for consistent styling.
- Slides: Fixed `useSlideState` by adding `activeSlide` to `useEffect` dependencies, ensuring proper re-measurement on slide changes.
- Theme Browser: Added `m-1` margin to `ThemePreviewCard` for improved visual spacing between theme previews.
* feat(db:migration): Implement automatic schema migration (#78)
* feat(db:migration): Implement automatic schema migration
This commit introduces automatic schema migration capabilities to the `sqlite-wrapper`.
The `db.createTable()` method now automatically detects schema changes when a table already exists and performs an atomic migration if differences are found. This process ensures smooth schema evolution without manual intervention, including:
- Creating a temporary table with the new schema.
- Copying existing data, mapping common columns and applying defaults for new ones.
- Recreating indexes, triggers, and foreign key constraints.
- Swapping the tables safely within a transaction.
**Key Migration Features & Options:**
- **Schema Detection**: Automatically identifies additions, removals, and changes in column constraints (NOT NULL, UNIQUE, Primary Key status) and types.
- **Data Preservation**: Data is preserved by default (`preserveData: true`), with options to control how constraint violations are handled (`onConflict: 'fail' | 'ignore' | 'replace'`).
- **Customization**: Supports `dropMissingColumns` and `tempTableSuffix` for fine-grained control.
- **Disabling Migration**: Migration can be explicitly disabled per table using `migrate: false` in `TableOptions`.
- **Type Handling**: Correctly migrates JSON and Boolean columns.
This feature significantly simplifies schema management for applications using `sqlite-wrapper`.
A new test suite (`__test__/migration.test.ts`) has been added to thoroughly validate various migration scenarios.
The `README.md` has been updated to document the new "Automatic Schema Migration" feature in detail, including usage examples and best practices. The package version is bumped to `1.3.5`.
* deps(bun): update @types/bun to 1.3.9
* fix(migration): improve migration robustness and add comprehensive tests
Migration robustness:
- Foreign key `PRAGMA` statements are now correctly handled outside the migration transaction, ensuring proper disabling and re-enabling of FK constraints for reliable table alterations.
- Improved logging in `schemasAreDifferent` to provide more detail on column count differences.
- The `currentSchema` is now passed to `migrateTable` from `checkAndMigrate` to avoid redundant database calls.
New migration tests:
- Added a test to verify that migration fails with the default `onConflict` strategy when constraints (e.g., `NOT NULL`) are violated.
- Added tests to confirm that no actual migration (ALTER TABLE) occurs when switching between type aliases (e.g., `TEXT` to `JSON`, `INTEGER` to `BOOLEAN`), ensuring data is preserved and correctly interpreted.
Type centralization:
- Moved `TableColumn`, `IndexInfo`, `ForeignKeyInfo`, and `ForeignKeyStatus` interfaces to `src/types.ts` for better organization and reusability.
Minor fixes and improvements:
- Corrected the in-memory database name check from `:memory` to `:memory:` in the `DB` class.
- Updated README.md to fix a typo from "Wrong packing" to "incorrect packaging".
- Removed the `dropMissingColumns` option from `MigrationOptions` as it was never implemented.
* Sqlite wrapper automatic table migration on schema change (#79)
* feat(db:migration): Implement automatic schema migration
This commit introduces automatic schema migration capabilities to the `sqlite-wrapper`.
The `db.createTable()` method now automatically detects schema changes when a table already exists and performs an atomic migration if differences are found. This process ensures smooth schema evolution without manual intervention, including:
- Creating a temporary table with the new schema.
- Copying existing data, mapping common columns and applying defaults for new ones.
- Recreating indexes, triggers, and foreign key constraints.
- Swapping the tables safely within a transaction.
**Key Migration Features & Options:**
- **Schema Detection**: Automatically identifies additions, removals, and changes in column constraints (NOT NULL, UNIQUE, Primary Key status) and types.
- **Data Preservation**: Data is preserved by default (`preserveData: true`), with options to control how constraint violations are handled (`onConflict: 'fail' | 'ignore' | 'replace'`).
- **Customization**: Supports `dropMissingColumns` and `tempTableSuffix` for fine-grained control.
- **Disabling Migration**: Migration can be explicitly disabled per table using `migrate: false` in `TableOptions`.
- **Type Handling**: Correctly migrates JSON and Boolean columns.
This feature significantly simplifies schema management for applications using `sqlite-wrapper`.
A new test suite (`__test__/migration.test.ts`) has been added to thoroughly validate various migration scenarios.
The `README.md` has been updated to document the new "Automatic Schema Migration" feature in detail, including usage examples and best practices. The package version is bumped to `1.3.5`.
* deps(bun): update @types/bun to 1.3.9
* fix(migration): improve migration robustness and add comprehensive tests
Migration robustness:
- Foreign key `PRAGMA` statements are now correctly handled outside the migration transaction, ensuring proper disabling and re-enabling of FK constraints for reliable table alterations.
- Improved logging in `schemasAreDifferent` to provide more detail on column count differences.
- The `currentSchema` is now passed to `migrateTable` from `checkAndMigrate` to avoid redundant database calls.
New migration tests:
- Added a test to verify that migration fails with the default `onConflict` strategy when constraints (e.g., `NOT NULL`) are violated.
- Added tests to confirm that no actual migration (ALTER TABLE) occurs when switching between type aliases (e.g., `TEXT` to `JSON`, `INTEGER` to `BOOLEAN`), ensuring data is preserved and correctly interpreted.
Type centralization:
- Moved `TableColumn`, `IndexInfo`, `ForeignKeyInfo`, and `ForeignKeyStatus` interfaces to `src/types.ts` for better organization and reusability.
Minor fixes and improvements:
- Corrected the in-memory database name check from `:memory` to `:memory:` in the `DB` class.
- Updated README.md to fix a typo from "Wrong packing" to "incorrect packaging".
- Removed the `dropMissingColumns` option from `MigrationOptions` as it was never implemented.
* refactor(sqlite-wrapper): Extract createTable helper methods
Introduces `normalizeMigrationOptions` to centralize the parsing of the `migrate` option into a standardized `{ enabled, options }` object.
Adds `shouldCheckExistingTable` to encapsulate the conditions for checking if a table already exists (e.g., excluding temporary or in-memory tables).
These private helper methods refactor the `createTable` method, improving its readability and maintainability by extracting complex conditional logic. This makes the `createTable` method more focused on its primary responsibility.
* feat(sqlite-wrapper): Introduce migration onConflict options and SQL-based schema comparison
**Migration Conflict Resolution:** Adds `onConflict` options (`ignore` and `replace`) to schema migration, allowing users to define how existing data is handled when new unique constraints are introduced during a migration.
**Robust Schema Comparison:** Reworks the `schemasAreDifferent` logic to compare the full `CREATE TABLE` SQL statements. This provides a more precise and comprehensive detection of schema changes, including intricate column definitions, constraints, and default values, greatly improving migration reliability.
**SQL Generation Refactoring:** Extracts the `CREATE TABLE` SQL generation into a new `buildTableSQL` utility function, enhancing modularity and reusability.
**Standardized Migration Options:** Normalizes the `migrate` option in `TableOptions` to always be a `MigrationOptions` object, providing a consistent API for configuring migration behavior.
Updates internal schema retrieval mechanisms and tests to leverage the full `CREATE TABLE` SQL for migration decisions.
* fix(sqlite-wrapper): Correct handling of 'migrate' option in migrateTable
* refactor(types): Relax column definition type constraints
The `InferTableSchema` type in `plugin-builder` and `PluginConfig['table']['columns']` (along with `DBPlugin`'s generic type) in `typings` were previously constrained to `Record<string, ColumnDefinition>`.
This commit relaxes these constraints to `Record<string, unknown>`. This change offers greater flexibility for defining columns within plugin configurations and during table schema inference, reducing tight coupling to the `ColumnDefinition` type from `@dockstat/sqlite-wrapper`. It allows for more generic or custom column definitions without needing to strictly conform to `ColumnDefinition` at the interface level.
Additionally, this commit includes minor import reordering in `sqlite-wrapper` and `migration` for consistency.
* feat(sqlite-wrapper): Prevent auto-migration for temporary and in-memory tables
The `createTable` method will no longer automatically apply schema migrations to certain types of tables.
This change introduces an `allowMigration` utility that determines if a table is eligible for automatic schema migration based on its properties and name. Migrations are now explicitly denied for:
- Tables created with the `temporary: true` option.
- In-memory tables (identified by the name `":memory:"`).
- Tables prefixed with `temp_` (which SQLite uses for internal temporary objects).
- Tables used internally by the migration process (matching `_migration_temp` suffix).
This ensures that only persistent, user-managed tables are subject to schema changes, preventing unintended modifications to ephemeral table structures.
Additionally, the `createTable` method now includes a `try...catch` block to handle `SQLiteError` with `errno === 1` (table already exists). This allows the method to gracefully proceed and return the `QueryBuilder` for an existing table even if a `CREATE TABLE` statement fails because the table already exists, ensuring robust behavior in various scenarios.
New tests have been added to validate that temporary and in-memory tables do not trigger automatic schema migrations.
---------
Signed-off-by: ItsNik <info@itsnik.de>
* 80 migrations always run when ifnotexists is true (#81)
* feat(migration): Implement automatic table schema migration and refactor logging
This release introduces robust automatic schema migration capabilities for tables managed by `sqlite-wrapper`, alongside a comprehensive refactor of the internal logging system.
**Automatic Schema Migration:**
* **Intelligent Detection**: `createTable` now automatically detects schema differences (column additions, removals, constraint changes, default values) between the existing table and the desired schema.
* **Data Preservation**: Migrations are performed without data loss by creating a temporary table, copying data, and re-creating the original table.
* **Flexible Conflict Handling**: Supports `onConflict` strategies (`ignore`, `replace`) during migration when adding unique constraints that might conflict with existing data.
* **Index and Foreign Key Preservation**: Ensures that existing indexes and foreign key constraints are re-established after migration.
* **Alias-Aware Type Handling**: Correctly identifies column type aliases (e.g., `JSON` as `TEXT`, `BOOLEAN` as `INTEGER`) to prevent unnecessary migrations.
* **Migration Control**: Introduces `migrate` options to explicitly enable/disable migration or customize the temporary table suffix.
* **Exclusion for Special Tables**: Automatically skips migration for `:memory:` databases and `TEMPORARY` tables.
* **Enhanced Comparison**: The `schemasAreDifferent` logic has been improved to normalize `CREATE TABLE` state…
Summary by Sourcery
Update API documentation and development tooling for DockStat API.
Build:
Documentation: