добавил модули для web-ui

This commit is contained in:
kirill.labutin 2026-01-14 21:57:58 +03:00
parent 3f022de862
commit 9e5b70161d
33 changed files with 9846 additions and 6 deletions

3
.gitignore vendored
View File

@ -40,3 +40,6 @@ build/
/.mvn/
xcp.conf
xcpdata.mv.db
/web-ui/api.spec.json
api-sandbox/app/node_modules
api-sandbox/app/api.spec.json

View File

@ -0,0 +1,41 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API Debug Console</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.form-group { margin: 10px 0; }
label { display: block; margin-bottom: 5px; }
select, input { padding: 8px; width: 100%; max-width: 300px; }
button { padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer; }
button:hover { background: #0056b3; }
#result { margin-top: 20px; white-space: pre-wrap; background: #f8f9fa; padding: 10px; border-radius: 4px; }
.params { margin-top: 10px; }
.param { margin-bottom: 10px; }
</style>
</head>
<body>
<div id="app">
<h1>API Debug Console</h1>
<div class="form-group">
<label for="service">Сервис:</label>
<select id="service"></select>
</div>
<div class="form-group">
<label for="method">Метод:</label>
<select id="method"></select>
</div>
<div id="params-container" class="params"></div>
<button id="send-btn">Отправить</button>
<div id="result"></div>
</div>
<script type="module" src="/main.js"></script>
</body>
</html>

134
api-sandbox/app/main.js Normal file
View File

@ -0,0 +1,134 @@
import $ from 'jquery'
let apiSpec = null
async function loadApiSpec() {
try {
const response = await fetch('/api.spec.json', {
method: 'GET',
headers: {
'Cache-Control': 'no-cache',
'Accept': 'application/json'
}
})
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
}
apiSpec = await response.json()
console.log('API Spec loaded:', apiSpec)
return apiSpec
} catch (error) {
console.error('Ошибка загрузки API спецификации:', error)
$('#result').text('Ошибка загрузки API спецификации: ' + error.message)
}
}
function populateServices() {
const $serviceSelect = $('#service')
$serviceSelect.empty()
$serviceSelect.append('<option value="">Выберите сервис</option>')
Object.keys(apiSpec).forEach(serviceName => {
$serviceSelect.append(`<option value="${serviceName}">${serviceName}</option>`)
})
}
function populateMethods(serviceName) {
const $methodSelect = $('#method')
$methodSelect.empty()
$methodSelect.append('<option value="">Выберите метод</option>')
if (serviceName && apiSpec[serviceName] && apiSpec[serviceName].methods) {
apiSpec[serviceName].methods.forEach(method => {
$methodSelect.append(`<option value="${method.name}">${method.name}</option>`)
})
}
}
function createParamInputs(methodName, serviceName) {
const $paramsContainer = $('#params-container')
$paramsContainer.empty()
if (!serviceName || !methodName) return
const service = apiSpec[serviceName]
if (!service || !service.methods) return
const method = service.methods.find(m => m.name === methodName)
if (!method || !method.params) return
method.params.forEach(param => {
const required = !param.optional ? ' (обязательно)' : ''
const $paramDiv = $(`
<div class="param">
<label for="param-${param.name}">${param.name}${required} (${param.type}):</label>
<input type="text" id="param-${param.name}" data-param="${param.name}" placeholder="${param.description}">
</div>
`)
$paramsContainer.append($paramDiv)
})
}
async function sendRequest() {
const serviceName = $('#service').val()
const methodName = $('#method').val()
if (!serviceName || !methodName) {
$('#result').text('Выберите сервис и метод')
return
}
const params = {}
$('.param input').each(function() {
const paramName = $(this).data('param')
const value = $(this).val()
if (value.trim() !== '') {
params[paramName] = value
}
})
const requestData = {
jsonrpc: '2.0',
method: `${serviceName}.${methodName}`,
params: params,
id: Date.now()
}
$('#result').text('Отправка запроса...')
try {
const response = await fetch('/api', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestData)
})
const result = await response.json()
$('#result').text(JSON.stringify(result, null, 2))
} catch (error) {
$('#result').text(`Ошибка: ${error.message}`)
}
}
$(document).ready(async () => {
await loadApiSpec()
if (apiSpec) {
populateServices()
$('#service').on('change', function() {
const serviceName = $(this).val()
populateMethods(serviceName)
$('#params-container').empty()
})
$('#method').on('change', function() {
const serviceName = $('#service').val()
const methodName = $(this).val()
createParamInputs(methodName, serviceName)
})
$('#send-btn').on('click', sendRequest)
}
})

1664
api-sandbox/app/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,22 @@
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "vite",
"predev": "node -e \"const fs=require('fs'); try{fs.copyFileSync('../../api.spec.json','./api.spec.json');console.log('Copied api.spec.json');}catch(e){console.log('api.spec.json not found');}\"",
"build": "vite build",
"preview": "vite preview",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs",
"devDependencies": {
"jquery": "^3.7.1",
"rollup-plugin-copy": "^3.5.0",
"vite": "^7.3.1"
}
}

View File

@ -0,0 +1,96 @@
import { defineConfig } from 'vite'
import { resolve } from 'path'
import copy from 'rollup-plugin-copy'
export default defineConfig({
root: '.',
build: {
outDir: 'dist',
rollupOptions: {
plugins: [
copy({
targets: [
{
src: resolve(__dirname, '../../api.spec.json'),
dest: 'dist'
}
],
hook: 'writeBundle'
})
]
}
},
resolve: {
alias: {
'@': resolve(__dirname, './')
}
},
server: {
port: 3000,
fs: {
allow: ['..', '../..']
},
historyApiFallback: false
},
publicDir: false,
configureServer(server) {
server.middlewares.use('/', (req, res, next) => {
if (req.url === '/api.spec.json' && req.method === 'GET') {
const fs = require('fs')
const path = require('path')
const apiSpecPath = path.resolve(__dirname, './api.spec.json')
console.log('Serving api.spec.json from:', apiSpecPath)
try {
const content = fs.readFileSync(apiSpecPath, 'utf-8')
res.setHeader('Content-Type', 'application/json')
res.setHeader('Cache-Control', 'no-cache')
res.end(content)
} catch (error) {
console.error('Error reading api.spec.json:', error)
res.statusCode = 404
res.setHeader('Content-Type', 'text/plain')
res.end('File not found')
}
} else {
next()
}
})
// Mock API endpoint for testing
server.middlewares.use('/api', (req, res, next) => {
if (req.method === 'POST') {
let body = ''
req.on('data', chunk => {
body += chunk.toString()
})
req.on('end', () => {
try {
const requestData = JSON.parse(body)
const response = {
jsonrpc: '2.0',
result: {
success: true,
message: `Method ${requestData.method} called with params: ${JSON.stringify(requestData.params)}`,
timestamp: new Date().toISOString()
},
id: requestData.id
}
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify(response))
} catch (error) {
res.statusCode = 400
res.end(JSON.stringify({
jsonrpc: '2.0',
error: { code: -32700, message: 'Parse error' },
id: null
}))
}
})
} else {
next()
}
})
}
})

20
api-sandbox/pom.xml Normal file
View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>ru.kirillius</groupId>
<artifactId>XCP</artifactId>
<version>1.0.0.0</version>
</parent>
<artifactId>api-sandbox</artifactId>
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -37,7 +37,7 @@
<arguments>
<argument>rpc/src/main/java</argument>
<argument>ru.kirillius.XCP.RPC.Services</argument>
<argument>target/generated-sources/api.spec.json</argument>
<argument>api.spec.json</argument>
</arguments>
</configuration>
</execution>

View File

@ -98,7 +98,10 @@ public class SpecGenerator {
}
public void writeSpecs() throws IOException {
outputFile.getParentFile().mkdirs();
var parentFile = outputFile.getParentFile();
if (parentFile != null) {
parentFile.mkdirs();
}
try (var stream = new FileOutputStream(outputFile)) {
var mapper = new ObjectMapper();
mapper.writerWithDefaultPrettyPrinter().writeValue(stream, specs);

99
api.spec.json Normal file
View File

@ -0,0 +1,99 @@
{
"Auth" : {
"name" : "Auth",
"methods" : [ {
"name" : "generateToken",
"description" : "Generates a new API token and returns its details",
"return" : "Object",
"accessLevel" : "User",
"params" : [ {
"name" : "permanent",
"type" : "boolean",
"description" : "If true, creates a token that never expires",
"optional" : true
}, {
"name" : "name",
"type" : "string",
"description" : "Display name for the token. If not provided, the User-Agent header will be used",
"optional" : true
} ]
}, {
"name" : "authenticateByPassword",
"description" : "Authenticates a user using login and password. Returns true if authentication is successful.",
"return" : "boolean",
"accessLevel" : "Guest",
"params" : [ {
"name" : "login",
"type" : "string",
"description" : "User's login name",
"optional" : false
}, {
"name" : "password",
"type" : "string",
"description" : "User's password",
"optional" : false
} ]
}, {
"name" : "logout",
"description" : "Logs out the current user. Returns true if logout is successful, false if the user is not logged in",
"return" : "boolean",
"accessLevel" : "User",
"params" : [ ]
}, {
"name" : "getTokens",
"description" : "Retrieves all API tokens associated with the current user",
"return" : "Array",
"accessLevel" : "User",
"params" : [ ]
}, {
"name" : "authenticateByToken",
"description" : "Authenticates a user using an API token. Returns true if authentication is successful.",
"return" : "boolean",
"accessLevel" : "Guest",
"params" : [ {
"name" : "token",
"type" : "string",
"description" : "API token string for authentication",
"optional" : false
} ]
} ]
},
"Profile" : {
"name" : "Profile",
"methods" : [ {
"name" : "get",
"description" : "",
"return" : "void",
"accessLevel" : "User",
"params" : [ ]
}, {
"name" : "save",
"description" : "",
"return" : "void",
"accessLevel" : "User",
"params" : [ ]
} ]
},
"UserManagement" : {
"name" : "UserManagement",
"methods" : [ {
"name" : "save",
"description" : "",
"return" : "void",
"accessLevel" : "Admin",
"params" : [ ]
}, {
"name" : "getAll",
"description" : "",
"return" : "void",
"accessLevel" : "Admin",
"params" : [ ]
}, {
"name" : "getById",
"description" : "",
"return" : "void",
"accessLevel" : "Admin",
"params" : [ ]
} ]
}
}

View File

@ -19,4 +19,6 @@ public interface Context {
LoggingSystem getLoggingSystem();
List<String> getLaunchArgs();
boolean isDebuggingEnabled();
}

View File

@ -16,7 +16,6 @@ import ru.kirillius.XCP.Services.ServiceLoadPriority;
import ru.kirillius.XCP.Services.WebService;
import ru.kirillius.XCP.web.WebServiceImpl;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
@ -152,6 +151,11 @@ public class Application implements Context {
}
}
@Override
public boolean isDebuggingEnabled() {
return launchArgs.contains("--debug");
}
public static void main(String[] args) {
try {
new Application(args);

View File

@ -15,13 +15,16 @@ import java.util.logging.LogRecord;
public class LogHandlerImpl extends Handler {
private final EventHandler<LogMessage> eventHandler;
private final boolean debugging;
public LogHandlerImpl(LoggingSystem loggingSystem, Context context) {
eventHandler = loggingSystem.getEventHandler();
debugging = context.getLaunchArgs().contains("--debug");
this.context = context;
}
private final Context context;
private final static SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss", Locale.US);
private String format(LogRecord logRecord) {
@ -36,7 +39,7 @@ public class LogHandlerImpl extends Handler {
var thrown = logRecord.getThrown();
if (thrown != null) {
builder.append("\n\tThrown ").append(thrown.getClass().getSimpleName()).append(": ").append(thrown.getMessage());
if (debugging) {
if (context.isDebuggingEnabled()) {
builder.append("\nStack trace:\n");
try (var writer = new StringWriter()) {

View File

@ -18,6 +18,7 @@
<module>app</module>
<module>logging</module>
<module>web-ui</module>
<module>api-sandbox</module>
</modules>
<properties>

View File

@ -0,0 +1,15 @@
/* eslint-env node */
require('@rushstack/eslint-patch/modern-module-resolution')
module.exports = {
root: true,
extends: [
'plugin:vue/vue3-essential',
'eslint:recommended',
'@vue/eslint-config-typescript',
'@vue/eslint-config-prettier'
],
parserOptions: {
ecmaVersion: 'latest'
}
}

28
web-ui/vue-app/.gitignore vendored Normal file
View File

@ -0,0 +1,28 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
.DS_Store
dist
dist-ssr
coverage
*.local
/cypress/videos/
/cypress/screenshots/
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/prettierrc",
"semi": false,
"tabWidth": 2,
"singleQuote": true,
"printWidth": 100,
"trailingComma": "none"
}

25
web-ui/vue-app/README.md Normal file
View File

@ -0,0 +1,25 @@
# Vue App
Vue 3 + TypeScript + Vite project with modern tooling.
## Stack
- Vue 3
- TypeScript
- Vite
- Vue Router
- Pinia
- Vitest
- ESLint
- Prettier
- Cypress
## Scripts
- `npm run dev` - Start development server
- `npm run build` - Build for production
- `npm run preview` - Preview production build
- `npm run test:unit` - Run unit tests
- `npm run test:e2e` - Run E2E tests
- `npm run lint` - Run linter
- `npm run format` - Format code

13
web-ui/vue-app/index.html Normal file
View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

7421
web-ui/vue-app/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,42 @@
{
"name": "vue-app",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc && vite build",
"preview": "vite preview",
"test:unit": "vitest",
"test:e2e": "cypress run",
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore",
"format": "prettier --write src/"
},
"dependencies": {
"pinia": "^3.0.4",
"vue": "^3.5.26",
"vue-router": "^4.6.4"
},
"devDependencies": {
"@cypress/vite-dev-server": "^7.1.0",
"@cypress/vue": "^6.0.2",
"@rushstack/eslint-patch": "^1.10.3",
"@tsconfig/node18": "^18.2.4",
"@types/jsdom": "^21.1.7",
"@types/node": "^22.9.0",
"@vitejs/plugin-vue": "^6.0.3",
"@vue/eslint-config-prettier": "^10.2.0",
"@vue/eslint-config-typescript": "^14.6.0",
"@vue/test-utils": "^2.4.6",
"@vue/tsconfig": "^0.8.1",
"cypress": "^15.9.0",
"eslint": "^9.39.2",
"eslint-plugin-vue": "^9.32.0",
"jsdom": "^27.4.0",
"prettier": "^3.7.4",
"typescript": "^5.9.3",
"vite": "^7.3.1",
"vitest": "^4.0.17",
"vue-tsc": "^3.2.2"
}
}

View File

@ -0,0 +1,21 @@
<template>
<div id="app">
<nav>
<RouterLink to="/">Home</RouterLink>
<RouterLink to="/about">About</RouterLink>
</nav>
<RouterView />
</div>
</template>
<script setup lang="ts">
import { RouterLink, RouterView } from 'vue-router'
</script>
<style scoped>
nav {
padding: 1rem;
display: flex;
gap: 1rem;
}
</style>

View File

@ -0,0 +1,49 @@
:root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
#app {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
}

View File

@ -0,0 +1,10 @@
import { describe, it, expect } from 'vitest'
import { mount } from '@vue/test-utils'
import HelloWorld from '../src/components/HelloWorld.vue'
describe('HelloWorld', () => {
it('renders properly', () => {
const wrapper = mount(HelloWorld, { props: { msg: 'Hello Vitest' } })
expect(wrapper.text()).toContain('Hello Vitest')
})
})

View File

@ -0,0 +1,17 @@
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script setup lang="ts">
defineProps<{
msg: string
}>()
</script>
<style scoped>
.hello {
color: #42b883;
}
</style>

7
web-ui/vue-app/src/env.d.ts vendored Normal file
View File

@ -0,0 +1,7 @@
/// <reference types="vite/client" />
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}

View File

@ -0,0 +1,14 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import './assets/main.css'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.mount('#app')

View File

@ -0,0 +1,20 @@
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
component: () => import('../views/AboutView.vue')
}
]
})
export default router

View File

@ -0,0 +1,9 @@
<template>
<div class="about">
<h1>About Page</h1>
<p>This is a Vue 3 + TypeScript project with Vite.</p>
</div>
</template>
<script setup lang="ts">
</script>

View File

@ -0,0 +1,8 @@
<template>
<div class="home">
<h1>Welcome to Vue + TypeScript + Vite</h1>
</div>
</template>
<script setup lang="ts">
</script>

View File

@ -0,0 +1,14 @@
import { defineConfig } from 'tsbuild'
export default defineConfig({
extends: '@vue/tsconfig/tsconfig.dom.json',
include: ['env.d.ts', 'src/**/*', 'src/**/*.vue'],
exclude: ['src/**/__tests__/*'],
compilerOptions: {
composite: true,
baseUrl: '.',
paths: {
'@/*': ['./src/*']
}
}
})

View File

@ -0,0 +1,12 @@
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
}
})

View File

@ -0,0 +1,15 @@
import { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'node:url'
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
test: {
globals: true
}
})