[
  {
    "path": ".claude/skills/api-generator/SKILL.md",
    "content": "---\nname: api-generator\ndescription: Specialized skill for developing and refactoring the DST (Don't Starve Together) Admin Go project. Use this skill whenever the user mentions DST, game server management, API refactoring, adding handlers/services, creating CRUD endpoints, or working within the dst-admin-go codebase. This skill ensures all code follows the project's architectural patterns including dependency injection, layered architecture (Handler → Service → Model), and specific naming conventions. Make sure to use this skill when the user asks to refactor existing APIs, add new features, fix bugs, or modify any part of the dst-admin-go project structure.\nlicense: MIT\nmetadata:\n  author: DST Admin Go Team\n  version: \"2.0.0\"\n  domain: application\n  triggers: DST, dst-admin-go, Don't Starve Together, game server, refactor API, add handler, create service, GORM, Gin, cluster management, backup service, player management, mod management, CRUD generator, generate API, create endpoint, 生成API, 创建接口\n  role: specialist\n  scope: implementation\n  output-format: code\n  related-skills: golang-pro, golang-patterns\n---\n\n# DST Admin Go API Generator\n\nSpecialized skill for developing and refactoring the DST (Don't Starve Together) Admin Go project. Use this skill whenever the user mentions DST, game server management, API refactoring, adding handlers/services, creating CRUD endpoints, or working within the dst-admin-go codebase. This skill ensures all code follows the project's architectural patterns including dependency injection, layered architecture (Handler → Service → Model), and specific naming conventions.\n\n---\n\n## Project Context\n\nDST Admin Go is a web-based management panel for \"Don't Starve Together\" game servers written in Go. It follows a three-layer architecture:\n\n1. **Handler Layer** (`internal/api/handler/`): HTTP request handling, validation, response formatting\n2. **Service Layer** (`internal/service/`): Business logic, orchestration\n3. **Model Layer** (`internal/model/`): Database entities (GORM)\n\n### Architecture Patterns\n\n- **Dependency Injection**: All services instantiated in `internal/api/router.go`, injected via constructors\n- **No Global Variables**: Pass config and dependencies through constructors\n- **Platform Abstraction**: Factory patterns for Linux/Windows differences\n- **Naming Conventions**:\n  - Files: `snake_case.go` (e.g., `backup_service.go`)\n  - Structs: `PascalCase` without suffix (e.g., `BackupInfo`, NOT `BackupInfoVO`)\n  - Constructors: `New{Name}` (e.g., `NewBackupService`)\n  - Interfaces: Simple names (e.g., `Config`, `Process`)\n\n### Project Structure\n\n```\ndst-admin-go/\n├── cmd/server/main.go           # Entry point\n├── internal/\n│   ├── api/\n│   │   ├── handler/             # HTTP handlers (controllers)\n│   │   │   └── {entity}_handler.go\n│   │   └── router.go            # Route registration & DI\n│   ├── model/                   # GORM models\n│   │   └── {entity}.go\n│   ├── service/                 # Business logic\n│   │   └── {domain}/\n│   │       ├── {domain}_service.go\n│   │       ├── factory.go       # (if platform-specific)\n│   │       ├── linux_{domain}.go\n│   │       └── window_{domain}.go\n│   └── pkg/\n│       ├── response/            # Standard responses\n│       └── utils/               # Utilities\n└── config.yml                   # Application config\n```\n\n---\n\n## Your Instructions\n\nYou are an expert Go developer specializing in the DST Admin Go project. When the user requests creating a CRUD module, refactoring APIs, or adding new functionality:\n\n### Step 1: Gather Requirements\n\nAsk the user for the following information (use a friendly, concise tone):\n\n1. **Entity/Model Name**: What is the entity called? (e.g., \"Announcement\", \"ModConfig\", \"Player\")\n2. **Chinese Name**: What is the Chinese name for Swagger docs? (e.g., \"公告\", \"模组配置\")\n3. **Database Fields**: What fields does this entity have?\n   - Field name, type (string, int, bool, time.Time, etc.)\n   - GORM constraints (e.g., `unique`, `not null`, `default`)\n   - JSON tag name (camelCase for API responses)\n   - Example: `Title string, required, JSON: \"title\"` or `IsActive bool, default true, JSON: \"isActive\"`\n4. **Operations Needed**: Which operations should be available?\n   - Standard CRUD: Create, Read (Get by ID), Update, Delete, List (with pagination)\n   - Custom operations: Batch delete, toggle status, search, etc.\n5. **Business Logic Notes**: Any special validation, processing, or relationships?\n   - E.g., \"Must validate expiresAt is in the future\", \"Needs to interact with game process\"\n6. **Cluster Context**: Does this entity belong to a specific cluster/server?\n   - If yes: Endpoints will be under `/api/{clusterName}/{entity}` and need cluster middleware\n\n### Step 2: Analyze Dependencies\n\nBased on the requirements, determine:\n\n- **Always needed**: `*gorm.DB` for database operations\n- **Game-related**: If interacting with game state → `game.Process`\n- **File operations**: If handling files/archives → `archive.PathResolver`\n- **DST config**: If reading/writing DST configs → `dstConfig.Config`\n- **Level config**: If working with world configs → `levelConfig.LevelConfigUtils`\n- **Platform-specific**: If operations differ on Linux vs Windows → factory pattern\n\n### Step 3: Generate Model File\n\nCreate `internal/model/{entity}.go`:\n\n```go\npackage model\n\nimport (\n\t\"gorm.io/gorm\"\n\t\"time\"\n)\n\n// {EntityName} {中文描述}\ntype {EntityName} struct {\n\tgorm.Model\n\t// Fields based on user input\n\tTitle       string     `json:\"title\" gorm:\"type:varchar(255);not null\"`\n\tContent     string     `json:\"content\" gorm:\"type:text\"`\n\tIsActive    bool       `json:\"isActive\" gorm:\"default:true\"`\n\tExpiresAt   *time.Time `json:\"expiresAt\"`\n}\n```\n\n**Guidelines**:\n- Always embed `gorm.Model` (provides ID, CreatedAt, UpdatedAt, DeletedAt)\n- Use GORM tags for constraints: `type:`, `not null`, `unique`, `default:`\n- Use JSON tags in camelCase\n- Add struct comment with Chinese description\n- Use pointer types for nullable fields (e.g., `*time.Time`, `*string`)\n\n### Step 4: Generate Service File\n\nCreate `internal/service/{domain}/{domain}_service.go`:\n\n```go\npackage {domain}\n\nimport (\n\t\"dst-admin-go/internal/model\"\n\t\"gorm.io/gorm\"\n)\n\ntype {Entity}Service struct {\n\tdb *gorm.DB\n\t// Add other dependencies as detected\n}\n\nfunc New{Entity}Service(db *gorm.DB /* other deps */) *{Entity}Service {\n\treturn &{Entity}Service{\n\t\tdb: db,\n\t}\n}\n\n// List{Entity} 获取{中文名}列表\nfunc (s *{Entity}Service) List{Entity}(page, pageSize int) ([]model.{Entity}, int64, error) {\n\tvar list []model.{Entity}\n\tvar total int64\n\n\toffset := (page - 1) * pageSize\n\n\terr := s.db.Model(&model.{Entity}{}).Count(&total).Error\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\terr = s.db.Offset(offset).Limit(pageSize).Find(&list).Error\n\treturn list, total, err\n}\n\n// Get{Entity} 获取{中文名}详情\nfunc (s *{Entity}Service) Get{Entity}(id uint) (*model.{Entity}, error) {\n\tvar entity model.{Entity}\n\terr := s.db.First(&entity, id).Error\n\treturn &entity, err\n}\n\n// Create{Entity} 创建{中文名}\nfunc (s *{Entity}Service) Create{Entity}(entity *model.{Entity}) error {\n\treturn s.db.Create(entity).Error\n}\n\n// Update{Entity} 更新{中文名}\nfunc (s *{Entity}Service) Update{Entity}(entity *model.{Entity}) error {\n\treturn s.db.Save(entity).Error\n}\n\n// Delete{Entity} 删除{中文名}\nfunc (s *{Entity}Service) Delete{Entity}(id uint) error {\n\treturn s.db.Delete(&model.{Entity}{}, id).Error\n}\n```\n\n**Guidelines**:\n- Constructor accepts all dependencies\n- Chinese comments for all exported methods\n- Use GORM for database operations\n- Add pagination support for List (offset/limit)\n- Return errors, don't handle them here\n- Add custom business logic methods as needed\n\n### Step 5: Generate Handler File\n\nCreate `internal/api/handler/{entity}_handler.go`:\n\n```go\npackage handler\n\nimport (\n\t\"dst-admin-go/internal/model\"\n\t\"dst-admin-go/internal/pkg/response\"\n\t\"dst-admin-go/internal/service/{domain}\"\n\t\"github.com/gin-gonic/gin\"\n\t\"net/http\"\n\t\"strconv\"\n)\n\ntype {Entity}Handler struct {\n\tservice *{domain}.{Entity}Service\n}\n\nfunc New{Entity}Handler(service *{domain}.{Entity}Service) *{Entity}Handler {\n\treturn &{Entity}Handler{service: service}\n}\n\nfunc (h *{Entity}Handler) RegisterRoute(router *gin.RouterGroup) {\n\trouter.GET(\"/api/{entity}/list\", h.List)\n\trouter.GET(\"/api/{entity}/:id\", h.Get)\n\trouter.POST(\"/api/{entity}\", h.Create)\n\trouter.PUT(\"/api/{entity}/:id\", h.Update)\n\trouter.DELETE(\"/api/{entity}/:id\", h.Delete)\n}\n\n// List 获取{中文名}列表\n// @Summary 获取{中文名}列表\n// @Description 分页获取{中文名}列表\n// @Tags {entity}\n// @Accept json\n// @Produce json\n// @Param page query int false \"页码\" default(1)\n// @Param pageSize query int false \"每页数量\" default(10)\n// @Success 200 {object} response.Response{data=object{list=[]model.{Entity},total=int,page=int,pageSize=int}}\n// @Router /api/{entity}/list [get]\nfunc (h *{Entity}Handler) List(ctx *gin.Context) {\n\tpage, _ := strconv.Atoi(ctx.DefaultQuery(\"page\", \"1\"))\n\tpageSize, _ := strconv.Atoi(ctx.DefaultQuery(\"pageSize\", \"10\"))\n\n\tif page < 1 {\n\t\tpage = 1\n\t}\n\tif pageSize < 1 || pageSize > 100 {\n\t\tpageSize = 10\n\t}\n\n\tlist, total, err := h.service.List{Entity}(page, pageSize)\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"获取列表失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tresponse.OkWithData(gin.H{\n\t\t\"list\":     list,\n\t\t\"total\":    total,\n\t\t\"page\":     page,\n\t\t\"pageSize\": pageSize,\n\t}, ctx)\n}\n\n// Get 获取{中文名}详情\n// @Summary 获取{中文名}详情\n// @Description 根据ID获取{中文名}详情\n// @Tags {entity}\n// @Accept json\n// @Produce json\n// @Param id path int true \"{中文名}ID\"\n// @Success 200 {object} response.Response{data=model.{Entity}}\n// @Router /api/{entity}/{id} [get]\nfunc (h *{Entity}Handler) Get(ctx *gin.Context) {\n\tid, err := strconv.ParseUint(ctx.Param(\"id\"), 10, 32)\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"无效的ID\", ctx)\n\t\treturn\n\t}\n\n\tentity, err := h.service.Get{Entity}(uint(id))\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"获取详情失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tresponse.OkWithData(entity, ctx)\n}\n\n// Create 创建{中文名}\n// @Summary 创建{中文名}\n// @Description 创建新的{中文名}\n// @Tags {entity}\n// @Accept json\n// @Produce json\n// @Param data body model.{Entity} true \"{中文名}信息\"\n// @Success 200 {object} response.Response{data=model.{Entity}}\n// @Router /api/{entity} [post]\nfunc (h *{Entity}Handler) Create(ctx *gin.Context) {\n\tvar entity model.{Entity}\n\tif err := ctx.ShouldBindJSON(&entity); err != nil {\n\t\tresponse.FailWithMessage(\"参数错误: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tif err := h.service.Create{Entity}(&entity); err != nil {\n\t\tresponse.FailWithMessage(\"创建失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tresponse.OkWithData(entity, ctx)\n}\n\n// Update 更新{中文名}\n// @Summary 更新{中文名}\n// @Description 更新{中文名}信息\n// @Tags {entity}\n// @Accept json\n// @Produce json\n// @Param id path int true \"{中文名}ID\"\n// @Param data body model.{Entity} true \"{中文名}信息\"\n// @Success 200 {object} response.Response{data=model.{Entity}}\n// @Router /api/{entity}/{id} [put]\nfunc (h *{Entity}Handler) Update(ctx *gin.Context) {\n\tid, err := strconv.ParseUint(ctx.Param(\"id\"), 10, 32)\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"无效的ID\", ctx)\n\t\treturn\n\t}\n\n\tvar entity model.{Entity}\n\tif err := ctx.ShouldBindJSON(&entity); err != nil {\n\t\tresponse.FailWithMessage(\"参数错误: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tentity.ID = uint(id)\n\tif err := h.service.Update{Entity}(&entity); err != nil {\n\t\tresponse.FailWithMessage(\"更新失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tresponse.OkWithData(entity, ctx)\n}\n\n// Delete 删除{中文名}\n// @Summary 删除{中文名}\n// @Description 根据ID删除{中文名}\n// @Tags {entity}\n// @Accept json\n// @Produce json\n// @Param id path int true \"{中文名}ID\"\n// @Success 200 {object} response.Response\n// @Router /api/{entity}/{id} [delete]\nfunc (h *{Entity}Handler) Delete(ctx *gin.Context) {\n\tid, err := strconv.ParseUint(ctx.Param(\"id\"), 10, 32)\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"无效的ID\", ctx)\n\t\treturn\n\t}\n\n\tif err := h.service.Delete{Entity}(uint(id)); err != nil {\n\t\tresponse.FailWithMessage(\"删除失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tresponse.OkWithMessage(\"删除成功\", ctx)\n}\n```\n\n**Guidelines**:\n- Complete Swagger annotations for every handler\n- Use `response.Response` helpers: `OkWithData`, `FailWithMessage`, `OkWithMessage`\n- Validate all input parameters\n- Chinese error messages\n- Parse ID from path parameter as uint\n- Bind JSON request body with `ShouldBindJSON`\n- Return HTTP 200 even for errors (error code in response body)\n\n### Step 6: Update Router\n\nRead `internal/api/router.go` and make these changes:\n\n1. **Add import** (if not exists):\n```go\n\"{domain}\" \"dst-admin-go/internal/service/{domain}\"\n```\n\n2. **In `Register()` function, add service initialization** (after existing services):\n```go\n// {entity} service\n{entity}Service := {domain}.New{Entity}Service(db /* add detected dependencies */)\n```\n\n3. **Add handler initialization** (after existing handlers):\n```go\n{entity}Handler := handler.New{Entity}Handler({entity}Service)\n```\n\n4. **Add route registration** (after existing routes):\n```go\n{entity}Handler.RegisterRoute(router)\n```\n\n**Important**: Maintain the existing order and formatting. Add new code at the end of each section.\n\n### Step 7: Handle Platform-Specific Code (if needed)\n\nIf the service needs platform-specific behavior:\n\n1. Create `internal/service/{domain}/factory.go`:\n```go\npackage {domain}\n\nimport (\n\t\"gorm.io/gorm\"\n\t\"runtime\"\n)\n\nfunc New{Entity}Service(db *gorm.DB) {Entity}Service {\n\tif runtime.GOOS == \"windows\" {\n\t\treturn &Windows{Entity}Service{db: db}\n\t}\n\treturn &Linux{Entity}Service{db: db}\n}\n```\n\n2. Create interface in `{domain}_service.go`:\n```go\ntype {Entity}Service interface {\n\tList{Entity}(page, pageSize int) ([]model.{Entity}, int64, error)\n\t// ... other methods\n}\n```\n\n3. Create platform implementations:\n   - `internal/service/{domain}/linux_{domain}.go`\n   - `internal/service/{domain}/window_{domain}.go`\n\n### Step 8: Verify and Test\n\nAfter generating all files:\n\n1. **Run compilation check**:\n```bash\ngo mod tidy\ngo build cmd/server/main.go\n```\n\n2. **Report to user**:\n   - List all generated files\n   - Show modified files (router.go)\n   - Provide curl test commands\n   - Mention Swagger UI location\n\n3. **Provide test commands**:\n```bash\n# List\ncurl -X GET \"http://localhost:8082/api/{entity}/list?page=1&pageSize=10\"\n\n# Create\ncurl -X POST \"http://localhost:8082/api/{entity}\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"field1\": \"value1\", \"field2\": \"value2\"}'\n\n# Get\ncurl -X GET \"http://localhost:8082/api/{entity}/1\"\n\n# Update\ncurl -X PUT \"http://localhost:8082/api/{entity}/1\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"field1\": \"new_value\"}'\n\n# Delete\ncurl -X DELETE \"http://localhost:8082/api/{entity}/1\"\n```\n\n4. **Remind user**: Access Swagger UI at `http://localhost:8082/swagger/index.html` (after running the server)\n\n---\n\n## Common Patterns Reference\n\n### Response Helpers\n\nLocated in `internal/pkg/response/response.go`:\n\n```go\n// Success with data\nresponse.OkWithData(data, ctx)\n\n// Success with message\nresponse.OkWithMessage(\"操作成功\", ctx)\n\n// Error with message\nresponse.FailWithMessage(\"操作失败: \"+err.Error(), ctx)\n```\n\n### Common Dependencies\n\n- `*gorm.DB`: Database access\n- `*gin.Context`: HTTP request context\n- `dstConfig.Config`: DST configuration interface\n- `game.Process`: Game process management interface\n- `archive.PathResolver`: Archive path resolution\n- `levelConfig.LevelConfigUtils`: Level config parsing\n\n### Cluster-Aware Endpoints\n\nIf entity belongs to a cluster, routes should be:\n```go\nrouter.GET(\"/api/:cluster_name/{entity}/list\", h.List)\nrouter.GET(\"/api/:cluster_name/{entity}/:id\", h.Get)\n// etc.\n```\n\n**IMPORTANT**: Handler should use cluster context helper to get clusterName:\n```go\nimport \"dst-admin-go/internal/pkg/context\"\n\nclusterName := context.GetClusterName(ctx)\n// Use clusterName in service calls\n```\n\n**DO NOT** use `ctx.Query(\"clusterName\")` or `ctx.Param(\"cluster_name\")` directly. Always use `context.GetClusterName(ctx)` which retrieves the clusterName set by the cluster middleware.\n\n### Pagination Pattern\n\nAlways use this pattern for list endpoints:\n```go\npage, _ := strconv.Atoi(ctx.DefaultQuery(\"page\", \"1\"))\npageSize, _ := strconv.Atoi(ctx.DefaultQuery(\"pageSize\", \"10\"))\n\nif page < 1 {\n\tpage = 1\n}\nif pageSize < 1 || pageSize > 100 {\n\tpageSize = 10\n}\n\noffset := (page - 1) * pageSize\n```\n\n### GORM Common Tags\n\n- `type:varchar(255)` - String with length\n- `type:text` - Long text\n- `not null` - Required field\n- `unique` - Unique constraint\n- `default:true` - Default value\n- `index` - Create index\n- `foreignKey:UserID` - Foreign key\n\n---\n\n## Examples\n\n### Example 1: Simple Announcement System\n\n**User Input**:\n- Entity: Announcement\n- Chinese: 公告\n- Fields: Title (string, required), Content (text), IsActive (bool, default true), ExpiresAt (time, nullable)\n- Operations: Full CRUD + List\n- Cluster context: No\n\n**Generated Files**:\n- `internal/model/announce.go`\n- `internal/service/announce/announce_service.go`\n- `internal/api/handler/announce_handler.go`\n- Modified: `internal/api/router.go`\n\n### Example 2: Mod Management (Game-Related)\n\n**User Input**:\n- Entity: ModInfo\n- Chinese: 模组信息\n- Fields: ModId (string, unique), Name (string), Author (string), Version (string), IsEnabled (bool), ClusterName (string)\n- Operations: Full CRUD + List + Toggle status\n- Business logic: Needs to interact with game process when toggling\n- Cluster context: Yes\n\n**Generated Files**:\n- `internal/model/modInfo.go`\n- `internal/service/mod/mod_service.go` (with `game.Process` dependency)\n- `internal/api/handler/mod_handler.go` (with cluster-aware routes)\n- Modified: `internal/api/router.go`\n\n**Additional method in service**:\n```go\n// ToggleModStatus 切换模组启用状态\nfunc (s *ModService) ToggleModStatus(clusterName, modId string) error {\n\t// Update database\n\t// Interact with game process\n\treturn nil\n}\n```\n\n---\n\n## Critical Checklist\n\nBefore completing the task, verify:\n\n- [ ] Model file has `gorm.Model` embedded\n- [ ] All fields have both `json` and `gorm` tags\n- [ ] Service has constructor accepting all dependencies\n- [ ] All service methods have Chinese comments\n- [ ] Handler has `RegisterRoute` method\n- [ ] All handler methods have complete Swagger annotations\n- [ ] Swagger tags use entity name (e.g., `@Tags announcement`)\n- [ ] Chinese names used in Swagger summaries\n- [ ] router.go has import added\n- [ ] router.go has service initialization\n- [ ] router.go has handler initialization\n- [ ] router.go has route registration\n- [ ] Naming follows conventions (snake_case files, PascalCase types, no VO suffix)\n- [ ] Code compiles without errors\n- [ ] Test commands provided to user\n\n---\n\n## DST-Specific Domain Knowledge\n\n### Cluster Architecture\n\nA **cluster** contains multiple **levels** (worlds):\n- **Master** - Overworld (surface world)\n- **Caves** - Underground world\n\nEach level runs as a separate process with its own configuration.\n\n### Important Paths\n\n```go\n// Use pathResolver service for all path operations\npathResolver.ClusterPath(clusterName)          // e.g., ~/.klei/DoNotStarveTogether/MyCluster/\npathResolver.LevelPath(clusterName, \"Master\")  // e.g., ~/.klei/DoNotStarveTogether/MyCluster/Master/\npathResolver.SavePath(clusterName, \"Master\")   // e.g., ~/.klei/DoNotStarveTogether/MyCluster/Master/save/\n```\n\n### Configuration Files\n\n- `cluster.ini` - Cluster settings (game mode, max players, passwords)\n- `leveldataoverride.lua` - World generation settings (Lua table format)\n- `modoverrides.lua` - Enabled mods configuration (Lua table format)\n- `server.ini` - Server-specific settings\n\nUse `luaUtils` package to parse/generate Lua configuration files.\n\n### Process Management\n\n**Linux**: Uses `screen` sessions\n```go\nscreenName := fmt.Sprintf(\"dst_%s_%s\", clusterName, levelName)\n```\n\n**Windows**: Uses custom CLI wrapper (`windowGameCli.go`)\n\n---\n\n## Common Utilities\n\n### File Operations\n\n```go\nimport \"dst-admin-go/internal/pkg/utils/fileUtils\"\n\nfileUtils.PathExists(path)\nfileUtils.CreateDir(path)\nfileUtils.CopyFile(src, dst)\nfileUtils.Unzip(zipPath, destPath)\n```\n\n### Shell Commands\n\n```go\nimport \"dst-admin-go/internal/pkg/utils/shellUtils\"\n\noutput, err := shellUtils.ExecuteCommand(\"ls\", \"-la\")\n```\n\n### Lua Configuration\n\n```go\nimport \"dst-admin-go/internal/pkg/utils/luaUtils\"\n\n// Parse Lua table to map\nconfig, err := luaUtils.ParseLuaTable(luaContent)\n\n// Generate Lua table from map\nluaContent := luaUtils.GenerateLuaTable(configMap)\n```\n\n---\n\n## Tips\n\n- **Be concise**: Don't over-explain. Generate code efficiently.\n- **Follow patterns**: Always reference existing code in the project for consistency.\n- **Chinese comments**: Use Chinese for inline comments and method descriptions, English for Swagger and exported names.\n- **Dependency detection**: Ask about business logic to determine dependencies accurately.\n- **Platform awareness**: Ask if operations differ on Windows vs Linux.\n- **Cluster context**: Ask if entity belongs to a specific cluster/server.\n- **Validation**: Add appropriate validation in handlers (required fields, format checks).\n- **Error messages**: Always include the original error in Chinese messages: \"操作失败: \" + err.Error()\n\n---\n\n## When NOT to Use This Skill\n\nDon't use this skill if:\n- User is asking general Go questions (not specific to DST Admin Go)\n- User wants to modify frontend code\n- User is asking about Docker, deployment, or infrastructure\n- Task doesn't involve creating/modifying handlers, services, or models\n\nIn those cases, handle the request normally without the skill context.\n\n---\n\n## Summary\n\nThis skill automates the creation of complete CRUD modules in DST Admin Go following the project's three-layer architecture. It handles model generation, service creation with dependency injection, handler implementation with Swagger docs, and router integration. Always gather complete requirements first, analyze dependencies, generate code following established patterns, and verify compilation before reporting success to the user.\n"
  },
  {
    "path": ".claude/skills/find-skills/SKILL.md",
    "content": "---\nname: find-skills\ndescription: Helps users discover and install agent skills when they ask questions like \"how do I do X\", \"find a skill for X\", \"is there a skill that can...\", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.\n---\n\n# Find Skills\n\nThis skill helps you discover and install skills from the open agent skills ecosystem.\n\n## When to Use This Skill\n\nUse this skill when the user:\n\n- Asks \"how do I do X\" where X might be a common task with an existing skill\n- Says \"find a skill for X\" or \"is there a skill for X\"\n- Asks \"can you do X\" where X is a specialized capability\n- Expresses interest in extending agent capabilities\n- Wants to search for tools, templates, or workflows\n- Mentions they wish they had help with a specific domain (design, testing, deployment, etc.)\n\n## What is the Skills CLI?\n\nThe Skills CLI (`npx skills`) is the package manager for the open agent skills ecosystem. Skills are modular packages that extend agent capabilities with specialized knowledge, workflows, and tools.\n\n**Key commands:**\n\n- `npx skills find [query]` - Search for skills interactively or by keyword\n- `npx skills add <package>` - Install a skill from GitHub or other sources\n- `npx skills check` - Check for skill updates\n- `npx skills update` - Update all installed skills\n\n**Browse skills at:** https://skills.sh/\n\n## How to Help Users Find Skills\n\n### Step 1: Understand What They Need\n\nWhen a user asks for help with something, identify:\n\n1. The domain (e.g., React, testing, design, deployment)\n2. The specific task (e.g., writing tests, creating animations, reviewing PRs)\n3. Whether this is a common enough task that a skill likely exists\n\n### Step 2: Search for Skills\n\nRun the find command with a relevant query:\n\n```bash\nnpx skills find [query]\n```\n\nFor example:\n\n- User asks \"how do I make my React app faster?\" → `npx skills find react performance`\n- User asks \"can you help me with PR reviews?\" → `npx skills find pr review`\n- User asks \"I need to create a changelog\" → `npx skills find changelog`\n\nThe command will return results like:\n\n```\nInstall with npx skills add <owner/repo@skill>\n\nvercel-labs/agent-skills@vercel-react-best-practices\n└ https://skills.sh/vercel-labs/agent-skills/vercel-react-best-practices\n```\n\n### Step 3: Present Options to the User\n\nWhen you find relevant skills, present them to the user with:\n\n1. The skill name and what it does\n2. The install command they can run\n3. A link to learn more at skills.sh\n\nExample response:\n\n```\nI found a skill that might help! The \"vercel-react-best-practices\" skill provides\nReact and Next.js performance optimization guidelines from Vercel Engineering.\n\nTo install it:\nnpx skills add vercel-labs/agent-skills@vercel-react-best-practices\n\nLearn more: https://skills.sh/vercel-labs/agent-skills/vercel-react-best-practices\n```\n\n### Step 4: Offer to Install\n\nIf the user wants to proceed, you can install the skill for them:\n\n```bash\nnpx skills add <owner/repo@skill> -g -y\n```\n\nThe `-g` flag installs globally (user-level) and `-y` skips confirmation prompts.\n\n## Common Skill Categories\n\nWhen searching, consider these common categories:\n\n| Category        | Example Queries                          |\n| --------------- | ---------------------------------------- |\n| Web Development | react, nextjs, typescript, css, tailwind |\n| Testing         | testing, jest, playwright, e2e           |\n| DevOps          | deploy, docker, kubernetes, ci-cd        |\n| Documentation   | docs, readme, changelog, api-docs        |\n| Code Quality    | review, lint, refactor, best-practices   |\n| Design          | ui, ux, design-system, accessibility     |\n| Productivity    | workflow, automation, git                |\n\n## Tips for Effective Searches\n\n1. **Use specific keywords**: \"react testing\" is better than just \"testing\"\n2. **Try alternative terms**: If \"deploy\" doesn't work, try \"deployment\" or \"ci-cd\"\n3. **Check popular sources**: Many skills come from `vercel-labs/agent-skills` or `ComposioHQ/awesome-claude-skills`\n\n## When No Skills Are Found\n\nIf no relevant skills exist:\n\n1. Acknowledge that no existing skill was found\n2. Offer to help with the task directly using your general capabilities\n3. Suggest the user could create their own skill with `npx skills init`\n\nExample:\n\n```\nI searched for skills related to \"xyz\" but didn't find any matches.\nI can still help you with this task directly! Would you like me to proceed?\n\nIf this is something you do often, you could create your own skill:\nnpx skills init my-xyz-skill\n```\n"
  },
  {
    "path": ".claude/skills/go-concurrency-patterns/SKILL.md",
    "content": "---\nname: go-concurrency-patterns\ndescription: Master Go concurrency with goroutines, channels, sync primitives, and context. Use when building concurrent Go applications, implementing worker pools, or debugging race conditions.\n---\n\n# Go Concurrency Patterns\n\nProduction patterns for Go concurrency including goroutines, channels, synchronization primitives, and context management.\n\n## When to Use This Skill\n\n- Building concurrent Go applications\n- Implementing worker pools and pipelines\n- Managing goroutine lifecycles\n- Using channels for communication\n- Debugging race conditions\n- Implementing graceful shutdown\n\n## Core Concepts\n\n### 1. Go Concurrency Primitives\n\n| Primitive         | Purpose                          |\n| ----------------- | -------------------------------- |\n| `goroutine`       | Lightweight concurrent execution |\n| `channel`         | Communication between goroutines |\n| `select`          | Multiplex channel operations     |\n| `sync.Mutex`      | Mutual exclusion                 |\n| `sync.WaitGroup`  | Wait for goroutines to complete  |\n| `context.Context` | Cancellation and deadlines       |\n\n### 2. Go Concurrency Mantra\n\n```\nDon't communicate by sharing memory;\nshare memory by communicating.\n```\n\n## Quick Start\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"sync\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n    defer cancel()\n\n    results := make(chan string, 10)\n    var wg sync.WaitGroup\n\n    // Spawn workers\n    for i := 0; i < 3; i++ {\n        wg.Add(1)\n        go worker(ctx, i, results, &wg)\n    }\n\n    // Close results when done\n    go func() {\n        wg.Wait()\n        close(results)\n    }()\n\n    // Collect results\n    for result := range results {\n        fmt.Println(result)\n    }\n}\n\nfunc worker(ctx context.Context, id int, results chan<- string, wg *sync.WaitGroup) {\n    defer wg.Done()\n\n    select {\n    case <-ctx.Done():\n        return\n    case results <- fmt.Sprintf(\"Worker %d done\", id):\n    }\n}\n```\n\n## Patterns\n\n### Pattern 1: Worker Pool\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"sync\"\n)\n\ntype Job struct {\n    ID   int\n    Data string\n}\n\ntype Result struct {\n    JobID int\n    Output string\n    Err   error\n}\n\nfunc WorkerPool(ctx context.Context, numWorkers int, jobs <-chan Job) <-chan Result {\n    results := make(chan Result, len(jobs))\n\n    var wg sync.WaitGroup\n    for i := 0; i < numWorkers; i++ {\n        wg.Add(1)\n        go func(workerID int) {\n            defer wg.Done()\n            for job := range jobs {\n                select {\n                case <-ctx.Done():\n                    return\n                default:\n                    result := processJob(job)\n                    results <- result\n                }\n            }\n        }(i)\n    }\n\n    go func() {\n        wg.Wait()\n        close(results)\n    }()\n\n    return results\n}\n\nfunc processJob(job Job) Result {\n    // Simulate work\n    return Result{\n        JobID:  job.ID,\n        Output: fmt.Sprintf(\"Processed: %s\", job.Data),\n    }\n}\n\n// Usage\nfunc main() {\n    ctx, cancel := context.WithCancel(context.Background())\n    defer cancel()\n\n    jobs := make(chan Job, 100)\n\n    // Send jobs\n    go func() {\n        for i := 0; i < 50; i++ {\n            jobs <- Job{ID: i, Data: fmt.Sprintf(\"job-%d\", i)}\n        }\n        close(jobs)\n    }()\n\n    // Process with 5 workers\n    results := WorkerPool(ctx, 5, jobs)\n\n    for result := range results {\n        fmt.Printf(\"Result: %+v\\n\", result)\n    }\n}\n```\n\n### Pattern 2: Fan-Out/Fan-In Pipeline\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"sync\"\n)\n\n// Stage 1: Generate numbers\nfunc generate(ctx context.Context, nums ...int) <-chan int {\n    out := make(chan int)\n    go func() {\n        defer close(out)\n        for _, n := range nums {\n            select {\n            case <-ctx.Done():\n                return\n            case out <- n:\n            }\n        }\n    }()\n    return out\n}\n\n// Stage 2: Square numbers (can run multiple instances)\nfunc square(ctx context.Context, in <-chan int) <-chan int {\n    out := make(chan int)\n    go func() {\n        defer close(out)\n        for n := range in {\n            select {\n            case <-ctx.Done():\n                return\n            case out <- n * n:\n            }\n        }\n    }()\n    return out\n}\n\n// Fan-in: Merge multiple channels into one\nfunc merge(ctx context.Context, cs ...<-chan int) <-chan int {\n    var wg sync.WaitGroup\n    out := make(chan int)\n\n    // Start output goroutine for each input channel\n    output := func(c <-chan int) {\n        defer wg.Done()\n        for n := range c {\n            select {\n            case <-ctx.Done():\n                return\n            case out <- n:\n            }\n        }\n    }\n\n    wg.Add(len(cs))\n    for _, c := range cs {\n        go output(c)\n    }\n\n    // Close out after all inputs are done\n    go func() {\n        wg.Wait()\n        close(out)\n    }()\n\n    return out\n}\n\nfunc main() {\n    ctx, cancel := context.WithCancel(context.Background())\n    defer cancel()\n\n    // Generate input\n    in := generate(ctx, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n\n    // Fan out to multiple squarers\n    c1 := square(ctx, in)\n    c2 := square(ctx, in)\n    c3 := square(ctx, in)\n\n    // Fan in results\n    for result := range merge(ctx, c1, c2, c3) {\n        fmt.Println(result)\n    }\n}\n```\n\n### Pattern 3: Bounded Concurrency with Semaphore\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"golang.org/x/sync/semaphore\"\n    \"sync\"\n)\n\ntype RateLimitedWorker struct {\n    sem *semaphore.Weighted\n}\n\nfunc NewRateLimitedWorker(maxConcurrent int64) *RateLimitedWorker {\n    return &RateLimitedWorker{\n        sem: semaphore.NewWeighted(maxConcurrent),\n    }\n}\n\nfunc (w *RateLimitedWorker) Do(ctx context.Context, tasks []func() error) []error {\n    var (\n        wg     sync.WaitGroup\n        mu     sync.Mutex\n        errors []error\n    )\n\n    for _, task := range tasks {\n        // Acquire semaphore (blocks if at limit)\n        if err := w.sem.Acquire(ctx, 1); err != nil {\n            return []error{err}\n        }\n\n        wg.Add(1)\n        go func(t func() error) {\n            defer wg.Done()\n            defer w.sem.Release(1)\n\n            if err := t(); err != nil {\n                mu.Lock()\n                errors = append(errors, err)\n                mu.Unlock()\n            }\n        }(task)\n    }\n\n    wg.Wait()\n    return errors\n}\n\n// Alternative: Channel-based semaphore\ntype Semaphore chan struct{}\n\nfunc NewSemaphore(n int) Semaphore {\n    return make(chan struct{}, n)\n}\n\nfunc (s Semaphore) Acquire() {\n    s <- struct{}{}\n}\n\nfunc (s Semaphore) Release() {\n    <-s\n}\n```\n\n### Pattern 4: Graceful Shutdown\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"os\"\n    \"os/signal\"\n    \"sync\"\n    \"syscall\"\n    \"time\"\n)\n\ntype Server struct {\n    shutdown chan struct{}\n    wg       sync.WaitGroup\n}\n\nfunc NewServer() *Server {\n    return &Server{\n        shutdown: make(chan struct{}),\n    }\n}\n\nfunc (s *Server) Start(ctx context.Context) {\n    // Start workers\n    for i := 0; i < 5; i++ {\n        s.wg.Add(1)\n        go s.worker(ctx, i)\n    }\n}\n\nfunc (s *Server) worker(ctx context.Context, id int) {\n    defer s.wg.Done()\n    defer fmt.Printf(\"Worker %d stopped\\n\", id)\n\n    ticker := time.NewTicker(time.Second)\n    defer ticker.Stop()\n\n    for {\n        select {\n        case <-ctx.Done():\n            // Cleanup\n            fmt.Printf(\"Worker %d cleaning up...\\n\", id)\n            time.Sleep(500 * time.Millisecond) // Simulated cleanup\n            return\n        case <-ticker.C:\n            fmt.Printf(\"Worker %d working...\\n\", id)\n        }\n    }\n}\n\nfunc (s *Server) Shutdown(timeout time.Duration) {\n    // Signal shutdown\n    close(s.shutdown)\n\n    // Wait with timeout\n    done := make(chan struct{})\n    go func() {\n        s.wg.Wait()\n        close(done)\n    }()\n\n    select {\n    case <-done:\n        fmt.Println(\"Clean shutdown completed\")\n    case <-time.After(timeout):\n        fmt.Println(\"Shutdown timed out, forcing exit\")\n    }\n}\n\nfunc main() {\n    // Setup signal handling\n    ctx, cancel := context.WithCancel(context.Background())\n\n    sigCh := make(chan os.Signal, 1)\n    signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)\n\n    server := NewServer()\n    server.Start(ctx)\n\n    // Wait for signal\n    sig := <-sigCh\n    fmt.Printf(\"\\nReceived signal: %v\\n\", sig)\n\n    // Cancel context to stop workers\n    cancel()\n\n    // Wait for graceful shutdown\n    server.Shutdown(5 * time.Second)\n}\n```\n\n### Pattern 5: Error Group with Cancellation\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"golang.org/x/sync/errgroup\"\n    \"net/http\"\n)\n\nfunc fetchAllURLs(ctx context.Context, urls []string) ([]string, error) {\n    g, ctx := errgroup.WithContext(ctx)\n\n    results := make([]string, len(urls))\n\n    for i, url := range urls {\n        i, url := i, url // Capture loop variables\n\n        g.Go(func() error {\n            req, err := http.NewRequestWithContext(ctx, \"GET\", url, nil)\n            if err != nil {\n                return fmt.Errorf(\"creating request for %s: %w\", url, err)\n            }\n\n            resp, err := http.DefaultClient.Do(req)\n            if err != nil {\n                return fmt.Errorf(\"fetching %s: %w\", url, err)\n            }\n            defer resp.Body.Close()\n\n            results[i] = fmt.Sprintf(\"%s: %d\", url, resp.StatusCode)\n            return nil\n        })\n    }\n\n    // Wait for all goroutines to complete or one to fail\n    if err := g.Wait(); err != nil {\n        return nil, err // First error cancels all others\n    }\n\n    return results, nil\n}\n\n// With concurrency limit\nfunc fetchWithLimit(ctx context.Context, urls []string, limit int) ([]string, error) {\n    g, ctx := errgroup.WithContext(ctx)\n    g.SetLimit(limit) // Max concurrent goroutines\n\n    results := make([]string, len(urls))\n    var mu sync.Mutex\n\n    for i, url := range urls {\n        i, url := i, url\n\n        g.Go(func() error {\n            result, err := fetchURL(ctx, url)\n            if err != nil {\n                return err\n            }\n\n            mu.Lock()\n            results[i] = result\n            mu.Unlock()\n            return nil\n        })\n    }\n\n    if err := g.Wait(); err != nil {\n        return nil, err\n    }\n\n    return results, nil\n}\n```\n\n### Pattern 6: Concurrent Map with sync.Map\n\n```go\npackage main\n\nimport (\n    \"sync\"\n)\n\n// For frequent reads, infrequent writes\ntype Cache struct {\n    m sync.Map\n}\n\nfunc (c *Cache) Get(key string) (interface{}, bool) {\n    return c.m.Load(key)\n}\n\nfunc (c *Cache) Set(key string, value interface{}) {\n    c.m.Store(key, value)\n}\n\nfunc (c *Cache) GetOrSet(key string, value interface{}) (interface{}, bool) {\n    return c.m.LoadOrStore(key, value)\n}\n\nfunc (c *Cache) Delete(key string) {\n    c.m.Delete(key)\n}\n\n// For write-heavy workloads, use sharded map\ntype ShardedMap struct {\n    shards    []*shard\n    numShards int\n}\n\ntype shard struct {\n    sync.RWMutex\n    data map[string]interface{}\n}\n\nfunc NewShardedMap(numShards int) *ShardedMap {\n    m := &ShardedMap{\n        shards:    make([]*shard, numShards),\n        numShards: numShards,\n    }\n    for i := range m.shards {\n        m.shards[i] = &shard{data: make(map[string]interface{})}\n    }\n    return m\n}\n\nfunc (m *ShardedMap) getShard(key string) *shard {\n    // Simple hash\n    h := 0\n    for _, c := range key {\n        h = 31*h + int(c)\n    }\n    return m.shards[h%m.numShards]\n}\n\nfunc (m *ShardedMap) Get(key string) (interface{}, bool) {\n    shard := m.getShard(key)\n    shard.RLock()\n    defer shard.RUnlock()\n    v, ok := shard.data[key]\n    return v, ok\n}\n\nfunc (m *ShardedMap) Set(key string, value interface{}) {\n    shard := m.getShard(key)\n    shard.Lock()\n    defer shard.Unlock()\n    shard.data[key] = value\n}\n```\n\n### Pattern 7: Select with Timeout and Default\n\n```go\nfunc selectPatterns() {\n    ch := make(chan int)\n\n    // Timeout pattern\n    select {\n    case v := <-ch:\n        fmt.Println(\"Received:\", v)\n    case <-time.After(time.Second):\n        fmt.Println(\"Timeout!\")\n    }\n\n    // Non-blocking send/receive\n    select {\n    case ch <- 42:\n        fmt.Println(\"Sent\")\n    default:\n        fmt.Println(\"Channel full, skipping\")\n    }\n\n    // Priority select (check high priority first)\n    highPriority := make(chan int)\n    lowPriority := make(chan int)\n\n    for {\n        select {\n        case msg := <-highPriority:\n            fmt.Println(\"High priority:\", msg)\n        default:\n            select {\n            case msg := <-highPriority:\n                fmt.Println(\"High priority:\", msg)\n            case msg := <-lowPriority:\n                fmt.Println(\"Low priority:\", msg)\n            }\n        }\n    }\n}\n```\n\n## Race Detection\n\n```bash\n# Run tests with race detector\ngo test -race ./...\n\n# Build with race detector\ngo build -race .\n\n# Run with race detector\ngo run -race main.go\n```\n\n## Best Practices\n\n### Do's\n\n- **Use context** - For cancellation and deadlines\n- **Close channels** - From sender side only\n- **Use errgroup** - For concurrent operations with errors\n- **Buffer channels** - When you know the count\n- **Prefer channels** - Over mutexes when possible\n\n### Don'ts\n\n- **Don't leak goroutines** - Always have exit path\n- **Don't close from receiver** - Causes panic\n- **Don't use shared memory** - Unless necessary\n- **Don't ignore context cancellation** - Check ctx.Done()\n- **Don't use time.Sleep for sync** - Use proper primitives\n\n## Resources\n\n- [Go Concurrency Patterns](https://go.dev/blog/pipelines)\n- [Effective Go - Concurrency](https://go.dev/doc/effective_go#concurrency)\n- [Go by Example - Goroutines](https://gobyexample.com/goroutines)\n"
  },
  {
    "path": ".claude/skills/golang-patterns/SKILL.md",
    "content": "---\nname: golang-patterns\ndescription: Idiomatic Go patterns, best practices, and conventions for building robust, efficient, and maintainable Go applications.\norigin: ECC\n---\n\n# Go Development Patterns\n\nIdiomatic Go patterns and best practices for building robust, efficient, and maintainable applications.\n\n## When to Activate\n\n- Writing new Go code\n- Reviewing Go code\n- Refactoring existing Go code\n- Designing Go packages/modules\n\n## Core Principles\n\n### 1. Simplicity and Clarity\n\nGo favors simplicity over cleverness. Code should be obvious and easy to read.\n\n```go\n// Good: Clear and direct\nfunc GetUser(id string) (*User, error) {\n    user, err := db.FindUser(id)\n    if err != nil {\n        return nil, fmt.Errorf(\"get user %s: %w\", id, err)\n    }\n    return user, nil\n}\n\n// Bad: Overly clever\nfunc GetUser(id string) (*User, error) {\n    return func() (*User, error) {\n        if u, e := db.FindUser(id); e == nil {\n            return u, nil\n        } else {\n            return nil, e\n        }\n    }()\n}\n```\n\n### 2. Make the Zero Value Useful\n\nDesign types so their zero value is immediately usable without initialization.\n\n```go\n// Good: Zero value is useful\ntype Counter struct {\n    mu    sync.Mutex\n    count int // zero value is 0, ready to use\n}\n\nfunc (c *Counter) Inc() {\n    c.mu.Lock()\n    c.count++\n    c.mu.Unlock()\n}\n\n// Good: bytes.Buffer works with zero value\nvar buf bytes.Buffer\nbuf.WriteString(\"hello\")\n\n// Bad: Requires initialization\ntype BadCounter struct {\n    counts map[string]int // nil map will panic\n}\n```\n\n### 3. Accept Interfaces, Return Structs\n\nFunctions should accept interface parameters and return concrete types.\n\n```go\n// Good: Accepts interface, returns concrete type\nfunc ProcessData(r io.Reader) (*Result, error) {\n    data, err := io.ReadAll(r)\n    if err != nil {\n        return nil, err\n    }\n    return &Result{Data: data}, nil\n}\n\n// Bad: Returns interface (hides implementation details unnecessarily)\nfunc ProcessData(r io.Reader) (io.Reader, error) {\n    // ...\n}\n```\n\n## Error Handling Patterns\n\n### Error Wrapping with Context\n\n```go\n// Good: Wrap errors with context\nfunc LoadConfig(path string) (*Config, error) {\n    data, err := os.ReadFile(path)\n    if err != nil {\n        return nil, fmt.Errorf(\"load config %s: %w\", path, err)\n    }\n\n    var cfg Config\n    if err := json.Unmarshal(data, &cfg); err != nil {\n        return nil, fmt.Errorf(\"parse config %s: %w\", path, err)\n    }\n\n    return &cfg, nil\n}\n```\n\n### Custom Error Types\n\n```go\n// Define domain-specific errors\ntype ValidationError struct {\n    Field   string\n    Message string\n}\n\nfunc (e *ValidationError) Error() string {\n    return fmt.Sprintf(\"validation failed on %s: %s\", e.Field, e.Message)\n}\n\n// Sentinel errors for common cases\nvar (\n    ErrNotFound     = errors.New(\"resource not found\")\n    ErrUnauthorized = errors.New(\"unauthorized\")\n    ErrInvalidInput = errors.New(\"invalid input\")\n)\n```\n\n### Error Checking with errors.Is and errors.As\n\n```go\nfunc HandleError(err error) {\n    // Check for specific error\n    if errors.Is(err, sql.ErrNoRows) {\n        log.Println(\"No records found\")\n        return\n    }\n\n    // Check for error type\n    var validationErr *ValidationError\n    if errors.As(err, &validationErr) {\n        log.Printf(\"Validation error on field %s: %s\",\n            validationErr.Field, validationErr.Message)\n        return\n    }\n\n    // Unknown error\n    log.Printf(\"Unexpected error: %v\", err)\n}\n```\n\n### Never Ignore Errors\n\n```go\n// Bad: Ignoring error with blank identifier\nresult, _ := doSomething()\n\n// Good: Handle or explicitly document why it's safe to ignore\nresult, err := doSomething()\nif err != nil {\n    return err\n}\n\n// Acceptable: When error truly doesn't matter (rare)\n_ = writer.Close() // Best-effort cleanup, error logged elsewhere\n```\n\n## Concurrency Patterns\n\n### Worker Pool\n\n```go\nfunc WorkerPool(jobs <-chan Job, results chan<- Result, numWorkers int) {\n    var wg sync.WaitGroup\n\n    for i := 0; i < numWorkers; i++ {\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            for job := range jobs {\n                results <- process(job)\n            }\n        }()\n    }\n\n    wg.Wait()\n    close(results)\n}\n```\n\n### Context for Cancellation and Timeouts\n\n```go\nfunc FetchWithTimeout(ctx context.Context, url string) ([]byte, error) {\n    ctx, cancel := context.WithTimeout(ctx, 5*time.Second)\n    defer cancel()\n\n    req, err := http.NewRequestWithContext(ctx, \"GET\", url, nil)\n    if err != nil {\n        return nil, fmt.Errorf(\"create request: %w\", err)\n    }\n\n    resp, err := http.DefaultClient.Do(req)\n    if err != nil {\n        return nil, fmt.Errorf(\"fetch %s: %w\", url, err)\n    }\n    defer resp.Body.Close()\n\n    return io.ReadAll(resp.Body)\n}\n```\n\n### Graceful Shutdown\n\n```go\nfunc GracefulShutdown(server *http.Server) {\n    quit := make(chan os.Signal, 1)\n    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)\n\n    <-quit\n    log.Println(\"Shutting down server...\")\n\n    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n    defer cancel()\n\n    if err := server.Shutdown(ctx); err != nil {\n        log.Fatalf(\"Server forced to shutdown: %v\", err)\n    }\n\n    log.Println(\"Server exited\")\n}\n```\n\n### errgroup for Coordinated Goroutines\n\n```go\nimport \"golang.org/x/sync/errgroup\"\n\nfunc FetchAll(ctx context.Context, urls []string) ([][]byte, error) {\n    g, ctx := errgroup.WithContext(ctx)\n    results := make([][]byte, len(urls))\n\n    for i, url := range urls {\n        i, url := i, url // Capture loop variables\n        g.Go(func() error {\n            data, err := FetchWithTimeout(ctx, url)\n            if err != nil {\n                return err\n            }\n            results[i] = data\n            return nil\n        })\n    }\n\n    if err := g.Wait(); err != nil {\n        return nil, err\n    }\n    return results, nil\n}\n```\n\n### Avoiding Goroutine Leaks\n\n```go\n// Bad: Goroutine leak if context is cancelled\nfunc leakyFetch(ctx context.Context, url string) <-chan []byte {\n    ch := make(chan []byte)\n    go func() {\n        data, _ := fetch(url)\n        ch <- data // Blocks forever if no receiver\n    }()\n    return ch\n}\n\n// Good: Properly handles cancellation\nfunc safeFetch(ctx context.Context, url string) <-chan []byte {\n    ch := make(chan []byte, 1) // Buffered channel\n    go func() {\n        data, err := fetch(url)\n        if err != nil {\n            return\n        }\n        select {\n        case ch <- data:\n        case <-ctx.Done():\n        }\n    }()\n    return ch\n}\n```\n\n## Interface Design\n\n### Small, Focused Interfaces\n\n```go\n// Good: Single-method interfaces\ntype Reader interface {\n    Read(p []byte) (n int, err error)\n}\n\ntype Writer interface {\n    Write(p []byte) (n int, err error)\n}\n\ntype Closer interface {\n    Close() error\n}\n\n// Compose interfaces as needed\ntype ReadWriteCloser interface {\n    Reader\n    Writer\n    Closer\n}\n```\n\n### Define Interfaces Where They're Used\n\n```go\n// In the consumer package, not the provider\npackage service\n\n// UserStore defines what this service needs\ntype UserStore interface {\n    GetUser(id string) (*User, error)\n    SaveUser(user *User) error\n}\n\ntype Service struct {\n    store UserStore\n}\n\n// Concrete implementation can be in another package\n// It doesn't need to know about this interface\n```\n\n### Optional Behavior with Type Assertions\n\n```go\ntype Flusher interface {\n    Flush() error\n}\n\nfunc WriteAndFlush(w io.Writer, data []byte) error {\n    if _, err := w.Write(data); err != nil {\n        return err\n    }\n\n    // Flush if supported\n    if f, ok := w.(Flusher); ok {\n        return f.Flush()\n    }\n    return nil\n}\n```\n\n## Package Organization\n\n### Standard Project Layout\n\n```text\nmyproject/\n├── cmd/\n│   └── myapp/\n│       └── main.go           # Entry point\n├── internal/\n│   ├── handler/              # HTTP handlers\n│   ├── service/              # Business logic\n│   ├── repository/           # Data access\n│   └── config/               # Configuration\n├── pkg/\n│   └── client/               # Public API client\n├── api/\n│   └── v1/                   # API definitions (proto, OpenAPI)\n├── testdata/                 # Test fixtures\n├── go.mod\n├── go.sum\n└── Makefile\n```\n\n### Package Naming\n\n```go\n// Good: Short, lowercase, no underscores\npackage http\npackage json\npackage user\n\n// Bad: Verbose, mixed case, or redundant\npackage httpHandler\npackage json_parser\npackage userService // Redundant 'Service' suffix\n```\n\n### Avoid Package-Level State\n\n```go\n// Bad: Global mutable state\nvar db *sql.DB\n\nfunc init() {\n    db, _ = sql.Open(\"postgres\", os.Getenv(\"DATABASE_URL\"))\n}\n\n// Good: Dependency injection\ntype Server struct {\n    db *sql.DB\n}\n\nfunc NewServer(db *sql.DB) *Server {\n    return &Server{db: db}\n}\n```\n\n## Struct Design\n\n### Functional Options Pattern\n\n```go\ntype Server struct {\n    addr    string\n    timeout time.Duration\n    logger  *log.Logger\n}\n\ntype Option func(*Server)\n\nfunc WithTimeout(d time.Duration) Option {\n    return func(s *Server) {\n        s.timeout = d\n    }\n}\n\nfunc WithLogger(l *log.Logger) Option {\n    return func(s *Server) {\n        s.logger = l\n    }\n}\n\nfunc NewServer(addr string, opts ...Option) *Server {\n    s := &Server{\n        addr:    addr,\n        timeout: 30 * time.Second, // default\n        logger:  log.Default(),    // default\n    }\n    for _, opt := range opts {\n        opt(s)\n    }\n    return s\n}\n\n// Usage\nserver := NewServer(\":8080\",\n    WithTimeout(60*time.Second),\n    WithLogger(customLogger),\n)\n```\n\n### Embedding for Composition\n\n```go\ntype Logger struct {\n    prefix string\n}\n\nfunc (l *Logger) Log(msg string) {\n    fmt.Printf(\"[%s] %s\\n\", l.prefix, msg)\n}\n\ntype Server struct {\n    *Logger // Embedding - Server gets Log method\n    addr    string\n}\n\nfunc NewServer(addr string) *Server {\n    return &Server{\n        Logger: &Logger{prefix: \"SERVER\"},\n        addr:   addr,\n    }\n}\n\n// Usage\ns := NewServer(\":8080\")\ns.Log(\"Starting...\") // Calls embedded Logger.Log\n```\n\n## Memory and Performance\n\n### Preallocate Slices When Size is Known\n\n```go\n// Bad: Grows slice multiple times\nfunc processItems(items []Item) []Result {\n    var results []Result\n    for _, item := range items {\n        results = append(results, process(item))\n    }\n    return results\n}\n\n// Good: Single allocation\nfunc processItems(items []Item) []Result {\n    results := make([]Result, 0, len(items))\n    for _, item := range items {\n        results = append(results, process(item))\n    }\n    return results\n}\n```\n\n### Use sync.Pool for Frequent Allocations\n\n```go\nvar bufferPool = sync.Pool{\n    New: func() interface{} {\n        return new(bytes.Buffer)\n    },\n}\n\nfunc ProcessRequest(data []byte) []byte {\n    buf := bufferPool.Get().(*bytes.Buffer)\n    defer func() {\n        buf.Reset()\n        bufferPool.Put(buf)\n    }()\n\n    buf.Write(data)\n    // Process...\n    return buf.Bytes()\n}\n```\n\n### Avoid String Concatenation in Loops\n\n```go\n// Bad: Creates many string allocations\nfunc join(parts []string) string {\n    var result string\n    for _, p := range parts {\n        result += p + \",\"\n    }\n    return result\n}\n\n// Good: Single allocation with strings.Builder\nfunc join(parts []string) string {\n    var sb strings.Builder\n    for i, p := range parts {\n        if i > 0 {\n            sb.WriteString(\",\")\n        }\n        sb.WriteString(p)\n    }\n    return sb.String()\n}\n\n// Best: Use standard library\nfunc join(parts []string) string {\n    return strings.Join(parts, \",\")\n}\n```\n\n## Go Tooling Integration\n\n### Essential Commands\n\n```bash\n# Build and run\ngo build ./...\ngo run ./cmd/myapp\n\n# Testing\ngo test ./...\ngo test -race ./...\ngo test -cover ./...\n\n# Static analysis\ngo vet ./...\nstaticcheck ./...\ngolangci-lint run\n\n# Module management\ngo mod tidy\ngo mod verify\n\n# Formatting\ngofmt -w .\ngoimports -w .\n```\n\n### Recommended Linter Configuration (.golangci.yml)\n\n```yaml\nlinters:\n  enable:\n    - errcheck\n    - gosimple\n    - govet\n    - ineffassign\n    - staticcheck\n    - unused\n    - gofmt\n    - goimports\n    - misspell\n    - unconvert\n    - unparam\n\nlinters-settings:\n  errcheck:\n    check-type-assertions: true\n  govet:\n    check-shadowing: true\n\nissues:\n  exclude-use-default: false\n```\n\n## Quick Reference: Go Idioms\n\n| Idiom | Description |\n|-------|-------------|\n| Accept interfaces, return structs | Functions accept interface params, return concrete types |\n| Errors are values | Treat errors as first-class values, not exceptions |\n| Don't communicate by sharing memory | Use channels for coordination between goroutines |\n| Make the zero value useful | Types should work without explicit initialization |\n| A little copying is better than a little dependency | Avoid unnecessary external dependencies |\n| Clear is better than clever | Prioritize readability over cleverness |\n| gofmt is no one's favorite but everyone's friend | Always format with gofmt/goimports |\n| Return early | Handle errors first, keep happy path unindented |\n\n## Anti-Patterns to Avoid\n\n```go\n// Bad: Naked returns in long functions\nfunc process() (result int, err error) {\n    // ... 50 lines ...\n    return // What is being returned?\n}\n\n// Bad: Using panic for control flow\nfunc GetUser(id string) *User {\n    user, err := db.Find(id)\n    if err != nil {\n        panic(err) // Don't do this\n    }\n    return user\n}\n\n// Bad: Passing context in struct\ntype Request struct {\n    ctx context.Context // Context should be first param\n    ID  string\n}\n\n// Good: Context as first parameter\nfunc ProcessRequest(ctx context.Context, id string) error {\n    // ...\n}\n\n// Bad: Mixing value and pointer receivers\ntype Counter struct{ n int }\nfunc (c Counter) Value() int { return c.n }    // Value receiver\nfunc (c *Counter) Increment() { c.n++ }        // Pointer receiver\n// Pick one style and be consistent\n```\n\n**Remember**: Go code should be boring in the best way - predictable, consistent, and easy to understand. When in doubt, keep it simple.\n"
  },
  {
    "path": ".claude/skills/golang-pro/SKILL.md",
    "content": "---\nname: golang-pro\ndescription: Use when building Go applications requiring concurrent programming, microservices architecture, or high-performance systems. Invoke for goroutines, channels, Go generics, gRPC integration.\nlicense: MIT\nmetadata:\n  author: https://github.com/Jeffallan\n  version: \"1.0.0\"\n  domain: language\n  triggers: Go, Golang, goroutines, channels, gRPC, microservices Go, Go generics, concurrent programming, Go interfaces\n  role: specialist\n  scope: implementation\n  output-format: code\n  related-skills: devops-engineer, microservices-architect, test-master\n---\n\n# Golang Pro\n\nSenior Go developer with deep expertise in Go 1.21+, concurrent programming, and cloud-native microservices. Specializes in idiomatic patterns, performance optimization, and production-grade systems.\n\n## Role Definition\n\nYou are a senior Go engineer with 8+ years of systems programming experience. You specialize in Go 1.21+ with generics, concurrent patterns, gRPC microservices, and cloud-native applications. You build efficient, type-safe systems following Go proverbs.\n\n## When to Use This Skill\n\n- Building concurrent Go applications with goroutines and channels\n- Implementing microservices with gRPC or REST APIs\n- Creating CLI tools and system utilities\n- Optimizing Go code for performance and memory efficiency\n- Designing interfaces and using Go generics\n- Setting up testing with table-driven tests and benchmarks\n\n## Core Workflow\n\n1. **Analyze architecture** - Review module structure, interfaces, concurrency patterns\n2. **Design interfaces** - Create small, focused interfaces with composition\n3. **Implement** - Write idiomatic Go with proper error handling and context propagation\n4. **Optimize** - Profile with pprof, write benchmarks, eliminate allocations\n5. **Test** - Table-driven tests, race detector, fuzzing, 80%+ coverage\n\n## Reference Guide\n\nLoad detailed guidance based on context:\n\n| Topic | Reference | Load When |\n|-------|-----------|-----------|\n| Concurrency | `references/concurrency.md` | Goroutines, channels, select, sync primitives |\n| Interfaces | `references/interfaces.md` | Interface design, io.Reader/Writer, composition |\n| Generics | `references/generics.md` | Type parameters, constraints, generic patterns |\n| Testing | `references/testing.md` | Table-driven tests, benchmarks, fuzzing |\n| Project Structure | `references/project-structure.md` | Module layout, internal packages, go.mod |\n\n## Constraints\n\n### MUST DO\n- Use gofmt and golangci-lint on all code\n- Add context.Context to all blocking operations\n- Handle all errors explicitly (no naked returns)\n- Write table-driven tests with subtests\n- Document all exported functions, types, and packages\n- Use `X | Y` union constraints for generics (Go 1.18+)\n- Propagate errors with fmt.Errorf(\"%w\", err)\n- Run race detector on tests (-race flag)\n\n### MUST NOT DO\n- Ignore errors (avoid _ assignment without justification)\n- Use panic for normal error handling\n- Create goroutines without clear lifecycle management\n- Skip context cancellation handling\n- Use reflection without performance justification\n- Mix sync and async patterns carelessly\n- Hardcode configuration (use functional options or env vars)\n\n## Output Templates\n\nWhen implementing Go features, provide:\n1. Interface definitions (contracts first)\n2. Implementation files with proper package structure\n3. Test file with table-driven tests\n4. Brief explanation of concurrency patterns used\n\n## Knowledge Reference\n\nGo 1.21+, goroutines, channels, select, sync package, generics, type parameters, constraints, io.Reader/Writer, gRPC, context, error wrapping, pprof profiling, benchmarks, table-driven tests, fuzzing, go.mod, internal packages, functional options\n"
  },
  {
    "path": ".claude/skills/golang-pro/references/concurrency.md",
    "content": "# Concurrency Patterns\n\n## Goroutine Lifecycle Management\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"sync\"\n    \"time\"\n)\n\n// Worker pool with bounded concurrency\ntype WorkerPool struct {\n    workers int\n    tasks   chan func()\n    wg      sync.WaitGroup\n}\n\nfunc NewWorkerPool(workers int) *WorkerPool {\n    wp := &WorkerPool{\n        workers: workers,\n        tasks:   make(chan func(), workers*2), // Buffered channel\n    }\n    wp.start()\n    return wp\n}\n\nfunc (wp *WorkerPool) start() {\n    for i := 0; i < wp.workers; i++ {\n        wp.wg.Add(1)\n        go func() {\n            defer wp.wg.Done()\n            for task := range wp.tasks {\n                task()\n            }\n        }()\n    }\n}\n\nfunc (wp *WorkerPool) Submit(task func()) {\n    wp.tasks <- task\n}\n\nfunc (wp *WorkerPool) Shutdown() {\n    close(wp.tasks)\n    wp.wg.Wait()\n}\n```\n\n## Channel Patterns\n\n```go\n// Generator pattern\nfunc generateNumbers(ctx context.Context, max int) <-chan int {\n    out := make(chan int)\n    go func() {\n        defer close(out)\n        for i := 0; i < max; i++ {\n            select {\n            case out <- i:\n            case <-ctx.Done():\n                return\n            }\n        }\n    }()\n    return out\n}\n\n// Fan-out, fan-in pattern\nfunc fanOut(ctx context.Context, input <-chan int, workers int) []<-chan int {\n    channels := make([]<-chan int, workers)\n    for i := 0; i < workers; i++ {\n        channels[i] = process(ctx, input)\n    }\n    return channels\n}\n\nfunc process(ctx context.Context, input <-chan int) <-chan int {\n    out := make(chan int)\n    go func() {\n        defer close(out)\n        for val := range input {\n            select {\n            case out <- val * 2:\n            case <-ctx.Done():\n                return\n            }\n        }\n    }()\n    return out\n}\n\nfunc fanIn(ctx context.Context, channels ...<-chan int) <-chan int {\n    out := make(chan int)\n    var wg sync.WaitGroup\n\n    for _, ch := range channels {\n        wg.Add(1)\n        go func(c <-chan int) {\n            defer wg.Done()\n            for val := range c {\n                select {\n                case out <- val:\n                case <-ctx.Done():\n                    return\n                }\n            }\n        }(ch)\n    }\n\n    go func() {\n        wg.Wait()\n        close(out)\n    }()\n\n    return out\n}\n```\n\n## Select Statement Patterns\n\n```go\n// Timeout pattern\nfunc fetchWithTimeout(ctx context.Context, url string) (string, error) {\n    result := make(chan string, 1)\n    errCh := make(chan error, 1)\n\n    go func() {\n        // Simulate network call\n        time.Sleep(100 * time.Millisecond)\n        result <- \"data from \" + url\n    }()\n\n    select {\n    case res := <-result:\n        return res, nil\n    case err := <-errCh:\n        return \"\", err\n    case <-time.After(50 * time.Millisecond):\n        return \"\", fmt.Errorf(\"timeout\")\n    case <-ctx.Done():\n        return \"\", ctx.Err()\n    }\n}\n\n// Done channel pattern for graceful shutdown\ntype Server struct {\n    done chan struct{}\n}\n\nfunc (s *Server) Shutdown() {\n    close(s.done)\n}\n\nfunc (s *Server) Run(ctx context.Context) {\n    ticker := time.NewTicker(1 * time.Second)\n    defer ticker.Stop()\n\n    for {\n        select {\n        case <-ticker.C:\n            fmt.Println(\"tick\")\n        case <-s.done:\n            fmt.Println(\"shutting down\")\n            return\n        case <-ctx.Done():\n            fmt.Println(\"context cancelled\")\n            return\n        }\n    }\n}\n```\n\n## Sync Primitives\n\n```go\nimport \"sync\"\n\n// Mutex for protecting shared state\ntype Counter struct {\n    mu    sync.Mutex\n    count int\n}\n\nfunc (c *Counter) Increment() {\n    c.mu.Lock()\n    defer c.mu.Unlock()\n    c.count++\n}\n\nfunc (c *Counter) Value() int {\n    c.mu.Lock()\n    defer c.mu.Unlock()\n    return c.count\n}\n\n// RWMutex for read-heavy workloads\ntype Cache struct {\n    mu    sync.RWMutex\n    items map[string]string\n}\n\nfunc (c *Cache) Get(key string) (string, bool) {\n    c.mu.RLock()\n    defer c.mu.RUnlock()\n    val, ok := c.items[key]\n    return val, ok\n}\n\nfunc (c *Cache) Set(key, value string) {\n    c.mu.Lock()\n    defer c.mu.Unlock()\n    c.items[key] = value\n}\n\n// sync.Once for initialization\ntype Service struct {\n    once   sync.Once\n    config *Config\n}\n\nfunc (s *Service) getConfig() *Config {\n    s.once.Do(func() {\n        s.config = loadConfig() // Only called once\n    })\n    return s.config\n}\n```\n\n## Rate Limiting and Backpressure\n\n```go\nimport \"golang.org/x/time/rate\"\n\n// Token bucket rate limiter\ntype RateLimiter struct {\n    limiter *rate.Limiter\n}\n\nfunc NewRateLimiter(rps int) *RateLimiter {\n    return &RateLimiter{\n        limiter: rate.NewLimiter(rate.Limit(rps), rps),\n    }\n}\n\nfunc (rl *RateLimiter) Process(ctx context.Context, item string) error {\n    if err := rl.limiter.Wait(ctx); err != nil {\n        return err\n    }\n    // Process item\n    return nil\n}\n\n// Semaphore pattern for limiting concurrency\ntype Semaphore struct {\n    slots chan struct{}\n}\n\nfunc NewSemaphore(n int) *Semaphore {\n    return &Semaphore{\n        slots: make(chan struct{}, n),\n    }\n}\n\nfunc (s *Semaphore) Acquire() {\n    s.slots <- struct{}{}\n}\n\nfunc (s *Semaphore) Release() {\n    <-s.slots\n}\n\nfunc (s *Semaphore) Do(fn func()) {\n    s.Acquire()\n    defer s.Release()\n    fn()\n}\n```\n\n## Pipeline Pattern\n\n```go\n// Stage-based processing pipeline\nfunc pipeline(ctx context.Context, input <-chan int) <-chan int {\n    // Stage 1: Square numbers\n    stage1 := make(chan int)\n    go func() {\n        defer close(stage1)\n        for num := range input {\n            select {\n            case stage1 <- num * num:\n            case <-ctx.Done():\n                return\n            }\n        }\n    }()\n\n    // Stage 2: Filter even numbers\n    stage2 := make(chan int)\n    go func() {\n        defer close(stage2)\n        for num := range stage1 {\n            if num%2 == 0 {\n                select {\n                case stage2 <- num:\n                case <-ctx.Done():\n                    return\n                }\n            }\n        }\n    }()\n\n    return stage2\n}\n```\n\n## Quick Reference\n\n| Pattern | Use Case | Key Points |\n|---------|----------|------------|\n| Worker Pool | Bounded concurrency | Limit goroutines, reuse workers |\n| Fan-out/Fan-in | Parallel processing | Distribute work, merge results |\n| Pipeline | Stream processing | Chain transformations |\n| Rate Limiter | API throttling | Control request rate |\n| Semaphore | Resource limits | Cap concurrent operations |\n| Done Channel | Graceful shutdown | Signal completion |\n"
  },
  {
    "path": ".claude/skills/golang-pro/references/generics.md",
    "content": "# Generics and Type Parameters\n\n## Basic Type Parameters\n\n```go\npackage main\n\n// Generic function with type parameter\nfunc Max[T constraints.Ordered](a, b T) T {\n    if a > b {\n        return a\n    }\n    return b\n}\n\n// Multiple type parameters\nfunc Map[T, U any](slice []T, fn func(T) U) []U {\n    result := make([]U, len(slice))\n    for i, v := range slice {\n        result[i] = fn(v)\n    }\n    return result\n}\n\n// Usage\nfunc main() {\n    maxInt := Max(10, 20)           // T = int\n    maxFloat := Max(3.14, 2.71)     // T = float64\n    maxString := Max(\"abc\", \"xyz\")  // T = string\n\n    nums := []int{1, 2, 3}\n    doubled := Map(nums, func(n int) int { return n * 2 })\n    strings := Map(nums, func(n int) string { return fmt.Sprintf(\"%d\", n) })\n}\n```\n\n## Type Constraints\n\n```go\nimport \"constraints\"\n\n// Built-in constraints\ntype Number interface {\n    constraints.Integer | constraints.Float\n}\n\nfunc Sum[T Number](numbers []T) T {\n    var total T\n    for _, n := range numbers {\n        total += n\n    }\n    return total\n}\n\n// Custom constraints with methods\ntype Stringer interface {\n    String() string\n}\n\nfunc PrintAll[T Stringer](items []T) {\n    for _, item := range items {\n        fmt.Println(item.String())\n    }\n}\n\n// Approximate constraint using ~\ntype Integer interface {\n    ~int | ~int8 | ~int16 | ~int32 | ~int64\n}\n\ntype MyInt int\n\nfunc Double[T Integer](n T) T {\n    return n * 2\n}\n\n// Works with both int and MyInt\nfunc main() {\n    fmt.Println(Double(5))          // int\n    fmt.Println(Double(MyInt(5)))   // MyInt\n}\n```\n\n## Generic Data Structures\n\n```go\n// Generic Stack\ntype Stack[T any] struct {\n    items []T\n}\n\nfunc NewStack[T any]() *Stack[T] {\n    return &Stack[T]{\n        items: make([]T, 0),\n    }\n}\n\nfunc (s *Stack[T]) Push(item T) {\n    s.items = append(s.items, item)\n}\n\nfunc (s *Stack[T]) Pop() (T, bool) {\n    if len(s.items) == 0 {\n        var zero T\n        return zero, false\n    }\n    item := s.items[len(s.items)-1]\n    s.items = s.items[:len(s.items)-1]\n    return item, true\n}\n\nfunc (s *Stack[T]) IsEmpty() bool {\n    return len(s.items) == 0\n}\n\n// Usage\nintStack := NewStack[int]()\nintStack.Push(1)\nintStack.Push(2)\n\nstringStack := NewStack[string]()\nstringStack.Push(\"hello\")\nstringStack.Push(\"world\")\n```\n\n## Generic Map Operations\n\n```go\n// Filter with generics\nfunc Filter[T any](slice []T, predicate func(T) bool) []T {\n    result := make([]T, 0, len(slice))\n    for _, v := range slice {\n        if predicate(v) {\n            result = append(result, v)\n        }\n    }\n    return result\n}\n\n// Reduce/Fold\nfunc Reduce[T, U any](slice []T, initial U, fn func(U, T) U) U {\n    acc := initial\n    for _, v := range slice {\n        acc = fn(acc, v)\n    }\n    return acc\n}\n\n// Keys from map\nfunc Keys[K comparable, V any](m map[K]V) []K {\n    keys := make([]K, 0, len(m))\n    for k := range m {\n        keys = append(keys, k)\n    }\n    return keys\n}\n\n// Values from map\nfunc Values[K comparable, V any](m map[K]V) []V {\n    values := make([]V, 0, len(m))\n    for _, v := range m {\n        values = append(values, v)\n    }\n    return values\n}\n\n// Usage\nnumbers := []int{1, 2, 3, 4, 5, 6}\nevens := Filter(numbers, func(n int) bool { return n%2 == 0 })\n\nsum := Reduce(numbers, 0, func(acc, n int) int { return acc + n })\n\nm := map[string]int{\"a\": 1, \"b\": 2}\nkeys := Keys(m)     // []string{\"a\", \"b\"}\nvalues := Values(m) // []int{1, 2}\n```\n\n## Generic Pairs and Tuples\n\n```go\n// Generic Pair\ntype Pair[T, U any] struct {\n    First  T\n    Second U\n}\n\nfunc NewPair[T, U any](first T, second U) Pair[T, U] {\n    return Pair[T, U]{First: first, Second: second}\n}\n\nfunc (p Pair[T, U]) Swap() Pair[U, T] {\n    return Pair[U, T]{First: p.Second, Second: p.First}\n}\n\n// Usage\npair := NewPair(\"name\", 42)\nswapped := pair.Swap() // Pair[int, string]\n\n// Generic Result type (like Rust's Result<T, E>)\ntype Result[T any] struct {\n    value T\n    err   error\n}\n\nfunc Ok[T any](value T) Result[T] {\n    return Result[T]{value: value}\n}\n\nfunc Err[T any](err error) Result[T] {\n    return Result[T]{err: err}\n}\n\nfunc (r Result[T]) IsOk() bool {\n    return r.err == nil\n}\n\nfunc (r Result[T]) Unwrap() (T, error) {\n    return r.value, r.err\n}\n\nfunc (r Result[T]) UnwrapOr(defaultValue T) T {\n    if r.err != nil {\n        return defaultValue\n    }\n    return r.value\n}\n```\n\n## Comparable Constraint\n\n```go\n// Find using comparable\nfunc Find[T comparable](slice []T, target T) (int, bool) {\n    for i, v := range slice {\n        if v == target {\n            return i, true\n        }\n    }\n    return -1, false\n}\n\n// Contains\nfunc Contains[T comparable](slice []T, target T) bool {\n    _, found := Find(slice, target)\n    return found\n}\n\n// Unique elements\nfunc Unique[T comparable](slice []T) []T {\n    seen := make(map[T]struct{})\n    result := make([]T, 0, len(slice))\n\n    for _, v := range slice {\n        if _, exists := seen[v]; !exists {\n            seen[v] = struct{}{}\n            result = append(result, v)\n        }\n    }\n\n    return result\n}\n\n// Usage\nnums := []int{1, 2, 2, 3, 3, 4}\nunique := Unique(nums) // []int{1, 2, 3, 4}\n\nidx, found := Find([]string{\"a\", \"b\", \"c\"}, \"b\") // 1, true\n```\n\n## Generic Interfaces\n\n```go\n// Generic interface\ntype Container[T any] interface {\n    Add(item T)\n    Remove() (T, bool)\n    Size() int\n}\n\n// Implementation\ntype Queue[T any] struct {\n    items []T\n}\n\nfunc (q *Queue[T]) Add(item T) {\n    q.items = append(q.items, item)\n}\n\nfunc (q *Queue[T]) Remove() (T, bool) {\n    if len(q.items) == 0 {\n        var zero T\n        return zero, false\n    }\n    item := q.items[0]\n    q.items = q.items[1:]\n    return item, true\n}\n\nfunc (q *Queue[T]) Size() int {\n    return len(q.items)\n}\n\n// Function accepting generic interface\nfunc ProcessContainer[T any](c Container[T], item T) {\n    c.Add(item)\n    fmt.Printf(\"Container size: %d\\n\", c.Size())\n}\n```\n\n## Type Inference\n\n```go\n// Type inference works in most cases\nfunc Identity[T any](x T) T {\n    return x\n}\n\n// No need to specify type\nresult := Identity(42)          // T inferred as int\nstr := Identity(\"hello\")        // T inferred as string\n\n// Type inference with constraints\nfunc Min[T constraints.Ordered](a, b T) T {\n    if a < b {\n        return a\n    }\n    return b\n}\n\n// Inferred from arguments\nminVal := Min(10, 20)           // T = int\nminFloat := Min(1.5, 2.5)       // T = float64\n\n// Explicit type when needed\nresult := Map[int, string]([]int{1, 2}, func(n int) string {\n    return fmt.Sprintf(\"%d\", n)\n})\n```\n\n## Generic Channels\n\n```go\n// Generic channel operations\nfunc Merge[T any](channels ...<-chan T) <-chan T {\n    out := make(chan T)\n    var wg sync.WaitGroup\n\n    for _, ch := range channels {\n        wg.Add(1)\n        go func(c <-chan T) {\n            defer wg.Done()\n            for v := range c {\n                out <- v\n            }\n        }(ch)\n    }\n\n    go func() {\n        wg.Wait()\n        close(out)\n    }()\n\n    return out\n}\n\n// Generic pipeline stage\nfunc Stage[T, U any](in <-chan T, fn func(T) U) <-chan U {\n    out := make(chan U)\n    go func() {\n        defer close(out)\n        for v := range in {\n            out <- fn(v)\n        }\n    }()\n    return out\n}\n\n// Usage\nch1 := make(chan int)\nch2 := make(chan int)\n\nmerged := Merge(ch1, ch2)\n\nnumbers := make(chan int)\ndoubled := Stage(numbers, func(n int) int { return n * 2 })\nstrings := Stage(doubled, func(n int) string { return fmt.Sprintf(\"%d\", n) })\n```\n\n## Union Constraints\n\n```go\n// Union of types\ntype StringOrInt interface {\n    string | int\n}\n\nfunc Process[T StringOrInt](val T) string {\n    return fmt.Sprintf(\"%v\", val)\n}\n\n// More complex unions\ntype Numeric interface {\n    int | int8 | int16 | int32 | int64 |\n    uint | uint8 | uint16 | uint32 | uint64 |\n    float32 | float64\n}\n\nfunc Abs[T Numeric](n T) T {\n    if n < 0 {\n        return -n\n    }\n    return n\n}\n\n// Union with methods\ntype Serializable interface {\n    string | []byte\n}\n\nfunc Serialize[T Serializable](data T) []byte {\n    switch v := any(data).(type) {\n    case string:\n        return []byte(v)\n    case []byte:\n        return v\n    default:\n        panic(\"unreachable\")\n    }\n}\n```\n\n## Quick Reference\n\n| Feature | Syntax | Use Case |\n|---------|--------|----------|\n| Basic generic | `func F[T any]()` | Any type |\n| Constraint | `func F[T Constraint]()` | Restricted types |\n| Multiple params | `func F[T, U any]()` | Multiple type variables |\n| Comparable | `func F[T comparable]()` | Types supporting == and != |\n| Ordered | `func F[T constraints.Ordered]()` | Types supporting <, >, <=, >= |\n| Union | `T interface{int \\| string}` | Either type |\n| Approximate | `~int` | Include type aliases |\n"
  },
  {
    "path": ".claude/skills/golang-pro/references/interfaces.md",
    "content": "# Interface Design and Composition\n\n## Small, Focused Interfaces\n\n```go\n// Single-method interfaces (idiomatic Go)\ntype Reader interface {\n    Read(p []byte) (n int, err error)\n}\n\ntype Writer interface {\n    Write(p []byte) (n int, err error)\n}\n\ntype Closer interface {\n    Close() error\n}\n\n// Interface composition\ntype ReadCloser interface {\n    Reader\n    Closer\n}\n\ntype WriteCloser interface {\n    Writer\n    Closer\n}\n\ntype ReadWriteCloser interface {\n    Reader\n    Writer\n    Closer\n}\n```\n\n## Accept Interfaces, Return Structs\n\n```go\npackage storage\n\nimport \"io\"\n\n// Storage is the concrete type (struct)\ntype Storage struct {\n    baseDir string\n}\n\n// NewStorage returns a concrete type\nfunc NewStorage(baseDir string) *Storage {\n    return &Storage{baseDir: baseDir}\n}\n\n// SaveFile accepts an interface for flexibility\nfunc (s *Storage) SaveFile(filename string, data io.Reader) error {\n    // Implementation can work with any Reader\n    // (file, network, buffer, etc.)\n    return nil\n}\n\n// Usage allows dependency injection\ntype Uploader interface {\n    SaveFile(filename string, data io.Reader) error\n}\n\ntype Service struct {\n    uploader Uploader // Accept interface\n}\n\n// NewService accepts interface for testing flexibility\nfunc NewService(uploader Uploader) *Service {\n    return &Service{uploader: uploader}\n}\n```\n\n## io.Reader and io.Writer Patterns\n\n```go\nimport (\n    \"io\"\n    \"strings\"\n)\n\n// Chain readers with io.MultiReader\nfunc combineReaders() io.Reader {\n    r1 := strings.NewReader(\"Hello \")\n    r2 := strings.NewReader(\"World\")\n    return io.MultiReader(r1, r2)\n}\n\n// Tee reader for duplicating reads\nfunc duplicateRead(r io.Reader, w io.Writer) io.Reader {\n    return io.TeeReader(r, w) // Writes to w while reading from r\n}\n\n// Limit reader to prevent reading too much\nfunc limitedRead(r io.Reader, n int64) io.Reader {\n    return io.LimitReader(r, n)\n}\n\n// Custom Reader implementation\ntype UppercaseReader struct {\n    src io.Reader\n}\n\nfunc (u *UppercaseReader) Read(p []byte) (n int, err error) {\n    n, err = u.src.Read(p)\n    for i := 0; i < n; i++ {\n        if p[i] >= 'a' && p[i] <= 'z' {\n            p[i] = p[i] - 32\n        }\n    }\n    return n, err\n}\n\n// Custom Writer implementation\ntype CountingWriter struct {\n    w     io.Writer\n    count int64\n}\n\nfunc (cw *CountingWriter) Write(p []byte) (n int, err error) {\n    n, err = cw.w.Write(p)\n    cw.count += int64(n)\n    return n, err\n}\n\nfunc (cw *CountingWriter) BytesWritten() int64 {\n    return cw.count\n}\n```\n\n## Embedding for Composition\n\n```go\nimport \"sync\"\n\n// Embed to extend behavior\ntype SafeCounter struct {\n    mu sync.Mutex\n    m  map[string]int\n}\n\nfunc (sc *SafeCounter) Inc(key string) {\n    sc.mu.Lock()\n    defer sc.mu.Unlock()\n    sc.m[key]++\n}\n\n// Embed interface to add default behavior\ntype Logger interface {\n    Log(msg string)\n}\n\ntype NoOpLogger struct{}\n\nfunc (NoOpLogger) Log(msg string) {}\n\ntype Service struct {\n    Logger // Embedded interface (default implementation can be provided)\n}\n\nfunc NewService(logger Logger) *Service {\n    if logger == nil {\n        logger = NoOpLogger{} // Provide default\n    }\n    return &Service{Logger: logger}\n}\n\n// Now Service.Log() is available\n```\n\n## Interface Satisfaction Verification\n\n```go\nimport \"io\"\n\n// Compile-time interface verification\nvar _ io.Reader = (*MyReader)(nil)\nvar _ io.Writer = (*MyWriter)(nil)\nvar _ io.Closer = (*MyCloser)(nil)\n\ntype MyReader struct{}\n\nfunc (m *MyReader) Read(p []byte) (n int, err error) {\n    return 0, nil\n}\n\ntype MyWriter struct{}\n\nfunc (m *MyWriter) Write(p []byte) (n int, err error) {\n    return len(p), nil\n}\n\ntype MyCloser struct{}\n\nfunc (m *MyCloser) Close() error {\n    return nil\n}\n```\n\n## Functional Options Pattern\n\n```go\npackage server\n\nimport \"time\"\n\ntype Server struct {\n    host         string\n    port         int\n    timeout      time.Duration\n    maxConns     int\n    enableLogger bool\n}\n\n// Option is a functional option for configuring Server\ntype Option func(*Server)\n\nfunc WithHost(host string) Option {\n    return func(s *Server) {\n        s.host = host\n    }\n}\n\nfunc WithPort(port int) Option {\n    return func(s *Server) {\n        s.port = port\n    }\n}\n\nfunc WithTimeout(timeout time.Duration) Option {\n    return func(s *Server) {\n        s.timeout = timeout\n    }\n}\n\nfunc WithMaxConnections(max int) Option {\n    return func(s *Server) {\n        s.maxConns = max\n    }\n}\n\nfunc WithLogger(enabled bool) Option {\n    return func(s *Server) {\n        s.enableLogger = enabled\n    }\n}\n\n// NewServer creates a server with functional options\nfunc NewServer(opts ...Option) *Server {\n    // Defaults\n    s := &Server{\n        host:     \"localhost\",\n        port:     8080,\n        timeout:  30 * time.Second,\n        maxConns: 100,\n    }\n\n    // Apply options\n    for _, opt := range opts {\n        opt(s)\n    }\n\n    return s\n}\n\n// Usage:\n// server := NewServer(\n//     WithHost(\"0.0.0.0\"),\n//     WithPort(9000),\n//     WithTimeout(60 * time.Second),\n//     WithLogger(true),\n// )\n```\n\n## Interface Segregation\n\n```go\n// Bad: Fat interface\ntype BadRepository interface {\n    Create(item Item) error\n    Read(id string) (Item, error)\n    Update(item Item) error\n    Delete(id string) error\n    List() ([]Item, error)\n    Search(query string) ([]Item, error)\n    Count() (int, error)\n}\n\n// Good: Segregated interfaces\ntype Creator interface {\n    Create(item Item) error\n}\n\ntype Reader interface {\n    Read(id string) (Item, error)\n}\n\ntype Updater interface {\n    Update(item Item) error\n}\n\ntype Deleter interface {\n    Delete(id string) error\n}\n\ntype Lister interface {\n    List() ([]Item, error)\n}\n\n// Compose only what you need\ntype ReadWriter interface {\n    Reader\n    Creator\n}\n\ntype FullRepository interface {\n    Creator\n    Reader\n    Updater\n    Deleter\n    Lister\n}\n```\n\n## Type Assertions and Type Switches\n\n```go\nimport \"fmt\"\n\n// Safe type assertion\nfunc processValue(v interface{}) {\n    // Two-value assertion (safe)\n    if str, ok := v.(string); ok {\n        fmt.Println(\"String:\", str)\n        return\n    }\n\n    // Type switch\n    switch val := v.(type) {\n    case int:\n        fmt.Println(\"Int:\", val)\n    case string:\n        fmt.Println(\"String:\", val)\n    case bool:\n        fmt.Println(\"Bool:\", val)\n    default:\n        fmt.Println(\"Unknown type\")\n    }\n}\n\n// Check for optional interface methods\ntype Flusher interface {\n    Flush() error\n}\n\nfunc writeAndFlush(w io.Writer, data []byte) error {\n    if _, err := w.Write(data); err != nil {\n        return err\n    }\n\n    // Check if Writer also implements Flusher\n    if flusher, ok := w.(Flusher); ok {\n        return flusher.Flush()\n    }\n\n    return nil\n}\n```\n\n## Dependency Injection via Interfaces\n\n```go\npackage app\n\nimport \"context\"\n\n// Define interfaces for dependencies\ntype UserRepository interface {\n    GetUser(ctx context.Context, id string) (*User, error)\n    SaveUser(ctx context.Context, user *User) error\n}\n\ntype EmailSender interface {\n    SendEmail(ctx context.Context, to, subject, body string) error\n}\n\n// Service depends on interfaces\ntype UserService struct {\n    repo   UserRepository\n    mailer EmailSender\n}\n\nfunc NewUserService(repo UserRepository, mailer EmailSender) *UserService {\n    return &UserService{\n        repo:   repo,\n        mailer: mailer,\n    }\n}\n\nfunc (s *UserService) RegisterUser(ctx context.Context, email string) error {\n    user := &User{Email: email}\n    if err := s.repo.SaveUser(ctx, user); err != nil {\n        return err\n    }\n    return s.mailer.SendEmail(ctx, email, \"Welcome\", \"Thanks for registering!\")\n}\n\n// Easy to mock in tests\ntype MockUserRepository struct{}\n\nfunc (m *MockUserRepository) GetUser(ctx context.Context, id string) (*User, error) {\n    return &User{ID: id}, nil\n}\n\nfunc (m *MockUserRepository) SaveUser(ctx context.Context, user *User) error {\n    return nil\n}\n```\n\n## Quick Reference\n\n| Pattern | Use Case | Key Principle |\n|---------|----------|---------------|\n| Small interfaces | Flexibility | Single-method interfaces |\n| Accept interfaces | Testability | Depend on abstractions |\n| Return structs | Clarity | Concrete return types |\n| io.Reader/Writer | I/O operations | Standard library integration |\n| Embedding | Composition | Extend behavior without inheritance |\n| Functional options | Configuration | Flexible constructors |\n| Type assertions | Runtime checks | Safe downcasting |\n"
  },
  {
    "path": ".claude/skills/golang-pro/references/project-structure.md",
    "content": "# Project Structure and Module Management\n\n## Standard Project Layout\n\n```\nmyproject/\n├── cmd/                    # Main applications\n│   ├── server/\n│   │   └── main.go        # Entry point for server\n│   └── cli/\n│       └── main.go        # Entry point for CLI tool\n├── internal/              # Private application code\n│   ├── api/              # API handlers\n│   ├── service/          # Business logic\n│   └── repository/       # Data access layer\n├── pkg/                   # Public library code\n│   └── models/           # Shared models\n├── api/                   # API definitions\n│   ├── openapi.yaml      # OpenAPI spec\n│   └── proto/            # Protocol buffers\n├── web/                   # Web assets\n│   ├── static/\n│   └── templates/\n├── scripts/               # Build and install scripts\n├── configs/              # Configuration files\n├── deployments/          # Docker, K8s configs\n├── test/                 # Additional test data\n├── docs/                 # Documentation\n├── go.mod               # Module definition\n├── go.sum               # Dependency checksums\n├── Makefile             # Build automation\n└── README.md\n```\n\n## go.mod Basics\n\n```go\n// Initialize module\n// go mod init github.com/user/project\n\nmodule github.com/user/myproject\n\ngo 1.21\n\nrequire (\n    github.com/gin-gonic/gin v1.9.1\n    github.com/lib/pq v1.10.9\n    go.uber.org/zap v1.26.0\n)\n\nrequire (\n    // Indirect dependencies (automatically managed)\n    github.com/bytedance/sonic v1.9.1 // indirect\n    github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect\n)\n\n// Replace directive for local development\nreplace github.com/user/mylib => ../mylib\n\n// Retract directive to mark bad versions\nretract v1.0.1 // Contains critical bug\n```\n\n## Module Commands\n\n```bash\n# Initialize module\ngo mod init github.com/user/project\n\n# Add missing dependencies\ngo mod tidy\n\n# Download dependencies\ngo mod download\n\n# Verify dependencies\ngo mod verify\n\n# Show module graph\ngo mod graph\n\n# Show why package is needed\ngo mod why github.com/user/package\n\n# Vendor dependencies (copy to vendor/)\ngo mod vendor\n\n# Update dependency\ngo get -u github.com/user/package\n\n# Update to specific version\ngo get github.com/user/package@v1.2.3\n\n# Update all dependencies\ngo get -u ./...\n\n# Remove unused dependencies\ngo mod tidy\n```\n\n## Internal Packages\n\n```go\n// internal/ packages can only be imported by code in the parent tree\n\nmyproject/\n├── internal/\n│   ├── auth/           # Can only be imported by myproject\n│   │   └── jwt.go\n│   └── database/\n│       └── postgres.go\n└── pkg/\n    └── models/         # Can be imported by anyone\n        └── user.go\n\n// This works (same project):\nimport \"github.com/user/myproject/internal/auth\"\n\n// This fails (different project):\nimport \"github.com/other/project/internal/auth\" // Error!\n\n// Internal subdirectories\nmyproject/\n└── api/\n    └── internal/       # Can only be imported by code in api/\n        └── helpers.go\n```\n\n## Package Organization\n\n```go\n// user/user.go - Domain package\npackage user\n\nimport (\n    \"context\"\n    \"time\"\n)\n\n// User represents a user entity\ntype User struct {\n    ID        string\n    Email     string\n    CreatedAt time.Time\n}\n\n// Repository defines data access interface\ntype Repository interface {\n    Create(ctx context.Context, user *User) error\n    GetByID(ctx context.Context, id string) (*User, error)\n    Update(ctx context.Context, user *User) error\n    Delete(ctx context.Context, id string) error\n}\n\n// Service handles business logic\ntype Service struct {\n    repo Repository\n}\n\n// NewService creates a new user service\nfunc NewService(repo Repository) *Service {\n    return &Service{repo: repo}\n}\n\nfunc (s *Service) RegisterUser(ctx context.Context, email string) (*User, error) {\n    user := &User{\n        ID:        generateID(),\n        Email:     email,\n        CreatedAt: time.Now(),\n    }\n    return user, s.repo.Create(ctx, user)\n}\n```\n\n## Multi-Module Repository (Monorepo)\n\n```\nmonorepo/\n├── go.work              # Workspace file\n├── services/\n│   ├── api/\n│   │   ├── go.mod\n│   │   └── main.go\n│   └── worker/\n│       ├── go.mod\n│       └── main.go\n└── shared/\n    └── models/\n        ├── go.mod\n        └── user.go\n\n// go.work\ngo 1.21\n\nuse (\n    ./services/api\n    ./services/worker\n    ./shared/models\n)\n\n// Commands:\n// go work init ./services/api ./services/worker\n// go work use ./shared/models\n// go work sync\n```\n\n## Build Tags and Constraints\n\n```go\n// +build integration\n// integration_test.go\n\npackage myapp\n\nimport \"testing\"\n\nfunc TestIntegration(t *testing.T) {\n    // Integration test code\n}\n\n// Build: go test -tags=integration\n\n// File-level build constraints (Go 1.17+)\n//go:build linux && amd64\n\npackage myapp\n\n// Multiple constraints\n//go:build linux || darwin\n//go:build amd64\n\n// Negation\n//go:build !windows\n\n// Common tags:\n// linux, darwin, windows, freebsd\n// amd64, arm64, 386, arm\n// cgo, !cgo\n```\n\n## Makefile Example\n\n```makefile\n# Makefile\n.PHONY: build test lint clean run\n\n# Variables\nBINARY_NAME=myapp\nBUILD_DIR=bin\nGO=go\nGOFLAGS=-v\n\n# Build the application\nbuild:\n\t$(GO) build $(GOFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME) ./cmd/server\n\n# Run tests\ntest:\n\t$(GO) test -v -race -coverprofile=coverage.out ./...\n\n# Run tests with coverage report\ntest-coverage: test\n\t$(GO) tool cover -html=coverage.out\n\n# Run linters\nlint:\n\tgolangci-lint run ./...\n\n# Format code\nfmt:\n\t$(GO) fmt ./...\n\tgoimports -w .\n\n# Run the application\nrun:\n\t$(GO) run ./cmd/server\n\n# Clean build artifacts\nclean:\n\trm -rf $(BUILD_DIR)\n\trm -f coverage.out\n\n# Install dependencies\ndeps:\n\t$(GO) mod download\n\t$(GO) mod tidy\n\n# Build for multiple platforms\nbuild-all:\n\tGOOS=linux GOARCH=amd64 $(GO) build -o $(BUILD_DIR)/$(BINARY_NAME)-linux-amd64 ./cmd/server\n\tGOOS=darwin GOARCH=amd64 $(GO) build -o $(BUILD_DIR)/$(BINARY_NAME)-darwin-amd64 ./cmd/server\n\tGOOS=windows GOARCH=amd64 $(GO) build -o $(BUILD_DIR)/$(BINARY_NAME)-windows-amd64.exe ./cmd/server\n\n# Run with race detector\nrun-race:\n\t$(GO) run -race ./cmd/server\n\n# Generate code\ngenerate:\n\t$(GO) generate ./...\n\n# Docker build\ndocker-build:\n\tdocker build -t $(BINARY_NAME):latest .\n\n# Help\nhelp:\n\t@echo \"Available targets:\"\n\t@echo \"  build         - Build the application\"\n\t@echo \"  test          - Run tests\"\n\t@echo \"  test-coverage - Run tests with coverage report\"\n\t@echo \"  lint          - Run linters\"\n\t@echo \"  fmt           - Format code\"\n\t@echo \"  run           - Run the application\"\n\t@echo \"  clean         - Clean build artifacts\"\n\t@echo \"  deps          - Install dependencies\"\n```\n\n## Dockerfile Multi-Stage Build\n\n```dockerfile\n# Build stage\nFROM golang:1.21-alpine AS builder\n\nWORKDIR /app\n\n# Copy go mod files\nCOPY go.mod go.sum ./\nRUN go mod download\n\n# Copy source code\nCOPY . .\n\n# Build binary\nRUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o server ./cmd/server\n\n# Final stage\nFROM alpine:latest\n\nRUN apk --no-cache add ca-certificates\n\nWORKDIR /root/\n\n# Copy binary from builder\nCOPY --from=builder /app/server .\n\n# Copy config files if needed\nCOPY --from=builder /app/configs ./configs\n\nEXPOSE 8080\n\nCMD [\"./server\"]\n```\n\n## Version Information\n\n```go\n// version/version.go\npackage version\n\nimport \"runtime\"\n\nvar (\n    // Set via ldflags during build\n    Version   = \"dev\"\n    GitCommit = \"none\"\n    BuildTime = \"unknown\"\n)\n\n// Info returns version information\nfunc Info() map[string]string {\n    return map[string]string{\n        \"version\":    Version,\n        \"git_commit\": GitCommit,\n        \"build_time\": BuildTime,\n        \"go_version\": runtime.Version(),\n        \"os\":         runtime.GOOS,\n        \"arch\":       runtime.GOARCH,\n    }\n}\n\n// Build with version info:\n// go build -ldflags \"-X github.com/user/project/version.Version=1.0.0 \\\n//   -X github.com/user/project/version.GitCommit=$(git rev-parse HEAD) \\\n//   -X github.com/user/project/version.BuildTime=$(date -u +%Y-%m-%dT%H:%M:%SZ)\"\n```\n\n## Go Generate\n\n```go\n// models/user.go\n//go:generate mockgen -source=user.go -destination=../mocks/user_mock.go -package=mocks\n\npackage models\n\ntype UserRepository interface {\n    GetUser(id string) (*User, error)\n    SaveUser(user *User) error\n}\n\n// tools.go - Track tool dependencies\n//go:build tools\n\npackage tools\n\nimport (\n    _ \"github.com/golang/mock/mockgen\"\n    _ \"golang.org/x/tools/cmd/stringer\"\n)\n\n// Install tools:\n// go install github.com/golang/mock/mockgen@latest\n\n// Run generate:\n// go generate ./...\n```\n\n## Configuration Management\n\n```go\n// config/config.go\npackage config\n\nimport (\n    \"os\"\n    \"time\"\n\n    \"github.com/kelseyhightower/envconfig\"\n)\n\ntype Config struct {\n    Server   ServerConfig\n    Database DatabaseConfig\n    Redis    RedisConfig\n}\n\ntype ServerConfig struct {\n    Host         string        `envconfig:\"SERVER_HOST\" default:\"0.0.0.0\"`\n    Port         int           `envconfig:\"SERVER_PORT\" default:\"8080\"`\n    ReadTimeout  time.Duration `envconfig:\"SERVER_READ_TIMEOUT\" default:\"10s\"`\n    WriteTimeout time.Duration `envconfig:\"SERVER_WRITE_TIMEOUT\" default:\"10s\"`\n}\n\ntype DatabaseConfig struct {\n    URL          string `envconfig:\"DATABASE_URL\" required:\"true\"`\n    MaxOpenConns int    `envconfig:\"DB_MAX_OPEN_CONNS\" default:\"25\"`\n    MaxIdleConns int    `envconfig:\"DB_MAX_IDLE_CONNS\" default:\"5\"`\n}\n\ntype RedisConfig struct {\n    Addr     string `envconfig:\"REDIS_ADDR\" default:\"localhost:6379\"`\n    Password string `envconfig:\"REDIS_PASSWORD\"`\n    DB       int    `envconfig:\"REDIS_DB\" default:\"0\"`\n}\n\n// Load loads configuration from environment\nfunc Load() (*Config, error) {\n    var cfg Config\n    if err := envconfig.Process(\"\", &cfg); err != nil {\n        return nil, err\n    }\n    return &cfg, nil\n}\n```\n\n## Quick Reference\n\n| Command | Description |\n|---------|-------------|\n| `go mod init` | Initialize module |\n| `go mod tidy` | Add/remove dependencies |\n| `go mod download` | Download dependencies |\n| `go get package@version` | Add/update dependency |\n| `go build -ldflags \"-X ...\"` | Set version info |\n| `go generate ./...` | Run code generation |\n| `GOOS=linux go build` | Cross-compile |\n| `go work init` | Initialize workspace |\n"
  },
  {
    "path": ".claude/skills/golang-pro/references/testing.md",
    "content": "# Testing and Benchmarking\n\n## Table-Driven Tests\n\n```go\npackage math\n\nimport \"testing\"\n\nfunc Add(a, b int) int {\n    return a + b\n}\n\nfunc TestAdd(t *testing.T) {\n    tests := []struct {\n        name     string\n        a, b     int\n        expected int\n    }{\n        {\"positive numbers\", 2, 3, 5},\n        {\"negative numbers\", -2, -3, -5},\n        {\"mixed signs\", -2, 3, 1},\n        {\"zeros\", 0, 0, 0},\n        {\"large numbers\", 1000000, 2000000, 3000000},\n    }\n\n    for _, tt := range tests {\n        t.Run(tt.name, func(t *testing.T) {\n            result := Add(tt.a, tt.b)\n            if result != tt.expected {\n                t.Errorf(\"Add(%d, %d) = %d; want %d\", tt.a, tt.b, result, tt.expected)\n            }\n        })\n    }\n}\n```\n\n## Subtests and Parallel Execution\n\n```go\nfunc TestParallel(t *testing.T) {\n    tests := []struct {\n        name  string\n        input string\n        want  string\n    }{\n        {\"lowercase\", \"hello\", \"HELLO\"},\n        {\"uppercase\", \"WORLD\", \"WORLD\"},\n        {\"mixed\", \"HeLLo\", \"HELLO\"},\n    }\n\n    for _, tt := range tests {\n        tt := tt // Capture range variable for parallel tests\n        t.Run(tt.name, func(t *testing.T) {\n            t.Parallel() // Run subtests in parallel\n\n            result := strings.ToUpper(tt.input)\n            if result != tt.want {\n                t.Errorf(\"got %q, want %q\", result, tt.want)\n            }\n        })\n    }\n}\n```\n\n## Test Helpers and Setup/Teardown\n\n```go\nfunc TestWithSetup(t *testing.T) {\n    // Setup\n    db := setupTestDB(t)\n    defer cleanupTestDB(t, db)\n\n    tests := []struct {\n        name string\n        user User\n    }{\n        {\"valid user\", User{Name: \"John\", Email: \"john@example.com\"}},\n        {\"empty name\", User{Name: \"\", Email: \"test@example.com\"}},\n    }\n\n    for _, tt := range tests {\n        t.Run(tt.name, func(t *testing.T) {\n            err := db.SaveUser(tt.user)\n            if err != nil {\n                t.Fatalf(\"SaveUser failed: %v\", err)\n            }\n        })\n    }\n}\n\n// Helper function (doesn't show in stack trace)\nfunc setupTestDB(t *testing.T) *DB {\n    t.Helper()\n\n    db, err := NewDB(\":memory:\")\n    if err != nil {\n        t.Fatalf(\"failed to create test DB: %v\", err)\n    }\n    return db\n}\n\nfunc cleanupTestDB(t *testing.T, db *DB) {\n    t.Helper()\n\n    if err := db.Close(); err != nil {\n        t.Errorf(\"failed to close DB: %v\", err)\n    }\n}\n```\n\n## Mocking with Interfaces\n\n```go\n// Interface to mock\ntype EmailSender interface {\n    Send(to, subject, body string) error\n}\n\n// Mock implementation\ntype MockEmailSender struct {\n    SentEmails []Email\n    ShouldFail bool\n}\n\ntype Email struct {\n    To, Subject, Body string\n}\n\nfunc (m *MockEmailSender) Send(to, subject, body string) error {\n    if m.ShouldFail {\n        return fmt.Errorf(\"failed to send email\")\n    }\n    m.SentEmails = append(m.SentEmails, Email{to, subject, body})\n    return nil\n}\n\n// Test using mock\nfunc TestUserService_Register(t *testing.T) {\n    mockSender := &MockEmailSender{}\n    service := NewUserService(mockSender)\n\n    err := service.Register(\"user@example.com\")\n    if err != nil {\n        t.Fatalf(\"Register failed: %v\", err)\n    }\n\n    if len(mockSender.SentEmails) != 1 {\n        t.Errorf(\"expected 1 email sent, got %d\", len(mockSender.SentEmails))\n    }\n\n    email := mockSender.SentEmails[0]\n    if email.To != \"user@example.com\" {\n        t.Errorf(\"expected email to user@example.com, got %s\", email.To)\n    }\n}\n```\n\n## Benchmarking\n\n```go\nfunc BenchmarkAdd(b *testing.B) {\n    for i := 0; i < b.N; i++ {\n        Add(100, 200)\n    }\n}\n\n// Benchmark with subtests\nfunc BenchmarkStringOperations(b *testing.B) {\n    benchmarks := []struct {\n        name  string\n        input string\n    }{\n        {\"short\", \"hello\"},\n        {\"medium\", strings.Repeat(\"hello\", 10)},\n        {\"long\", strings.Repeat(\"hello\", 100)},\n    }\n\n    for _, bm := range benchmarks {\n        b.Run(bm.name, func(b *testing.B) {\n            for i := 0; i < b.N; i++ {\n                _ = strings.ToUpper(bm.input)\n            }\n        })\n    }\n}\n\n// Benchmark with setup\nfunc BenchmarkMapOperations(b *testing.B) {\n    m := make(map[string]int)\n    for i := 0; i < 1000; i++ {\n        m[fmt.Sprintf(\"key%d\", i)] = i\n    }\n\n    b.ResetTimer() // Don't count setup time\n\n    for i := 0; i < b.N; i++ {\n        _ = m[\"key500\"]\n    }\n}\n\n// Parallel benchmark\nfunc BenchmarkConcurrentAccess(b *testing.B) {\n    var counter int64\n\n    b.RunParallel(func(pb *testing.PB) {\n        for pb.Next() {\n            atomic.AddInt64(&counter, 1)\n        }\n    })\n}\n\n// Memory allocation benchmark\nfunc BenchmarkAllocation(b *testing.B) {\n    b.ReportAllocs() // Report allocations\n\n    for i := 0; i < b.N; i++ {\n        s := make([]int, 1000)\n        _ = s\n    }\n}\n```\n\n## Fuzzing (Go 1.18+)\n\n```go\nfunc FuzzReverse(f *testing.F) {\n    // Seed corpus\n    testcases := []string{\"hello\", \"world\", \"123\", \"\"}\n    for _, tc := range testcases {\n        f.Add(tc)\n    }\n\n    f.Fuzz(func(t *testing.T, input string) {\n        reversed := Reverse(input)\n        doubleReversed := Reverse(reversed)\n\n        if input != doubleReversed {\n            t.Errorf(\"Reverse(Reverse(%q)) = %q, want %q\", input, doubleReversed, input)\n        }\n    })\n}\n\n// Fuzz with multiple parameters\nfunc FuzzAdd(f *testing.F) {\n    f.Add(1, 2)\n    f.Add(0, 0)\n    f.Add(-1, 1)\n\n    f.Fuzz(func(t *testing.T, a, b int) {\n        result := Add(a, b)\n\n        // Properties that should always hold\n        if result < a && b >= 0 {\n            t.Errorf(\"Add(%d, %d) = %d; result should be >= a when b >= 0\", a, b, result)\n        }\n    })\n}\n```\n\n## Test Coverage\n\n```go\n// Run tests with coverage:\n// go test -cover\n// go test -coverprofile=coverage.out\n// go tool cover -html=coverage.out\n\nfunc TestCalculate(t *testing.T) {\n    tests := []struct {\n        name     string\n        input    int\n        expected int\n    }{\n        {\"zero\", 0, 0},\n        {\"positive\", 5, 25},\n        {\"negative\", -3, 9},\n    }\n\n    for _, tt := range tests {\n        t.Run(tt.name, func(t *testing.T) {\n            result := Calculate(tt.input)\n            if result != tt.expected {\n                t.Errorf(\"Calculate(%d) = %d; want %d\", tt.input, result, tt.expected)\n            }\n        })\n    }\n}\n```\n\n## Race Detector\n\n```go\n// Run with: go test -race\n\nfunc TestConcurrentAccess(t *testing.T) {\n    var counter int\n    var wg sync.WaitGroup\n\n    // This will fail with -race if not synchronized\n    for i := 0; i < 10; i++ {\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            counter++ // Data race!\n        }()\n    }\n\n    wg.Wait()\n}\n\n// Fixed version with mutex\nfunc TestConcurrentAccessSafe(t *testing.T) {\n    var counter int\n    var mu sync.Mutex\n    var wg sync.WaitGroup\n\n    for i := 0; i < 10; i++ {\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            mu.Lock()\n            counter++\n            mu.Unlock()\n        }()\n    }\n\n    wg.Wait()\n\n    if counter != 10 {\n        t.Errorf(\"expected 10, got %d\", counter)\n    }\n}\n```\n\n## Golden Files\n\n```go\nimport (\n    \"os\"\n    \"path/filepath\"\n    \"testing\"\n)\n\nfunc TestRenderHTML(t *testing.T) {\n    data := Data{Title: \"Test\", Content: \"Hello\"}\n    result := RenderHTML(data)\n\n    goldenFile := filepath.Join(\"testdata\", \"expected.html\")\n\n    if *update {\n        // Update golden file: go test -update\n        os.WriteFile(goldenFile, []byte(result), 0644)\n    }\n\n    expected, err := os.ReadFile(goldenFile)\n    if err != nil {\n        t.Fatalf(\"failed to read golden file: %v\", err)\n    }\n\n    if result != string(expected) {\n        t.Errorf(\"output doesn't match golden file\\ngot:\\n%s\\nwant:\\n%s\", result, expected)\n    }\n}\n\nvar update = flag.Bool(\"update\", false, \"update golden files\")\n```\n\n## Integration Tests\n\n```go\n// integration_test.go\n// +build integration\n\npackage myapp\n\nimport (\n    \"testing\"\n    \"time\"\n)\n\nfunc TestIntegration(t *testing.T) {\n    if testing.Short() {\n        t.Skip(\"skipping integration test in short mode\")\n    }\n\n    // Long-running integration test\n    server := startTestServer(t)\n    defer server.Stop()\n\n    time.Sleep(100 * time.Millisecond) // Wait for server\n\n    client := NewClient(server.URL)\n    resp, err := client.Get(\"/health\")\n    if err != nil {\n        t.Fatalf(\"health check failed: %v\", err)\n    }\n\n    if resp.Status != \"ok\" {\n        t.Errorf(\"expected status ok, got %s\", resp.Status)\n    }\n}\n\n// Run: go test -tags=integration\n// Run short tests only: go test -short\n```\n\n## Testable Examples\n\n```go\n// Example tests that appear in godoc\nfunc ExampleAdd() {\n    result := Add(2, 3)\n    fmt.Println(result)\n    // Output: 5\n}\n\nfunc ExampleAdd_negative() {\n    result := Add(-2, -3)\n    fmt.Println(result)\n    // Output: -5\n}\n\n// Unordered output\nfunc ExampleKeys() {\n    m := map[string]int{\"a\": 1, \"b\": 2, \"c\": 3}\n    keys := Keys(m)\n    for _, k := range keys {\n        fmt.Println(k)\n    }\n    // Unordered output:\n    // a\n    // b\n    // c\n}\n```\n\n## Quick Reference\n\n| Command | Description |\n|---------|-------------|\n| `go test` | Run tests |\n| `go test -v` | Verbose output |\n| `go test -run TestName` | Run specific test |\n| `go test -bench .` | Run benchmarks |\n| `go test -cover` | Show coverage |\n| `go test -race` | Run race detector |\n| `go test -short` | Skip long tests |\n| `go test -fuzz FuzzName` | Run fuzzing |\n| `go test -cpuprofile cpu.prof` | CPU profiling |\n| `go test -memprofile mem.prof` | Memory profiling |\n"
  },
  {
    "path": ".claude/skills/skill-creator/LICENSE.txt",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License."
  },
  {
    "path": ".claude/skills/skill-creator/SKILL.md",
    "content": "---\nname: skill-creator\ndescription: Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, update or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.\n---\n\n# Skill Creator\n\nA skill for creating new skills and iteratively improving them.\n\nAt a high level, the process of creating a skill goes like this:\n\n- Decide what you want the skill to do and roughly how it should do it\n- Write a draft of the skill\n- Create a few test prompts and run claude-with-access-to-the-skill on them\n- Help the user evaluate the results both qualitatively and quantitatively\n  - While the runs happen in the background, draft some quantitative evals if there aren't any (if there are some, you can either use as is or modify if you feel something needs to change about them). Then explain them to the user (or if they already existed, explain the ones that already exist)\n  - Use the `eval-viewer/generate_review.py` script to show the user the results for them to look at, and also let them look at the quantitative metrics\n- Rewrite the skill based on feedback from the user's evaluation of the results (and also if there are any glaring flaws that become apparent from the quantitative benchmarks)\n- Repeat until you're satisfied\n- Expand the test set and try again at larger scale\n\nYour job when using this skill is to figure out where the user is in this process and then jump in and help them progress through these stages. So for instance, maybe they're like \"I want to make a skill for X\". You can help narrow down what they mean, write a draft, write the test cases, figure out how they want to evaluate, run all the prompts, and repeat.\n\nOn the other hand, maybe they already have a draft of the skill. In this case you can go straight to the eval/iterate part of the loop.\n\nOf course, you should always be flexible and if the user is like \"I don't need to run a bunch of evaluations, just vibe with me\", you can do that instead.\n\nThen after the skill is done (but again, the order is flexible), you can also run the skill description improver, which we have a whole separate script for, to optimize the triggering of the skill.\n\nCool? Cool.\n\n## Communicating with the user\n\nThe skill creator is liable to be used by people across a wide range of familiarity with coding jargon. If you haven't heard (and how could you, it's only very recently that it started), there's a trend now where the power of Claude is inspiring plumbers to open up their terminals, parents and grandparents to google \"how to install npm\". On the other hand, the bulk of users are probably fairly computer-literate.\n\nSo please pay attention to context cues to understand how to phrase your communication! In the default case, just to give you some idea:\n\n- \"evaluation\" and \"benchmark\" are borderline, but OK\n- for \"JSON\" and \"assertion\" you want to see serious cues from the user that they know what those things are before using them without explaining them\n\nIt's OK to briefly explain terms if you're in doubt, and feel free to clarify terms with a short definition if you're unsure if the user will get it.\n\n---\n\n## Creating a skill\n\n### Capture Intent\n\nStart by understanding the user's intent. The current conversation might already contain a workflow the user wants to capture (e.g., they say \"turn this into a skill\"). If so, extract answers from the conversation history first — the tools used, the sequence of steps, corrections the user made, input/output formats observed. The user may need to fill the gaps, and should confirm before proceeding to the next step.\n\n1. What should this skill enable Claude to do?\n2. When should this skill trigger? (what user phrases/contexts)\n3. What's the expected output format?\n4. Should we set up test cases to verify the skill works? Skills with objectively verifiable outputs (file transforms, data extraction, code generation, fixed workflow steps) benefit from test cases. Skills with subjective outputs (writing style, art) often don't need them. Suggest the appropriate default based on the skill type, but let the user decide.\n\n### Interview and Research\n\nProactively ask questions about edge cases, input/output formats, example files, success criteria, and dependencies. Wait to write test prompts until you've got this part ironed out.\n\nCheck available MCPs - if useful for research (searching docs, finding similar skills, looking up best practices), research in parallel via subagents if available, otherwise inline. Come prepared with context to reduce burden on the user.\n\n### Write the SKILL.md\n\nBased on the user interview, fill in these components:\n\n- **name**: Skill identifier\n- **description**: When to trigger, what it does. This is the primary triggering mechanism - include both what the skill does AND specific contexts for when to use it. All \"when to use\" info goes here, not in the body. Note: currently Claude has a tendency to \"undertrigger\" skills -- to not use them when they'd be useful. To combat this, please make the skill descriptions a little bit \"pushy\". So for instance, instead of \"How to build a simple fast dashboard to display internal Anthropic data.\", you might write \"How to build a simple fast dashboard to display internal Anthropic data. Make sure to use this skill whenever the user mentions dashboards, data visualization, internal metrics, or wants to display any kind of company data, even if they don't explicitly ask for a 'dashboard.'\"\n- **compatibility**: Required tools, dependencies (optional, rarely needed)\n- **the rest of the skill :)**\n\n### Skill Writing Guide\n\n#### Anatomy of a Skill\n\n```\nskill-name/\n├── SKILL.md (required)\n│   ├── YAML frontmatter (name, description required)\n│   └── Markdown instructions\n└── Bundled Resources (optional)\n    ├── scripts/    - Executable code for deterministic/repetitive tasks\n    ├── references/ - Docs loaded into context as needed\n    └── assets/     - Files used in output (templates, icons, fonts)\n```\n\n#### Progressive Disclosure\n\nSkills use a three-level loading system:\n1. **Metadata** (name + description) - Always in context (~100 words)\n2. **SKILL.md body** - In context whenever skill triggers (<500 lines ideal)\n3. **Bundled resources** - As needed (unlimited, scripts can execute without loading)\n\nThese word counts are approximate and you can feel free to go longer if needed.\n\n**Key patterns:**\n- Keep SKILL.md under 500 lines; if you're approaching this limit, add an additional layer of hierarchy along with clear pointers about where the model using the skill should go next to follow up.\n- Reference files clearly from SKILL.md with guidance on when to read them\n- For large reference files (>300 lines), include a table of contents\n\n**Domain organization**: When a skill supports multiple domains/frameworks, organize by variant:\n```\ncloud-deploy/\n├── SKILL.md (workflow + selection)\n└── references/\n    ├── aws.md\n    ├── gcp.md\n    └── azure.md\n```\nClaude reads only the relevant reference file.\n\n#### Principle of Lack of Surprise\n\nThis goes without saying, but skills must not contain malware, exploit code, or any content that could compromise system security. A skill's contents should not surprise the user in their intent if described. Don't go along with requests to create misleading skills or skills designed to facilitate unauthorized access, data exfiltration, or other malicious activities. Things like a \"roleplay as an XYZ\" are OK though.\n\n#### Writing Patterns\n\nPrefer using the imperative form in instructions.\n\n**Defining output formats** - You can do it like this:\n```markdown\n## Report structure\nALWAYS use this exact template:\n# [Title]\n## Executive summary\n## Key findings\n## Recommendations\n```\n\n**Examples pattern** - It's useful to include examples. You can format them like this (but if \"Input\" and \"Output\" are in the examples you might want to deviate a little):\n```markdown\n## Commit message format\n**Example 1:**\nInput: Added user authentication with JWT tokens\nOutput: feat(auth): implement JWT-based authentication\n```\n\n### Writing Style\n\nTry to explain to the model why things are important in lieu of heavy-handed musty MUSTs. Use theory of mind and try to make the skill general and not super-narrow to specific examples. Start by writing a draft and then look at it with fresh eyes and improve it.\n\n### Test Cases\n\nAfter writing the skill draft, come up with 2-3 realistic test prompts — the kind of thing a real user would actually say. Share them with the user: [you don't have to use this exact language] \"Here are a few test cases I'd like to try. Do these look right, or do you want to add more?\" Then run them.\n\nSave test cases to `evals/evals.json`. Don't write assertions yet — just the prompts. You'll draft assertions in the next step while the runs are in progress.\n\n```json\n{\n  \"skill_name\": \"example-skill\",\n  \"evals\": [\n    {\n      \"id\": 1,\n      \"prompt\": \"User's task prompt\",\n      \"expected_output\": \"Description of expected result\",\n      \"files\": []\n    }\n  ]\n}\n```\n\nSee `references/schemas.md` for the full schema (including the `assertions` field, which you'll add later).\n\n## Running and evaluating test cases\n\nThis section is one continuous sequence — don't stop partway through. Do NOT use `/skill-test` or any other testing skill.\n\nPut results in `<skill-name>-workspace/` as a sibling to the skill directory. Within the workspace, organize results by iteration (`iteration-1/`, `iteration-2/`, etc.) and within that, each test case gets a directory (`eval-0/`, `eval-1/`, etc.). Don't create all of this upfront — just create directories as you go.\n\n### Step 1: Spawn all runs (with-skill AND baseline) in the same turn\n\nFor each test case, spawn two subagents in the same turn — one with the skill, one without. This is important: don't spawn the with-skill runs first and then come back for baselines later. Launch everything at once so it all finishes around the same time.\n\n**With-skill run:**\n\n```\nExecute this task:\n- Skill path: <path-to-skill>\n- Task: <eval prompt>\n- Input files: <eval files if any, or \"none\">\n- Save outputs to: <workspace>/iteration-<N>/eval-<ID>/with_skill/outputs/\n- Outputs to save: <what the user cares about — e.g., \"the .docx file\", \"the final CSV\">\n```\n\n**Baseline run** (same prompt, but the baseline depends on context):\n- **Creating a new skill**: no skill at all. Same prompt, no skill path, save to `without_skill/outputs/`.\n- **Improving an existing skill**: the old version. Before editing, snapshot the skill (`cp -r <skill-path> <workspace>/skill-snapshot/`), then point the baseline subagent at the snapshot. Save to `old_skill/outputs/`.\n\nWrite an `eval_metadata.json` for each test case (assertions can be empty for now). Give each eval a descriptive name based on what it's testing — not just \"eval-0\". Use this name for the directory too. If this iteration uses new or modified eval prompts, create these files for each new eval directory — don't assume they carry over from previous iterations.\n\n```json\n{\n  \"eval_id\": 0,\n  \"eval_name\": \"descriptive-name-here\",\n  \"prompt\": \"The user's task prompt\",\n  \"assertions\": []\n}\n```\n\n### Step 2: While runs are in progress, draft assertions\n\nDon't just wait for the runs to finish — you can use this time productively. Draft quantitative assertions for each test case and explain them to the user. If assertions already exist in `evals/evals.json`, review them and explain what they check.\n\nGood assertions are objectively verifiable and have descriptive names — they should read clearly in the benchmark viewer so someone glancing at the results immediately understands what each one checks. Subjective skills (writing style, design quality) are better evaluated qualitatively — don't force assertions onto things that need human judgment.\n\nUpdate the `eval_metadata.json` files and `evals/evals.json` with the assertions once drafted. Also explain to the user what they'll see in the viewer — both the qualitative outputs and the quantitative benchmark.\n\n### Step 3: As runs complete, capture timing data\n\nWhen each subagent task completes, you receive a notification containing `total_tokens` and `duration_ms`. Save this data immediately to `timing.json` in the run directory:\n\n```json\n{\n  \"total_tokens\": 84852,\n  \"duration_ms\": 23332,\n  \"total_duration_seconds\": 23.3\n}\n```\n\nThis is the only opportunity to capture this data — it comes through the task notification and isn't persisted elsewhere. Process each notification as it arrives rather than trying to batch them.\n\n### Step 4: Grade, aggregate, and launch the viewer\n\nOnce all runs are done:\n\n1. **Grade each run** — spawn a grader subagent (or grade inline) that reads `agents/grader.md` and evaluates each assertion against the outputs. Save results to `grading.json` in each run directory. The grading.json expectations array must use the fields `text`, `passed`, and `evidence` (not `name`/`met`/`details` or other variants) — the viewer depends on these exact field names. For assertions that can be checked programmatically, write and run a script rather than eyeballing it — scripts are faster, more reliable, and can be reused across iterations.\n\n2. **Aggregate into benchmark** — run the aggregation script from the skill-creator directory:\n   ```bash\n   python -m scripts.aggregate_benchmark <workspace>/iteration-N --skill-name <name>\n   ```\n   This produces `benchmark.json` and `benchmark.md` with pass_rate, time, and tokens for each configuration, with mean ± stddev and the delta. If generating benchmark.json manually, see `references/schemas.md` for the exact schema the viewer expects.\nPut each with_skill version before its baseline counterpart.\n\n3. **Do an analyst pass** — read the benchmark data and surface patterns the aggregate stats might hide. See `agents/analyzer.md` (the \"Analyzing Benchmark Results\" section) for what to look for — things like assertions that always pass regardless of skill (non-discriminating), high-variance evals (possibly flaky), and time/token tradeoffs.\n\n4. **Launch the viewer** with both qualitative outputs and quantitative data:\n   ```bash\n   nohup python <skill-creator-path>/eval-viewer/generate_review.py \\\n     <workspace>/iteration-N \\\n     --skill-name \"my-skill\" \\\n     --benchmark <workspace>/iteration-N/benchmark.json \\\n     > /dev/null 2>&1 &\n   VIEWER_PID=$!\n   ```\n   For iteration 2+, also pass `--previous-workspace <workspace>/iteration-<N-1>`.\n\n   **Cowork / headless environments:** If `webbrowser.open()` is not available or the environment has no display, use `--static <output_path>` to write a standalone HTML file instead of starting a server. Feedback will be downloaded as a `feedback.json` file when the user clicks \"Submit All Reviews\". After download, copy `feedback.json` into the workspace directory for the next iteration to pick up.\n\nNote: please use generate_review.py to create the viewer; there's no need to write custom HTML.\n\n5. **Tell the user** something like: \"I've opened the results in your browser. There are two tabs — 'Outputs' lets you click through each test case and leave feedback, 'Benchmark' shows the quantitative comparison. When you're done, come back here and let me know.\"\n\n### What the user sees in the viewer\n\nThe \"Outputs\" tab shows one test case at a time:\n- **Prompt**: the task that was given\n- **Output**: the files the skill produced, rendered inline where possible\n- **Previous Output** (iteration 2+): collapsed section showing last iteration's output\n- **Formal Grades** (if grading was run): collapsed section showing assertion pass/fail\n- **Feedback**: a textbox that auto-saves as they type\n- **Previous Feedback** (iteration 2+): their comments from last time, shown below the textbox\n\nThe \"Benchmark\" tab shows the stats summary: pass rates, timing, and token usage for each configuration, with per-eval breakdowns and analyst observations.\n\nNavigation is via prev/next buttons or arrow keys. When done, they click \"Submit All Reviews\" which saves all feedback to `feedback.json`.\n\n### Step 5: Read the feedback\n\nWhen the user tells you they're done, read `feedback.json`:\n\n```json\n{\n  \"reviews\": [\n    {\"run_id\": \"eval-0-with_skill\", \"feedback\": \"the chart is missing axis labels\", \"timestamp\": \"...\"},\n    {\"run_id\": \"eval-1-with_skill\", \"feedback\": \"\", \"timestamp\": \"...\"},\n    {\"run_id\": \"eval-2-with_skill\", \"feedback\": \"perfect, love this\", \"timestamp\": \"...\"}\n  ],\n  \"status\": \"complete\"\n}\n```\n\nEmpty feedback means the user thought it was fine. Focus your improvements on the test cases where the user had specific complaints.\n\nKill the viewer server when you're done with it:\n\n```bash\nkill $VIEWER_PID 2>/dev/null\n```\n\n---\n\n## Improving the skill\n\nThis is the heart of the loop. You've run the test cases, the user has reviewed the results, and now you need to make the skill better based on their feedback.\n\n### How to think about improvements\n\n1. **Generalize from the feedback.** The big picture thing that's happening here is that we're trying to create skills that can be used a million times (maybe literally, maybe even more who knows) across many different prompts. Here you and the user are iterating on only a few examples over and over again because it helps move faster. The user knows these examples in and out and it's quick for them to assess new outputs. But if the skill you and the user are codeveloping works only for those examples, it's useless. Rather than put in fiddly overfitty changes, or oppressively constrictive MUSTs, if there's some stubborn issue, you might try branching out and using different metaphors, or recommending different patterns of working. It's relatively cheap to try and maybe you'll land on something great.\n\n2. **Keep the prompt lean.** Remove things that aren't pulling their weight. Make sure to read the transcripts, not just the final outputs — if it looks like the skill is making the model waste a bunch of time doing things that are unproductive, you can try getting rid of the parts of the skill that are making it do that and seeing what happens.\n\n3. **Explain the why.** Try hard to explain the **why** behind everything you're asking the model to do. Today's LLMs are *smart*. They have good theory of mind and when given a good harness can go beyond rote instructions and really make things happen. Even if the feedback from the user is terse or frustrated, try to actually understand the task and why the user is writing what they wrote, and what they actually wrote, and then transmit this understanding into the instructions. If you find yourself writing ALWAYS or NEVER in all caps, or using super rigid structures, that's a yellow flag — if possible, reframe and explain the reasoning so that the model understands why the thing you're asking for is important. That's a more humane, powerful, and effective approach.\n\n4. **Look for repeated work across test cases.** Read the transcripts from the test runs and notice if the subagents all independently wrote similar helper scripts or took the same multi-step approach to something. If all 3 test cases resulted in the subagent writing a `create_docx.py` or a `build_chart.py`, that's a strong signal the skill should bundle that script. Write it once, put it in `scripts/`, and tell the skill to use it. This saves every future invocation from reinventing the wheel.\n\nThis task is pretty important (we are trying to create billions a year in economic value here!) and your thinking time is not the blocker; take your time and really mull things over. I'd suggest writing a draft revision and then looking at it anew and making improvements. Really do your best to get into the head of the user and understand what they want and need.\n\n### The iteration loop\n\nAfter improving the skill:\n\n1. Apply your improvements to the skill\n2. Rerun all test cases into a new `iteration-<N+1>/` directory, including baseline runs. If you're creating a new skill, the baseline is always `without_skill` (no skill) — that stays the same across iterations. If you're improving an existing skill, use your judgment on what makes sense as the baseline: the original version the user came in with, or the previous iteration.\n3. Launch the reviewer with `--previous-workspace` pointing at the previous iteration\n4. Wait for the user to review and tell you they're done\n5. Read the new feedback, improve again, repeat\n\nKeep going until:\n- The user says they're happy\n- The feedback is all empty (everything looks good)\n- You're not making meaningful progress\n\n---\n\n## Advanced: Blind comparison\n\nFor situations where you want a more rigorous comparison between two versions of a skill (e.g., the user asks \"is the new version actually better?\"), there's a blind comparison system. Read `agents/comparator.md` and `agents/analyzer.md` for the details. The basic idea is: give two outputs to an independent agent without telling it which is which, and let it judge quality. Then analyze why the winner won.\n\nThis is optional, requires subagents, and most users won't need it. The human review loop is usually sufficient.\n\n---\n\n## Description Optimization\n\nThe description field in SKILL.md frontmatter is the primary mechanism that determines whether Claude invokes a skill. After creating or improving a skill, offer to optimize the description for better triggering accuracy.\n\n### Step 1: Generate trigger eval queries\n\nCreate 20 eval queries — a mix of should-trigger and should-not-trigger. Save as JSON:\n\n```json\n[\n  {\"query\": \"the user prompt\", \"should_trigger\": true},\n  {\"query\": \"another prompt\", \"should_trigger\": false}\n]\n```\n\nThe queries must be realistic and something a Claude Code or Claude.ai user would actually type. Not abstract requests, but requests that are concrete and specific and have a good amount of detail. For instance, file paths, personal context about the user's job or situation, column names and values, company names, URLs. A little bit of backstory. Some might be in lowercase or contain abbreviations or typos or casual speech. Use a mix of different lengths, and focus on edge cases rather than making them clear-cut (the user will get a chance to sign off on them).\n\nBad: `\"Format this data\"`, `\"Extract text from PDF\"`, `\"Create a chart\"`\n\nGood: `\"ok so my boss just sent me this xlsx file (its in my downloads, called something like 'Q4 sales final FINAL v2.xlsx') and she wants me to add a column that shows the profit margin as a percentage. The revenue is in column C and costs are in column D i think\"`\n\nFor the **should-trigger** queries (8-10), think about coverage. You want different phrasings of the same intent — some formal, some casual. Include cases where the user doesn't explicitly name the skill or file type but clearly needs it. Throw in some uncommon use cases and cases where this skill competes with another but should win.\n\nFor the **should-not-trigger** queries (8-10), the most valuable ones are the near-misses — queries that share keywords or concepts with the skill but actually need something different. Think adjacent domains, ambiguous phrasing where a naive keyword match would trigger but shouldn't, and cases where the query touches on something the skill does but in a context where another tool is more appropriate.\n\nThe key thing to avoid: don't make should-not-trigger queries obviously irrelevant. \"Write a fibonacci function\" as a negative test for a PDF skill is too easy — it doesn't test anything. The negative cases should be genuinely tricky.\n\n### Step 2: Review with user\n\nPresent the eval set to the user for review using the HTML template:\n\n1. Read the template from `assets/eval_review.html`\n2. Replace the placeholders:\n   - `__EVAL_DATA_PLACEHOLDER__` → the JSON array of eval items (no quotes around it — it's a JS variable assignment)\n   - `__SKILL_NAME_PLACEHOLDER__` → the skill's name\n   - `__SKILL_DESCRIPTION_PLACEHOLDER__` → the skill's current description\n3. Write to a temp file (e.g., `/tmp/eval_review_<skill-name>.html`) and open it: `open /tmp/eval_review_<skill-name>.html`\n4. The user can edit queries, toggle should-trigger, add/remove entries, then click \"Export Eval Set\"\n5. The file downloads to `~/Downloads/eval_set.json` — check the Downloads folder for the most recent version in case there are multiple (e.g., `eval_set (1).json`)\n\nThis step matters — bad eval queries lead to bad descriptions.\n\n### Step 3: Run the optimization loop\n\nTell the user: \"This will take some time — I'll run the optimization loop in the background and check on it periodically.\"\n\nSave the eval set to the workspace, then run in the background:\n\n```bash\npython -m scripts.run_loop \\\n  --eval-set <path-to-trigger-eval.json> \\\n  --skill-path <path-to-skill> \\\n  --model <model-id-powering-this-session> \\\n  --max-iterations 5 \\\n  --verbose\n```\n\nUse the model ID from your system prompt (the one powering the current session) so the triggering test matches what the user actually experiences.\n\nWhile it runs, periodically tail the output to give the user updates on which iteration it's on and what the scores look like.\n\nThis handles the full optimization loop automatically. It splits the eval set into 60% train and 40% held-out test, evaluates the current description (running each query 3 times to get a reliable trigger rate), then calls Claude with extended thinking to propose improvements based on what failed. It re-evaluates each new description on both train and test, iterating up to 5 times. When it's done, it opens an HTML report in the browser showing the results per iteration and returns JSON with `best_description` — selected by test score rather than train score to avoid overfitting.\n\n### How skill triggering works\n\nUnderstanding the triggering mechanism helps design better eval queries. Skills appear in Claude's `available_skills` list with their name + description, and Claude decides whether to consult a skill based on that description. The important thing to know is that Claude only consults skills for tasks it can't easily handle on its own — simple, one-step queries like \"read this PDF\" may not trigger a skill even if the description matches perfectly, because Claude can handle them directly with basic tools. Complex, multi-step, or specialized queries reliably trigger skills when the description matches.\n\nThis means your eval queries should be substantive enough that Claude would actually benefit from consulting a skill. Simple queries like \"read file X\" are poor test cases — they won't trigger skills regardless of description quality.\n\n### Step 4: Apply the result\n\nTake `best_description` from the JSON output and update the skill's SKILL.md frontmatter. Show the user before/after and report the scores.\n\n---\n\n### Package and Present (only if `present_files` tool is available)\n\nCheck whether you have access to the `present_files` tool. If you don't, skip this step. If you do, package the skill and present the .skill file to the user:\n\n```bash\npython -m scripts.package_skill <path/to/skill-folder>\n```\n\nAfter packaging, direct the user to the resulting `.skill` file path so they can install it.\n\n---\n\n## Claude.ai-specific instructions\n\nIn Claude.ai, the core workflow is the same (draft → test → review → improve → repeat), but because Claude.ai doesn't have subagents, some mechanics change. Here's what to adapt:\n\n**Running test cases**: No subagents means no parallel execution. For each test case, read the skill's SKILL.md, then follow its instructions to accomplish the test prompt yourself. Do them one at a time. This is less rigorous than independent subagents (you wrote the skill and you're also running it, so you have full context), but it's a useful sanity check — and the human review step compensates. Skip the baseline runs — just use the skill to complete the task as requested.\n\n**Reviewing results**: If you can't open a browser (e.g., Claude.ai's VM has no display, or you're on a remote server), skip the browser reviewer entirely. Instead, present results directly in the conversation. For each test case, show the prompt and the output. If the output is a file the user needs to see (like a .docx or .xlsx), save it to the filesystem and tell them where it is so they can download and inspect it. Ask for feedback inline: \"How does this look? Anything you'd change?\"\n\n**Benchmarking**: Skip the quantitative benchmarking — it relies on baseline comparisons which aren't meaningful without subagents. Focus on qualitative feedback from the user.\n\n**The iteration loop**: Same as before — improve the skill, rerun the test cases, ask for feedback — just without the browser reviewer in the middle. You can still organize results into iteration directories on the filesystem if you have one.\n\n**Description optimization**: This section requires the `claude` CLI tool (specifically `claude -p`) which is only available in Claude Code. Skip it if you're on Claude.ai.\n\n**Blind comparison**: Requires subagents. Skip it.\n\n**Packaging**: The `package_skill.py` script works anywhere with Python and a filesystem. On Claude.ai, you can run it and the user can download the resulting `.skill` file.\n\n---\n\n## Cowork-Specific Instructions\n\nIf you're in Cowork, the main things to know are:\n\n- You have subagents, so the main workflow (spawn test cases in parallel, run baselines, grade, etc.) all works. (However, if you run into severe problems with timeouts, it's OK to run the test prompts in series rather than parallel.)\n- You don't have a browser or display, so when generating the eval viewer, use `--static <output_path>` to write a standalone HTML file instead of starting a server. Then proffer a link that the user can click to open the HTML in their browser.\n- For whatever reason, the Cowork setup seems to disincline Claude from generating the eval viewer after running the tests, so just to reiterate: whether you're in Cowork or in Claude Code, after running tests, you should always generate the eval viewer for the human to look at examples before revising the skill yourself and trying to make corrections, using `generate_review.py` (not writing your own boutique html code). Sorry in advance but I'm gonna go all caps here: GENERATE THE EVAL VIEWER *BEFORE* evaluating inputs yourself. You want to get them in front of the human ASAP!\n- Feedback works differently: since there's no running server, the viewer's \"Submit All Reviews\" button will download `feedback.json` as a file. You can then read it from there (you may have to request access first).\n- Packaging works — `package_skill.py` just needs Python and a filesystem.\n- Description optimization (`run_loop.py` / `run_eval.py`) should work in Cowork just fine since it uses `claude -p` via subprocess, not a browser, but please save it until you've fully finished making the skill and the user agrees it's in good shape.\n\n---\n\n## Reference files\n\nThe agents/ directory contains instructions for specialized subagents. Read them when you need to spawn the relevant subagent.\n\n- `agents/grader.md` — How to evaluate assertions against outputs\n- `agents/comparator.md` — How to do blind A/B comparison between two outputs\n- `agents/analyzer.md` — How to analyze why one version beat another\n\nThe references/ directory has additional documentation:\n- `references/schemas.md` — JSON structures for evals.json, grading.json, etc.\n\n---\n\nRepeating one more time the core loop here for emphasis:\n\n- Figure out what the skill is about\n- Draft or edit the skill\n- Run claude-with-access-to-the-skill on test prompts\n- With the user, evaluate the outputs:\n  - Create benchmark.json and run `eval-viewer/generate_review.py` to help the user review them\n  - Run quantitative evals\n- Repeat until you and the user are satisfied\n- Package the final skill and return it to the user.\n\nPlease add steps to your TodoList, if you have such a thing, to make sure you don't forget. If you're in Cowork, please specifically put \"Create evals JSON and run `eval-viewer/generate_review.py` so human can review test cases\" in your TodoList to make sure it happens.\n\nGood luck!\n"
  },
  {
    "path": ".claude/skills/skill-creator/agents/analyzer.md",
    "content": "# Post-hoc Analyzer Agent\n\nAnalyze blind comparison results to understand WHY the winner won and generate improvement suggestions.\n\n## Role\n\nAfter the blind comparator determines a winner, the Post-hoc Analyzer \"unblids\" the results by examining the skills and transcripts. The goal is to extract actionable insights: what made the winner better, and how can the loser be improved?\n\n## Inputs\n\nYou receive these parameters in your prompt:\n\n- **winner**: \"A\" or \"B\" (from blind comparison)\n- **winner_skill_path**: Path to the skill that produced the winning output\n- **winner_transcript_path**: Path to the execution transcript for the winner\n- **loser_skill_path**: Path to the skill that produced the losing output\n- **loser_transcript_path**: Path to the execution transcript for the loser\n- **comparison_result_path**: Path to the blind comparator's output JSON\n- **output_path**: Where to save the analysis results\n\n## Process\n\n### Step 1: Read Comparison Result\n\n1. Read the blind comparator's output at comparison_result_path\n2. Note the winning side (A or B), the reasoning, and any scores\n3. Understand what the comparator valued in the winning output\n\n### Step 2: Read Both Skills\n\n1. Read the winner skill's SKILL.md and key referenced files\n2. Read the loser skill's SKILL.md and key referenced files\n3. Identify structural differences:\n   - Instructions clarity and specificity\n   - Script/tool usage patterns\n   - Example coverage\n   - Edge case handling\n\n### Step 3: Read Both Transcripts\n\n1. Read the winner's transcript\n2. Read the loser's transcript\n3. Compare execution patterns:\n   - How closely did each follow their skill's instructions?\n   - What tools were used differently?\n   - Where did the loser diverge from optimal behavior?\n   - Did either encounter errors or make recovery attempts?\n\n### Step 4: Analyze Instruction Following\n\nFor each transcript, evaluate:\n- Did the agent follow the skill's explicit instructions?\n- Did the agent use the skill's provided tools/scripts?\n- Were there missed opportunities to leverage skill content?\n- Did the agent add unnecessary steps not in the skill?\n\nScore instruction following 1-10 and note specific issues.\n\n### Step 5: Identify Winner Strengths\n\nDetermine what made the winner better:\n- Clearer instructions that led to better behavior?\n- Better scripts/tools that produced better output?\n- More comprehensive examples that guided edge cases?\n- Better error handling guidance?\n\nBe specific. Quote from skills/transcripts where relevant.\n\n### Step 6: Identify Loser Weaknesses\n\nDetermine what held the loser back:\n- Ambiguous instructions that led to suboptimal choices?\n- Missing tools/scripts that forced workarounds?\n- Gaps in edge case coverage?\n- Poor error handling that caused failures?\n\n### Step 7: Generate Improvement Suggestions\n\nBased on the analysis, produce actionable suggestions for improving the loser skill:\n- Specific instruction changes to make\n- Tools/scripts to add or modify\n- Examples to include\n- Edge cases to address\n\nPrioritize by impact. Focus on changes that would have changed the outcome.\n\n### Step 8: Write Analysis Results\n\nSave structured analysis to `{output_path}`.\n\n## Output Format\n\nWrite a JSON file with this structure:\n\n```json\n{\n  \"comparison_summary\": {\n    \"winner\": \"A\",\n    \"winner_skill\": \"path/to/winner/skill\",\n    \"loser_skill\": \"path/to/loser/skill\",\n    \"comparator_reasoning\": \"Brief summary of why comparator chose winner\"\n  },\n  \"winner_strengths\": [\n    \"Clear step-by-step instructions for handling multi-page documents\",\n    \"Included validation script that caught formatting errors\",\n    \"Explicit guidance on fallback behavior when OCR fails\"\n  ],\n  \"loser_weaknesses\": [\n    \"Vague instruction 'process the document appropriately' led to inconsistent behavior\",\n    \"No script for validation, agent had to improvise and made errors\",\n    \"No guidance on OCR failure, agent gave up instead of trying alternatives\"\n  ],\n  \"instruction_following\": {\n    \"winner\": {\n      \"score\": 9,\n      \"issues\": [\n        \"Minor: skipped optional logging step\"\n      ]\n    },\n    \"loser\": {\n      \"score\": 6,\n      \"issues\": [\n        \"Did not use the skill's formatting template\",\n        \"Invented own approach instead of following step 3\",\n        \"Missed the 'always validate output' instruction\"\n      ]\n    }\n  },\n  \"improvement_suggestions\": [\n    {\n      \"priority\": \"high\",\n      \"category\": \"instructions\",\n      \"suggestion\": \"Replace 'process the document appropriately' with explicit steps: 1) Extract text, 2) Identify sections, 3) Format per template\",\n      \"expected_impact\": \"Would eliminate ambiguity that caused inconsistent behavior\"\n    },\n    {\n      \"priority\": \"high\",\n      \"category\": \"tools\",\n      \"suggestion\": \"Add validate_output.py script similar to winner skill's validation approach\",\n      \"expected_impact\": \"Would catch formatting errors before final output\"\n    },\n    {\n      \"priority\": \"medium\",\n      \"category\": \"error_handling\",\n      \"suggestion\": \"Add fallback instructions: 'If OCR fails, try: 1) different resolution, 2) image preprocessing, 3) manual extraction'\",\n      \"expected_impact\": \"Would prevent early failure on difficult documents\"\n    }\n  ],\n  \"transcript_insights\": {\n    \"winner_execution_pattern\": \"Read skill -> Followed 5-step process -> Used validation script -> Fixed 2 issues -> Produced output\",\n    \"loser_execution_pattern\": \"Read skill -> Unclear on approach -> Tried 3 different methods -> No validation -> Output had errors\"\n  }\n}\n```\n\n## Guidelines\n\n- **Be specific**: Quote from skills and transcripts, don't just say \"instructions were unclear\"\n- **Be actionable**: Suggestions should be concrete changes, not vague advice\n- **Focus on skill improvements**: The goal is to improve the losing skill, not critique the agent\n- **Prioritize by impact**: Which changes would most likely have changed the outcome?\n- **Consider causation**: Did the skill weakness actually cause the worse output, or is it incidental?\n- **Stay objective**: Analyze what happened, don't editorialize\n- **Think about generalization**: Would this improvement help on other evals too?\n\n## Categories for Suggestions\n\nUse these categories to organize improvement suggestions:\n\n| Category | Description |\n|----------|-------------|\n| `instructions` | Changes to the skill's prose instructions |\n| `tools` | Scripts, templates, or utilities to add/modify |\n| `examples` | Example inputs/outputs to include |\n| `error_handling` | Guidance for handling failures |\n| `structure` | Reorganization of skill content |\n| `references` | External docs or resources to add |\n\n## Priority Levels\n\n- **high**: Would likely change the outcome of this comparison\n- **medium**: Would improve quality but may not change win/loss\n- **low**: Nice to have, marginal improvement\n\n---\n\n# Analyzing Benchmark Results\n\nWhen analyzing benchmark results, the analyzer's purpose is to **surface patterns and anomalies** across multiple runs, not suggest skill improvements.\n\n## Role\n\nReview all benchmark run results and generate freeform notes that help the user understand skill performance. Focus on patterns that wouldn't be visible from aggregate metrics alone.\n\n## Inputs\n\nYou receive these parameters in your prompt:\n\n- **benchmark_data_path**: Path to the in-progress benchmark.json with all run results\n- **skill_path**: Path to the skill being benchmarked\n- **output_path**: Where to save the notes (as JSON array of strings)\n\n## Process\n\n### Step 1: Read Benchmark Data\n\n1. Read the benchmark.json containing all run results\n2. Note the configurations tested (with_skill, without_skill)\n3. Understand the run_summary aggregates already calculated\n\n### Step 2: Analyze Per-Assertion Patterns\n\nFor each expectation across all runs:\n- Does it **always pass** in both configurations? (may not differentiate skill value)\n- Does it **always fail** in both configurations? (may be broken or beyond capability)\n- Does it **always pass with skill but fail without**? (skill clearly adds value here)\n- Does it **always fail with skill but pass without**? (skill may be hurting)\n- Is it **highly variable**? (flaky expectation or non-deterministic behavior)\n\n### Step 3: Analyze Cross-Eval Patterns\n\nLook for patterns across evals:\n- Are certain eval types consistently harder/easier?\n- Do some evals show high variance while others are stable?\n- Are there surprising results that contradict expectations?\n\n### Step 4: Analyze Metrics Patterns\n\nLook at time_seconds, tokens, tool_calls:\n- Does the skill significantly increase execution time?\n- Is there high variance in resource usage?\n- Are there outlier runs that skew the aggregates?\n\n### Step 5: Generate Notes\n\nWrite freeform observations as a list of strings. Each note should:\n- State a specific observation\n- Be grounded in the data (not speculation)\n- Help the user understand something the aggregate metrics don't show\n\nExamples:\n- \"Assertion 'Output is a PDF file' passes 100% in both configurations - may not differentiate skill value\"\n- \"Eval 3 shows high variance (50% ± 40%) - run 2 had an unusual failure that may be flaky\"\n- \"Without-skill runs consistently fail on table extraction expectations (0% pass rate)\"\n- \"Skill adds 13s average execution time but improves pass rate by 50%\"\n- \"Token usage is 80% higher with skill, primarily due to script output parsing\"\n- \"All 3 without-skill runs for eval 1 produced empty output\"\n\n### Step 6: Write Notes\n\nSave notes to `{output_path}` as a JSON array of strings:\n\n```json\n[\n  \"Assertion 'Output is a PDF file' passes 100% in both configurations - may not differentiate skill value\",\n  \"Eval 3 shows high variance (50% ± 40%) - run 2 had an unusual failure\",\n  \"Without-skill runs consistently fail on table extraction expectations\",\n  \"Skill adds 13s average execution time but improves pass rate by 50%\"\n]\n```\n\n## Guidelines\n\n**DO:**\n- Report what you observe in the data\n- Be specific about which evals, expectations, or runs you're referring to\n- Note patterns that aggregate metrics would hide\n- Provide context that helps interpret the numbers\n\n**DO NOT:**\n- Suggest improvements to the skill (that's for the improvement step, not benchmarking)\n- Make subjective quality judgments (\"the output was good/bad\")\n- Speculate about causes without evidence\n- Repeat information already in the run_summary aggregates\n"
  },
  {
    "path": ".claude/skills/skill-creator/agents/comparator.md",
    "content": "# Blind Comparator Agent\n\nCompare two outputs WITHOUT knowing which skill produced them.\n\n## Role\n\nThe Blind Comparator judges which output better accomplishes the eval task. You receive two outputs labeled A and B, but you do NOT know which skill produced which. This prevents bias toward a particular skill or approach.\n\nYour judgment is based purely on output quality and task completion.\n\n## Inputs\n\nYou receive these parameters in your prompt:\n\n- **output_a_path**: Path to the first output file or directory\n- **output_b_path**: Path to the second output file or directory\n- **eval_prompt**: The original task/prompt that was executed\n- **expectations**: List of expectations to check (optional - may be empty)\n\n## Process\n\n### Step 1: Read Both Outputs\n\n1. Examine output A (file or directory)\n2. Examine output B (file or directory)\n3. Note the type, structure, and content of each\n4. If outputs are directories, examine all relevant files inside\n\n### Step 2: Understand the Task\n\n1. Read the eval_prompt carefully\n2. Identify what the task requires:\n   - What should be produced?\n   - What qualities matter (accuracy, completeness, format)?\n   - What would distinguish a good output from a poor one?\n\n### Step 3: Generate Evaluation Rubric\n\nBased on the task, generate a rubric with two dimensions:\n\n**Content Rubric** (what the output contains):\n| Criterion | 1 (Poor) | 3 (Acceptable) | 5 (Excellent) |\n|-----------|----------|----------------|---------------|\n| Correctness | Major errors | Minor errors | Fully correct |\n| Completeness | Missing key elements | Mostly complete | All elements present |\n| Accuracy | Significant inaccuracies | Minor inaccuracies | Accurate throughout |\n\n**Structure Rubric** (how the output is organized):\n| Criterion | 1 (Poor) | 3 (Acceptable) | 5 (Excellent) |\n|-----------|----------|----------------|---------------|\n| Organization | Disorganized | Reasonably organized | Clear, logical structure |\n| Formatting | Inconsistent/broken | Mostly consistent | Professional, polished |\n| Usability | Difficult to use | Usable with effort | Easy to use |\n\nAdapt criteria to the specific task. For example:\n- PDF form → \"Field alignment\", \"Text readability\", \"Data placement\"\n- Document → \"Section structure\", \"Heading hierarchy\", \"Paragraph flow\"\n- Data output → \"Schema correctness\", \"Data types\", \"Completeness\"\n\n### Step 4: Evaluate Each Output Against the Rubric\n\nFor each output (A and B):\n\n1. **Score each criterion** on the rubric (1-5 scale)\n2. **Calculate dimension totals**: Content score, Structure score\n3. **Calculate overall score**: Average of dimension scores, scaled to 1-10\n\n### Step 5: Check Assertions (if provided)\n\nIf expectations are provided:\n\n1. Check each expectation against output A\n2. Check each expectation against output B\n3. Count pass rates for each output\n4. Use expectation scores as secondary evidence (not the primary decision factor)\n\n### Step 6: Determine the Winner\n\nCompare A and B based on (in priority order):\n\n1. **Primary**: Overall rubric score (content + structure)\n2. **Secondary**: Assertion pass rates (if applicable)\n3. **Tiebreaker**: If truly equal, declare a TIE\n\nBe decisive - ties should be rare. One output is usually better, even if marginally.\n\n### Step 7: Write Comparison Results\n\nSave results to a JSON file at the path specified (or `comparison.json` if not specified).\n\n## Output Format\n\nWrite a JSON file with this structure:\n\n```json\n{\n  \"winner\": \"A\",\n  \"reasoning\": \"Output A provides a complete solution with proper formatting and all required fields. Output B is missing the date field and has formatting inconsistencies.\",\n  \"rubric\": {\n    \"A\": {\n      \"content\": {\n        \"correctness\": 5,\n        \"completeness\": 5,\n        \"accuracy\": 4\n      },\n      \"structure\": {\n        \"organization\": 4,\n        \"formatting\": 5,\n        \"usability\": 4\n      },\n      \"content_score\": 4.7,\n      \"structure_score\": 4.3,\n      \"overall_score\": 9.0\n    },\n    \"B\": {\n      \"content\": {\n        \"correctness\": 3,\n        \"completeness\": 2,\n        \"accuracy\": 3\n      },\n      \"structure\": {\n        \"organization\": 3,\n        \"formatting\": 2,\n        \"usability\": 3\n      },\n      \"content_score\": 2.7,\n      \"structure_score\": 2.7,\n      \"overall_score\": 5.4\n    }\n  },\n  \"output_quality\": {\n    \"A\": {\n      \"score\": 9,\n      \"strengths\": [\"Complete solution\", \"Well-formatted\", \"All fields present\"],\n      \"weaknesses\": [\"Minor style inconsistency in header\"]\n    },\n    \"B\": {\n      \"score\": 5,\n      \"strengths\": [\"Readable output\", \"Correct basic structure\"],\n      \"weaknesses\": [\"Missing date field\", \"Formatting inconsistencies\", \"Partial data extraction\"]\n    }\n  },\n  \"expectation_results\": {\n    \"A\": {\n      \"passed\": 4,\n      \"total\": 5,\n      \"pass_rate\": 0.80,\n      \"details\": [\n        {\"text\": \"Output includes name\", \"passed\": true},\n        {\"text\": \"Output includes date\", \"passed\": true},\n        {\"text\": \"Format is PDF\", \"passed\": true},\n        {\"text\": \"Contains signature\", \"passed\": false},\n        {\"text\": \"Readable text\", \"passed\": true}\n      ]\n    },\n    \"B\": {\n      \"passed\": 3,\n      \"total\": 5,\n      \"pass_rate\": 0.60,\n      \"details\": [\n        {\"text\": \"Output includes name\", \"passed\": true},\n        {\"text\": \"Output includes date\", \"passed\": false},\n        {\"text\": \"Format is PDF\", \"passed\": true},\n        {\"text\": \"Contains signature\", \"passed\": false},\n        {\"text\": \"Readable text\", \"passed\": true}\n      ]\n    }\n  }\n}\n```\n\nIf no expectations were provided, omit the `expectation_results` field entirely.\n\n## Field Descriptions\n\n- **winner**: \"A\", \"B\", or \"TIE\"\n- **reasoning**: Clear explanation of why the winner was chosen (or why it's a tie)\n- **rubric**: Structured rubric evaluation for each output\n  - **content**: Scores for content criteria (correctness, completeness, accuracy)\n  - **structure**: Scores for structure criteria (organization, formatting, usability)\n  - **content_score**: Average of content criteria (1-5)\n  - **structure_score**: Average of structure criteria (1-5)\n  - **overall_score**: Combined score scaled to 1-10\n- **output_quality**: Summary quality assessment\n  - **score**: 1-10 rating (should match rubric overall_score)\n  - **strengths**: List of positive aspects\n  - **weaknesses**: List of issues or shortcomings\n- **expectation_results**: (Only if expectations provided)\n  - **passed**: Number of expectations that passed\n  - **total**: Total number of expectations\n  - **pass_rate**: Fraction passed (0.0 to 1.0)\n  - **details**: Individual expectation results\n\n## Guidelines\n\n- **Stay blind**: DO NOT try to infer which skill produced which output. Judge purely on output quality.\n- **Be specific**: Cite specific examples when explaining strengths and weaknesses.\n- **Be decisive**: Choose a winner unless outputs are genuinely equivalent.\n- **Output quality first**: Assertion scores are secondary to overall task completion.\n- **Be objective**: Don't favor outputs based on style preferences; focus on correctness and completeness.\n- **Explain your reasoning**: The reasoning field should make it clear why you chose the winner.\n- **Handle edge cases**: If both outputs fail, pick the one that fails less badly. If both are excellent, pick the one that's marginally better.\n"
  },
  {
    "path": ".claude/skills/skill-creator/agents/grader.md",
    "content": "# Grader Agent\n\nEvaluate expectations against an execution transcript and outputs.\n\n## Role\n\nThe Grader reviews a transcript and output files, then determines whether each expectation passes or fails. Provide clear evidence for each judgment.\n\nYou have two jobs: grade the outputs, and critique the evals themselves. A passing grade on a weak assertion is worse than useless — it creates false confidence. When you notice an assertion that's trivially satisfied, or an important outcome that no assertion checks, say so.\n\n## Inputs\n\nYou receive these parameters in your prompt:\n\n- **expectations**: List of expectations to evaluate (strings)\n- **transcript_path**: Path to the execution transcript (markdown file)\n- **outputs_dir**: Directory containing output files from execution\n\n## Process\n\n### Step 1: Read the Transcript\n\n1. Read the transcript file completely\n2. Note the eval prompt, execution steps, and final result\n3. Identify any issues or errors documented\n\n### Step 2: Examine Output Files\n\n1. List files in outputs_dir\n2. Read/examine each file relevant to the expectations. If outputs aren't plain text, use the inspection tools provided in your prompt — don't rely solely on what the transcript says the executor produced.\n3. Note contents, structure, and quality\n\n### Step 3: Evaluate Each Assertion\n\nFor each expectation:\n\n1. **Search for evidence** in the transcript and outputs\n2. **Determine verdict**:\n   - **PASS**: Clear evidence the expectation is true AND the evidence reflects genuine task completion, not just surface-level compliance\n   - **FAIL**: No evidence, or evidence contradicts the expectation, or the evidence is superficial (e.g., correct filename but empty/wrong content)\n3. **Cite the evidence**: Quote the specific text or describe what you found\n\n### Step 4: Extract and Verify Claims\n\nBeyond the predefined expectations, extract implicit claims from the outputs and verify them:\n\n1. **Extract claims** from the transcript and outputs:\n   - Factual statements (\"The form has 12 fields\")\n   - Process claims (\"Used pypdf to fill the form\")\n   - Quality claims (\"All fields were filled correctly\")\n\n2. **Verify each claim**:\n   - **Factual claims**: Can be checked against the outputs or external sources\n   - **Process claims**: Can be verified from the transcript\n   - **Quality claims**: Evaluate whether the claim is justified\n\n3. **Flag unverifiable claims**: Note claims that cannot be verified with available information\n\nThis catches issues that predefined expectations might miss.\n\n### Step 5: Read User Notes\n\nIf `{outputs_dir}/user_notes.md` exists:\n1. Read it and note any uncertainties or issues flagged by the executor\n2. Include relevant concerns in the grading output\n3. These may reveal problems even when expectations pass\n\n### Step 6: Critique the Evals\n\nAfter grading, consider whether the evals themselves could be improved. Only surface suggestions when there's a clear gap.\n\nGood suggestions test meaningful outcomes — assertions that are hard to satisfy without actually doing the work correctly. Think about what makes an assertion *discriminating*: it passes when the skill genuinely succeeds and fails when it doesn't.\n\nSuggestions worth raising:\n- An assertion that passed but would also pass for a clearly wrong output (e.g., checking filename existence but not file content)\n- An important outcome you observed — good or bad — that no assertion covers at all\n- An assertion that can't actually be verified from the available outputs\n\nKeep the bar high. The goal is to flag things the eval author would say \"good catch\" about, not to nitpick every assertion.\n\n### Step 7: Write Grading Results\n\nSave results to `{outputs_dir}/../grading.json` (sibling to outputs_dir).\n\n## Grading Criteria\n\n**PASS when**:\n- The transcript or outputs clearly demonstrate the expectation is true\n- Specific evidence can be cited\n- The evidence reflects genuine substance, not just surface compliance (e.g., a file exists AND contains correct content, not just the right filename)\n\n**FAIL when**:\n- No evidence found for the expectation\n- Evidence contradicts the expectation\n- The expectation cannot be verified from available information\n- The evidence is superficial — the assertion is technically satisfied but the underlying task outcome is wrong or incomplete\n- The output appears to meet the assertion by coincidence rather than by actually doing the work\n\n**When uncertain**: The burden of proof to pass is on the expectation.\n\n### Step 8: Read Executor Metrics and Timing\n\n1. If `{outputs_dir}/metrics.json` exists, read it and include in grading output\n2. If `{outputs_dir}/../timing.json` exists, read it and include timing data\n\n## Output Format\n\nWrite a JSON file with this structure:\n\n```json\n{\n  \"expectations\": [\n    {\n      \"text\": \"The output includes the name 'John Smith'\",\n      \"passed\": true,\n      \"evidence\": \"Found in transcript Step 3: 'Extracted names: John Smith, Sarah Johnson'\"\n    },\n    {\n      \"text\": \"The spreadsheet has a SUM formula in cell B10\",\n      \"passed\": false,\n      \"evidence\": \"No spreadsheet was created. The output was a text file.\"\n    },\n    {\n      \"text\": \"The assistant used the skill's OCR script\",\n      \"passed\": true,\n      \"evidence\": \"Transcript Step 2 shows: 'Tool: Bash - python ocr_script.py image.png'\"\n    }\n  ],\n  \"summary\": {\n    \"passed\": 2,\n    \"failed\": 1,\n    \"total\": 3,\n    \"pass_rate\": 0.67\n  },\n  \"execution_metrics\": {\n    \"tool_calls\": {\n      \"Read\": 5,\n      \"Write\": 2,\n      \"Bash\": 8\n    },\n    \"total_tool_calls\": 15,\n    \"total_steps\": 6,\n    \"errors_encountered\": 0,\n    \"output_chars\": 12450,\n    \"transcript_chars\": 3200\n  },\n  \"timing\": {\n    \"executor_duration_seconds\": 165.0,\n    \"grader_duration_seconds\": 26.0,\n    \"total_duration_seconds\": 191.0\n  },\n  \"claims\": [\n    {\n      \"claim\": \"The form has 12 fillable fields\",\n      \"type\": \"factual\",\n      \"verified\": true,\n      \"evidence\": \"Counted 12 fields in field_info.json\"\n    },\n    {\n      \"claim\": \"All required fields were populated\",\n      \"type\": \"quality\",\n      \"verified\": false,\n      \"evidence\": \"Reference section was left blank despite data being available\"\n    }\n  ],\n  \"user_notes_summary\": {\n    \"uncertainties\": [\"Used 2023 data, may be stale\"],\n    \"needs_review\": [],\n    \"workarounds\": [\"Fell back to text overlay for non-fillable fields\"]\n  },\n  \"eval_feedback\": {\n    \"suggestions\": [\n      {\n        \"assertion\": \"The output includes the name 'John Smith'\",\n        \"reason\": \"A hallucinated document that mentions the name would also pass — consider checking it appears as the primary contact with matching phone and email from the input\"\n      },\n      {\n        \"reason\": \"No assertion checks whether the extracted phone numbers match the input — I observed incorrect numbers in the output that went uncaught\"\n      }\n    ],\n    \"overall\": \"Assertions check presence but not correctness. Consider adding content verification.\"\n  }\n}\n```\n\n## Field Descriptions\n\n- **expectations**: Array of graded expectations\n  - **text**: The original expectation text\n  - **passed**: Boolean - true if expectation passes\n  - **evidence**: Specific quote or description supporting the verdict\n- **summary**: Aggregate statistics\n  - **passed**: Count of passed expectations\n  - **failed**: Count of failed expectations\n  - **total**: Total expectations evaluated\n  - **pass_rate**: Fraction passed (0.0 to 1.0)\n- **execution_metrics**: Copied from executor's metrics.json (if available)\n  - **output_chars**: Total character count of output files (proxy for tokens)\n  - **transcript_chars**: Character count of transcript\n- **timing**: Wall clock timing from timing.json (if available)\n  - **executor_duration_seconds**: Time spent in executor subagent\n  - **total_duration_seconds**: Total elapsed time for the run\n- **claims**: Extracted and verified claims from the output\n  - **claim**: The statement being verified\n  - **type**: \"factual\", \"process\", or \"quality\"\n  - **verified**: Boolean - whether the claim holds\n  - **evidence**: Supporting or contradicting evidence\n- **user_notes_summary**: Issues flagged by the executor\n  - **uncertainties**: Things the executor wasn't sure about\n  - **needs_review**: Items requiring human attention\n  - **workarounds**: Places where the skill didn't work as expected\n- **eval_feedback**: Improvement suggestions for the evals (only when warranted)\n  - **suggestions**: List of concrete suggestions, each with a `reason` and optionally an `assertion` it relates to\n  - **overall**: Brief assessment — can be \"No suggestions, evals look solid\" if nothing to flag\n\n## Guidelines\n\n- **Be objective**: Base verdicts on evidence, not assumptions\n- **Be specific**: Quote the exact text that supports your verdict\n- **Be thorough**: Check both transcript and output files\n- **Be consistent**: Apply the same standard to each expectation\n- **Explain failures**: Make it clear why evidence was insufficient\n- **No partial credit**: Each expectation is pass or fail, not partial\n"
  },
  {
    "path": ".claude/skills/skill-creator/assets/eval_review.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n  <title>Eval Set Review - __SKILL_NAME_PLACEHOLDER__</title>\n  <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n  <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n  <link href=\"https://fonts.googleapis.com/css2?family=Poppins:wght@500;600&family=Lora:wght@400;500&display=swap\" rel=\"stylesheet\">\n  <style>\n    * { box-sizing: border-box; margin: 0; padding: 0; }\n    body { font-family: 'Lora', Georgia, serif; background: #faf9f5; padding: 2rem; color: #141413; }\n    h1 { font-family: 'Poppins', sans-serif; margin-bottom: 0.5rem; font-size: 1.5rem; }\n    .description { color: #b0aea5; margin-bottom: 1.5rem; font-style: italic; max-width: 900px; }\n    .controls { margin-bottom: 1rem; display: flex; gap: 0.5rem; }\n    .btn { font-family: 'Poppins', sans-serif; padding: 0.5rem 1rem; border: none; border-radius: 6px; cursor: pointer; font-size: 0.875rem; font-weight: 500; }\n    .btn-add { background: #6a9bcc; color: white; }\n    .btn-add:hover { background: #5889b8; }\n    .btn-export { background: #d97757; color: white; }\n    .btn-export:hover { background: #c4613f; }\n    table { width: 100%; max-width: 1100px; border-collapse: collapse; background: white; border-radius: 6px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.08); }\n    th { font-family: 'Poppins', sans-serif; background: #141413; color: #faf9f5; padding: 0.75rem 1rem; text-align: left; font-size: 0.875rem; }\n    td { padding: 0.75rem 1rem; border-bottom: 1px solid #e8e6dc; vertical-align: top; }\n    tr:nth-child(even) td { background: #faf9f5; }\n    tr:hover td { background: #f3f1ea; }\n    .section-header td { background: #e8e6dc; font-family: 'Poppins', sans-serif; font-weight: 500; font-size: 0.8rem; color: #141413; text-transform: uppercase; letter-spacing: 0.05em; }\n    .query-input { width: 100%; padding: 0.4rem; border: 1px solid #e8e6dc; border-radius: 4px; font-size: 0.875rem; font-family: 'Lora', Georgia, serif; resize: vertical; min-height: 60px; }\n    .query-input:focus { outline: none; border-color: #d97757; box-shadow: 0 0 0 2px rgba(217,119,87,0.15); }\n    .toggle { position: relative; display: inline-block; width: 44px; height: 24px; }\n    .toggle input { opacity: 0; width: 0; height: 0; }\n    .toggle .slider { position: absolute; inset: 0; background: #b0aea5; border-radius: 24px; cursor: pointer; transition: 0.2s; }\n    .toggle .slider::before { content: \"\"; position: absolute; width: 18px; height: 18px; left: 3px; bottom: 3px; background: white; border-radius: 50%; transition: 0.2s; }\n    .toggle input:checked + .slider { background: #d97757; }\n    .toggle input:checked + .slider::before { transform: translateX(20px); }\n    .btn-delete { background: #c44; color: white; padding: 0.3rem 0.6rem; border: none; border-radius: 4px; cursor: pointer; font-size: 0.75rem; font-family: 'Poppins', sans-serif; }\n    .btn-delete:hover { background: #a33; }\n    .summary { margin-top: 1rem; color: #b0aea5; font-size: 0.875rem; }\n  </style>\n</head>\n<body>\n  <h1>Eval Set Review: <span id=\"skill-name\">__SKILL_NAME_PLACEHOLDER__</span></h1>\n  <p class=\"description\">Current description: <span id=\"skill-desc\">__SKILL_DESCRIPTION_PLACEHOLDER__</span></p>\n\n  <div class=\"controls\">\n    <button class=\"btn btn-add\" onclick=\"addRow()\">+ Add Query</button>\n    <button class=\"btn btn-export\" onclick=\"exportEvalSet()\">Export Eval Set</button>\n  </div>\n\n  <table>\n    <thead>\n      <tr>\n        <th style=\"width:65%\">Query</th>\n        <th style=\"width:18%\">Should Trigger</th>\n        <th style=\"width:10%\">Actions</th>\n      </tr>\n    </thead>\n    <tbody id=\"eval-body\"></tbody>\n  </table>\n\n  <p class=\"summary\" id=\"summary\"></p>\n\n  <script>\n    const EVAL_DATA = __EVAL_DATA_PLACEHOLDER__;\n\n    let evalItems = [...EVAL_DATA];\n\n    function render() {\n      const tbody = document.getElementById('eval-body');\n      tbody.innerHTML = '';\n\n      // Sort: should-trigger first, then should-not-trigger\n      const sorted = evalItems\n        .map((item, origIdx) => ({ ...item, origIdx }))\n        .sort((a, b) => (b.should_trigger ? 1 : 0) - (a.should_trigger ? 1 : 0));\n\n      let lastGroup = null;\n      sorted.forEach(item => {\n        const group = item.should_trigger ? 'trigger' : 'no-trigger';\n        if (group !== lastGroup) {\n          const headerRow = document.createElement('tr');\n          headerRow.className = 'section-header';\n          headerRow.innerHTML = `<td colspan=\"3\">${item.should_trigger ? 'Should Trigger' : 'Should NOT Trigger'}</td>`;\n          tbody.appendChild(headerRow);\n          lastGroup = group;\n        }\n\n        const idx = item.origIdx;\n        const tr = document.createElement('tr');\n        tr.innerHTML = `\n          <td><textarea class=\"query-input\" onchange=\"updateQuery(${idx}, this.value)\">${escapeHtml(item.query)}</textarea></td>\n          <td>\n            <label class=\"toggle\">\n              <input type=\"checkbox\" ${item.should_trigger ? 'checked' : ''} onchange=\"updateTrigger(${idx}, this.checked)\">\n              <span class=\"slider\"></span>\n            </label>\n            <span style=\"margin-left:8px;font-size:0.8rem;color:#b0aea5\">${item.should_trigger ? 'Yes' : 'No'}</span>\n          </td>\n          <td><button class=\"btn-delete\" onclick=\"deleteRow(${idx})\">Delete</button></td>\n        `;\n        tbody.appendChild(tr);\n      });\n      updateSummary();\n    }\n\n    function escapeHtml(text) {\n      const div = document.createElement('div');\n      div.textContent = text;\n      return div.innerHTML;\n    }\n\n    function updateQuery(idx, value) { evalItems[idx].query = value; updateSummary(); }\n    function updateTrigger(idx, value) { evalItems[idx].should_trigger = value; render(); }\n    function deleteRow(idx) { evalItems.splice(idx, 1); render(); }\n\n    function addRow() {\n      evalItems.push({ query: '', should_trigger: true });\n      render();\n      const inputs = document.querySelectorAll('.query-input');\n      inputs[inputs.length - 1].focus();\n    }\n\n    function updateSummary() {\n      const trigger = evalItems.filter(i => i.should_trigger).length;\n      const noTrigger = evalItems.filter(i => !i.should_trigger).length;\n      document.getElementById('summary').textContent =\n        `${evalItems.length} queries total: ${trigger} should trigger, ${noTrigger} should not trigger`;\n    }\n\n    function exportEvalSet() {\n      const valid = evalItems.filter(i => i.query.trim() !== '');\n      const data = valid.map(i => ({ query: i.query.trim(), should_trigger: i.should_trigger }));\n      const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });\n      const url = URL.createObjectURL(blob);\n      const a = document.createElement('a');\n      a.href = url;\n      a.download = 'eval_set.json';\n      document.body.appendChild(a);\n      a.click();\n      document.body.removeChild(a);\n      URL.revokeObjectURL(url);\n    }\n\n    render();\n  </script>\n</body>\n</html>\n"
  },
  {
    "path": ".claude/skills/skill-creator/eval-viewer/generate_review.py",
    "content": "#!/usr/bin/env python3\n\"\"\"Generate and serve a review page for eval results.\n\nReads the workspace directory, discovers runs (directories with outputs/),\nembeds all output data into a self-contained HTML page, and serves it via\na tiny HTTP server. Feedback auto-saves to feedback.json in the workspace.\n\nUsage:\n    python generate_review.py <workspace-path> [--port PORT] [--skill-name NAME]\n    python generate_review.py <workspace-path> --previous-feedback /path/to/old/feedback.json\n\nNo dependencies beyond the Python stdlib are required.\n\"\"\"\n\nimport argparse\nimport base64\nimport json\nimport mimetypes\nimport os\nimport re\nimport signal\nimport subprocess\nimport sys\nimport time\nimport webbrowser\nfrom functools import partial\nfrom http.server import HTTPServer, BaseHTTPRequestHandler\nfrom pathlib import Path\n\n# Files to exclude from output listings\nMETADATA_FILES = {\"transcript.md\", \"user_notes.md\", \"metrics.json\"}\n\n# Extensions we render as inline text\nTEXT_EXTENSIONS = {\n    \".txt\", \".md\", \".json\", \".csv\", \".py\", \".js\", \".ts\", \".tsx\", \".jsx\",\n    \".yaml\", \".yml\", \".xml\", \".html\", \".css\", \".sh\", \".rb\", \".go\", \".rs\",\n    \".java\", \".c\", \".cpp\", \".h\", \".hpp\", \".sql\", \".r\", \".toml\",\n}\n\n# Extensions we render as inline images\nIMAGE_EXTENSIONS = {\".png\", \".jpg\", \".jpeg\", \".gif\", \".svg\", \".webp\"}\n\n# MIME type overrides for common types\nMIME_OVERRIDES = {\n    \".svg\": \"image/svg+xml\",\n    \".xlsx\": \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n    \".docx\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n    \".pptx\": \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n}\n\n\ndef get_mime_type(path: Path) -> str:\n    ext = path.suffix.lower()\n    if ext in MIME_OVERRIDES:\n        return MIME_OVERRIDES[ext]\n    mime, _ = mimetypes.guess_type(str(path))\n    return mime or \"application/octet-stream\"\n\n\ndef find_runs(workspace: Path) -> list[dict]:\n    \"\"\"Recursively find directories that contain an outputs/ subdirectory.\"\"\"\n    runs: list[dict] = []\n    _find_runs_recursive(workspace, workspace, runs)\n    runs.sort(key=lambda r: (r.get(\"eval_id\", float(\"inf\")), r[\"id\"]))\n    return runs\n\n\ndef _find_runs_recursive(root: Path, current: Path, runs: list[dict]) -> None:\n    if not current.is_dir():\n        return\n\n    outputs_dir = current / \"outputs\"\n    if outputs_dir.is_dir():\n        run = build_run(root, current)\n        if run:\n            runs.append(run)\n        return\n\n    skip = {\"node_modules\", \".git\", \"__pycache__\", \"skill\", \"inputs\"}\n    for child in sorted(current.iterdir()):\n        if child.is_dir() and child.name not in skip:\n            _find_runs_recursive(root, child, runs)\n\n\ndef build_run(root: Path, run_dir: Path) -> dict | None:\n    \"\"\"Build a run dict with prompt, outputs, and grading data.\"\"\"\n    prompt = \"\"\n    eval_id = None\n\n    # Try eval_metadata.json\n    for candidate in [run_dir / \"eval_metadata.json\", run_dir.parent / \"eval_metadata.json\"]:\n        if candidate.exists():\n            try:\n                metadata = json.loads(candidate.read_text())\n                prompt = metadata.get(\"prompt\", \"\")\n                eval_id = metadata.get(\"eval_id\")\n            except (json.JSONDecodeError, OSError):\n                pass\n            if prompt:\n                break\n\n    # Fall back to transcript.md\n    if not prompt:\n        for candidate in [run_dir / \"transcript.md\", run_dir / \"outputs\" / \"transcript.md\"]:\n            if candidate.exists():\n                try:\n                    text = candidate.read_text()\n                    match = re.search(r\"## Eval Prompt\\n\\n([\\s\\S]*?)(?=\\n##|$)\", text)\n                    if match:\n                        prompt = match.group(1).strip()\n                except OSError:\n                    pass\n                if prompt:\n                    break\n\n    if not prompt:\n        prompt = \"(No prompt found)\"\n\n    run_id = str(run_dir.relative_to(root)).replace(\"/\", \"-\").replace(\"\\\\\", \"-\")\n\n    # Collect output files\n    outputs_dir = run_dir / \"outputs\"\n    output_files: list[dict] = []\n    if outputs_dir.is_dir():\n        for f in sorted(outputs_dir.iterdir()):\n            if f.is_file() and f.name not in METADATA_FILES:\n                output_files.append(embed_file(f))\n\n    # Load grading if present\n    grading = None\n    for candidate in [run_dir / \"grading.json\", run_dir.parent / \"grading.json\"]:\n        if candidate.exists():\n            try:\n                grading = json.loads(candidate.read_text())\n            except (json.JSONDecodeError, OSError):\n                pass\n            if grading:\n                break\n\n    return {\n        \"id\": run_id,\n        \"prompt\": prompt,\n        \"eval_id\": eval_id,\n        \"outputs\": output_files,\n        \"grading\": grading,\n    }\n\n\ndef embed_file(path: Path) -> dict:\n    \"\"\"Read a file and return an embedded representation.\"\"\"\n    ext = path.suffix.lower()\n    mime = get_mime_type(path)\n\n    if ext in TEXT_EXTENSIONS:\n        try:\n            content = path.read_text(errors=\"replace\")\n        except OSError:\n            content = \"(Error reading file)\"\n        return {\n            \"name\": path.name,\n            \"type\": \"text\",\n            \"content\": content,\n        }\n    elif ext in IMAGE_EXTENSIONS:\n        try:\n            raw = path.read_bytes()\n            b64 = base64.b64encode(raw).decode(\"ascii\")\n        except OSError:\n            return {\"name\": path.name, \"type\": \"error\", \"content\": \"(Error reading file)\"}\n        return {\n            \"name\": path.name,\n            \"type\": \"image\",\n            \"mime\": mime,\n            \"data_uri\": f\"data:{mime};base64,{b64}\",\n        }\n    elif ext == \".pdf\":\n        try:\n            raw = path.read_bytes()\n            b64 = base64.b64encode(raw).decode(\"ascii\")\n        except OSError:\n            return {\"name\": path.name, \"type\": \"error\", \"content\": \"(Error reading file)\"}\n        return {\n            \"name\": path.name,\n            \"type\": \"pdf\",\n            \"data_uri\": f\"data:{mime};base64,{b64}\",\n        }\n    elif ext == \".xlsx\":\n        try:\n            raw = path.read_bytes()\n            b64 = base64.b64encode(raw).decode(\"ascii\")\n        except OSError:\n            return {\"name\": path.name, \"type\": \"error\", \"content\": \"(Error reading file)\"}\n        return {\n            \"name\": path.name,\n            \"type\": \"xlsx\",\n            \"data_b64\": b64,\n        }\n    else:\n        # Binary / unknown — base64 download link\n        try:\n            raw = path.read_bytes()\n            b64 = base64.b64encode(raw).decode(\"ascii\")\n        except OSError:\n            return {\"name\": path.name, \"type\": \"error\", \"content\": \"(Error reading file)\"}\n        return {\n            \"name\": path.name,\n            \"type\": \"binary\",\n            \"mime\": mime,\n            \"data_uri\": f\"data:{mime};base64,{b64}\",\n        }\n\n\ndef load_previous_iteration(workspace: Path) -> dict[str, dict]:\n    \"\"\"Load previous iteration's feedback and outputs.\n\n    Returns a map of run_id -> {\"feedback\": str, \"outputs\": list[dict]}.\n    \"\"\"\n    result: dict[str, dict] = {}\n\n    # Load feedback\n    feedback_map: dict[str, str] = {}\n    feedback_path = workspace / \"feedback.json\"\n    if feedback_path.exists():\n        try:\n            data = json.loads(feedback_path.read_text())\n            feedback_map = {\n                r[\"run_id\"]: r[\"feedback\"]\n                for r in data.get(\"reviews\", [])\n                if r.get(\"feedback\", \"\").strip()\n            }\n        except (json.JSONDecodeError, OSError, KeyError):\n            pass\n\n    # Load runs (to get outputs)\n    prev_runs = find_runs(workspace)\n    for run in prev_runs:\n        result[run[\"id\"]] = {\n            \"feedback\": feedback_map.get(run[\"id\"], \"\"),\n            \"outputs\": run.get(\"outputs\", []),\n        }\n\n    # Also add feedback for run_ids that had feedback but no matching run\n    for run_id, fb in feedback_map.items():\n        if run_id not in result:\n            result[run_id] = {\"feedback\": fb, \"outputs\": []}\n\n    return result\n\n\ndef generate_html(\n    runs: list[dict],\n    skill_name: str,\n    previous: dict[str, dict] | None = None,\n    benchmark: dict | None = None,\n) -> str:\n    \"\"\"Generate the complete standalone HTML page with embedded data.\"\"\"\n    template_path = Path(__file__).parent / \"viewer.html\"\n    template = template_path.read_text()\n\n    # Build previous_feedback and previous_outputs maps for the template\n    previous_feedback: dict[str, str] = {}\n    previous_outputs: dict[str, list[dict]] = {}\n    if previous:\n        for run_id, data in previous.items():\n            if data.get(\"feedback\"):\n                previous_feedback[run_id] = data[\"feedback\"]\n            if data.get(\"outputs\"):\n                previous_outputs[run_id] = data[\"outputs\"]\n\n    embedded = {\n        \"skill_name\": skill_name,\n        \"runs\": runs,\n        \"previous_feedback\": previous_feedback,\n        \"previous_outputs\": previous_outputs,\n    }\n    if benchmark:\n        embedded[\"benchmark\"] = benchmark\n\n    data_json = json.dumps(embedded)\n\n    return template.replace(\"/*__EMBEDDED_DATA__*/\", f\"const EMBEDDED_DATA = {data_json};\")\n\n\n# ---------------------------------------------------------------------------\n# HTTP server (stdlib only, zero dependencies)\n# ---------------------------------------------------------------------------\n\ndef _kill_port(port: int) -> None:\n    \"\"\"Kill any process listening on the given port.\"\"\"\n    try:\n        result = subprocess.run(\n            [\"lsof\", \"-ti\", f\":{port}\"],\n            capture_output=True, text=True, timeout=5,\n        )\n        for pid_str in result.stdout.strip().split(\"\\n\"):\n            if pid_str.strip():\n                try:\n                    os.kill(int(pid_str.strip()), signal.SIGTERM)\n                except (ProcessLookupError, ValueError):\n                    pass\n        if result.stdout.strip():\n            time.sleep(0.5)\n    except subprocess.TimeoutExpired:\n        pass\n    except FileNotFoundError:\n        print(\"Note: lsof not found, cannot check if port is in use\", file=sys.stderr)\n\nclass ReviewHandler(BaseHTTPRequestHandler):\n    \"\"\"Serves the review HTML and handles feedback saves.\n\n    Regenerates the HTML on each page load so that refreshing the browser\n    picks up new eval outputs without restarting the server.\n    \"\"\"\n\n    def __init__(\n        self,\n        workspace: Path,\n        skill_name: str,\n        feedback_path: Path,\n        previous: dict[str, dict],\n        benchmark_path: Path | None,\n        *args,\n        **kwargs,\n    ):\n        self.workspace = workspace\n        self.skill_name = skill_name\n        self.feedback_path = feedback_path\n        self.previous = previous\n        self.benchmark_path = benchmark_path\n        super().__init__(*args, **kwargs)\n\n    def do_GET(self) -> None:\n        if self.path == \"/\" or self.path == \"/index.html\":\n            # Regenerate HTML on each request (re-scans workspace for new outputs)\n            runs = find_runs(self.workspace)\n            benchmark = None\n            if self.benchmark_path and self.benchmark_path.exists():\n                try:\n                    benchmark = json.loads(self.benchmark_path.read_text())\n                except (json.JSONDecodeError, OSError):\n                    pass\n            html = generate_html(runs, self.skill_name, self.previous, benchmark)\n            content = html.encode(\"utf-8\")\n            self.send_response(200)\n            self.send_header(\"Content-Type\", \"text/html; charset=utf-8\")\n            self.send_header(\"Content-Length\", str(len(content)))\n            self.end_headers()\n            self.wfile.write(content)\n        elif self.path == \"/api/feedback\":\n            data = b\"{}\"\n            if self.feedback_path.exists():\n                data = self.feedback_path.read_bytes()\n            self.send_response(200)\n            self.send_header(\"Content-Type\", \"application/json\")\n            self.send_header(\"Content-Length\", str(len(data)))\n            self.end_headers()\n            self.wfile.write(data)\n        else:\n            self.send_error(404)\n\n    def do_POST(self) -> None:\n        if self.path == \"/api/feedback\":\n            length = int(self.headers.get(\"Content-Length\", 0))\n            body = self.rfile.read(length)\n            try:\n                data = json.loads(body)\n                if not isinstance(data, dict) or \"reviews\" not in data:\n                    raise ValueError(\"Expected JSON object with 'reviews' key\")\n                self.feedback_path.write_text(json.dumps(data, indent=2) + \"\\n\")\n                resp = b'{\"ok\":true}'\n                self.send_response(200)\n            except (json.JSONDecodeError, OSError, ValueError) as e:\n                resp = json.dumps({\"error\": str(e)}).encode()\n                self.send_response(500)\n            self.send_header(\"Content-Type\", \"application/json\")\n            self.send_header(\"Content-Length\", str(len(resp)))\n            self.end_headers()\n            self.wfile.write(resp)\n        else:\n            self.send_error(404)\n\n    def log_message(self, format: str, *args: object) -> None:\n        # Suppress request logging to keep terminal clean\n        pass\n\n\ndef main() -> None:\n    parser = argparse.ArgumentParser(description=\"Generate and serve eval review\")\n    parser.add_argument(\"workspace\", type=Path, help=\"Path to workspace directory\")\n    parser.add_argument(\"--port\", \"-p\", type=int, default=3117, help=\"Server port (default: 3117)\")\n    parser.add_argument(\"--skill-name\", \"-n\", type=str, default=None, help=\"Skill name for header\")\n    parser.add_argument(\n        \"--previous-workspace\", type=Path, default=None,\n        help=\"Path to previous iteration's workspace (shows old outputs and feedback as context)\",\n    )\n    parser.add_argument(\n        \"--benchmark\", type=Path, default=None,\n        help=\"Path to benchmark.json to show in the Benchmark tab\",\n    )\n    parser.add_argument(\n        \"--static\", \"-s\", type=Path, default=None,\n        help=\"Write standalone HTML to this path instead of starting a server\",\n    )\n    args = parser.parse_args()\n\n    workspace = args.workspace.resolve()\n    if not workspace.is_dir():\n        print(f\"Error: {workspace} is not a directory\", file=sys.stderr)\n        sys.exit(1)\n\n    runs = find_runs(workspace)\n    if not runs:\n        print(f\"No runs found in {workspace}\", file=sys.stderr)\n        sys.exit(1)\n\n    skill_name = args.skill_name or workspace.name.replace(\"-workspace\", \"\")\n    feedback_path = workspace / \"feedback.json\"\n\n    previous: dict[str, dict] = {}\n    if args.previous_workspace:\n        previous = load_previous_iteration(args.previous_workspace.resolve())\n\n    benchmark_path = args.benchmark.resolve() if args.benchmark else None\n    benchmark = None\n    if benchmark_path and benchmark_path.exists():\n        try:\n            benchmark = json.loads(benchmark_path.read_text())\n        except (json.JSONDecodeError, OSError):\n            pass\n\n    if args.static:\n        html = generate_html(runs, skill_name, previous, benchmark)\n        args.static.parent.mkdir(parents=True, exist_ok=True)\n        args.static.write_text(html)\n        print(f\"\\n  Static viewer written to: {args.static}\\n\")\n        sys.exit(0)\n\n    # Kill any existing process on the target port\n    port = args.port\n    _kill_port(port)\n    handler = partial(ReviewHandler, workspace, skill_name, feedback_path, previous, benchmark_path)\n    try:\n        server = HTTPServer((\"127.0.0.1\", port), handler)\n    except OSError:\n        # Port still in use after kill attempt — find a free one\n        server = HTTPServer((\"127.0.0.1\", 0), handler)\n        port = server.server_address[1]\n\n    url = f\"http://localhost:{port}\"\n    print(f\"\\n  Eval Viewer\")\n    print(f\"  ─────────────────────────────────\")\n    print(f\"  URL:       {url}\")\n    print(f\"  Workspace: {workspace}\")\n    print(f\"  Feedback:  {feedback_path}\")\n    if previous:\n        print(f\"  Previous:  {args.previous_workspace} ({len(previous)} runs)\")\n    if benchmark_path:\n        print(f\"  Benchmark: {benchmark_path}\")\n    print(f\"\\n  Press Ctrl+C to stop.\\n\")\n\n    webbrowser.open(url)\n\n    try:\n        server.serve_forever()\n    except KeyboardInterrupt:\n        print(\"\\nStopped.\")\n        server.server_close()\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": ".claude/skills/skill-creator/eval-viewer/viewer.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n  <title>Eval Review</title>\n  <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n  <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n  <link href=\"https://fonts.googleapis.com/css2?family=Poppins:wght@500;600&family=Lora:wght@400;500&display=swap\" rel=\"stylesheet\">\n  <script src=\"https://cdn.sheetjs.com/xlsx-0.20.3/package/dist/xlsx.full.min.js\" integrity=\"sha384-EnyY0/GSHQGSxSgMwaIPzSESbqoOLSexfnSMN2AP+39Ckmn92stwABZynq1JyzdT\" crossorigin=\"anonymous\"></script>\n  <style>\n    :root {\n      --bg: #faf9f5;\n      --surface: #ffffff;\n      --border: #e8e6dc;\n      --text: #141413;\n      --text-muted: #b0aea5;\n      --accent: #d97757;\n      --accent-hover: #c4613f;\n      --green: #788c5d;\n      --green-bg: #eef2e8;\n      --red: #c44;\n      --red-bg: #fceaea;\n      --header-bg: #141413;\n      --header-text: #faf9f5;\n      --radius: 6px;\n    }\n\n    * { box-sizing: border-box; margin: 0; padding: 0; }\n\n    body {\n      font-family: 'Lora', Georgia, serif;\n      background: var(--bg);\n      color: var(--text);\n      height: 100vh;\n      display: flex;\n      flex-direction: column;\n    }\n\n    /* ---- Header ---- */\n    .header {\n      background: var(--header-bg);\n      color: var(--header-text);\n      padding: 1rem 2rem;\n      display: flex;\n      justify-content: space-between;\n      align-items: center;\n      flex-shrink: 0;\n    }\n    .header h1 {\n      font-family: 'Poppins', sans-serif;\n      font-size: 1.25rem;\n      font-weight: 600;\n    }\n    .header .instructions {\n      font-size: 0.8rem;\n      opacity: 0.7;\n      margin-top: 0.25rem;\n    }\n    .header .progress {\n      font-size: 0.875rem;\n      opacity: 0.8;\n      text-align: right;\n    }\n\n    /* ---- Main content ---- */\n    .main {\n      flex: 1;\n      overflow-y: auto;\n      padding: 1.5rem 2rem;\n      display: flex;\n      flex-direction: column;\n      gap: 1.25rem;\n    }\n\n    /* ---- Sections ---- */\n    .section {\n      background: var(--surface);\n      border: 1px solid var(--border);\n      border-radius: var(--radius);\n      flex-shrink: 0;\n    }\n    .section-header {\n      font-family: 'Poppins', sans-serif;\n      padding: 0.75rem 1rem;\n      font-size: 0.75rem;\n      font-weight: 500;\n      text-transform: uppercase;\n      letter-spacing: 0.05em;\n      color: var(--text-muted);\n      border-bottom: 1px solid var(--border);\n      background: var(--bg);\n    }\n    .section-body {\n      padding: 1rem;\n    }\n\n    /* ---- Config badge ---- */\n    .config-badge {\n      display: inline-block;\n      padding: 0.2rem 0.625rem;\n      border-radius: 9999px;\n      font-family: 'Poppins', sans-serif;\n      font-size: 0.6875rem;\n      font-weight: 600;\n      text-transform: uppercase;\n      letter-spacing: 0.03em;\n      margin-left: 0.75rem;\n      vertical-align: middle;\n    }\n    .config-badge.config-primary {\n      background: rgba(33, 150, 243, 0.12);\n      color: #1976d2;\n    }\n    .config-badge.config-baseline {\n      background: rgba(255, 193, 7, 0.15);\n      color: #f57f17;\n    }\n\n    /* ---- Prompt ---- */\n    .prompt-text {\n      white-space: pre-wrap;\n      font-size: 0.9375rem;\n      line-height: 1.6;\n    }\n\n    /* ---- Outputs ---- */\n    .output-file {\n      border: 1px solid var(--border);\n      border-radius: var(--radius);\n      overflow: hidden;\n    }\n    .output-file + .output-file {\n      margin-top: 1rem;\n    }\n    .output-file-header {\n      padding: 0.5rem 0.75rem;\n      font-size: 0.8rem;\n      font-weight: 600;\n      color: var(--text-muted);\n      background: var(--bg);\n      border-bottom: 1px solid var(--border);\n      font-family: 'SF Mono', SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;\n      display: flex;\n      justify-content: space-between;\n      align-items: center;\n    }\n    .output-file-header .dl-btn {\n      font-size: 0.7rem;\n      color: var(--accent);\n      text-decoration: none;\n      cursor: pointer;\n      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;\n      font-weight: 500;\n      opacity: 0.8;\n    }\n    .output-file-header .dl-btn:hover {\n      opacity: 1;\n      text-decoration: underline;\n    }\n    .output-file-content {\n      padding: 0.75rem;\n      overflow-x: auto;\n    }\n    .output-file-content pre {\n      font-size: 0.8125rem;\n      line-height: 1.5;\n      white-space: pre-wrap;\n      word-break: break-word;\n      font-family: 'SF Mono', SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;\n    }\n    .output-file-content img {\n      max-width: 100%;\n      height: auto;\n      border-radius: 4px;\n    }\n    .output-file-content iframe {\n      width: 100%;\n      height: 600px;\n      border: none;\n    }\n    .output-file-content table {\n      border-collapse: collapse;\n      font-size: 0.8125rem;\n      width: 100%;\n    }\n    .output-file-content table td,\n    .output-file-content table th {\n      border: 1px solid var(--border);\n      padding: 0.375rem 0.5rem;\n      text-align: left;\n    }\n    .output-file-content table th {\n      background: var(--bg);\n      font-weight: 600;\n    }\n    .output-file-content .download-link {\n      display: inline-flex;\n      align-items: center;\n      gap: 0.5rem;\n      padding: 0.5rem 1rem;\n      background: var(--bg);\n      border: 1px solid var(--border);\n      border-radius: 4px;\n      color: var(--accent);\n      text-decoration: none;\n      font-size: 0.875rem;\n      cursor: pointer;\n    }\n    .output-file-content .download-link:hover {\n      background: var(--border);\n    }\n    .empty-state {\n      color: var(--text-muted);\n      font-style: italic;\n      padding: 2rem;\n      text-align: center;\n    }\n\n    /* ---- Feedback ---- */\n    .prev-feedback {\n      background: var(--bg);\n      border: 1px solid var(--border);\n      border-radius: 4px;\n      padding: 0.625rem 0.75rem;\n      margin-top: 0.75rem;\n      font-size: 0.8125rem;\n      color: var(--text-muted);\n      line-height: 1.5;\n    }\n    .prev-feedback-label {\n      font-size: 0.7rem;\n      font-weight: 600;\n      text-transform: uppercase;\n      letter-spacing: 0.04em;\n      margin-bottom: 0.25rem;\n      color: var(--text-muted);\n    }\n    .feedback-textarea {\n      width: 100%;\n      min-height: 100px;\n      padding: 0.75rem;\n      border: 1px solid var(--border);\n      border-radius: 4px;\n      font-family: inherit;\n      font-size: 0.9375rem;\n      line-height: 1.5;\n      resize: vertical;\n      color: var(--text);\n    }\n    .feedback-textarea:focus {\n      outline: none;\n      border-color: var(--accent);\n      box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);\n    }\n    .feedback-status {\n      font-size: 0.75rem;\n      color: var(--text-muted);\n      margin-top: 0.5rem;\n      min-height: 1.1em;\n    }\n\n    /* ---- Grades (collapsible) ---- */\n    .grades-toggle {\n      display: flex;\n      align-items: center;\n      cursor: pointer;\n      user-select: none;\n    }\n    .grades-toggle:hover {\n      color: var(--accent);\n    }\n    .grades-toggle .arrow {\n      margin-right: 0.5rem;\n      transition: transform 0.15s;\n      font-size: 0.75rem;\n    }\n    .grades-toggle .arrow.open {\n      transform: rotate(90deg);\n    }\n    .grades-content {\n      display: none;\n      margin-top: 0.75rem;\n    }\n    .grades-content.open {\n      display: block;\n    }\n    .grades-summary {\n      font-size: 0.875rem;\n      margin-bottom: 0.75rem;\n      display: flex;\n      align-items: center;\n      gap: 0.5rem;\n    }\n    .grade-badge {\n      display: inline-block;\n      padding: 0.125rem 0.5rem;\n      border-radius: 9999px;\n      font-size: 0.75rem;\n      font-weight: 600;\n    }\n    .grade-pass { background: var(--green-bg); color: var(--green); }\n    .grade-fail { background: var(--red-bg); color: var(--red); }\n    .assertion-list {\n      list-style: none;\n    }\n    .assertion-item {\n      padding: 0.625rem 0;\n      border-bottom: 1px solid var(--border);\n      font-size: 0.8125rem;\n    }\n    .assertion-item:last-child { border-bottom: none; }\n    .assertion-status {\n      font-weight: 600;\n      margin-right: 0.5rem;\n    }\n    .assertion-status.pass { color: var(--green); }\n    .assertion-status.fail { color: var(--red); }\n    .assertion-evidence {\n      color: var(--text-muted);\n      font-size: 0.75rem;\n      margin-top: 0.25rem;\n      padding-left: 1.5rem;\n    }\n\n    /* ---- View tabs ---- */\n    .view-tabs {\n      display: flex;\n      gap: 0;\n      padding: 0 2rem;\n      background: var(--bg);\n      border-bottom: 1px solid var(--border);\n      flex-shrink: 0;\n    }\n    .view-tab {\n      font-family: 'Poppins', sans-serif;\n      padding: 0.625rem 1.25rem;\n      font-size: 0.8125rem;\n      font-weight: 500;\n      cursor: pointer;\n      border: none;\n      background: none;\n      color: var(--text-muted);\n      border-bottom: 2px solid transparent;\n      transition: all 0.15s;\n    }\n    .view-tab:hover { color: var(--text); }\n    .view-tab.active {\n      color: var(--accent);\n      border-bottom-color: var(--accent);\n    }\n    .view-panel { display: none; }\n    .view-panel.active { display: flex; flex-direction: column; flex: 1; overflow: hidden; }\n\n    /* ---- Benchmark view ---- */\n    .benchmark-view {\n      padding: 1.5rem 2rem;\n      overflow-y: auto;\n      flex: 1;\n    }\n    .benchmark-table {\n      border-collapse: collapse;\n      background: var(--surface);\n      border: 1px solid var(--border);\n      border-radius: var(--radius);\n      font-size: 0.8125rem;\n      width: 100%;\n      margin-bottom: 1.5rem;\n    }\n    .benchmark-table th, .benchmark-table td {\n      padding: 0.625rem 0.75rem;\n      text-align: left;\n      border: 1px solid var(--border);\n    }\n    .benchmark-table th {\n      font-family: 'Poppins', sans-serif;\n      background: var(--header-bg);\n      color: var(--header-text);\n      font-weight: 500;\n      font-size: 0.75rem;\n      text-transform: uppercase;\n      letter-spacing: 0.04em;\n    }\n    .benchmark-table tr:hover { background: var(--bg); }\n    .benchmark-table tr.benchmark-row-with { background: rgba(33, 150, 243, 0.06); }\n    .benchmark-table tr.benchmark-row-without { background: rgba(255, 193, 7, 0.06); }\n    .benchmark-table tr.benchmark-row-with:hover { background: rgba(33, 150, 243, 0.12); }\n    .benchmark-table tr.benchmark-row-without:hover { background: rgba(255, 193, 7, 0.12); }\n    .benchmark-table tr.benchmark-row-avg { font-weight: 600; border-top: 2px solid var(--border); }\n    .benchmark-table tr.benchmark-row-avg.benchmark-row-with { background: rgba(33, 150, 243, 0.12); }\n    .benchmark-table tr.benchmark-row-avg.benchmark-row-without { background: rgba(255, 193, 7, 0.12); }\n    .benchmark-delta-positive { color: var(--green); font-weight: 600; }\n    .benchmark-delta-negative { color: var(--red); font-weight: 600; }\n    .benchmark-notes {\n      background: var(--surface);\n      border: 1px solid var(--border);\n      border-radius: var(--radius);\n      padding: 1rem;\n    }\n    .benchmark-notes h3 {\n      font-family: 'Poppins', sans-serif;\n      font-size: 0.875rem;\n      margin-bottom: 0.75rem;\n    }\n    .benchmark-notes ul {\n      list-style: disc;\n      padding-left: 1.25rem;\n    }\n    .benchmark-notes li {\n      font-size: 0.8125rem;\n      line-height: 1.6;\n      margin-bottom: 0.375rem;\n    }\n    .benchmark-empty {\n      color: var(--text-muted);\n      font-style: italic;\n      text-align: center;\n      padding: 3rem;\n    }\n\n    /* ---- Navigation ---- */\n    .nav {\n      display: flex;\n      justify-content: space-between;\n      align-items: center;\n      padding: 1rem 2rem;\n      border-top: 1px solid var(--border);\n      background: var(--surface);\n      flex-shrink: 0;\n    }\n    .nav-btn {\n      font-family: 'Poppins', sans-serif;\n      padding: 0.5rem 1.25rem;\n      border: 1px solid var(--border);\n      border-radius: var(--radius);\n      background: var(--surface);\n      cursor: pointer;\n      font-size: 0.875rem;\n      font-weight: 500;\n      color: var(--text);\n      transition: all 0.15s;\n    }\n    .nav-btn:hover:not(:disabled) {\n      background: var(--bg);\n      border-color: var(--text-muted);\n    }\n    .nav-btn:disabled {\n      opacity: 0.4;\n      cursor: not-allowed;\n    }\n    .done-btn {\n      font-family: 'Poppins', sans-serif;\n      padding: 0.5rem 1.5rem;\n      border: 1px solid var(--border);\n      border-radius: var(--radius);\n      background: var(--surface);\n      color: var(--text);\n      cursor: pointer;\n      font-size: 0.875rem;\n      font-weight: 500;\n      transition: all 0.15s;\n    }\n    .done-btn:hover {\n      background: var(--bg);\n      border-color: var(--text-muted);\n    }\n    .done-btn.ready {\n      border: none;\n      background: var(--accent);\n      color: white;\n      font-weight: 600;\n    }\n    .done-btn.ready:hover {\n      background: var(--accent-hover);\n    }\n    /* ---- Done overlay ---- */\n    .done-overlay {\n      display: none;\n      position: fixed;\n      inset: 0;\n      background: rgba(0, 0, 0, 0.5);\n      z-index: 100;\n      justify-content: center;\n      align-items: center;\n    }\n    .done-overlay.visible {\n      display: flex;\n    }\n    .done-card {\n      background: var(--surface);\n      border-radius: 12px;\n      padding: 2rem 3rem;\n      text-align: center;\n      box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);\n      max-width: 500px;\n    }\n    .done-card h2 {\n      font-size: 1.5rem;\n      margin-bottom: 0.5rem;\n    }\n    .done-card p {\n      color: var(--text-muted);\n      margin-bottom: 1.5rem;\n      line-height: 1.5;\n    }\n    .done-card .btn-row {\n      display: flex;\n      gap: 0.5rem;\n      justify-content: center;\n    }\n    .done-card button {\n      padding: 0.5rem 1.25rem;\n      border: 1px solid var(--border);\n      border-radius: var(--radius);\n      background: var(--surface);\n      cursor: pointer;\n      font-size: 0.875rem;\n    }\n    .done-card button:hover {\n      background: var(--bg);\n    }\n    /* ---- Toast ---- */\n    .toast {\n      position: fixed;\n      bottom: 5rem;\n      left: 50%;\n      transform: translateX(-50%);\n      background: var(--header-bg);\n      color: var(--header-text);\n      padding: 0.625rem 1.25rem;\n      border-radius: var(--radius);\n      font-size: 0.875rem;\n      opacity: 0;\n      transition: opacity 0.3s;\n      pointer-events: none;\n      z-index: 200;\n    }\n    .toast.visible {\n      opacity: 1;\n    }\n  </style>\n</head>\n<body>\n  <div id=\"app\" style=\"height:100vh; display:flex; flex-direction:column;\">\n    <div class=\"header\">\n      <div>\n        <h1>Eval Review: <span id=\"skill-name\"></span></h1>\n        <div class=\"instructions\">Review each output and leave feedback below. Navigate with arrow keys or buttons. When done, copy feedback and paste into Claude Code.</div>\n      </div>\n      <div class=\"progress\" id=\"progress\"></div>\n    </div>\n\n    <!-- View tabs (only shown when benchmark data exists) -->\n    <div class=\"view-tabs\" id=\"view-tabs\" style=\"display:none;\">\n      <button class=\"view-tab active\" onclick=\"switchView('outputs')\">Outputs</button>\n      <button class=\"view-tab\" onclick=\"switchView('benchmark')\">Benchmark</button>\n    </div>\n\n    <!-- Outputs panel (qualitative review) -->\n    <div class=\"view-panel active\" id=\"panel-outputs\">\n    <div class=\"main\">\n      <!-- Prompt -->\n      <div class=\"section\">\n        <div class=\"section-header\">Prompt <span class=\"config-badge\" id=\"config-badge\" style=\"display:none;\"></span></div>\n        <div class=\"section-body\">\n          <div class=\"prompt-text\" id=\"prompt-text\"></div>\n        </div>\n      </div>\n\n      <!-- Outputs -->\n      <div class=\"section\">\n        <div class=\"section-header\">Output</div>\n        <div class=\"section-body\" id=\"outputs-body\">\n          <div class=\"empty-state\">No output files found</div>\n        </div>\n      </div>\n\n      <!-- Previous Output (collapsible) -->\n      <div class=\"section\" id=\"prev-outputs-section\" style=\"display:none;\">\n        <div class=\"section-header\">\n          <div class=\"grades-toggle\" onclick=\"togglePrevOutputs()\">\n            <span class=\"arrow\" id=\"prev-outputs-arrow\">&#9654;</span>\n            Previous Output\n          </div>\n        </div>\n        <div class=\"grades-content\" id=\"prev-outputs-content\"></div>\n      </div>\n\n      <!-- Grades (collapsible) -->\n      <div class=\"section\" id=\"grades-section\" style=\"display:none;\">\n        <div class=\"section-header\">\n          <div class=\"grades-toggle\" onclick=\"toggleGrades()\">\n            <span class=\"arrow\" id=\"grades-arrow\">&#9654;</span>\n            Formal Grades\n          </div>\n        </div>\n        <div class=\"grades-content\" id=\"grades-content\"></div>\n      </div>\n\n      <!-- Feedback -->\n      <div class=\"section\">\n        <div class=\"section-header\">Your Feedback</div>\n        <div class=\"section-body\">\n          <textarea\n            class=\"feedback-textarea\"\n            id=\"feedback\"\n            placeholder=\"What do you think of this output? Any issues, suggestions, or things that look great?\"\n          ></textarea>\n          <div class=\"feedback-status\" id=\"feedback-status\"></div>\n          <div class=\"prev-feedback\" id=\"prev-feedback\" style=\"display:none;\">\n            <div class=\"prev-feedback-label\">Previous feedback</div>\n            <div id=\"prev-feedback-text\"></div>\n          </div>\n        </div>\n      </div>\n    </div>\n\n    <div class=\"nav\" id=\"outputs-nav\">\n      <button class=\"nav-btn\" id=\"prev-btn\" onclick=\"navigate(-1)\">&#8592; Previous</button>\n      <button class=\"done-btn\" id=\"done-btn\" onclick=\"showDoneDialog()\">Submit All Reviews</button>\n      <button class=\"nav-btn\" id=\"next-btn\" onclick=\"navigate(1)\">Next &#8594;</button>\n    </div>\n    </div><!-- end panel-outputs -->\n\n    <!-- Benchmark panel (quantitative stats) -->\n    <div class=\"view-panel\" id=\"panel-benchmark\">\n      <div class=\"benchmark-view\" id=\"benchmark-content\">\n        <div class=\"benchmark-empty\">No benchmark data available. Run a benchmark to see quantitative results here.</div>\n      </div>\n    </div>\n  </div>\n\n  <!-- Done overlay -->\n  <div class=\"done-overlay\" id=\"done-overlay\">\n    <div class=\"done-card\">\n      <h2>Review Complete</h2>\n      <p>Your feedback has been saved. Go back to your Claude Code session and tell Claude you're done reviewing.</p>\n      <div class=\"btn-row\">\n        <button onclick=\"closeDoneDialog()\">OK</button>\n      </div>\n    </div>\n  </div>\n\n  <!-- Toast -->\n  <div class=\"toast\" id=\"toast\"></div>\n\n  <script>\n    // ---- Embedded data (injected by generate_review.py) ----\n    /*__EMBEDDED_DATA__*/\n\n    // ---- State ----\n    let feedbackMap = {};  // run_id -> feedback text\n    let currentIndex = 0;\n    let visitedRuns = new Set();\n\n    // ---- Init ----\n    async function init() {\n      // Load saved feedback from server — but only if this isn't a fresh\n      // iteration (indicated by previous_feedback being present). When\n      // previous feedback exists, the feedback.json on disk is stale from\n      // the prior iteration and should not pre-fill the textareas.\n      const hasPrevious = Object.keys(EMBEDDED_DATA.previous_feedback || {}).length > 0\n        || Object.keys(EMBEDDED_DATA.previous_outputs || {}).length > 0;\n      if (!hasPrevious) {\n        try {\n          const resp = await fetch(\"/api/feedback\");\n          const data = await resp.json();\n          if (data.reviews) {\n            for (const r of data.reviews) feedbackMap[r.run_id] = r.feedback;\n          }\n        } catch { /* first run, no feedback yet */ }\n      }\n\n      document.getElementById(\"skill-name\").textContent = EMBEDDED_DATA.skill_name;\n      showRun(0);\n\n      // Wire up feedback auto-save\n      const textarea = document.getElementById(\"feedback\");\n      let saveTimeout = null;\n      textarea.addEventListener(\"input\", () => {\n        clearTimeout(saveTimeout);\n        document.getElementById(\"feedback-status\").textContent = \"\";\n        saveTimeout = setTimeout(() => saveCurrentFeedback(), 800);\n      });\n    }\n\n    // ---- Navigation ----\n    function navigate(delta) {\n      const newIndex = currentIndex + delta;\n      if (newIndex >= 0 && newIndex < EMBEDDED_DATA.runs.length) {\n        saveCurrentFeedback();\n        showRun(newIndex);\n      }\n    }\n\n    function updateNavButtons() {\n      document.getElementById(\"prev-btn\").disabled = currentIndex === 0;\n      document.getElementById(\"next-btn\").disabled =\n        currentIndex === EMBEDDED_DATA.runs.length - 1;\n    }\n\n    // ---- Show a run ----\n    function showRun(index) {\n      currentIndex = index;\n      const run = EMBEDDED_DATA.runs[index];\n\n      // Progress\n      document.getElementById(\"progress\").textContent =\n        `${index + 1} of ${EMBEDDED_DATA.runs.length}`;\n\n      // Prompt\n      document.getElementById(\"prompt-text\").textContent = run.prompt;\n\n      // Config badge\n      const badge = document.getElementById(\"config-badge\");\n      const configMatch = run.id.match(/(with_skill|without_skill|new_skill|old_skill)/);\n      if (configMatch) {\n        const config = configMatch[1];\n        const isBaseline = config === \"without_skill\" || config === \"old_skill\";\n        badge.textContent = config.replace(/_/g, \" \");\n        badge.className = \"config-badge \" + (isBaseline ? \"config-baseline\" : \"config-primary\");\n        badge.style.display = \"inline-block\";\n      } else {\n        badge.style.display = \"none\";\n      }\n\n      // Outputs\n      renderOutputs(run);\n\n      // Previous outputs\n      renderPrevOutputs(run);\n\n      // Grades\n      renderGrades(run);\n\n      // Previous feedback\n      const prevFb = (EMBEDDED_DATA.previous_feedback || {})[run.id];\n      const prevEl = document.getElementById(\"prev-feedback\");\n      if (prevFb) {\n        document.getElementById(\"prev-feedback-text\").textContent = prevFb;\n        prevEl.style.display = \"block\";\n      } else {\n        prevEl.style.display = \"none\";\n      }\n\n      // Feedback\n      document.getElementById(\"feedback\").value = feedbackMap[run.id] || \"\";\n      document.getElementById(\"feedback-status\").textContent = \"\";\n\n      updateNavButtons();\n\n      // Track visited runs and promote done button when all visited\n      visitedRuns.add(index);\n      const doneBtn = document.getElementById(\"done-btn\");\n      if (visitedRuns.size >= EMBEDDED_DATA.runs.length) {\n        doneBtn.classList.add(\"ready\");\n      }\n\n      // Scroll main content to top\n      document.querySelector(\".main\").scrollTop = 0;\n    }\n\n    // ---- Render outputs ----\n    function renderOutputs(run) {\n      const container = document.getElementById(\"outputs-body\");\n      container.innerHTML = \"\";\n\n      const outputs = run.outputs || [];\n      if (outputs.length === 0) {\n        container.innerHTML = '<div class=\"empty-state\">No output files</div>';\n        return;\n      }\n\n      for (const file of outputs) {\n        const fileDiv = document.createElement(\"div\");\n        fileDiv.className = \"output-file\";\n\n        // Always show file header with download link\n        const header = document.createElement(\"div\");\n        header.className = \"output-file-header\";\n        const nameSpan = document.createElement(\"span\");\n        nameSpan.textContent = file.name;\n        header.appendChild(nameSpan);\n        const dlBtn = document.createElement(\"a\");\n        dlBtn.className = \"dl-btn\";\n        dlBtn.textContent = \"Download\";\n        dlBtn.download = file.name;\n        dlBtn.href = getDownloadUri(file);\n        header.appendChild(dlBtn);\n        fileDiv.appendChild(header);\n\n        const content = document.createElement(\"div\");\n        content.className = \"output-file-content\";\n\n        if (file.type === \"text\") {\n          const pre = document.createElement(\"pre\");\n          pre.textContent = file.content;\n          content.appendChild(pre);\n        } else if (file.type === \"image\") {\n          const img = document.createElement(\"img\");\n          img.src = file.data_uri;\n          img.alt = file.name;\n          content.appendChild(img);\n        } else if (file.type === \"pdf\") {\n          const iframe = document.createElement(\"iframe\");\n          iframe.src = file.data_uri;\n          content.appendChild(iframe);\n        } else if (file.type === \"xlsx\") {\n          renderXlsx(content, file.data_b64);\n        } else if (file.type === \"binary\") {\n          const a = document.createElement(\"a\");\n          a.className = \"download-link\";\n          a.href = file.data_uri;\n          a.download = file.name;\n          a.textContent = \"Download \" + file.name;\n          content.appendChild(a);\n        } else if (file.type === \"error\") {\n          const pre = document.createElement(\"pre\");\n          pre.textContent = file.content;\n          pre.style.color = \"var(--red)\";\n          content.appendChild(pre);\n        }\n\n        fileDiv.appendChild(content);\n        container.appendChild(fileDiv);\n      }\n    }\n\n    // ---- XLSX rendering via SheetJS ----\n    function renderXlsx(container, b64Data) {\n      try {\n        const raw = Uint8Array.from(atob(b64Data), c => c.charCodeAt(0));\n        const wb = XLSX.read(raw, { type: \"array\" });\n\n        for (let i = 0; i < wb.SheetNames.length; i++) {\n          const sheetName = wb.SheetNames[i];\n          const ws = wb.Sheets[sheetName];\n\n          if (wb.SheetNames.length > 1) {\n            const sheetLabel = document.createElement(\"div\");\n            sheetLabel.style.cssText =\n              \"font-weight:600; font-size:0.8rem; color:#b0aea5; margin-top:0.5rem; margin-bottom:0.25rem;\";\n            sheetLabel.textContent = \"Sheet: \" + sheetName;\n            container.appendChild(sheetLabel);\n          }\n\n          const htmlStr = XLSX.utils.sheet_to_html(ws, { editable: false });\n          const wrapper = document.createElement(\"div\");\n          wrapper.innerHTML = htmlStr;\n          container.appendChild(wrapper);\n        }\n      } catch (err) {\n        container.textContent = \"Error rendering spreadsheet: \" + err.message;\n      }\n    }\n\n    // ---- Grades ----\n    function renderGrades(run) {\n      const section = document.getElementById(\"grades-section\");\n      const content = document.getElementById(\"grades-content\");\n\n      if (!run.grading) {\n        section.style.display = \"none\";\n        return;\n      }\n\n      const grading = run.grading;\n      section.style.display = \"block\";\n      // Reset to collapsed\n      content.classList.remove(\"open\");\n      document.getElementById(\"grades-arrow\").classList.remove(\"open\");\n\n      const summary = grading.summary || {};\n      const expectations = grading.expectations || [];\n\n      let html = '<div style=\"padding: 1rem;\">';\n\n      // Summary line\n      const passRate = summary.pass_rate != null\n        ? Math.round(summary.pass_rate * 100) + \"%\"\n        : \"?\";\n      const badgeClass = summary.pass_rate >= 0.8 ? \"grade-pass\" : summary.pass_rate >= 0.5 ? \"\" : \"grade-fail\";\n      html += '<div class=\"grades-summary\">';\n      html += '<span class=\"grade-badge ' + badgeClass + '\">' + passRate + '</span>';\n      html += '<span>' + (summary.passed || 0) + ' passed, ' + (summary.failed || 0) + ' failed of ' + (summary.total || 0) + '</span>';\n      html += '</div>';\n\n      // Assertions list\n      html += '<ul class=\"assertion-list\">';\n      for (const exp of expectations) {\n        const statusClass = exp.passed ? \"pass\" : \"fail\";\n        const statusIcon = exp.passed ? \"\\u2713\" : \"\\u2717\";\n        html += '<li class=\"assertion-item\">';\n        html += '<span class=\"assertion-status ' + statusClass + '\">' + statusIcon + '</span>';\n        html += '<span>' + escapeHtml(exp.text) + '</span>';\n        if (exp.evidence) {\n          html += '<div class=\"assertion-evidence\">' + escapeHtml(exp.evidence) + '</div>';\n        }\n        html += '</li>';\n      }\n      html += '</ul>';\n\n      html += '</div>';\n      content.innerHTML = html;\n    }\n\n    function toggleGrades() {\n      const content = document.getElementById(\"grades-content\");\n      const arrow = document.getElementById(\"grades-arrow\");\n      content.classList.toggle(\"open\");\n      arrow.classList.toggle(\"open\");\n    }\n\n    // ---- Previous outputs (collapsible) ----\n    function renderPrevOutputs(run) {\n      const section = document.getElementById(\"prev-outputs-section\");\n      const content = document.getElementById(\"prev-outputs-content\");\n      const prevOutputs = (EMBEDDED_DATA.previous_outputs || {})[run.id];\n\n      if (!prevOutputs || prevOutputs.length === 0) {\n        section.style.display = \"none\";\n        return;\n      }\n\n      section.style.display = \"block\";\n      // Reset to collapsed\n      content.classList.remove(\"open\");\n      document.getElementById(\"prev-outputs-arrow\").classList.remove(\"open\");\n\n      // Render the files into the content area\n      content.innerHTML = \"\";\n      const wrapper = document.createElement(\"div\");\n      wrapper.style.padding = \"1rem\";\n\n      for (const file of prevOutputs) {\n        const fileDiv = document.createElement(\"div\");\n        fileDiv.className = \"output-file\";\n\n        const header = document.createElement(\"div\");\n        header.className = \"output-file-header\";\n        const nameSpan = document.createElement(\"span\");\n        nameSpan.textContent = file.name;\n        header.appendChild(nameSpan);\n        const dlBtn = document.createElement(\"a\");\n        dlBtn.className = \"dl-btn\";\n        dlBtn.textContent = \"Download\";\n        dlBtn.download = file.name;\n        dlBtn.href = getDownloadUri(file);\n        header.appendChild(dlBtn);\n        fileDiv.appendChild(header);\n\n        const fc = document.createElement(\"div\");\n        fc.className = \"output-file-content\";\n\n        if (file.type === \"text\") {\n          const pre = document.createElement(\"pre\");\n          pre.textContent = file.content;\n          fc.appendChild(pre);\n        } else if (file.type === \"image\") {\n          const img = document.createElement(\"img\");\n          img.src = file.data_uri;\n          img.alt = file.name;\n          fc.appendChild(img);\n        } else if (file.type === \"pdf\") {\n          const iframe = document.createElement(\"iframe\");\n          iframe.src = file.data_uri;\n          fc.appendChild(iframe);\n        } else if (file.type === \"xlsx\") {\n          renderXlsx(fc, file.data_b64);\n        } else if (file.type === \"binary\") {\n          const a = document.createElement(\"a\");\n          a.className = \"download-link\";\n          a.href = file.data_uri;\n          a.download = file.name;\n          a.textContent = \"Download \" + file.name;\n          fc.appendChild(a);\n        }\n\n        fileDiv.appendChild(fc);\n        wrapper.appendChild(fileDiv);\n      }\n\n      content.appendChild(wrapper);\n    }\n\n    function togglePrevOutputs() {\n      const content = document.getElementById(\"prev-outputs-content\");\n      const arrow = document.getElementById(\"prev-outputs-arrow\");\n      content.classList.toggle(\"open\");\n      arrow.classList.toggle(\"open\");\n    }\n\n    // ---- Feedback (saved to server -> feedback.json) ----\n    function saveCurrentFeedback() {\n      const run = EMBEDDED_DATA.runs[currentIndex];\n      const text = document.getElementById(\"feedback\").value;\n\n      if (text.trim() === \"\") {\n        delete feedbackMap[run.id];\n      } else {\n        feedbackMap[run.id] = text;\n      }\n\n      // Build reviews array from map\n      const reviews = [];\n      for (const [run_id, feedback] of Object.entries(feedbackMap)) {\n        if (feedback.trim()) {\n          reviews.push({ run_id, feedback, timestamp: new Date().toISOString() });\n        }\n      }\n\n      fetch(\"/api/feedback\", {\n        method: \"POST\",\n        headers: { \"Content-Type\": \"application/json\" },\n        body: JSON.stringify({ reviews, status: \"in_progress\" }),\n      }).then(() => {\n        document.getElementById(\"feedback-status\").textContent = \"Saved\";\n      }).catch(() => {\n        // Static mode or server unavailable — no-op on auto-save,\n        // feedback will be downloaded on final submit\n        document.getElementById(\"feedback-status\").textContent = \"Will download on submit\";\n      });\n    }\n\n    // ---- Done ----\n    function showDoneDialog() {\n      // Save current textarea to feedbackMap (but don't POST yet)\n      const run = EMBEDDED_DATA.runs[currentIndex];\n      const text = document.getElementById(\"feedback\").value;\n      if (text.trim() === \"\") {\n        delete feedbackMap[run.id];\n      } else {\n        feedbackMap[run.id] = text;\n      }\n\n      // POST once with status: complete — include ALL runs so the model\n      // can distinguish \"no feedback\" (looks good) from \"not reviewed\"\n      const reviews = [];\n      const ts = new Date().toISOString();\n      for (const r of EMBEDDED_DATA.runs) {\n        reviews.push({ run_id: r.id, feedback: feedbackMap[r.id] || \"\", timestamp: ts });\n      }\n      const payload = JSON.stringify({ reviews, status: \"complete\" }, null, 2);\n      fetch(\"/api/feedback\", {\n        method: \"POST\",\n        headers: { \"Content-Type\": \"application/json\" },\n        body: payload,\n      }).then(() => {\n        document.getElementById(\"done-overlay\").classList.add(\"visible\");\n      }).catch(() => {\n        // Server not available (static mode) — download as file\n        const blob = new Blob([payload], { type: \"application/json\" });\n        const url = URL.createObjectURL(blob);\n        const a = document.createElement(\"a\");\n        a.href = url;\n        a.download = \"feedback.json\";\n        a.click();\n        URL.revokeObjectURL(url);\n        document.getElementById(\"done-overlay\").classList.add(\"visible\");\n      });\n    }\n\n    function closeDoneDialog() {\n      // Reset status back to in_progress\n      saveCurrentFeedback();\n      document.getElementById(\"done-overlay\").classList.remove(\"visible\");\n    }\n\n    // ---- Toast ----\n    function showToast(message) {\n      const toast = document.getElementById(\"toast\");\n      toast.textContent = message;\n      toast.classList.add(\"visible\");\n      setTimeout(() => toast.classList.remove(\"visible\"), 2000);\n    }\n\n    // ---- Keyboard nav ----\n    document.addEventListener(\"keydown\", (e) => {\n      // Don't capture when typing in textarea\n      if (e.target.tagName === \"TEXTAREA\") return;\n\n      if (e.key === \"ArrowLeft\" || e.key === \"ArrowUp\") {\n        e.preventDefault();\n        navigate(-1);\n      } else if (e.key === \"ArrowRight\" || e.key === \"ArrowDown\") {\n        e.preventDefault();\n        navigate(1);\n      }\n    });\n\n    // ---- Util ----\n    function getDownloadUri(file) {\n      if (file.data_uri) return file.data_uri;\n      if (file.data_b64) return \"data:application/octet-stream;base64,\" + file.data_b64;\n      if (file.type === \"text\") return \"data:text/plain;charset=utf-8,\" + encodeURIComponent(file.content);\n      return \"#\";\n    }\n\n    function escapeHtml(text) {\n      const div = document.createElement(\"div\");\n      div.textContent = text;\n      return div.innerHTML;\n    }\n\n    // ---- View switching ----\n    function switchView(view) {\n      document.querySelectorAll(\".view-tab\").forEach(t => t.classList.remove(\"active\"));\n      document.querySelectorAll(\".view-panel\").forEach(p => p.classList.remove(\"active\"));\n      document.querySelector(`[onclick=\"switchView('${view}')\"]`).classList.add(\"active\");\n      document.getElementById(\"panel-\" + view).classList.add(\"active\");\n    }\n\n    // ---- Benchmark rendering ----\n    function renderBenchmark() {\n      const data = EMBEDDED_DATA.benchmark;\n      if (!data) return;\n\n      // Show the tabs\n      document.getElementById(\"view-tabs\").style.display = \"flex\";\n\n      const container = document.getElementById(\"benchmark-content\");\n      const summary = data.run_summary || {};\n      const metadata = data.metadata || {};\n      const notes = data.notes || [];\n\n      let html = \"\";\n\n      // Header\n      html += \"<h2 style='font-family: Poppins, sans-serif; margin-bottom: 0.5rem;'>Benchmark Results</h2>\";\n      html += \"<p style='color: var(--text-muted); font-size: 0.875rem; margin-bottom: 1.25rem;'>\";\n      if (metadata.skill_name) html += \"<strong>\" + escapeHtml(metadata.skill_name) + \"</strong> &mdash; \";\n      if (metadata.timestamp) html += metadata.timestamp + \" &mdash; \";\n      if (metadata.evals_run) html += \"Evals: \" + metadata.evals_run.join(\", \") + \" &mdash; \";\n      html += (metadata.runs_per_configuration || \"?\") + \" runs per configuration\";\n      html += \"</p>\";\n\n      // Summary table\n      html += '<table class=\"benchmark-table\">';\n\n      function fmtStat(stat, pct) {\n        if (!stat) return \"—\";\n        const suffix = pct ? \"%\" : \"\";\n        const m = pct ? (stat.mean * 100).toFixed(0) : stat.mean.toFixed(1);\n        const s = pct ? (stat.stddev * 100).toFixed(0) : stat.stddev.toFixed(1);\n        return m + suffix + \" ± \" + s + suffix;\n      }\n\n      function deltaClass(val) {\n        if (!val) return \"\";\n        const n = parseFloat(val);\n        if (n > 0) return \"benchmark-delta-positive\";\n        if (n < 0) return \"benchmark-delta-negative\";\n        return \"\";\n      }\n\n      // Discover config names dynamically (everything except \"delta\")\n      const configs = Object.keys(summary).filter(k => k !== \"delta\");\n      const configA = configs[0] || \"config_a\";\n      const configB = configs[1] || \"config_b\";\n      const labelA = configA.replace(/_/g, \" \").replace(/\\b\\w/g, c => c.toUpperCase());\n      const labelB = configB.replace(/_/g, \" \").replace(/\\b\\w/g, c => c.toUpperCase());\n      const a = summary[configA] || {};\n      const b = summary[configB] || {};\n      const delta = summary.delta || {};\n\n      html += \"<thead><tr><th>Metric</th><th>\" + escapeHtml(labelA) + \"</th><th>\" + escapeHtml(labelB) + \"</th><th>Delta</th></tr></thead>\";\n      html += \"<tbody>\";\n\n      html += \"<tr><td><strong>Pass Rate</strong></td>\";\n      html += \"<td>\" + fmtStat(a.pass_rate, true) + \"</td>\";\n      html += \"<td>\" + fmtStat(b.pass_rate, true) + \"</td>\";\n      html += '<td class=\"' + deltaClass(delta.pass_rate) + '\">' + (delta.pass_rate || \"—\") + \"</td></tr>\";\n\n      // Time (only show row if data exists)\n      if (a.time_seconds || b.time_seconds) {\n        html += \"<tr><td><strong>Time (s)</strong></td>\";\n        html += \"<td>\" + fmtStat(a.time_seconds, false) + \"</td>\";\n        html += \"<td>\" + fmtStat(b.time_seconds, false) + \"</td>\";\n        html += '<td class=\"' + deltaClass(delta.time_seconds) + '\">' + (delta.time_seconds ? delta.time_seconds + \"s\" : \"—\") + \"</td></tr>\";\n      }\n\n      // Tokens (only show row if data exists)\n      if (a.tokens || b.tokens) {\n        html += \"<tr><td><strong>Tokens</strong></td>\";\n        html += \"<td>\" + fmtStat(a.tokens, false) + \"</td>\";\n        html += \"<td>\" + fmtStat(b.tokens, false) + \"</td>\";\n        html += '<td class=\"' + deltaClass(delta.tokens) + '\">' + (delta.tokens || \"—\") + \"</td></tr>\";\n      }\n\n      html += \"</tbody></table>\";\n\n      // Per-eval breakdown (if runs data available)\n      const runs = data.runs || [];\n      if (runs.length > 0) {\n        const evalIds = [...new Set(runs.map(r => r.eval_id))].sort((a, b) => a - b);\n\n        html += \"<h3 style='font-family: Poppins, sans-serif; margin-bottom: 0.75rem;'>Per-Eval Breakdown</h3>\";\n\n        const hasTime = runs.some(r => r.result && r.result.time_seconds != null);\n        const hasErrors = runs.some(r => r.result && r.result.errors > 0);\n\n        for (const evalId of evalIds) {\n          const evalRuns = runs.filter(r => r.eval_id === evalId);\n          const evalName = evalRuns[0] && evalRuns[0].eval_name ? evalRuns[0].eval_name : \"Eval \" + evalId;\n\n          html += \"<h4 style='font-family: Poppins, sans-serif; margin: 1rem 0 0.5rem; color: var(--text);'>\" + escapeHtml(evalName) + \"</h4>\";\n          html += '<table class=\"benchmark-table\">';\n          html += \"<thead><tr><th>Config</th><th>Run</th><th>Pass Rate</th>\";\n          if (hasTime) html += \"<th>Time (s)</th>\";\n          if (hasErrors) html += \"<th>Crashes During Execution</th>\";\n          html += \"</tr></thead>\";\n          html += \"<tbody>\";\n\n          // Group by config and render with average rows\n          const configGroups = [...new Set(evalRuns.map(r => r.configuration))];\n          for (let ci = 0; ci < configGroups.length; ci++) {\n            const config = configGroups[ci];\n            const configRuns = evalRuns.filter(r => r.configuration === config);\n            if (configRuns.length === 0) continue;\n\n            const rowClass = ci === 0 ? \"benchmark-row-with\" : \"benchmark-row-without\";\n            const configLabel = config.replace(/_/g, \" \").replace(/\\b\\w/g, c => c.toUpperCase());\n\n            for (const run of configRuns) {\n              const r = run.result || {};\n              const prClass = r.pass_rate >= 0.8 ? \"benchmark-delta-positive\" : r.pass_rate < 0.5 ? \"benchmark-delta-negative\" : \"\";\n              html += '<tr class=\"' + rowClass + '\">';\n              html += \"<td>\" + configLabel + \"</td>\";\n              html += \"<td>\" + run.run_number + \"</td>\";\n              html += '<td class=\"' + prClass + '\">' + ((r.pass_rate || 0) * 100).toFixed(0) + \"% (\" + (r.passed || 0) + \"/\" + (r.total || 0) + \")</td>\";\n              if (hasTime) html += \"<td>\" + (r.time_seconds != null ? r.time_seconds.toFixed(1) : \"—\") + \"</td>\";\n              if (hasErrors) html += \"<td>\" + (r.errors || 0) + \"</td>\";\n              html += \"</tr>\";\n            }\n\n            // Average row\n            const rates = configRuns.map(r => (r.result || {}).pass_rate || 0);\n            const avgRate = rates.reduce((a, b) => a + b, 0) / rates.length;\n            const avgPrClass = avgRate >= 0.8 ? \"benchmark-delta-positive\" : avgRate < 0.5 ? \"benchmark-delta-negative\" : \"\";\n            html += '<tr class=\"benchmark-row-avg ' + rowClass + '\">';\n            html += \"<td>\" + configLabel + \"</td>\";\n            html += \"<td>Avg</td>\";\n            html += '<td class=\"' + avgPrClass + '\">' + (avgRate * 100).toFixed(0) + \"%</td>\";\n            if (hasTime) {\n              const times = configRuns.map(r => (r.result || {}).time_seconds).filter(t => t != null);\n              html += \"<td>\" + (times.length ? (times.reduce((a, b) => a + b, 0) / times.length).toFixed(1) : \"—\") + \"</td>\";\n            }\n            if (hasErrors) html += \"<td></td>\";\n            html += \"</tr>\";\n          }\n          html += \"</tbody></table>\";\n\n          // Per-assertion detail for this eval\n          const runsWithExpectations = {};\n          for (const config of configGroups) {\n            runsWithExpectations[config] = evalRuns.filter(r => r.configuration === config && r.expectations && r.expectations.length > 0);\n          }\n          const hasAnyExpectations = Object.values(runsWithExpectations).some(runs => runs.length > 0);\n          if (hasAnyExpectations) {\n            // Collect all unique assertion texts across all configs\n            const allAssertions = [];\n            const seen = new Set();\n            for (const config of configGroups) {\n              for (const run of runsWithExpectations[config]) {\n                for (const exp of (run.expectations || [])) {\n                  if (!seen.has(exp.text)) {\n                    seen.add(exp.text);\n                    allAssertions.push(exp.text);\n                  }\n                }\n              }\n            }\n\n            html += '<table class=\"benchmark-table\" style=\"margin-top: 0.5rem;\">';\n            html += \"<thead><tr><th>Assertion</th>\";\n            for (const config of configGroups) {\n              const label = config.replace(/_/g, \" \").replace(/\\b\\w/g, c => c.toUpperCase());\n              html += \"<th>\" + escapeHtml(label) + \"</th>\";\n            }\n            html += \"</tr></thead><tbody>\";\n\n            for (const assertionText of allAssertions) {\n              html += \"<tr><td>\" + escapeHtml(assertionText) + \"</td>\";\n\n              for (const config of configGroups) {\n                html += \"<td>\";\n                for (const run of runsWithExpectations[config]) {\n                  const exp = (run.expectations || []).find(e => e.text === assertionText);\n                  if (exp) {\n                    const cls = exp.passed ? \"benchmark-delta-positive\" : \"benchmark-delta-negative\";\n                    const icon = exp.passed ? \"\\u2713\" : \"\\u2717\";\n                    html += '<span class=\"' + cls + '\" title=\"Run ' + run.run_number + ': ' + escapeHtml(exp.evidence || \"\") + '\">' + icon + \"</span> \";\n                  } else {\n                    html += \"— \";\n                  }\n                }\n                html += \"</td>\";\n              }\n              html += \"</tr>\";\n            }\n            html += \"</tbody></table>\";\n          }\n        }\n      }\n\n      // Notes\n      if (notes.length > 0) {\n        html += '<div class=\"benchmark-notes\">';\n        html += \"<h3>Analysis Notes</h3>\";\n        html += \"<ul>\";\n        for (const note of notes) {\n          html += \"<li>\" + escapeHtml(note) + \"</li>\";\n        }\n        html += \"</ul></div>\";\n      }\n\n      container.innerHTML = html;\n    }\n\n    // ---- Start ----\n    init();\n    renderBenchmark();\n  </script>\n</body>\n</html>\n"
  },
  {
    "path": ".claude/skills/skill-creator/references/schemas.md",
    "content": "# JSON Schemas\n\nThis document defines the JSON schemas used by skill-creator.\n\n---\n\n## evals.json\n\nDefines the evals for a skill. Located at `evals/evals.json` within the skill directory.\n\n```json\n{\n  \"skill_name\": \"example-skill\",\n  \"evals\": [\n    {\n      \"id\": 1,\n      \"prompt\": \"User's example prompt\",\n      \"expected_output\": \"Description of expected result\",\n      \"files\": [\"evals/files/sample1.pdf\"],\n      \"expectations\": [\n        \"The output includes X\",\n        \"The skill used script Y\"\n      ]\n    }\n  ]\n}\n```\n\n**Fields:**\n- `skill_name`: Name matching the skill's frontmatter\n- `evals[].id`: Unique integer identifier\n- `evals[].prompt`: The task to execute\n- `evals[].expected_output`: Human-readable description of success\n- `evals[].files`: Optional list of input file paths (relative to skill root)\n- `evals[].expectations`: List of verifiable statements\n\n---\n\n## history.json\n\nTracks version progression in Improve mode. Located at workspace root.\n\n```json\n{\n  \"started_at\": \"2026-01-15T10:30:00Z\",\n  \"skill_name\": \"pdf\",\n  \"current_best\": \"v2\",\n  \"iterations\": [\n    {\n      \"version\": \"v0\",\n      \"parent\": null,\n      \"expectation_pass_rate\": 0.65,\n      \"grading_result\": \"baseline\",\n      \"is_current_best\": false\n    },\n    {\n      \"version\": \"v1\",\n      \"parent\": \"v0\",\n      \"expectation_pass_rate\": 0.75,\n      \"grading_result\": \"won\",\n      \"is_current_best\": false\n    },\n    {\n      \"version\": \"v2\",\n      \"parent\": \"v1\",\n      \"expectation_pass_rate\": 0.85,\n      \"grading_result\": \"won\",\n      \"is_current_best\": true\n    }\n  ]\n}\n```\n\n**Fields:**\n- `started_at`: ISO timestamp of when improvement started\n- `skill_name`: Name of the skill being improved\n- `current_best`: Version identifier of the best performer\n- `iterations[].version`: Version identifier (v0, v1, ...)\n- `iterations[].parent`: Parent version this was derived from\n- `iterations[].expectation_pass_rate`: Pass rate from grading\n- `iterations[].grading_result`: \"baseline\", \"won\", \"lost\", or \"tie\"\n- `iterations[].is_current_best`: Whether this is the current best version\n\n---\n\n## grading.json\n\nOutput from the grader agent. Located at `<run-dir>/grading.json`.\n\n```json\n{\n  \"expectations\": [\n    {\n      \"text\": \"The output includes the name 'John Smith'\",\n      \"passed\": true,\n      \"evidence\": \"Found in transcript Step 3: 'Extracted names: John Smith, Sarah Johnson'\"\n    },\n    {\n      \"text\": \"The spreadsheet has a SUM formula in cell B10\",\n      \"passed\": false,\n      \"evidence\": \"No spreadsheet was created. The output was a text file.\"\n    }\n  ],\n  \"summary\": {\n    \"passed\": 2,\n    \"failed\": 1,\n    \"total\": 3,\n    \"pass_rate\": 0.67\n  },\n  \"execution_metrics\": {\n    \"tool_calls\": {\n      \"Read\": 5,\n      \"Write\": 2,\n      \"Bash\": 8\n    },\n    \"total_tool_calls\": 15,\n    \"total_steps\": 6,\n    \"errors_encountered\": 0,\n    \"output_chars\": 12450,\n    \"transcript_chars\": 3200\n  },\n  \"timing\": {\n    \"executor_duration_seconds\": 165.0,\n    \"grader_duration_seconds\": 26.0,\n    \"total_duration_seconds\": 191.0\n  },\n  \"claims\": [\n    {\n      \"claim\": \"The form has 12 fillable fields\",\n      \"type\": \"factual\",\n      \"verified\": true,\n      \"evidence\": \"Counted 12 fields in field_info.json\"\n    }\n  ],\n  \"user_notes_summary\": {\n    \"uncertainties\": [\"Used 2023 data, may be stale\"],\n    \"needs_review\": [],\n    \"workarounds\": [\"Fell back to text overlay for non-fillable fields\"]\n  },\n  \"eval_feedback\": {\n    \"suggestions\": [\n      {\n        \"assertion\": \"The output includes the name 'John Smith'\",\n        \"reason\": \"A hallucinated document that mentions the name would also pass\"\n      }\n    ],\n    \"overall\": \"Assertions check presence but not correctness.\"\n  }\n}\n```\n\n**Fields:**\n- `expectations[]`: Graded expectations with evidence\n- `summary`: Aggregate pass/fail counts\n- `execution_metrics`: Tool usage and output size (from executor's metrics.json)\n- `timing`: Wall clock timing (from timing.json)\n- `claims`: Extracted and verified claims from the output\n- `user_notes_summary`: Issues flagged by the executor\n- `eval_feedback`: (optional) Improvement suggestions for the evals, only present when the grader identifies issues worth raising\n\n---\n\n## metrics.json\n\nOutput from the executor agent. Located at `<run-dir>/outputs/metrics.json`.\n\n```json\n{\n  \"tool_calls\": {\n    \"Read\": 5,\n    \"Write\": 2,\n    \"Bash\": 8,\n    \"Edit\": 1,\n    \"Glob\": 2,\n    \"Grep\": 0\n  },\n  \"total_tool_calls\": 18,\n  \"total_steps\": 6,\n  \"files_created\": [\"filled_form.pdf\", \"field_values.json\"],\n  \"errors_encountered\": 0,\n  \"output_chars\": 12450,\n  \"transcript_chars\": 3200\n}\n```\n\n**Fields:**\n- `tool_calls`: Count per tool type\n- `total_tool_calls`: Sum of all tool calls\n- `total_steps`: Number of major execution steps\n- `files_created`: List of output files created\n- `errors_encountered`: Number of errors during execution\n- `output_chars`: Total character count of output files\n- `transcript_chars`: Character count of transcript\n\n---\n\n## timing.json\n\nWall clock timing for a run. Located at `<run-dir>/timing.json`.\n\n**How to capture:** When a subagent task completes, the task notification includes `total_tokens` and `duration_ms`. Save these immediately — they are not persisted anywhere else and cannot be recovered after the fact.\n\n```json\n{\n  \"total_tokens\": 84852,\n  \"duration_ms\": 23332,\n  \"total_duration_seconds\": 23.3,\n  \"executor_start\": \"2026-01-15T10:30:00Z\",\n  \"executor_end\": \"2026-01-15T10:32:45Z\",\n  \"executor_duration_seconds\": 165.0,\n  \"grader_start\": \"2026-01-15T10:32:46Z\",\n  \"grader_end\": \"2026-01-15T10:33:12Z\",\n  \"grader_duration_seconds\": 26.0\n}\n```\n\n---\n\n## benchmark.json\n\nOutput from Benchmark mode. Located at `benchmarks/<timestamp>/benchmark.json`.\n\n```json\n{\n  \"metadata\": {\n    \"skill_name\": \"pdf\",\n    \"skill_path\": \"/path/to/pdf\",\n    \"executor_model\": \"claude-sonnet-4-20250514\",\n    \"analyzer_model\": \"most-capable-model\",\n    \"timestamp\": \"2026-01-15T10:30:00Z\",\n    \"evals_run\": [1, 2, 3],\n    \"runs_per_configuration\": 3\n  },\n\n  \"runs\": [\n    {\n      \"eval_id\": 1,\n      \"eval_name\": \"Ocean\",\n      \"configuration\": \"with_skill\",\n      \"run_number\": 1,\n      \"result\": {\n        \"pass_rate\": 0.85,\n        \"passed\": 6,\n        \"failed\": 1,\n        \"total\": 7,\n        \"time_seconds\": 42.5,\n        \"tokens\": 3800,\n        \"tool_calls\": 18,\n        \"errors\": 0\n      },\n      \"expectations\": [\n        {\"text\": \"...\", \"passed\": true, \"evidence\": \"...\"}\n      ],\n      \"notes\": [\n        \"Used 2023 data, may be stale\",\n        \"Fell back to text overlay for non-fillable fields\"\n      ]\n    }\n  ],\n\n  \"run_summary\": {\n    \"with_skill\": {\n      \"pass_rate\": {\"mean\": 0.85, \"stddev\": 0.05, \"min\": 0.80, \"max\": 0.90},\n      \"time_seconds\": {\"mean\": 45.0, \"stddev\": 12.0, \"min\": 32.0, \"max\": 58.0},\n      \"tokens\": {\"mean\": 3800, \"stddev\": 400, \"min\": 3200, \"max\": 4100}\n    },\n    \"without_skill\": {\n      \"pass_rate\": {\"mean\": 0.35, \"stddev\": 0.08, \"min\": 0.28, \"max\": 0.45},\n      \"time_seconds\": {\"mean\": 32.0, \"stddev\": 8.0, \"min\": 24.0, \"max\": 42.0},\n      \"tokens\": {\"mean\": 2100, \"stddev\": 300, \"min\": 1800, \"max\": 2500}\n    },\n    \"delta\": {\n      \"pass_rate\": \"+0.50\",\n      \"time_seconds\": \"+13.0\",\n      \"tokens\": \"+1700\"\n    }\n  },\n\n  \"notes\": [\n    \"Assertion 'Output is a PDF file' passes 100% in both configurations - may not differentiate skill value\",\n    \"Eval 3 shows high variance (50% ± 40%) - may be flaky or model-dependent\",\n    \"Without-skill runs consistently fail on table extraction expectations\",\n    \"Skill adds 13s average execution time but improves pass rate by 50%\"\n  ]\n}\n```\n\n**Fields:**\n- `metadata`: Information about the benchmark run\n  - `skill_name`: Name of the skill\n  - `timestamp`: When the benchmark was run\n  - `evals_run`: List of eval names or IDs\n  - `runs_per_configuration`: Number of runs per config (e.g. 3)\n- `runs[]`: Individual run results\n  - `eval_id`: Numeric eval identifier\n  - `eval_name`: Human-readable eval name (used as section header in the viewer)\n  - `configuration`: Must be `\"with_skill\"` or `\"without_skill\"` (the viewer uses this exact string for grouping and color coding)\n  - `run_number`: Integer run number (1, 2, 3...)\n  - `result`: Nested object with `pass_rate`, `passed`, `total`, `time_seconds`, `tokens`, `errors`\n- `run_summary`: Statistical aggregates per configuration\n  - `with_skill` / `without_skill`: Each contains `pass_rate`, `time_seconds`, `tokens` objects with `mean` and `stddev` fields\n  - `delta`: Difference strings like `\"+0.50\"`, `\"+13.0\"`, `\"+1700\"`\n- `notes`: Freeform observations from the analyzer\n\n**Important:** The viewer reads these field names exactly. Using `config` instead of `configuration`, or putting `pass_rate` at the top level of a run instead of nested under `result`, will cause the viewer to show empty/zero values. Always reference this schema when generating benchmark.json manually.\n\n---\n\n## comparison.json\n\nOutput from blind comparator. Located at `<grading-dir>/comparison-N.json`.\n\n```json\n{\n  \"winner\": \"A\",\n  \"reasoning\": \"Output A provides a complete solution with proper formatting and all required fields. Output B is missing the date field and has formatting inconsistencies.\",\n  \"rubric\": {\n    \"A\": {\n      \"content\": {\n        \"correctness\": 5,\n        \"completeness\": 5,\n        \"accuracy\": 4\n      },\n      \"structure\": {\n        \"organization\": 4,\n        \"formatting\": 5,\n        \"usability\": 4\n      },\n      \"content_score\": 4.7,\n      \"structure_score\": 4.3,\n      \"overall_score\": 9.0\n    },\n    \"B\": {\n      \"content\": {\n        \"correctness\": 3,\n        \"completeness\": 2,\n        \"accuracy\": 3\n      },\n      \"structure\": {\n        \"organization\": 3,\n        \"formatting\": 2,\n        \"usability\": 3\n      },\n      \"content_score\": 2.7,\n      \"structure_score\": 2.7,\n      \"overall_score\": 5.4\n    }\n  },\n  \"output_quality\": {\n    \"A\": {\n      \"score\": 9,\n      \"strengths\": [\"Complete solution\", \"Well-formatted\", \"All fields present\"],\n      \"weaknesses\": [\"Minor style inconsistency in header\"]\n    },\n    \"B\": {\n      \"score\": 5,\n      \"strengths\": [\"Readable output\", \"Correct basic structure\"],\n      \"weaknesses\": [\"Missing date field\", \"Formatting inconsistencies\", \"Partial data extraction\"]\n    }\n  },\n  \"expectation_results\": {\n    \"A\": {\n      \"passed\": 4,\n      \"total\": 5,\n      \"pass_rate\": 0.80,\n      \"details\": [\n        {\"text\": \"Output includes name\", \"passed\": true}\n      ]\n    },\n    \"B\": {\n      \"passed\": 3,\n      \"total\": 5,\n      \"pass_rate\": 0.60,\n      \"details\": [\n        {\"text\": \"Output includes name\", \"passed\": true}\n      ]\n    }\n  }\n}\n```\n\n---\n\n## analysis.json\n\nOutput from post-hoc analyzer. Located at `<grading-dir>/analysis.json`.\n\n```json\n{\n  \"comparison_summary\": {\n    \"winner\": \"A\",\n    \"winner_skill\": \"path/to/winner/skill\",\n    \"loser_skill\": \"path/to/loser/skill\",\n    \"comparator_reasoning\": \"Brief summary of why comparator chose winner\"\n  },\n  \"winner_strengths\": [\n    \"Clear step-by-step instructions for handling multi-page documents\",\n    \"Included validation script that caught formatting errors\"\n  ],\n  \"loser_weaknesses\": [\n    \"Vague instruction 'process the document appropriately' led to inconsistent behavior\",\n    \"No script for validation, agent had to improvise\"\n  ],\n  \"instruction_following\": {\n    \"winner\": {\n      \"score\": 9,\n      \"issues\": [\"Minor: skipped optional logging step\"]\n    },\n    \"loser\": {\n      \"score\": 6,\n      \"issues\": [\n        \"Did not use the skill's formatting template\",\n        \"Invented own approach instead of following step 3\"\n      ]\n    }\n  },\n  \"improvement_suggestions\": [\n    {\n      \"priority\": \"high\",\n      \"category\": \"instructions\",\n      \"suggestion\": \"Replace 'process the document appropriately' with explicit steps\",\n      \"expected_impact\": \"Would eliminate ambiguity that caused inconsistent behavior\"\n    }\n  ],\n  \"transcript_insights\": {\n    \"winner_execution_pattern\": \"Read skill -> Followed 5-step process -> Used validation script\",\n    \"loser_execution_pattern\": \"Read skill -> Unclear on approach -> Tried 3 different methods\"\n  }\n}\n```\n"
  },
  {
    "path": ".claude/skills/skill-creator/scripts/aggregate_benchmark.py",
    "content": "#!/usr/bin/env python3\n\"\"\"\nAggregate individual run results into benchmark summary statistics.\n\nReads grading.json files from run directories and produces:\n- run_summary with mean, stddev, min, max for each metric\n- delta between with_skill and without_skill configurations\n\nUsage:\n    python aggregate_benchmark.py <benchmark_dir>\n\nExample:\n    python aggregate_benchmark.py benchmarks/2026-01-15T10-30-00/\n\nThe script supports two directory layouts:\n\n    Workspace layout (from skill-creator iterations):\n    <benchmark_dir>/\n    └── eval-N/\n        ├── with_skill/\n        │   ├── run-1/grading.json\n        │   └── run-2/grading.json\n        └── without_skill/\n            ├── run-1/grading.json\n            └── run-2/grading.json\n\n    Legacy layout (with runs/ subdirectory):\n    <benchmark_dir>/\n    └── runs/\n        └── eval-N/\n            ├── with_skill/\n            │   └── run-1/grading.json\n            └── without_skill/\n                └── run-1/grading.json\n\"\"\"\n\nimport argparse\nimport json\nimport math\nimport sys\nfrom datetime import datetime, timezone\nfrom pathlib import Path\n\n\ndef calculate_stats(values: list[float]) -> dict:\n    \"\"\"Calculate mean, stddev, min, max for a list of values.\"\"\"\n    if not values:\n        return {\"mean\": 0.0, \"stddev\": 0.0, \"min\": 0.0, \"max\": 0.0}\n\n    n = len(values)\n    mean = sum(values) / n\n\n    if n > 1:\n        variance = sum((x - mean) ** 2 for x in values) / (n - 1)\n        stddev = math.sqrt(variance)\n    else:\n        stddev = 0.0\n\n    return {\n        \"mean\": round(mean, 4),\n        \"stddev\": round(stddev, 4),\n        \"min\": round(min(values), 4),\n        \"max\": round(max(values), 4)\n    }\n\n\ndef load_run_results(benchmark_dir: Path) -> dict:\n    \"\"\"\n    Load all run results from a benchmark directory.\n\n    Returns dict keyed by config name (e.g. \"with_skill\"/\"without_skill\",\n    or \"new_skill\"/\"old_skill\"), each containing a list of run results.\n    \"\"\"\n    # Support both layouts: eval dirs directly under benchmark_dir, or under runs/\n    runs_dir = benchmark_dir / \"runs\"\n    if runs_dir.exists():\n        search_dir = runs_dir\n    elif list(benchmark_dir.glob(\"eval-*\")):\n        search_dir = benchmark_dir\n    else:\n        print(f\"No eval directories found in {benchmark_dir} or {benchmark_dir / 'runs'}\")\n        return {}\n\n    results: dict[str, list] = {}\n\n    for eval_idx, eval_dir in enumerate(sorted(search_dir.glob(\"eval-*\"))):\n        metadata_path = eval_dir / \"eval_metadata.json\"\n        if metadata_path.exists():\n            try:\n                with open(metadata_path) as mf:\n                    eval_id = json.load(mf).get(\"eval_id\", eval_idx)\n            except (json.JSONDecodeError, OSError):\n                eval_id = eval_idx\n        else:\n            try:\n                eval_id = int(eval_dir.name.split(\"-\")[1])\n            except ValueError:\n                eval_id = eval_idx\n\n        # Discover config directories dynamically rather than hardcoding names\n        for config_dir in sorted(eval_dir.iterdir()):\n            if not config_dir.is_dir():\n                continue\n            # Skip non-config directories (inputs, outputs, etc.)\n            if not list(config_dir.glob(\"run-*\")):\n                continue\n            config = config_dir.name\n            if config not in results:\n                results[config] = []\n\n            for run_dir in sorted(config_dir.glob(\"run-*\")):\n                run_number = int(run_dir.name.split(\"-\")[1])\n                grading_file = run_dir / \"grading.json\"\n\n                if not grading_file.exists():\n                    print(f\"Warning: grading.json not found in {run_dir}\")\n                    continue\n\n                try:\n                    with open(grading_file) as f:\n                        grading = json.load(f)\n                except json.JSONDecodeError as e:\n                    print(f\"Warning: Invalid JSON in {grading_file}: {e}\")\n                    continue\n\n                # Extract metrics\n                result = {\n                    \"eval_id\": eval_id,\n                    \"run_number\": run_number,\n                    \"pass_rate\": grading.get(\"summary\", {}).get(\"pass_rate\", 0.0),\n                    \"passed\": grading.get(\"summary\", {}).get(\"passed\", 0),\n                    \"failed\": grading.get(\"summary\", {}).get(\"failed\", 0),\n                    \"total\": grading.get(\"summary\", {}).get(\"total\", 0),\n                }\n\n                # Extract timing — check grading.json first, then sibling timing.json\n                timing = grading.get(\"timing\", {})\n                result[\"time_seconds\"] = timing.get(\"total_duration_seconds\", 0.0)\n                timing_file = run_dir / \"timing.json\"\n                if result[\"time_seconds\"] == 0.0 and timing_file.exists():\n                    try:\n                        with open(timing_file) as tf:\n                            timing_data = json.load(tf)\n                        result[\"time_seconds\"] = timing_data.get(\"total_duration_seconds\", 0.0)\n                        result[\"tokens\"] = timing_data.get(\"total_tokens\", 0)\n                    except json.JSONDecodeError:\n                        pass\n\n                # Extract metrics if available\n                metrics = grading.get(\"execution_metrics\", {})\n                result[\"tool_calls\"] = metrics.get(\"total_tool_calls\", 0)\n                if not result.get(\"tokens\"):\n                    result[\"tokens\"] = metrics.get(\"output_chars\", 0)\n                result[\"errors\"] = metrics.get(\"errors_encountered\", 0)\n\n                # Extract expectations — viewer requires fields: text, passed, evidence\n                raw_expectations = grading.get(\"expectations\", [])\n                for exp in raw_expectations:\n                    if \"text\" not in exp or \"passed\" not in exp:\n                        print(f\"Warning: expectation in {grading_file} missing required fields (text, passed, evidence): {exp}\")\n                result[\"expectations\"] = raw_expectations\n\n                # Extract notes from user_notes_summary\n                notes_summary = grading.get(\"user_notes_summary\", {})\n                notes = []\n                notes.extend(notes_summary.get(\"uncertainties\", []))\n                notes.extend(notes_summary.get(\"needs_review\", []))\n                notes.extend(notes_summary.get(\"workarounds\", []))\n                result[\"notes\"] = notes\n\n                results[config].append(result)\n\n    return results\n\n\ndef aggregate_results(results: dict) -> dict:\n    \"\"\"\n    Aggregate run results into summary statistics.\n\n    Returns run_summary with stats for each configuration and delta.\n    \"\"\"\n    run_summary = {}\n    configs = list(results.keys())\n\n    for config in configs:\n        runs = results.get(config, [])\n\n        if not runs:\n            run_summary[config] = {\n                \"pass_rate\": {\"mean\": 0.0, \"stddev\": 0.0, \"min\": 0.0, \"max\": 0.0},\n                \"time_seconds\": {\"mean\": 0.0, \"stddev\": 0.0, \"min\": 0.0, \"max\": 0.0},\n                \"tokens\": {\"mean\": 0, \"stddev\": 0, \"min\": 0, \"max\": 0}\n            }\n            continue\n\n        pass_rates = [r[\"pass_rate\"] for r in runs]\n        times = [r[\"time_seconds\"] for r in runs]\n        tokens = [r.get(\"tokens\", 0) for r in runs]\n\n        run_summary[config] = {\n            \"pass_rate\": calculate_stats(pass_rates),\n            \"time_seconds\": calculate_stats(times),\n            \"tokens\": calculate_stats(tokens)\n        }\n\n    # Calculate delta between the first two configs (if two exist)\n    if len(configs) >= 2:\n        primary = run_summary.get(configs[0], {})\n        baseline = run_summary.get(configs[1], {})\n    else:\n        primary = run_summary.get(configs[0], {}) if configs else {}\n        baseline = {}\n\n    delta_pass_rate = primary.get(\"pass_rate\", {}).get(\"mean\", 0) - baseline.get(\"pass_rate\", {}).get(\"mean\", 0)\n    delta_time = primary.get(\"time_seconds\", {}).get(\"mean\", 0) - baseline.get(\"time_seconds\", {}).get(\"mean\", 0)\n    delta_tokens = primary.get(\"tokens\", {}).get(\"mean\", 0) - baseline.get(\"tokens\", {}).get(\"mean\", 0)\n\n    run_summary[\"delta\"] = {\n        \"pass_rate\": f\"{delta_pass_rate:+.2f}\",\n        \"time_seconds\": f\"{delta_time:+.1f}\",\n        \"tokens\": f\"{delta_tokens:+.0f}\"\n    }\n\n    return run_summary\n\n\ndef generate_benchmark(benchmark_dir: Path, skill_name: str = \"\", skill_path: str = \"\") -> dict:\n    \"\"\"\n    Generate complete benchmark.json from run results.\n    \"\"\"\n    results = load_run_results(benchmark_dir)\n    run_summary = aggregate_results(results)\n\n    # Build runs array for benchmark.json\n    runs = []\n    for config in results:\n        for result in results[config]:\n            runs.append({\n                \"eval_id\": result[\"eval_id\"],\n                \"configuration\": config,\n                \"run_number\": result[\"run_number\"],\n                \"result\": {\n                    \"pass_rate\": result[\"pass_rate\"],\n                    \"passed\": result[\"passed\"],\n                    \"failed\": result[\"failed\"],\n                    \"total\": result[\"total\"],\n                    \"time_seconds\": result[\"time_seconds\"],\n                    \"tokens\": result.get(\"tokens\", 0),\n                    \"tool_calls\": result.get(\"tool_calls\", 0),\n                    \"errors\": result.get(\"errors\", 0)\n                },\n                \"expectations\": result[\"expectations\"],\n                \"notes\": result[\"notes\"]\n            })\n\n    # Determine eval IDs from results\n    eval_ids = sorted(set(\n        r[\"eval_id\"]\n        for config in results.values()\n        for r in config\n    ))\n\n    benchmark = {\n        \"metadata\": {\n            \"skill_name\": skill_name or \"<skill-name>\",\n            \"skill_path\": skill_path or \"<path/to/skill>\",\n            \"executor_model\": \"<model-name>\",\n            \"analyzer_model\": \"<model-name>\",\n            \"timestamp\": datetime.now(timezone.utc).strftime(\"%Y-%m-%dT%H:%M:%SZ\"),\n            \"evals_run\": eval_ids,\n            \"runs_per_configuration\": 3\n        },\n        \"runs\": runs,\n        \"run_summary\": run_summary,\n        \"notes\": []  # To be filled by analyzer\n    }\n\n    return benchmark\n\n\ndef generate_markdown(benchmark: dict) -> str:\n    \"\"\"Generate human-readable benchmark.md from benchmark data.\"\"\"\n    metadata = benchmark[\"metadata\"]\n    run_summary = benchmark[\"run_summary\"]\n\n    # Determine config names (excluding \"delta\")\n    configs = [k for k in run_summary if k != \"delta\"]\n    config_a = configs[0] if len(configs) >= 1 else \"config_a\"\n    config_b = configs[1] if len(configs) >= 2 else \"config_b\"\n    label_a = config_a.replace(\"_\", \" \").title()\n    label_b = config_b.replace(\"_\", \" \").title()\n\n    lines = [\n        f\"# Skill Benchmark: {metadata['skill_name']}\",\n        \"\",\n        f\"**Model**: {metadata['executor_model']}\",\n        f\"**Date**: {metadata['timestamp']}\",\n        f\"**Evals**: {', '.join(map(str, metadata['evals_run']))} ({metadata['runs_per_configuration']} runs each per configuration)\",\n        \"\",\n        \"## Summary\",\n        \"\",\n        f\"| Metric | {label_a} | {label_b} | Delta |\",\n        \"|--------|------------|---------------|-------|\",\n    ]\n\n    a_summary = run_summary.get(config_a, {})\n    b_summary = run_summary.get(config_b, {})\n    delta = run_summary.get(\"delta\", {})\n\n    # Format pass rate\n    a_pr = a_summary.get(\"pass_rate\", {})\n    b_pr = b_summary.get(\"pass_rate\", {})\n    lines.append(f\"| Pass Rate | {a_pr.get('mean', 0)*100:.0f}% ± {a_pr.get('stddev', 0)*100:.0f}% | {b_pr.get('mean', 0)*100:.0f}% ± {b_pr.get('stddev', 0)*100:.0f}% | {delta.get('pass_rate', '—')} |\")\n\n    # Format time\n    a_time = a_summary.get(\"time_seconds\", {})\n    b_time = b_summary.get(\"time_seconds\", {})\n    lines.append(f\"| Time | {a_time.get('mean', 0):.1f}s ± {a_time.get('stddev', 0):.1f}s | {b_time.get('mean', 0):.1f}s ± {b_time.get('stddev', 0):.1f}s | {delta.get('time_seconds', '—')}s |\")\n\n    # Format tokens\n    a_tokens = a_summary.get(\"tokens\", {})\n    b_tokens = b_summary.get(\"tokens\", {})\n    lines.append(f\"| Tokens | {a_tokens.get('mean', 0):.0f} ± {a_tokens.get('stddev', 0):.0f} | {b_tokens.get('mean', 0):.0f} ± {b_tokens.get('stddev', 0):.0f} | {delta.get('tokens', '—')} |\")\n\n    # Notes section\n    if benchmark.get(\"notes\"):\n        lines.extend([\n            \"\",\n            \"## Notes\",\n            \"\"\n        ])\n        for note in benchmark[\"notes\"]:\n            lines.append(f\"- {note}\")\n\n    return \"\\n\".join(lines)\n\n\ndef main():\n    parser = argparse.ArgumentParser(\n        description=\"Aggregate benchmark run results into summary statistics\"\n    )\n    parser.add_argument(\n        \"benchmark_dir\",\n        type=Path,\n        help=\"Path to the benchmark directory\"\n    )\n    parser.add_argument(\n        \"--skill-name\",\n        default=\"\",\n        help=\"Name of the skill being benchmarked\"\n    )\n    parser.add_argument(\n        \"--skill-path\",\n        default=\"\",\n        help=\"Path to the skill being benchmarked\"\n    )\n    parser.add_argument(\n        \"--output\", \"-o\",\n        type=Path,\n        help=\"Output path for benchmark.json (default: <benchmark_dir>/benchmark.json)\"\n    )\n\n    args = parser.parse_args()\n\n    if not args.benchmark_dir.exists():\n        print(f\"Directory not found: {args.benchmark_dir}\")\n        sys.exit(1)\n\n    # Generate benchmark\n    benchmark = generate_benchmark(args.benchmark_dir, args.skill_name, args.skill_path)\n\n    # Determine output paths\n    output_json = args.output or (args.benchmark_dir / \"benchmark.json\")\n    output_md = output_json.with_suffix(\".md\")\n\n    # Write benchmark.json\n    with open(output_json, \"w\") as f:\n        json.dump(benchmark, f, indent=2)\n    print(f\"Generated: {output_json}\")\n\n    # Write benchmark.md\n    markdown = generate_markdown(benchmark)\n    with open(output_md, \"w\") as f:\n        f.write(markdown)\n    print(f\"Generated: {output_md}\")\n\n    # Print summary\n    run_summary = benchmark[\"run_summary\"]\n    configs = [k for k in run_summary if k != \"delta\"]\n    delta = run_summary.get(\"delta\", {})\n\n    print(f\"\\nSummary:\")\n    for config in configs:\n        pr = run_summary[config][\"pass_rate\"][\"mean\"]\n        label = config.replace(\"_\", \" \").title()\n        print(f\"  {label}: {pr*100:.1f}% pass rate\")\n    print(f\"  Delta:         {delta.get('pass_rate', '—')}\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": ".claude/skills/skill-creator/scripts/generate_report.py",
    "content": "#!/usr/bin/env python3\n\"\"\"Generate an HTML report from run_loop.py output.\n\nTakes the JSON output from run_loop.py and generates a visual HTML report\nshowing each description attempt with check/x for each test case.\nDistinguishes between train and test queries.\n\"\"\"\n\nimport argparse\nimport html\nimport json\nimport sys\nfrom pathlib import Path\n\n\ndef generate_html(data: dict, auto_refresh: bool = False, skill_name: str = \"\") -> str:\n    \"\"\"Generate HTML report from loop output data. If auto_refresh is True, adds a meta refresh tag.\"\"\"\n    history = data.get(\"history\", [])\n    holdout = data.get(\"holdout\", 0)\n    title_prefix = html.escape(skill_name + \" \\u2014 \") if skill_name else \"\"\n\n    # Get all unique queries from train and test sets, with should_trigger info\n    train_queries: list[dict] = []\n    test_queries: list[dict] = []\n    if history:\n        for r in history[0].get(\"train_results\", history[0].get(\"results\", [])):\n            train_queries.append({\"query\": r[\"query\"], \"should_trigger\": r.get(\"should_trigger\", True)})\n        if history[0].get(\"test_results\"):\n            for r in history[0].get(\"test_results\", []):\n                test_queries.append({\"query\": r[\"query\"], \"should_trigger\": r.get(\"should_trigger\", True)})\n\n    refresh_tag = '    <meta http-equiv=\"refresh\" content=\"5\">\\n' if auto_refresh else \"\"\n\n    html_parts = [\"\"\"<!DOCTYPE html>\n<html>\n<head>\n    <meta charset=\"utf-8\">\n\"\"\" + refresh_tag + \"\"\"    <title>\"\"\" + title_prefix + \"\"\"Skill Description Optimization</title>\n    <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n    <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n    <link href=\"https://fonts.googleapis.com/css2?family=Poppins:wght@500;600&family=Lora:wght@400;500&display=swap\" rel=\"stylesheet\">\n    <style>\n        body {\n            font-family: 'Lora', Georgia, serif;\n            max-width: 100%;\n            margin: 0 auto;\n            padding: 20px;\n            background: #faf9f5;\n            color: #141413;\n        }\n        h1 { font-family: 'Poppins', sans-serif; color: #141413; }\n        .explainer {\n            background: white;\n            padding: 15px;\n            border-radius: 6px;\n            margin-bottom: 20px;\n            border: 1px solid #e8e6dc;\n            color: #b0aea5;\n            font-size: 0.875rem;\n            line-height: 1.6;\n        }\n        .summary {\n            background: white;\n            padding: 15px;\n            border-radius: 6px;\n            margin-bottom: 20px;\n            border: 1px solid #e8e6dc;\n        }\n        .summary p { margin: 5px 0; }\n        .best { color: #788c5d; font-weight: bold; }\n        .table-container {\n            overflow-x: auto;\n            width: 100%;\n        }\n        table {\n            border-collapse: collapse;\n            background: white;\n            border: 1px solid #e8e6dc;\n            border-radius: 6px;\n            font-size: 12px;\n            min-width: 100%;\n        }\n        th, td {\n            padding: 8px;\n            text-align: left;\n            border: 1px solid #e8e6dc;\n            white-space: normal;\n            word-wrap: break-word;\n        }\n        th {\n            font-family: 'Poppins', sans-serif;\n            background: #141413;\n            color: #faf9f5;\n            font-weight: 500;\n        }\n        th.test-col {\n            background: #6a9bcc;\n        }\n        th.query-col { min-width: 200px; }\n        td.description {\n            font-family: monospace;\n            font-size: 11px;\n            word-wrap: break-word;\n            max-width: 400px;\n        }\n        td.result {\n            text-align: center;\n            font-size: 16px;\n            min-width: 40px;\n        }\n        td.test-result {\n            background: #f0f6fc;\n        }\n        .pass { color: #788c5d; }\n        .fail { color: #c44; }\n        .rate {\n            font-size: 9px;\n            color: #b0aea5;\n            display: block;\n        }\n        tr:hover { background: #faf9f5; }\n        .score {\n            display: inline-block;\n            padding: 2px 6px;\n            border-radius: 4px;\n            font-weight: bold;\n            font-size: 11px;\n        }\n        .score-good { background: #eef2e8; color: #788c5d; }\n        .score-ok { background: #fef3c7; color: #d97706; }\n        .score-bad { background: #fceaea; color: #c44; }\n        .train-label { color: #b0aea5; font-size: 10px; }\n        .test-label { color: #6a9bcc; font-size: 10px; font-weight: bold; }\n        .best-row { background: #f5f8f2; }\n        th.positive-col { border-bottom: 3px solid #788c5d; }\n        th.negative-col { border-bottom: 3px solid #c44; }\n        th.test-col.positive-col { border-bottom: 3px solid #788c5d; }\n        th.test-col.negative-col { border-bottom: 3px solid #c44; }\n        .legend { font-family: 'Poppins', sans-serif; display: flex; gap: 20px; margin-bottom: 10px; font-size: 13px; align-items: center; }\n        .legend-item { display: flex; align-items: center; gap: 6px; }\n        .legend-swatch { width: 16px; height: 16px; border-radius: 3px; display: inline-block; }\n        .swatch-positive { background: #141413; border-bottom: 3px solid #788c5d; }\n        .swatch-negative { background: #141413; border-bottom: 3px solid #c44; }\n        .swatch-test { background: #6a9bcc; }\n        .swatch-train { background: #141413; }\n    </style>\n</head>\n<body>\n    <h1>\"\"\" + title_prefix + \"\"\"Skill Description Optimization</h1>\n    <div class=\"explainer\">\n        <strong>Optimizing your skill's description.</strong> This page updates automatically as Claude tests different versions of your skill's description. Each row is an iteration — a new description attempt. The columns show test queries: green checkmarks mean the skill triggered correctly (or correctly didn't trigger), red crosses mean it got it wrong. The \"Train\" score shows performance on queries used to improve the description; the \"Test\" score shows performance on held-out queries the optimizer hasn't seen. When it's done, Claude will apply the best-performing description to your skill.\n    </div>\n\"\"\"]\n\n    # Summary section\n    best_test_score = data.get('best_test_score')\n    best_train_score = data.get('best_train_score')\n    html_parts.append(f\"\"\"\n    <div class=\"summary\">\n        <p><strong>Original:</strong> {html.escape(data.get('original_description', 'N/A'))}</p>\n        <p class=\"best\"><strong>Best:</strong> {html.escape(data.get('best_description', 'N/A'))}</p>\n        <p><strong>Best Score:</strong> {data.get('best_score', 'N/A')} {'(test)' if best_test_score else '(train)'}</p>\n        <p><strong>Iterations:</strong> {data.get('iterations_run', 0)} | <strong>Train:</strong> {data.get('train_size', '?')} | <strong>Test:</strong> {data.get('test_size', '?')}</p>\n    </div>\n\"\"\")\n\n    # Legend\n    html_parts.append(\"\"\"\n    <div class=\"legend\">\n        <span style=\"font-weight:600\">Query columns:</span>\n        <span class=\"legend-item\"><span class=\"legend-swatch swatch-positive\"></span> Should trigger</span>\n        <span class=\"legend-item\"><span class=\"legend-swatch swatch-negative\"></span> Should NOT trigger</span>\n        <span class=\"legend-item\"><span class=\"legend-swatch swatch-train\"></span> Train</span>\n        <span class=\"legend-item\"><span class=\"legend-swatch swatch-test\"></span> Test</span>\n    </div>\n\"\"\")\n\n    # Table header\n    html_parts.append(\"\"\"\n    <div class=\"table-container\">\n    <table>\n        <thead>\n            <tr>\n                <th>Iter</th>\n                <th>Train</th>\n                <th>Test</th>\n                <th class=\"query-col\">Description</th>\n\"\"\")\n\n    # Add column headers for train queries\n    for qinfo in train_queries:\n        polarity = \"positive-col\" if qinfo[\"should_trigger\"] else \"negative-col\"\n        html_parts.append(f'                <th class=\"{polarity}\">{html.escape(qinfo[\"query\"])}</th>\\n')\n\n    # Add column headers for test queries (different color)\n    for qinfo in test_queries:\n        polarity = \"positive-col\" if qinfo[\"should_trigger\"] else \"negative-col\"\n        html_parts.append(f'                <th class=\"test-col {polarity}\">{html.escape(qinfo[\"query\"])}</th>\\n')\n\n    html_parts.append(\"\"\"            </tr>\n        </thead>\n        <tbody>\n\"\"\")\n\n    # Find best iteration for highlighting\n    if test_queries:\n        best_iter = max(history, key=lambda h: h.get(\"test_passed\") or 0).get(\"iteration\")\n    else:\n        best_iter = max(history, key=lambda h: h.get(\"train_passed\", h.get(\"passed\", 0))).get(\"iteration\")\n\n    # Add rows for each iteration\n    for h in history:\n        iteration = h.get(\"iteration\", \"?\")\n        train_passed = h.get(\"train_passed\", h.get(\"passed\", 0))\n        train_total = h.get(\"train_total\", h.get(\"total\", 0))\n        test_passed = h.get(\"test_passed\")\n        test_total = h.get(\"test_total\")\n        description = h.get(\"description\", \"\")\n        train_results = h.get(\"train_results\", h.get(\"results\", []))\n        test_results = h.get(\"test_results\", [])\n\n        # Create lookups for results by query\n        train_by_query = {r[\"query\"]: r for r in train_results}\n        test_by_query = {r[\"query\"]: r for r in test_results} if test_results else {}\n\n        # Compute aggregate correct/total runs across all retries\n        def aggregate_runs(results: list[dict]) -> tuple[int, int]:\n            correct = 0\n            total = 0\n            for r in results:\n                runs = r.get(\"runs\", 0)\n                triggers = r.get(\"triggers\", 0)\n                total += runs\n                if r.get(\"should_trigger\", True):\n                    correct += triggers\n                else:\n                    correct += runs - triggers\n            return correct, total\n\n        train_correct, train_runs = aggregate_runs(train_results)\n        test_correct, test_runs = aggregate_runs(test_results)\n\n        # Determine score classes\n        def score_class(correct: int, total: int) -> str:\n            if total > 0:\n                ratio = correct / total\n                if ratio >= 0.8:\n                    return \"score-good\"\n                elif ratio >= 0.5:\n                    return \"score-ok\"\n            return \"score-bad\"\n\n        train_class = score_class(train_correct, train_runs)\n        test_class = score_class(test_correct, test_runs)\n\n        row_class = \"best-row\" if iteration == best_iter else \"\"\n\n        html_parts.append(f\"\"\"            <tr class=\"{row_class}\">\n                <td>{iteration}</td>\n                <td><span class=\"score {train_class}\">{train_correct}/{train_runs}</span></td>\n                <td><span class=\"score {test_class}\">{test_correct}/{test_runs}</span></td>\n                <td class=\"description\">{html.escape(description)}</td>\n\"\"\")\n\n        # Add result for each train query\n        for qinfo in train_queries:\n            r = train_by_query.get(qinfo[\"query\"], {})\n            did_pass = r.get(\"pass\", False)\n            triggers = r.get(\"triggers\", 0)\n            runs = r.get(\"runs\", 0)\n\n            icon = \"✓\" if did_pass else \"✗\"\n            css_class = \"pass\" if did_pass else \"fail\"\n\n            html_parts.append(f'                <td class=\"result {css_class}\">{icon}<span class=\"rate\">{triggers}/{runs}</span></td>\\n')\n\n        # Add result for each test query (with different background)\n        for qinfo in test_queries:\n            r = test_by_query.get(qinfo[\"query\"], {})\n            did_pass = r.get(\"pass\", False)\n            triggers = r.get(\"triggers\", 0)\n            runs = r.get(\"runs\", 0)\n\n            icon = \"✓\" if did_pass else \"✗\"\n            css_class = \"pass\" if did_pass else \"fail\"\n\n            html_parts.append(f'                <td class=\"result test-result {css_class}\">{icon}<span class=\"rate\">{triggers}/{runs}</span></td>\\n')\n\n        html_parts.append(\"            </tr>\\n\")\n\n    html_parts.append(\"\"\"        </tbody>\n    </table>\n    </div>\n\"\"\")\n\n    html_parts.append(\"\"\"\n</body>\n</html>\n\"\"\")\n\n    return \"\".join(html_parts)\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=\"Generate HTML report from run_loop output\")\n    parser.add_argument(\"input\", help=\"Path to JSON output from run_loop.py (or - for stdin)\")\n    parser.add_argument(\"-o\", \"--output\", default=None, help=\"Output HTML file (default: stdout)\")\n    parser.add_argument(\"--skill-name\", default=\"\", help=\"Skill name to include in the report title\")\n    args = parser.parse_args()\n\n    if args.input == \"-\":\n        data = json.load(sys.stdin)\n    else:\n        data = json.loads(Path(args.input).read_text())\n\n    html_output = generate_html(data, skill_name=args.skill_name)\n\n    if args.output:\n        Path(args.output).write_text(html_output)\n        print(f\"Report written to {args.output}\", file=sys.stderr)\n    else:\n        print(html_output)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": ".claude/skills/skill-creator/scripts/improve_description.py",
    "content": "#!/usr/bin/env python3\n\"\"\"Improve a skill description based on eval results.\n\nTakes eval results (from run_eval.py) and generates an improved description\nusing Claude with extended thinking.\n\"\"\"\n\nimport argparse\nimport json\nimport re\nimport sys\nfrom pathlib import Path\n\nimport anthropic\n\nfrom scripts.utils import parse_skill_md\n\n\ndef improve_description(\n    client: anthropic.Anthropic,\n    skill_name: str,\n    skill_content: str,\n    current_description: str,\n    eval_results: dict,\n    history: list[dict],\n    model: str,\n    test_results: dict | None = None,\n    log_dir: Path | None = None,\n    iteration: int | None = None,\n) -> str:\n    \"\"\"Call Claude to improve the description based on eval results.\"\"\"\n    failed_triggers = [\n        r for r in eval_results[\"results\"]\n        if r[\"should_trigger\"] and not r[\"pass\"]\n    ]\n    false_triggers = [\n        r for r in eval_results[\"results\"]\n        if not r[\"should_trigger\"] and not r[\"pass\"]\n    ]\n\n    # Build scores summary\n    train_score = f\"{eval_results['summary']['passed']}/{eval_results['summary']['total']}\"\n    if test_results:\n        test_score = f\"{test_results['summary']['passed']}/{test_results['summary']['total']}\"\n        scores_summary = f\"Train: {train_score}, Test: {test_score}\"\n    else:\n        scores_summary = f\"Train: {train_score}\"\n\n    prompt = f\"\"\"You are optimizing a skill description for a Claude Code skill called \"{skill_name}\". A \"skill\" is sort of like a prompt, but with progressive disclosure -- there's a title and description that Claude sees when deciding whether to use the skill, and then if it does use the skill, it reads the .md file which has lots more details and potentially links to other resources in the skill folder like helper files and scripts and additional documentation or examples.\n\nThe description appears in Claude's \"available_skills\" list. When a user sends a query, Claude decides whether to invoke the skill based solely on the title and on this description. Your goal is to write a description that triggers for relevant queries, and doesn't trigger for irrelevant ones.\n\nHere's the current description:\n<current_description>\n\"{current_description}\"\n</current_description>\n\nCurrent scores ({scores_summary}):\n<scores_summary>\n\"\"\"\n    if failed_triggers:\n        prompt += \"FAILED TO TRIGGER (should have triggered but didn't):\\n\"\n        for r in failed_triggers:\n            prompt += f'  - \"{r[\"query\"]}\" (triggered {r[\"triggers\"]}/{r[\"runs\"]} times)\\n'\n        prompt += \"\\n\"\n\n    if false_triggers:\n        prompt += \"FALSE TRIGGERS (triggered but shouldn't have):\\n\"\n        for r in false_triggers:\n            prompt += f'  - \"{r[\"query\"]}\" (triggered {r[\"triggers\"]}/{r[\"runs\"]} times)\\n'\n        prompt += \"\\n\"\n\n    if history:\n        prompt += \"PREVIOUS ATTEMPTS (do NOT repeat these — try something structurally different):\\n\\n\"\n        for h in history:\n            train_s = f\"{h.get('train_passed', h.get('passed', 0))}/{h.get('train_total', h.get('total', 0))}\"\n            test_s = f\"{h.get('test_passed', '?')}/{h.get('test_total', '?')}\" if h.get('test_passed') is not None else None\n            score_str = f\"train={train_s}\" + (f\", test={test_s}\" if test_s else \"\")\n            prompt += f'<attempt {score_str}>\\n'\n            prompt += f'Description: \"{h[\"description\"]}\"\\n'\n            if \"results\" in h:\n                prompt += \"Train results:\\n\"\n                for r in h[\"results\"]:\n                    status = \"PASS\" if r[\"pass\"] else \"FAIL\"\n                    prompt += f'  [{status}] \"{r[\"query\"][:80]}\" (triggered {r[\"triggers\"]}/{r[\"runs\"]})\\n'\n            if h.get(\"note\"):\n                prompt += f'Note: {h[\"note\"]}\\n'\n            prompt += \"</attempt>\\n\\n\"\n\n    prompt += f\"\"\"</scores_summary>\n\nSkill content (for context on what the skill does):\n<skill_content>\n{skill_content}\n</skill_content>\n\nBased on the failures, write a new and improved description that is more likely to trigger correctly. When I say \"based on the failures\", it's a bit of a tricky line to walk because we don't want to overfit to the specific cases you're seeing. So what I DON'T want you to do is produce an ever-expanding list of specific queries that this skill should or shouldn't trigger for. Instead, try to generalize from the failures to broader categories of user intent and situations where this skill would be useful or not useful. The reason for this is twofold:\n\n1. Avoid overfitting\n2. The list might get loooong and it's injected into ALL queries and there might be a lot of skills, so we don't want to blow too much space on any given description.\n\nConcretely, your description should not be more than about 100-200 words, even if that comes at the cost of accuracy.\n\nHere are some tips that we've found to work well in writing these descriptions:\n- The skill should be phrased in the imperative -- \"Use this skill for\" rather than \"this skill does\"\n- The skill description should focus on the user's intent, what they are trying to achieve, vs. the implementation details of how the skill works.\n- The description competes with other skills for Claude's attention — make it distinctive and immediately recognizable.\n- If you're getting lots of failures after repeated attempts, change things up. Try different sentence structures or wordings.\n\nI'd encourage you to be creative and mix up the style in different iterations since you'll have multiple opportunities to try different approaches and we'll just grab the highest-scoring one at the end. \n\nPlease respond with only the new description text in <new_description> tags, nothing else.\"\"\"\n\n    response = client.messages.create(\n        model=model,\n        max_tokens=16000,\n        thinking={\n            \"type\": \"enabled\",\n            \"budget_tokens\": 10000,\n        },\n        messages=[{\"role\": \"user\", \"content\": prompt}],\n    )\n\n    # Extract thinking and text from response\n    thinking_text = \"\"\n    text = \"\"\n    for block in response.content:\n        if block.type == \"thinking\":\n            thinking_text = block.thinking\n        elif block.type == \"text\":\n            text = block.text\n\n    # Parse out the <new_description> tags\n    match = re.search(r\"<new_description>(.*?)</new_description>\", text, re.DOTALL)\n    description = match.group(1).strip().strip('\"') if match else text.strip().strip('\"')\n\n    # Log the transcript\n    transcript: dict = {\n        \"iteration\": iteration,\n        \"prompt\": prompt,\n        \"thinking\": thinking_text,\n        \"response\": text,\n        \"parsed_description\": description,\n        \"char_count\": len(description),\n        \"over_limit\": len(description) > 1024,\n    }\n\n    # If over 1024 chars, ask the model to shorten it\n    if len(description) > 1024:\n        shorten_prompt = f\"Your description is {len(description)} characters, which exceeds the hard 1024 character limit. Please rewrite it to be under 1024 characters while preserving the most important trigger words and intent coverage. Respond with only the new description in <new_description> tags.\"\n        shorten_response = client.messages.create(\n            model=model,\n            max_tokens=16000,\n            thinking={\n                \"type\": \"enabled\",\n                \"budget_tokens\": 10000,\n            },\n            messages=[\n                {\"role\": \"user\", \"content\": prompt},\n                {\"role\": \"assistant\", \"content\": text},\n                {\"role\": \"user\", \"content\": shorten_prompt},\n            ],\n        )\n\n        shorten_thinking = \"\"\n        shorten_text = \"\"\n        for block in shorten_response.content:\n            if block.type == \"thinking\":\n                shorten_thinking = block.thinking\n            elif block.type == \"text\":\n                shorten_text = block.text\n\n        match = re.search(r\"<new_description>(.*?)</new_description>\", shorten_text, re.DOTALL)\n        shortened = match.group(1).strip().strip('\"') if match else shorten_text.strip().strip('\"')\n\n        transcript[\"rewrite_prompt\"] = shorten_prompt\n        transcript[\"rewrite_thinking\"] = shorten_thinking\n        transcript[\"rewrite_response\"] = shorten_text\n        transcript[\"rewrite_description\"] = shortened\n        transcript[\"rewrite_char_count\"] = len(shortened)\n        description = shortened\n\n    transcript[\"final_description\"] = description\n\n    if log_dir:\n        log_dir.mkdir(parents=True, exist_ok=True)\n        log_file = log_dir / f\"improve_iter_{iteration or 'unknown'}.json\"\n        log_file.write_text(json.dumps(transcript, indent=2))\n\n    return description\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=\"Improve a skill description based on eval results\")\n    parser.add_argument(\"--eval-results\", required=True, help=\"Path to eval results JSON (from run_eval.py)\")\n    parser.add_argument(\"--skill-path\", required=True, help=\"Path to skill directory\")\n    parser.add_argument(\"--history\", default=None, help=\"Path to history JSON (previous attempts)\")\n    parser.add_argument(\"--model\", required=True, help=\"Model for improvement\")\n    parser.add_argument(\"--verbose\", action=\"store_true\", help=\"Print thinking to stderr\")\n    args = parser.parse_args()\n\n    skill_path = Path(args.skill_path)\n    if not (skill_path / \"SKILL.md\").exists():\n        print(f\"Error: No SKILL.md found at {skill_path}\", file=sys.stderr)\n        sys.exit(1)\n\n    eval_results = json.loads(Path(args.eval_results).read_text())\n    history = []\n    if args.history:\n        history = json.loads(Path(args.history).read_text())\n\n    name, _, content = parse_skill_md(skill_path)\n    current_description = eval_results[\"description\"]\n\n    if args.verbose:\n        print(f\"Current: {current_description}\", file=sys.stderr)\n        print(f\"Score: {eval_results['summary']['passed']}/{eval_results['summary']['total']}\", file=sys.stderr)\n\n    client = anthropic.Anthropic()\n    new_description = improve_description(\n        client=client,\n        skill_name=name,\n        skill_content=content,\n        current_description=current_description,\n        eval_results=eval_results,\n        history=history,\n        model=args.model,\n    )\n\n    if args.verbose:\n        print(f\"Improved: {new_description}\", file=sys.stderr)\n\n    # Output as JSON with both the new description and updated history\n    output = {\n        \"description\": new_description,\n        \"history\": history + [{\n            \"description\": current_description,\n            \"passed\": eval_results[\"summary\"][\"passed\"],\n            \"failed\": eval_results[\"summary\"][\"failed\"],\n            \"total\": eval_results[\"summary\"][\"total\"],\n            \"results\": eval_results[\"results\"],\n        }],\n    }\n    print(json.dumps(output, indent=2))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": ".claude/skills/skill-creator/scripts/package_skill.py",
    "content": "#!/usr/bin/env python3\n\"\"\"\nSkill Packager - Creates a distributable .skill file of a skill folder\n\nUsage:\n    python utils/package_skill.py <path/to/skill-folder> [output-directory]\n\nExample:\n    python utils/package_skill.py skills/public/my-skill\n    python utils/package_skill.py skills/public/my-skill ./dist\n\"\"\"\n\nimport fnmatch\nimport sys\nimport zipfile\nfrom pathlib import Path\nfrom scripts.quick_validate import validate_skill\n\n# Patterns to exclude when packaging skills.\nEXCLUDE_DIRS = {\"__pycache__\", \"node_modules\"}\nEXCLUDE_GLOBS = {\"*.pyc\"}\nEXCLUDE_FILES = {\".DS_Store\"}\n# Directories excluded only at the skill root (not when nested deeper).\nROOT_EXCLUDE_DIRS = {\"evals\"}\n\n\ndef should_exclude(rel_path: Path) -> bool:\n    \"\"\"Check if a path should be excluded from packaging.\"\"\"\n    parts = rel_path.parts\n    if any(part in EXCLUDE_DIRS for part in parts):\n        return True\n    # rel_path is relative to skill_path.parent, so parts[0] is the skill\n    # folder name and parts[1] (if present) is the first subdir.\n    if len(parts) > 1 and parts[1] in ROOT_EXCLUDE_DIRS:\n        return True\n    name = rel_path.name\n    if name in EXCLUDE_FILES:\n        return True\n    return any(fnmatch.fnmatch(name, pat) for pat in EXCLUDE_GLOBS)\n\n\ndef package_skill(skill_path, output_dir=None):\n    \"\"\"\n    Package a skill folder into a .skill file.\n\n    Args:\n        skill_path: Path to the skill folder\n        output_dir: Optional output directory for the .skill file (defaults to current directory)\n\n    Returns:\n        Path to the created .skill file, or None if error\n    \"\"\"\n    skill_path = Path(skill_path).resolve()\n\n    # Validate skill folder exists\n    if not skill_path.exists():\n        print(f\"❌ Error: Skill folder not found: {skill_path}\")\n        return None\n\n    if not skill_path.is_dir():\n        print(f\"❌ Error: Path is not a directory: {skill_path}\")\n        return None\n\n    # Validate SKILL.md exists\n    skill_md = skill_path / \"SKILL.md\"\n    if not skill_md.exists():\n        print(f\"❌ Error: SKILL.md not found in {skill_path}\")\n        return None\n\n    # Run validation before packaging\n    print(\"🔍 Validating skill...\")\n    valid, message = validate_skill(skill_path)\n    if not valid:\n        print(f\"❌ Validation failed: {message}\")\n        print(\"   Please fix the validation errors before packaging.\")\n        return None\n    print(f\"✅ {message}\\n\")\n\n    # Determine output location\n    skill_name = skill_path.name\n    if output_dir:\n        output_path = Path(output_dir).resolve()\n        output_path.mkdir(parents=True, exist_ok=True)\n    else:\n        output_path = Path.cwd()\n\n    skill_filename = output_path / f\"{skill_name}.skill\"\n\n    # Create the .skill file (zip format)\n    try:\n        with zipfile.ZipFile(skill_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:\n            # Walk through the skill directory, excluding build artifacts\n            for file_path in skill_path.rglob('*'):\n                if not file_path.is_file():\n                    continue\n                arcname = file_path.relative_to(skill_path.parent)\n                if should_exclude(arcname):\n                    print(f\"  Skipped: {arcname}\")\n                    continue\n                zipf.write(file_path, arcname)\n                print(f\"  Added: {arcname}\")\n\n        print(f\"\\n✅ Successfully packaged skill to: {skill_filename}\")\n        return skill_filename\n\n    except Exception as e:\n        print(f\"❌ Error creating .skill file: {e}\")\n        return None\n\n\ndef main():\n    if len(sys.argv) < 2:\n        print(\"Usage: python utils/package_skill.py <path/to/skill-folder> [output-directory]\")\n        print(\"\\nExample:\")\n        print(\"  python utils/package_skill.py skills/public/my-skill\")\n        print(\"  python utils/package_skill.py skills/public/my-skill ./dist\")\n        sys.exit(1)\n\n    skill_path = sys.argv[1]\n    output_dir = sys.argv[2] if len(sys.argv) > 2 else None\n\n    print(f\"📦 Packaging skill: {skill_path}\")\n    if output_dir:\n        print(f\"   Output directory: {output_dir}\")\n    print()\n\n    result = package_skill(skill_path, output_dir)\n\n    if result:\n        sys.exit(0)\n    else:\n        sys.exit(1)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": ".claude/skills/skill-creator/scripts/quick_validate.py",
    "content": "#!/usr/bin/env python3\n\"\"\"\nQuick validation script for skills - minimal version\n\"\"\"\n\nimport sys\nimport os\nimport re\nimport yaml\nfrom pathlib import Path\n\ndef validate_skill(skill_path):\n    \"\"\"Basic validation of a skill\"\"\"\n    skill_path = Path(skill_path)\n\n    # Check SKILL.md exists\n    skill_md = skill_path / 'SKILL.md'\n    if not skill_md.exists():\n        return False, \"SKILL.md not found\"\n\n    # Read and validate frontmatter\n    content = skill_md.read_text()\n    if not content.startswith('---'):\n        return False, \"No YAML frontmatter found\"\n\n    # Extract frontmatter\n    match = re.match(r'^---\\n(.*?)\\n---', content, re.DOTALL)\n    if not match:\n        return False, \"Invalid frontmatter format\"\n\n    frontmatter_text = match.group(1)\n\n    # Parse YAML frontmatter\n    try:\n        frontmatter = yaml.safe_load(frontmatter_text)\n        if not isinstance(frontmatter, dict):\n            return False, \"Frontmatter must be a YAML dictionary\"\n    except yaml.YAMLError as e:\n        return False, f\"Invalid YAML in frontmatter: {e}\"\n\n    # Define allowed properties\n    ALLOWED_PROPERTIES = {'name', 'description', 'license', 'allowed-tools', 'metadata', 'compatibility'}\n\n    # Check for unexpected properties (excluding nested keys under metadata)\n    unexpected_keys = set(frontmatter.keys()) - ALLOWED_PROPERTIES\n    if unexpected_keys:\n        return False, (\n            f\"Unexpected key(s) in SKILL.md frontmatter: {', '.join(sorted(unexpected_keys))}. \"\n            f\"Allowed properties are: {', '.join(sorted(ALLOWED_PROPERTIES))}\"\n        )\n\n    # Check required fields\n    if 'name' not in frontmatter:\n        return False, \"Missing 'name' in frontmatter\"\n    if 'description' not in frontmatter:\n        return False, \"Missing 'description' in frontmatter\"\n\n    # Extract name for validation\n    name = frontmatter.get('name', '')\n    if not isinstance(name, str):\n        return False, f\"Name must be a string, got {type(name).__name__}\"\n    name = name.strip()\n    if name:\n        # Check naming convention (kebab-case: lowercase with hyphens)\n        if not re.match(r'^[a-z0-9-]+$', name):\n            return False, f\"Name '{name}' should be kebab-case (lowercase letters, digits, and hyphens only)\"\n        if name.startswith('-') or name.endswith('-') or '--' in name:\n            return False, f\"Name '{name}' cannot start/end with hyphen or contain consecutive hyphens\"\n        # Check name length (max 64 characters per spec)\n        if len(name) > 64:\n            return False, f\"Name is too long ({len(name)} characters). Maximum is 64 characters.\"\n\n    # Extract and validate description\n    description = frontmatter.get('description', '')\n    if not isinstance(description, str):\n        return False, f\"Description must be a string, got {type(description).__name__}\"\n    description = description.strip()\n    if description:\n        # Check for angle brackets\n        if '<' in description or '>' in description:\n            return False, \"Description cannot contain angle brackets (< or >)\"\n        # Check description length (max 1024 characters per spec)\n        if len(description) > 1024:\n            return False, f\"Description is too long ({len(description)} characters). Maximum is 1024 characters.\"\n\n    # Validate compatibility field if present (optional)\n    compatibility = frontmatter.get('compatibility', '')\n    if compatibility:\n        if not isinstance(compatibility, str):\n            return False, f\"Compatibility must be a string, got {type(compatibility).__name__}\"\n        if len(compatibility) > 500:\n            return False, f\"Compatibility is too long ({len(compatibility)} characters). Maximum is 500 characters.\"\n\n    return True, \"Skill is valid!\"\n\nif __name__ == \"__main__\":\n    if len(sys.argv) != 2:\n        print(\"Usage: python quick_validate.py <skill_directory>\")\n        sys.exit(1)\n    \n    valid, message = validate_skill(sys.argv[1])\n    print(message)\n    sys.exit(0 if valid else 1)"
  },
  {
    "path": ".claude/skills/skill-creator/scripts/run_eval.py",
    "content": "#!/usr/bin/env python3\n\"\"\"Run trigger evaluation for a skill description.\n\nTests whether a skill's description causes Claude to trigger (read the skill)\nfor a set of queries. Outputs results as JSON.\n\"\"\"\n\nimport argparse\nimport json\nimport os\nimport select\nimport subprocess\nimport sys\nimport time\nimport uuid\nfrom concurrent.futures import ProcessPoolExecutor, as_completed\nfrom pathlib import Path\n\nfrom scripts.utils import parse_skill_md\n\n\ndef find_project_root() -> Path:\n    \"\"\"Find the project root by walking up from cwd looking for .claude/.\n\n    Mimics how Claude Code discovers its project root, so the command file\n    we create ends up where claude -p will look for it.\n    \"\"\"\n    current = Path.cwd()\n    for parent in [current, *current.parents]:\n        if (parent / \".claude\").is_dir():\n            return parent\n    return current\n\n\ndef run_single_query(\n    query: str,\n    skill_name: str,\n    skill_description: str,\n    timeout: int,\n    project_root: str,\n    model: str | None = None,\n) -> bool:\n    \"\"\"Run a single query and return whether the skill was triggered.\n\n    Creates a command file in .claude/commands/ so it appears in Claude's\n    available_skills list, then runs `claude -p` with the raw query.\n    Uses --include-partial-messages to detect triggering early from\n    stream events (content_block_start) rather than waiting for the\n    full assistant message, which only arrives after tool execution.\n    \"\"\"\n    unique_id = uuid.uuid4().hex[:8]\n    clean_name = f\"{skill_name}-skill-{unique_id}\"\n    project_commands_dir = Path(project_root) / \".claude\" / \"commands\"\n    command_file = project_commands_dir / f\"{clean_name}.md\"\n\n    try:\n        project_commands_dir.mkdir(parents=True, exist_ok=True)\n        # Use YAML block scalar to avoid breaking on quotes in description\n        indented_desc = \"\\n  \".join(skill_description.split(\"\\n\"))\n        command_content = (\n            f\"---\\n\"\n            f\"description: |\\n\"\n            f\"  {indented_desc}\\n\"\n            f\"---\\n\\n\"\n            f\"# {skill_name}\\n\\n\"\n            f\"This skill handles: {skill_description}\\n\"\n        )\n        command_file.write_text(command_content)\n\n        cmd = [\n            \"claude\",\n            \"-p\", query,\n            \"--output-format\", \"stream-json\",\n            \"--verbose\",\n            \"--include-partial-messages\",\n        ]\n        if model:\n            cmd.extend([\"--model\", model])\n\n        # Remove CLAUDECODE env var to allow nesting claude -p inside a\n        # Claude Code session. The guard is for interactive terminal conflicts;\n        # programmatic subprocess usage is safe.\n        env = {k: v for k, v in os.environ.items() if k != \"CLAUDECODE\"}\n\n        process = subprocess.Popen(\n            cmd,\n            stdout=subprocess.PIPE,\n            stderr=subprocess.DEVNULL,\n            cwd=project_root,\n            env=env,\n        )\n\n        triggered = False\n        start_time = time.time()\n        buffer = \"\"\n        # Track state for stream event detection\n        pending_tool_name = None\n        accumulated_json = \"\"\n\n        try:\n            while time.time() - start_time < timeout:\n                if process.poll() is not None:\n                    remaining = process.stdout.read()\n                    if remaining:\n                        buffer += remaining.decode(\"utf-8\", errors=\"replace\")\n                    break\n\n                ready, _, _ = select.select([process.stdout], [], [], 1.0)\n                if not ready:\n                    continue\n\n                chunk = os.read(process.stdout.fileno(), 8192)\n                if not chunk:\n                    break\n                buffer += chunk.decode(\"utf-8\", errors=\"replace\")\n\n                while \"\\n\" in buffer:\n                    line, buffer = buffer.split(\"\\n\", 1)\n                    line = line.strip()\n                    if not line:\n                        continue\n\n                    try:\n                        event = json.loads(line)\n                    except json.JSONDecodeError:\n                        continue\n\n                    # Early detection via stream events\n                    if event.get(\"type\") == \"stream_event\":\n                        se = event.get(\"event\", {})\n                        se_type = se.get(\"type\", \"\")\n\n                        if se_type == \"content_block_start\":\n                            cb = se.get(\"content_block\", {})\n                            if cb.get(\"type\") == \"tool_use\":\n                                tool_name = cb.get(\"name\", \"\")\n                                if tool_name in (\"Skill\", \"Read\"):\n                                    pending_tool_name = tool_name\n                                    accumulated_json = \"\"\n                                else:\n                                    return False\n\n                        elif se_type == \"content_block_delta\" and pending_tool_name:\n                            delta = se.get(\"delta\", {})\n                            if delta.get(\"type\") == \"input_json_delta\":\n                                accumulated_json += delta.get(\"partial_json\", \"\")\n                                if clean_name in accumulated_json:\n                                    return True\n\n                        elif se_type in (\"content_block_stop\", \"message_stop\"):\n                            if pending_tool_name:\n                                return clean_name in accumulated_json\n                            if se_type == \"message_stop\":\n                                return False\n\n                    # Fallback: full assistant message\n                    elif event.get(\"type\") == \"assistant\":\n                        message = event.get(\"message\", {})\n                        for content_item in message.get(\"content\", []):\n                            if content_item.get(\"type\") != \"tool_use\":\n                                continue\n                            tool_name = content_item.get(\"name\", \"\")\n                            tool_input = content_item.get(\"input\", {})\n                            if tool_name == \"Skill\" and clean_name in tool_input.get(\"skill\", \"\"):\n                                triggered = True\n                            elif tool_name == \"Read\" and clean_name in tool_input.get(\"file_path\", \"\"):\n                                triggered = True\n                            return triggered\n\n                    elif event.get(\"type\") == \"result\":\n                        return triggered\n        finally:\n            # Clean up process on any exit path (return, exception, timeout)\n            if process.poll() is None:\n                process.kill()\n                process.wait()\n\n        return triggered\n    finally:\n        if command_file.exists():\n            command_file.unlink()\n\n\ndef run_eval(\n    eval_set: list[dict],\n    skill_name: str,\n    description: str,\n    num_workers: int,\n    timeout: int,\n    project_root: Path,\n    runs_per_query: int = 1,\n    trigger_threshold: float = 0.5,\n    model: str | None = None,\n) -> dict:\n    \"\"\"Run the full eval set and return results.\"\"\"\n    results = []\n\n    with ProcessPoolExecutor(max_workers=num_workers) as executor:\n        future_to_info = {}\n        for item in eval_set:\n            for run_idx in range(runs_per_query):\n                future = executor.submit(\n                    run_single_query,\n                    item[\"query\"],\n                    skill_name,\n                    description,\n                    timeout,\n                    str(project_root),\n                    model,\n                )\n                future_to_info[future] = (item, run_idx)\n\n        query_triggers: dict[str, list[bool]] = {}\n        query_items: dict[str, dict] = {}\n        for future in as_completed(future_to_info):\n            item, _ = future_to_info[future]\n            query = item[\"query\"]\n            query_items[query] = item\n            if query not in query_triggers:\n                query_triggers[query] = []\n            try:\n                query_triggers[query].append(future.result())\n            except Exception as e:\n                print(f\"Warning: query failed: {e}\", file=sys.stderr)\n                query_triggers[query].append(False)\n\n    for query, triggers in query_triggers.items():\n        item = query_items[query]\n        trigger_rate = sum(triggers) / len(triggers)\n        should_trigger = item[\"should_trigger\"]\n        if should_trigger:\n            did_pass = trigger_rate >= trigger_threshold\n        else:\n            did_pass = trigger_rate < trigger_threshold\n        results.append({\n            \"query\": query,\n            \"should_trigger\": should_trigger,\n            \"trigger_rate\": trigger_rate,\n            \"triggers\": sum(triggers),\n            \"runs\": len(triggers),\n            \"pass\": did_pass,\n        })\n\n    passed = sum(1 for r in results if r[\"pass\"])\n    total = len(results)\n\n    return {\n        \"skill_name\": skill_name,\n        \"description\": description,\n        \"results\": results,\n        \"summary\": {\n            \"total\": total,\n            \"passed\": passed,\n            \"failed\": total - passed,\n        },\n    }\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=\"Run trigger evaluation for a skill description\")\n    parser.add_argument(\"--eval-set\", required=True, help=\"Path to eval set JSON file\")\n    parser.add_argument(\"--skill-path\", required=True, help=\"Path to skill directory\")\n    parser.add_argument(\"--description\", default=None, help=\"Override description to test\")\n    parser.add_argument(\"--num-workers\", type=int, default=10, help=\"Number of parallel workers\")\n    parser.add_argument(\"--timeout\", type=int, default=30, help=\"Timeout per query in seconds\")\n    parser.add_argument(\"--runs-per-query\", type=int, default=3, help=\"Number of runs per query\")\n    parser.add_argument(\"--trigger-threshold\", type=float, default=0.5, help=\"Trigger rate threshold\")\n    parser.add_argument(\"--model\", default=None, help=\"Model to use for claude -p (default: user's configured model)\")\n    parser.add_argument(\"--verbose\", action=\"store_true\", help=\"Print progress to stderr\")\n    args = parser.parse_args()\n\n    eval_set = json.loads(Path(args.eval_set).read_text())\n    skill_path = Path(args.skill_path)\n\n    if not (skill_path / \"SKILL.md\").exists():\n        print(f\"Error: No SKILL.md found at {skill_path}\", file=sys.stderr)\n        sys.exit(1)\n\n    name, original_description, content = parse_skill_md(skill_path)\n    description = args.description or original_description\n    project_root = find_project_root()\n\n    if args.verbose:\n        print(f\"Evaluating: {description}\", file=sys.stderr)\n\n    output = run_eval(\n        eval_set=eval_set,\n        skill_name=name,\n        description=description,\n        num_workers=args.num_workers,\n        timeout=args.timeout,\n        project_root=project_root,\n        runs_per_query=args.runs_per_query,\n        trigger_threshold=args.trigger_threshold,\n        model=args.model,\n    )\n\n    if args.verbose:\n        summary = output[\"summary\"]\n        print(f\"Results: {summary['passed']}/{summary['total']} passed\", file=sys.stderr)\n        for r in output[\"results\"]:\n            status = \"PASS\" if r[\"pass\"] else \"FAIL\"\n            rate_str = f\"{r['triggers']}/{r['runs']}\"\n            print(f\"  [{status}] rate={rate_str} expected={r['should_trigger']}: {r['query'][:70]}\", file=sys.stderr)\n\n    print(json.dumps(output, indent=2))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": ".claude/skills/skill-creator/scripts/run_loop.py",
    "content": "#!/usr/bin/env python3\n\"\"\"Run the eval + improve loop until all pass or max iterations reached.\n\nCombines run_eval.py and improve_description.py in a loop, tracking history\nand returning the best description found. Supports train/test split to prevent\noverfitting.\n\"\"\"\n\nimport argparse\nimport json\nimport random\nimport sys\nimport tempfile\nimport time\nimport webbrowser\nfrom pathlib import Path\n\nimport anthropic\n\nfrom scripts.generate_report import generate_html\nfrom scripts.improve_description import improve_description\nfrom scripts.run_eval import find_project_root, run_eval\nfrom scripts.utils import parse_skill_md\n\n\ndef split_eval_set(eval_set: list[dict], holdout: float, seed: int = 42) -> tuple[list[dict], list[dict]]:\n    \"\"\"Split eval set into train and test sets, stratified by should_trigger.\"\"\"\n    random.seed(seed)\n\n    # Separate by should_trigger\n    trigger = [e for e in eval_set if e[\"should_trigger\"]]\n    no_trigger = [e for e in eval_set if not e[\"should_trigger\"]]\n\n    # Shuffle each group\n    random.shuffle(trigger)\n    random.shuffle(no_trigger)\n\n    # Calculate split points\n    n_trigger_test = max(1, int(len(trigger) * holdout))\n    n_no_trigger_test = max(1, int(len(no_trigger) * holdout))\n\n    # Split\n    test_set = trigger[:n_trigger_test] + no_trigger[:n_no_trigger_test]\n    train_set = trigger[n_trigger_test:] + no_trigger[n_no_trigger_test:]\n\n    return train_set, test_set\n\n\ndef run_loop(\n    eval_set: list[dict],\n    skill_path: Path,\n    description_override: str | None,\n    num_workers: int,\n    timeout: int,\n    max_iterations: int,\n    runs_per_query: int,\n    trigger_threshold: float,\n    holdout: float,\n    model: str,\n    verbose: bool,\n    live_report_path: Path | None = None,\n    log_dir: Path | None = None,\n) -> dict:\n    \"\"\"Run the eval + improvement loop.\"\"\"\n    project_root = find_project_root()\n    name, original_description, content = parse_skill_md(skill_path)\n    current_description = description_override or original_description\n\n    # Split into train/test if holdout > 0\n    if holdout > 0:\n        train_set, test_set = split_eval_set(eval_set, holdout)\n        if verbose:\n            print(f\"Split: {len(train_set)} train, {len(test_set)} test (holdout={holdout})\", file=sys.stderr)\n    else:\n        train_set = eval_set\n        test_set = []\n\n    client = anthropic.Anthropic()\n    history = []\n    exit_reason = \"unknown\"\n\n    for iteration in range(1, max_iterations + 1):\n        if verbose:\n            print(f\"\\n{'='*60}\", file=sys.stderr)\n            print(f\"Iteration {iteration}/{max_iterations}\", file=sys.stderr)\n            print(f\"Description: {current_description}\", file=sys.stderr)\n            print(f\"{'='*60}\", file=sys.stderr)\n\n        # Evaluate train + test together in one batch for parallelism\n        all_queries = train_set + test_set\n        t0 = time.time()\n        all_results = run_eval(\n            eval_set=all_queries,\n            skill_name=name,\n            description=current_description,\n            num_workers=num_workers,\n            timeout=timeout,\n            project_root=project_root,\n            runs_per_query=runs_per_query,\n            trigger_threshold=trigger_threshold,\n            model=model,\n        )\n        eval_elapsed = time.time() - t0\n\n        # Split results back into train/test by matching queries\n        train_queries_set = {q[\"query\"] for q in train_set}\n        train_result_list = [r for r in all_results[\"results\"] if r[\"query\"] in train_queries_set]\n        test_result_list = [r for r in all_results[\"results\"] if r[\"query\"] not in train_queries_set]\n\n        train_passed = sum(1 for r in train_result_list if r[\"pass\"])\n        train_total = len(train_result_list)\n        train_summary = {\"passed\": train_passed, \"failed\": train_total - train_passed, \"total\": train_total}\n        train_results = {\"results\": train_result_list, \"summary\": train_summary}\n\n        if test_set:\n            test_passed = sum(1 for r in test_result_list if r[\"pass\"])\n            test_total = len(test_result_list)\n            test_summary = {\"passed\": test_passed, \"failed\": test_total - test_passed, \"total\": test_total}\n            test_results = {\"results\": test_result_list, \"summary\": test_summary}\n        else:\n            test_results = None\n            test_summary = None\n\n        history.append({\n            \"iteration\": iteration,\n            \"description\": current_description,\n            \"train_passed\": train_summary[\"passed\"],\n            \"train_failed\": train_summary[\"failed\"],\n            \"train_total\": train_summary[\"total\"],\n            \"train_results\": train_results[\"results\"],\n            \"test_passed\": test_summary[\"passed\"] if test_summary else None,\n            \"test_failed\": test_summary[\"failed\"] if test_summary else None,\n            \"test_total\": test_summary[\"total\"] if test_summary else None,\n            \"test_results\": test_results[\"results\"] if test_results else None,\n            # For backward compat with report generator\n            \"passed\": train_summary[\"passed\"],\n            \"failed\": train_summary[\"failed\"],\n            \"total\": train_summary[\"total\"],\n            \"results\": train_results[\"results\"],\n        })\n\n        # Write live report if path provided\n        if live_report_path:\n            partial_output = {\n                \"original_description\": original_description,\n                \"best_description\": current_description,\n                \"best_score\": \"in progress\",\n                \"iterations_run\": len(history),\n                \"holdout\": holdout,\n                \"train_size\": len(train_set),\n                \"test_size\": len(test_set),\n                \"history\": history,\n            }\n            live_report_path.write_text(generate_html(partial_output, auto_refresh=True, skill_name=name))\n\n        if verbose:\n            def print_eval_stats(label, results, elapsed):\n                pos = [r for r in results if r[\"should_trigger\"]]\n                neg = [r for r in results if not r[\"should_trigger\"]]\n                tp = sum(r[\"triggers\"] for r in pos)\n                pos_runs = sum(r[\"runs\"] for r in pos)\n                fn = pos_runs - tp\n                fp = sum(r[\"triggers\"] for r in neg)\n                neg_runs = sum(r[\"runs\"] for r in neg)\n                tn = neg_runs - fp\n                total = tp + tn + fp + fn\n                precision = tp / (tp + fp) if (tp + fp) > 0 else 1.0\n                recall = tp / (tp + fn) if (tp + fn) > 0 else 1.0\n                accuracy = (tp + tn) / total if total > 0 else 0.0\n                print(f\"{label}: {tp+tn}/{total} correct, precision={precision:.0%} recall={recall:.0%} accuracy={accuracy:.0%} ({elapsed:.1f}s)\", file=sys.stderr)\n                for r in results:\n                    status = \"PASS\" if r[\"pass\"] else \"FAIL\"\n                    rate_str = f\"{r['triggers']}/{r['runs']}\"\n                    print(f\"  [{status}] rate={rate_str} expected={r['should_trigger']}: {r['query'][:60]}\", file=sys.stderr)\n\n            print_eval_stats(\"Train\", train_results[\"results\"], eval_elapsed)\n            if test_summary:\n                print_eval_stats(\"Test \", test_results[\"results\"], 0)\n\n        if train_summary[\"failed\"] == 0:\n            exit_reason = f\"all_passed (iteration {iteration})\"\n            if verbose:\n                print(f\"\\nAll train queries passed on iteration {iteration}!\", file=sys.stderr)\n            break\n\n        if iteration == max_iterations:\n            exit_reason = f\"max_iterations ({max_iterations})\"\n            if verbose:\n                print(f\"\\nMax iterations reached ({max_iterations}).\", file=sys.stderr)\n            break\n\n        # Improve the description based on train results\n        if verbose:\n            print(f\"\\nImproving description...\", file=sys.stderr)\n\n        t0 = time.time()\n        # Strip test scores from history so improvement model can't see them\n        blinded_history = [\n            {k: v for k, v in h.items() if not k.startswith(\"test_\")}\n            for h in history\n        ]\n        new_description = improve_description(\n            client=client,\n            skill_name=name,\n            skill_content=content,\n            current_description=current_description,\n            eval_results=train_results,\n            history=blinded_history,\n            model=model,\n            log_dir=log_dir,\n            iteration=iteration,\n        )\n        improve_elapsed = time.time() - t0\n\n        if verbose:\n            print(f\"Proposed ({improve_elapsed:.1f}s): {new_description}\", file=sys.stderr)\n\n        current_description = new_description\n\n    # Find the best iteration by TEST score (or train if no test set)\n    if test_set:\n        best = max(history, key=lambda h: h[\"test_passed\"] or 0)\n        best_score = f\"{best['test_passed']}/{best['test_total']}\"\n    else:\n        best = max(history, key=lambda h: h[\"train_passed\"])\n        best_score = f\"{best['train_passed']}/{best['train_total']}\"\n\n    if verbose:\n        print(f\"\\nExit reason: {exit_reason}\", file=sys.stderr)\n        print(f\"Best score: {best_score} (iteration {best['iteration']})\", file=sys.stderr)\n\n    return {\n        \"exit_reason\": exit_reason,\n        \"original_description\": original_description,\n        \"best_description\": best[\"description\"],\n        \"best_score\": best_score,\n        \"best_train_score\": f\"{best['train_passed']}/{best['train_total']}\",\n        \"best_test_score\": f\"{best['test_passed']}/{best['test_total']}\" if test_set else None,\n        \"final_description\": current_description,\n        \"iterations_run\": len(history),\n        \"holdout\": holdout,\n        \"train_size\": len(train_set),\n        \"test_size\": len(test_set),\n        \"history\": history,\n    }\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=\"Run eval + improve loop\")\n    parser.add_argument(\"--eval-set\", required=True, help=\"Path to eval set JSON file\")\n    parser.add_argument(\"--skill-path\", required=True, help=\"Path to skill directory\")\n    parser.add_argument(\"--description\", default=None, help=\"Override starting description\")\n    parser.add_argument(\"--num-workers\", type=int, default=10, help=\"Number of parallel workers\")\n    parser.add_argument(\"--timeout\", type=int, default=30, help=\"Timeout per query in seconds\")\n    parser.add_argument(\"--max-iterations\", type=int, default=5, help=\"Max improvement iterations\")\n    parser.add_argument(\"--runs-per-query\", type=int, default=3, help=\"Number of runs per query\")\n    parser.add_argument(\"--trigger-threshold\", type=float, default=0.5, help=\"Trigger rate threshold\")\n    parser.add_argument(\"--holdout\", type=float, default=0.4, help=\"Fraction of eval set to hold out for testing (0 to disable)\")\n    parser.add_argument(\"--model\", required=True, help=\"Model for improvement\")\n    parser.add_argument(\"--verbose\", action=\"store_true\", help=\"Print progress to stderr\")\n    parser.add_argument(\"--report\", default=\"auto\", help=\"Generate HTML report at this path (default: 'auto' for temp file, 'none' to disable)\")\n    parser.add_argument(\"--results-dir\", default=None, help=\"Save all outputs (results.json, report.html, log.txt) to a timestamped subdirectory here\")\n    args = parser.parse_args()\n\n    eval_set = json.loads(Path(args.eval_set).read_text())\n    skill_path = Path(args.skill_path)\n\n    if not (skill_path / \"SKILL.md\").exists():\n        print(f\"Error: No SKILL.md found at {skill_path}\", file=sys.stderr)\n        sys.exit(1)\n\n    name, _, _ = parse_skill_md(skill_path)\n\n    # Set up live report path\n    if args.report != \"none\":\n        if args.report == \"auto\":\n            timestamp = time.strftime(\"%Y%m%d_%H%M%S\")\n            live_report_path = Path(tempfile.gettempdir()) / f\"skill_description_report_{skill_path.name}_{timestamp}.html\"\n        else:\n            live_report_path = Path(args.report)\n        # Open the report immediately so the user can watch\n        live_report_path.write_text(\"<html><body><h1>Starting optimization loop...</h1><meta http-equiv='refresh' content='5'></body></html>\")\n        webbrowser.open(str(live_report_path))\n    else:\n        live_report_path = None\n\n    # Determine output directory (create before run_loop so logs can be written)\n    if args.results_dir:\n        timestamp = time.strftime(\"%Y-%m-%d_%H%M%S\")\n        results_dir = Path(args.results_dir) / timestamp\n        results_dir.mkdir(parents=True, exist_ok=True)\n    else:\n        results_dir = None\n\n    log_dir = results_dir / \"logs\" if results_dir else None\n\n    output = run_loop(\n        eval_set=eval_set,\n        skill_path=skill_path,\n        description_override=args.description,\n        num_workers=args.num_workers,\n        timeout=args.timeout,\n        max_iterations=args.max_iterations,\n        runs_per_query=args.runs_per_query,\n        trigger_threshold=args.trigger_threshold,\n        holdout=args.holdout,\n        model=args.model,\n        verbose=args.verbose,\n        live_report_path=live_report_path,\n        log_dir=log_dir,\n    )\n\n    # Save JSON output\n    json_output = json.dumps(output, indent=2)\n    print(json_output)\n    if results_dir:\n        (results_dir / \"results.json\").write_text(json_output)\n\n    # Write final HTML report (without auto-refresh)\n    if live_report_path:\n        live_report_path.write_text(generate_html(output, auto_refresh=False, skill_name=name))\n        print(f\"\\nReport: {live_report_path}\", file=sys.stderr)\n\n    if results_dir and live_report_path:\n        (results_dir / \"report.html\").write_text(generate_html(output, auto_refresh=False, skill_name=name))\n\n    if results_dir:\n        print(f\"Results saved to: {results_dir}\", file=sys.stderr)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": ".claude/skills/skill-creator/scripts/utils.py",
    "content": "\"\"\"Shared utilities for skill-creator scripts.\"\"\"\n\nfrom pathlib import Path\n\n\n\ndef parse_skill_md(skill_path: Path) -> tuple[str, str, str]:\n    \"\"\"Parse a SKILL.md file, returning (name, description, full_content).\"\"\"\n    content = (skill_path / \"SKILL.md\").read_text()\n    lines = content.split(\"\\n\")\n\n    if lines[0].strip() != \"---\":\n        raise ValueError(\"SKILL.md missing frontmatter (no opening ---)\")\n\n    end_idx = None\n    for i, line in enumerate(lines[1:], start=1):\n        if line.strip() == \"---\":\n            end_idx = i\n            break\n\n    if end_idx is None:\n        raise ValueError(\"SKILL.md missing frontmatter (no closing ---)\")\n\n    name = \"\"\n    description = \"\"\n    frontmatter_lines = lines[1:end_idx]\n    i = 0\n    while i < len(frontmatter_lines):\n        line = frontmatter_lines[i]\n        if line.startswith(\"name:\"):\n            name = line[len(\"name:\"):].strip().strip('\"').strip(\"'\")\n        elif line.startswith(\"description:\"):\n            value = line[len(\"description:\"):].strip()\n            # Handle YAML multiline indicators (>, |, >-, |-)\n            if value in (\">\", \"|\", \">-\", \"|-\"):\n                continuation_lines: list[str] = []\n                i += 1\n                while i < len(frontmatter_lines) and (frontmatter_lines[i].startswith(\"  \") or frontmatter_lines[i].startswith(\"\\t\")):\n                    continuation_lines.append(frontmatter_lines[i].strip())\n                    i += 1\n                description = \" \".join(continuation_lines)\n                continue\n            else:\n                description = value.strip('\"').strip(\"'\")\n        i += 1\n\n    return name, description, content\n"
  },
  {
    "path": ".gitignore",
    "content": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/dist\n/dst\n.idea\n\nfirst\ndst-admin-go\ndst-admin-go.exe\ndst-admin-go.log\ndst-db\npassword.txt\n/.pnp\n.pnp.js\n\n# testing\n/coverage\n.vscode\n# production\n/build\n\n# misc\n.DS_Store\n.env.local\n.env.development.local\n.env.test.local\n.env.production.local\n\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n\n#py-dst-cli\n/script/py-dst-cli/__pycache__\n/script/py-dst-cli/data\n\n/test"
  },
  {
    "path": "CLAUDE.md",
    "content": "# CLAUDE.md\n\nThis file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.\n\n## Project Overview\n\nDST Admin Go is a web-based management panel for \"Don't Starve Together\" game servers. Written in Go, it provides a simple deployment, low memory footprint, and visual interface for managing game configurations, mods, clusters, backups, and multi-server operations across both Windows and Linux platforms.\n\n## Development Commands\n\n### Running the Application\n\n```bash\n# Install dependencies\ngo mod tidy\n\n# Run the application\ngo run cmd/server/main.go\n```\n\nThe server starts on port 8082 by default (configurable in `config.yml`).\n\n### Building\n\n```bash\n# Build for Linux\nbash scripts/build_linux.sh\n# Output: dst-admin-go (Linux amd64 binary)\n\n# Build for Windows\nbash scripts/build_window.sh\n# Output: dst-admin-go.exe (Windows amd64 binary)\n\n# Cross-platform build from Windows to Linux\nset GOARCH=amd64\nset GOOS=linux\ngo build\n```\n\n### Testing\n\nNo test files currently exist in the project. When writing tests, place them adjacent to the code they test with `_test.go` suffix.\n\n## Code Architecture\n\n### Entry Point\n\n- **Main entry**: `cmd/server/main.go` - Loads config, initializes database, sets up router, and starts the HTTP server.\n\n### Project Structure\n\n```\ndst-admin-go/\n├── cmd/server/           # Application entry point\n├── internal/             # Private application code\n│   ├── api/             # HTTP layer\n│   │   ├── handler/     # HTTP handlers (controllers)\n│   │   └── router.go    # Route registration and DI setup\n│   ├── config/          # Configuration loading\n│   ├── database/        # Database initialization\n│   ├── middleware/      # HTTP middleware (auth, error handling, cluster context)\n│   ├── model/           # Database models (GORM entities)\n│   ├── pkg/             # Internal shared utilities\n│   │   ├── response/    # Standard HTTP response helpers\n│   │   └── utils/       # Utility functions (file, shell, system, etc.)\n│   └── service/         # Business logic layer\n│       ├── archive/     # Archive path resolution\n│       ├── backup/      # Backup management\n│       ├── dstConfig/   # DST configuration management\n│       ├── dstPath/     # Platform-specific path handling\n│       ├── game/        # Game process management (start/stop/command)\n│       ├── gameArchive/ # Game archive operations\n│       ├── gameConfig/  # Game configuration files\n│       ├── level/       # Level (world) management\n│       ├── levelConfig/ # Level configuration parsing\n│       ├── login/       # Authentication\n│       ├── mod/         # Mod management\n│       ├── player/      # Player management\n│       └── update/      # Game update management\n├── scripts/             # Build and utility scripts\n└── config.yml          # Application configuration file\n```\n\n### Layered Architecture\n\nThe codebase follows a three-layer architecture:\n\n1. **Handler Layer** (`internal/api/handler/`): HTTP request handling, input validation, response formatting\n2. **Service Layer** (`internal/service/`): Business logic, orchestration between services\n3. **Model Layer** (`internal/model/`): Database entities (GORM models)\n\n### Dependency Injection\n\nAll services are instantiated in `internal/api/router.go` using constructor functions (`New{Service}Service`), then injected into handlers. This pattern:\n- Avoids global variables\n- Makes dependencies explicit\n- Enables testing with mock implementations\n\nExample flow:\n```\nrouter.go creates services → injects into handlers → handlers registered to routes\n```\n\n### Platform Abstraction\n\nServices use factory patterns for platform-specific implementations:\n- **Game Process**: `game.NewGame()` returns `LinuxProcess` or `WindowProcess` based on `runtime.GOOS`\n- **Update Service**: `update.NewUpdateService()` handles Linux/Windows differences\n- **DST Paths**: `dstPath` package provides platform-specific path resolution\n\n### Service Interfaces\n\nCore services define interfaces for flexibility and testing:\n- `dstConfig.Config`: DST configuration CRUD operations\n- `game.Process`: Game server lifecycle management\n- Simpler services may omit interfaces and use concrete types directly\n\n## Configuration\n\nThe application reads `config.yml` in the working directory:\n\n```yaml\nbindAddress: \"\"        # Bind address (empty = all interfaces)\nport: 8082            # HTTP server port\ndatabase: dst-db      # SQLite database filename\nsteamAPIKey: \"\"       # Steam API key (optional)\nautoCheck:            # Auto-check intervals (in minutes)\n  masterInterval: 5\n  cavesInterval: 5\n  masterModInterval: 10\n  # ... other intervals\n```\n\n## Database\n\n- **ORM**: GORM with SQLite (via glebarez/sqlite)\n- **Initialization**: `internal/database/sqlite.go` - Auto-migrates all models in `internal/model/`\n- **Models**: Represent game data (clusters, players, mods, backups, logs, etc.)\n\n## API Refactoring Guidelines\n\nThe project is undergoing a refactoring effort documented in `.sisyphus/plans/`. Key principles:\n\n### Code Organization Rules\n\n1. **No global variables**: Pass config and dependencies through constructors\n2. **No constants package**: Define constants locally using `const ()` blocks within each module\n3. **No VO suffix**: Data structures defined in services use PascalCase without VO suffix\n4. **Internal-only changes**: Do not modify code outside `internal/` directory\n5. **Dependency injection**: All service dependencies injected via constructors\n\n### Handler Pattern\n\nEach handler:\n- Is in `internal/api/handler/{name}_handler.go`\n- Has a `RegisterRoute(router *gin.RouterGroup)` method\n- Uses injected services for business logic\n- Uses `internal/pkg/response` for standardized responses\n\n### Service Pattern\n\nEach service:\n- Is in `internal/service/{domain}/` directory\n- Has a constructor `New{Service}Service()` accepting dependencies\n- Defines interfaces for core abstractions (optional for simple services)\n- Handles a single domain of business logic\n\n### Naming Conventions\n\n- **Files**: `snake_case.go` (e.g., `backup_service.go`)\n- **Interfaces**: `{ServiceName}` (e.g., `Config`, `Process`)\n- **Structs**: `PascalCase` without suffix (e.g., `BackupSnapshot` not `BackupSnapshotVO`)\n- **Constructors**: `New{Name}` (e.g., `NewBackupService`)\n\n## Game Server Management\n\nThe application manages Don't Starve Together dedicated servers:\n\n- **Clusters**: A cluster contains multiple \"levels\" (worlds) - typically Master (overworld) and Caves\n- **Process Management**: Uses platform-specific commands (screen/tmux on Linux, custom CLI on Windows)\n- **Configuration Files**: Parses and modifies Lua config files (`cluster.ini`, `leveldataoverride.lua`, `modoverrides.lua`)\n- **Session Names**: Identifies running processes by cluster and level names\n\n## Utilities\n\nCommon utilities in `internal/pkg/utils/`:\n- **fileUtils**: File operations, archive extraction\n- **shellUtils**: Execute shell commands\n- **systemUtils**: System information (CPU, memory)\n- **dstConfigUtils**: DST config file parsing\n- **luaUtils**: Lua table parsing/generation\n- **collectionUtils**: Slice/map helpers\n- **clusterUtils**: Cluster-specific utilities\n\n## Development Notes\n\n- Go version: 1.20+\n- Web framework: Gin\n- Session management: gin-contrib/sessions with memstore\n- Authentication: Session-based, checked via `middleware.Authentication`\n- All routes except `/hello` and login endpoints require authentication\n- Chinese comments and messages common in codebase (target audience is Chinese users)"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README-EN.md",
    "content": "# dst-admin-go\n> dst-admin-go manage web\n>\n> preview https://carrot-hu23.github.io/dst-admin-go-preview/\n\n[English](README-EN.md)/[中文](README.md)\n\n**Now supports both Windows and Linux platforms**\n\n## About\n\nDST Admin Go is a web-based management panel for \"Don't Starve Together\" dedicated servers, written in Go. Key features include:\n\n- 🚀 **Easy Deployment**: Single executable binary, no complex configuration required\n- 💾 **Low Resource Usage**: Built with Go, minimal memory footprint and high performance\n- 🎨 **Modern UI**: Clean and intuitive web interface\n- ⚙️ **Feature-Rich**:\n  - Visual configuration for game rooms and world settings\n  - Online mod management and configuration\n  - Multi-cluster and multi-world support\n  - Game save backup and snapshot restoration\n  - Player management (whitelist, blacklist, administrators)\n  - Real-time log viewing and game console access\n  - Automatic game server update detection\n\n## Preview\n\n![首页效果](docs/image/dashboard.png)\n![首页效果](docs/image/panel.png)\n![首页效果](docs/image/toomanyitemplus.png)\n![首页效果](docs/image/player.png)\n![房间效果](docs/image/home.png)\n![世界效果](docs/image/level.png)\n![世界效果](docs/image/selectormod.png)\n![模组效果](docs/image/mod1.png)\n![模组效果](docs/image/mod3.png)\n![模组效果](docs/image/mod2.png)\n![日志效果](docs/image/playerlog.png)\n![大厅效果](docs/image/lobby.png)\n\n\n\n## Run\n\n**Edit config.yml**\n```yaml\n# Bind address\nbindAddress: \"\"\n# Port\nport: 8082\n# Database\ndatabase: dst-db\n```\n\nRun\n```bash\ngo mod tidy\ngo run cmd/server/main.go\n```\n\n## Build\n\n### Build for Linux\n\n```bash\nbash scripts/build_linux.sh\n# Output: dst-admin-go (Linux amd64 binary)\n```\n\n### Build for Windows\n\n```bash\nbash scripts/build_window.sh\n# Output: dst-admin-go.exe (Windows amd64 binary)\n```\n\n### Cross-compile from Windows to Linux\n\n```cmd\n# Open cmd\nset GOARCH=amd64\nset GOOS=linux\ngo build -o dst-admin-go cmd/server/main.go\n```\n\n## QQ Group\n![QQ 群](docs/image/饥荒开服面板交流issue群聊二维码.png)"
  },
  {
    "path": "README.md",
    "content": "# dst-admin-go\n> 饥荒联机版管理后台\n> \n> 预览 https://carrot-hu23.github.io/dst-admin-go-preview/\n\n[English](README-EN.md)/[中文](README.md)\n\n**新面板 [泰拉瑞亚面板](https://github.com/carrot-hu23/terraria-panel-app) 支持window,linux 一键启动，内置 1449 版本**\n\n## 推广\n**广告位招租，联系QQ 1762858544**\n\n[【腾讯云】热卖套餐配置低至32元/月起，助您一键开服，即刻畅玩，立享优惠！](https://cloud.tencent.com/act/cps/redirect?redirect=5878&cps_key=8478a20880d339923787a350f9f8cbf5&from=console)\n![tengxunad1](docs/image/tengxunad1.png)\n\n## 项目简介\n\n**现已支持 Windows 和 Linux 平台**\n> 注意：Windows Server 低版本系统请使用 1.2.8 之前的版本，高版本系统使用最新版本\n\nDST Admin Go 是一个使用 Go 语言开发的《饥荒联机版》服务器管理面板，具有以下特点：\n\n- 🚀 **部署简单**：单个可执行文件，无需复杂配置，开箱即用\n- 💾 **资源占用低**：基于 Go 语言开发，内存占用小，运行高效\n- 🎨 **界面美观**：现代化的 Web 界面，操作直观友好\n- ⚙️ **功能完善**：\n  - 可视化配置游戏房间和世界参数\n  - 在线管理和配置 Mod（模组）\n  - 支持多个集群（Cluster）和世界的统一管理\n  - 游戏存档备份与快照恢复\n  - 玩家管理（白名单、黑名单、管理员）\n  - 实时日志查看和游戏控制台\n  - 游戏服务器自动更新检测\n\n## 部署\n注意目录必须要有读写权限。\n\n点击查看 [部署文档](https://carrot-hu23.github.io/dst-admin-go-docs/)\n\n## 预览\n\n![首页效果](docs/image/dashboard.png)\n![首页效果](docs/image/panel.png)\n![首页效果](docs/image/toomanyitemplus.png)\n![首页效果](docs/image/player.png)\n![房间效果](docs/image/home.png)\n![世界效果](docs/image/level.png)\n![世界效果](docs/image/selectormod.png)\n![模组效果](docs/image/mod1.png)\n![模组效果](docs/image/mod3.png)\n![模组效果](docs/image/mod2.png)\n![日志效果](docs/image/playerlog.png)\n![大厅效果](docs/image/lobby.png)\n\n## 运行\n\n**修改config.yml**\n```yaml\n#绑定地址\nbindAddress: \"\"\n#启动端口\nport: 8082\n#数据库\ndatabase: dst-db\n```\n\n运行\n```bash\ngo mod tidy\ngo run cmd/server/main.go\n```\n\n## 打包\n\n### Linux 打包\n\n```bash\nbash scripts/build_linux.sh\n# 输出: dst-admin-go (Linux amd64 二进制文件)\n```\n\n### Windows 打包\n\n```bash\nbash scripts/build_window.sh\n# 输出: dst-admin-go.exe (Windows amd64 二进制文件)\n```\n\n### Window 下打包 Linux 二进制\n\n```cmd\n打开 cmd\nset GOARCH=amd64\nset GOOS=linux\ngo build -o dst-admin-go cmd/server/main.go\n```\n\n## QQ 群\n![QQ 群](docs/image/饥荒开服面板交流issue群聊二维码.png)\n\n\n"
  },
  {
    "path": "cmd/server/main.go",
    "content": "// @title           DST Admin Go API\n// @version         1.0\n// @description     饥荒联机版服务器管理后台 API 文档\n// @termsOfService  http://swagger.io/terms/\n\n// @contact.name   API Support\n// @contact.url    https://github.com/carrot-hu23/dst-admin-go\n// @license.name  Apache 2.0\n// @license.url   http://www.apache.org/licenses/LICENSE-2.0.html\n\n// @host      localhost:8082\n// @BasePath  /\n\n// @securityDefinitions.apikey BearerAuth\n// @in header\n// @name Authorization\n// @description Type \"Bearer\" followed by a space and JWT token.\n\npackage main\n\nimport (\n\t\"dst-admin-go/internal/api\"\n\t\"dst-admin-go/internal/config\"\n\t\"dst-admin-go/internal/database\"\n\t\"fmt\"\n)\n\nfunc main() {\n\n\tcfg := config.Load()\n\tdb := database.InitDB(cfg)\n\n\troute := api.NewRoute(cfg, db)\n\n\terr := route.Run(cfg.BindAddress + \":\" + cfg.Port)\n\tif err != nil {\n\t\tfmt.Println(\"启动失败！！！\", err)\n\t}\n}\n"
  },
  {
    "path": "config.yml",
    "content": "#绑定地址\nbindAddress: \"\"\n#启动端口\nport: 8082\n#数据库\ndatabase: dst-db\n#自动检测 单位都是 分钟\nautoCheck:\n  # 森林状态检测间隔时间\n  masterInterval: 5\n  # 洞穴状态检测间隔时间\n  cavesInterval: 5\n  # 森林模组更新检测间隔时间\n  masterModInterval: 10\n  # 洞穴模组更新检测间隔时间\n  cavesIModInterval: 10\n  # 游戏更新检测间隔时间\n  gameUpdateInterval: 20\n  modUpdatePrompt: \"xxx\"\n  gameUpdatePrompt: \"xxx\"\n"
  },
  {
    "path": "docs/docs.go",
    "content": "// Package docs Code generated by swaggo/swag. DO NOT EDIT\npackage docs\n\nimport \"github.com/swaggo/swag\"\n\nconst docTemplate = `{\n    \"schemes\": {{ marshal .Schemes }},\n    \"swagger\": \"2.0\",\n    \"info\": {\n        \"description\": \"{{escape .Description}}\",\n        \"title\": \"{{.Title}}\",\n        \"termsOfService\": \"http://swagger.io/terms/\",\n        \"contact\": {\n            \"name\": \"API Support\",\n            \"url\": \"https://github.com/carrot-hu23/dst-admin-go\"\n        },\n        \"license\": {\n            \"name\": \"Apache 2.0\",\n            \"url\": \"http://www.apache.org/licenses/LICENSE-2.0.html\"\n        },\n        \"version\": \"{{.Version}}\"\n    },\n    \"host\": \"{{.Host}}\",\n    \"basePath\": \"{{.BasePath}}\",\n    \"paths\": {\n        \"/api/cluster/level\": {\n            \"get\": {\n                \"description\": \"获取指定世界的详细信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"level\"\n                ],\n                \"summary\": \"获取单个世界\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"世界名称\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"put\": {\n                \"description\": \"批量更新多个世界的配置信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"level\"\n                ],\n                \"summary\": \"批量更新世界\",\n                \"parameters\": [\n                    {\n                        \"description\": \"世界配置信息列表\",\n                        \"name\": \"levels\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"array\",\n                            \"items\": {\n                                \"$ref\": \"#/definitions/levelConfig.LevelInfo\"\n                            }\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"创建一个新的世界(等级)\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"level\"\n                ],\n                \"summary\": \"创建世界\",\n                \"parameters\": [\n                    {\n                        \"description\": \"世界配置信息\",\n                        \"name\": \"level\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/levelConfig.LevelInfo\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"delete\": {\n                \"description\": \"删除指定的世界\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"level\"\n                ],\n                \"summary\": \"删除世界\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"世界名称\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/dst/map/gen\": {\n            \"get\": {\n                \"description\": \"生成地图\",\n                \"tags\": [\n                    \"dstMap\"\n                ],\n                \"summary\": \"生成地图\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"levelName\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    },\n                    \"400\": {\n                        \"description\": \"Bad Request\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/dst/map/has/walrusHut/plains\": {\n            \"get\": {\n                \"description\": \"检测地图中是否有walrusHutPlains\",\n                \"tags\": [\n                    \"dstMap\"\n                ],\n                \"summary\": \"检测地图中是否有walrusHutPlains\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"levelName\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    },\n                    \"400\": {\n                        \"description\": \"Bad Request\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/dst/map/image\": {\n            \"get\": {\n                \"description\": \"获取地图图片\",\n                \"tags\": [\n                    \"dstMap\"\n                ],\n                \"summary\": \"获取地图图片\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"levelName\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    },\n                    \"400\": {\n                        \"description\": \"Bad Request\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/dst/map/player/session/file\": {\n            \"get\": {\n                \"description\": \"获取玩家存档文件\",\n                \"tags\": [\n                    \"dstMap\"\n                ],\n                \"summary\": \"获取玩家存档文件\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"levelName\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    },\n                    \"400\": {\n                        \"description\": \"Bad Request\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/dst/map/session/file\": {\n            \"get\": {\n                \"description\": \"获取存档文件\",\n                \"tags\": [\n                    \"dstMap\"\n                ],\n                \"summary\": \"获取存档文件\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"levelName\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    },\n                    \"400\": {\n                        \"description\": \"Bad Request\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/8level/status\": {\n            \"get\": {\n                \"description\": \"获取所有世界的运行状态信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"game\"\n                ],\n                \"summary\": \"获取服务器状态\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"type\": \"array\",\n                                            \"items\": {\n                                                \"$ref\": \"#/definitions/handler.LevelStatus\"\n                                            }\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/archive\": {\n            \"get\": {\n                \"description\": \"获取当前集群的游戏存档列表\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"game\"\n                ],\n                \"summary\": \"获取游戏存档列表\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/backup\": {\n            \"get\": {\n                \"description\": \"获取当前集群的所有备份文件列表\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"获取备份列表\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"put\": {\n                \"description\": \"重命名指定的备份文件\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"重命名备份\",\n                \"parameters\": [\n                    {\n                        \"description\": \"请求体\",\n                        \"name\": \"request\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"object\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"创建新的游戏存档备份\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"创建备份\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"备份名称\",\n                        \"name\": \"backupName\",\n                        \"in\": \"query\"\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"delete\": {\n                \"description\": \"删除指定的备份文件\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"删除备份\",\n                \"parameters\": [\n                    {\n                        \"description\": \"要删除的文件名列表\",\n                        \"name\": \"fileNames\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"array\",\n                            \"items\": {\n                                \"type\": \"string\"\n                            }\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/backup/download\": {\n            \"get\": {\n                \"description\": \"下载指定的备份文件\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"下载备份\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"备份文件名\",\n                        \"name\": \"backupName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/backup/snapshot/list\": {\n            \"get\": {\n                \"description\": \"获取当前集群的所有快照备份列表\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"获取快照列表\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/backup/snapshot/setting\": {\n            \"get\": {\n                \"description\": \"获取自动快照备份的设置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"获取快照设置\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"保存自动快照备份的设置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"保存快照设置\",\n                \"parameters\": [\n                    {\n                        \"description\": \"快照设置\",\n                        \"name\": \"setting\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/model.BackupSnapshot\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/backup/upload\": {\n            \"post\": {\n                \"description\": \"上传新的备份文件\",\n                \"consumes\": [\n                    \"multipart/form-data\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"上传备份\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/command\": {\n            \"post\": {\n                \"description\": \"运行命令\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"game\"\n                ],\n                \"summary\": \"运行命令\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"命令\",\n                        \"name\": \"command\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/config\": {\n            \"get\": {\n                \"description\": \"获取房间配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"gameConfig\"\n                ],\n                \"summary\": \"获取房间配置\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"$ref\": \"#/definitions/gameConfig.HomeConfigVO\"\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/config/adminlist\": {\n            \"get\": {\n                \"description\": \"获取房间 adminlist.txt 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"gameConfig\"\n                ],\n                \"summary\": \"获取房间 adminlist.txt 配置\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"type\": \"array\",\n                                            \"items\": {\n                                                \"type\": \"string\"\n                                            }\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"保存房间 adminlist.txt 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"gameConfig\"\n                ],\n                \"summary\": \"保存房间 adminlist.txt 配置\",\n                \"parameters\": [\n                    {\n                        \"description\": \"adminlist.txt 配置\",\n                        \"name\": \"list\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"array\",\n                            \"items\": {\n                                \"type\": \"string\"\n                            }\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/config/blacklist\": {\n            \"get\": {\n                \"description\": \"获取房间 blacklist.txt 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"gameConfig\"\n                ],\n                \"summary\": \"获取房间 blacklist.txt 配置\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"type\": \"array\",\n                                            \"items\": {\n                                                \"type\": \"string\"\n                                            }\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"保存房间 blacklist.txt 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"gameConfig\"\n                ],\n                \"summary\": \"保存房间 blacklist.txt 配置\",\n                \"parameters\": [\n                    {\n                        \"description\": \"blacklist.txt 配置\",\n                        \"name\": \"list\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"array\",\n                            \"items\": {\n                                \"type\": \"string\"\n                            }\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/config/clusterIni\": {\n            \"get\": {\n                \"description\": \"获取房间 cluster.ini 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"gameConfig\"\n                ],\n                \"summary\": \"获取房间 cluster.ini 配置\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"$ref\": \"#/definitions/gameConfig.ClusterIniConfig\"\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"保存房间 cluster.ini 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"gameConfig\"\n                ],\n                \"summary\": \"保存房间 cluster.ini 配置\",\n                \"parameters\": [\n                    {\n                        \"description\": \"cluster.ini 配置\",\n                        \"name\": \"config\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/gameConfig.ClusterIniConfig\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/config/whitelist\": {\n            \"get\": {\n                \"description\": \"获取房间 whitelist.txt 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"gameConfig\"\n                ],\n                \"summary\": \"获取房间 whitelist.txt 配置\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"type\": \"array\",\n                                            \"items\": {\n                                                \"type\": \"string\"\n                                            }\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"保存房间 whitelist.txt 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"gameConfig\"\n                ],\n                \"summary\": \"保存房间 whitelist.txt 配置\",\n                \"parameters\": [\n                    {\n                        \"description\": \"whitelist.txt 配置\",\n                        \"name\": \"list\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"array\",\n                            \"items\": {\n                                \"type\": \"string\"\n                            }\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/dst/config\": {\n            \"get\": {\n                \"description\": \"获取房间 dst 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"dstConfig\"\n                ],\n                \"summary\": \"获取房间 dst 配置\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"$ref\": \"#/definitions/dstConfig.DstConfig\"\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"保存房间 dst 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"dstConfig\"\n                ],\n                \"summary\": \"保存房间 dst 配置\",\n                \"parameters\": [\n                    {\n                        \"description\": \"dst 配置\",\n                        \"name\": \"config\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/dstConfig.DstConfig\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/level/server/download\": {\n            \"get\": {\n                \"description\": \"下载指定世界的完整服务器日志文件\",\n                \"produces\": [\n                    \"application/octet-stream\"\n                ],\n                \"tags\": [\n                    \"log\"\n                ],\n                \"summary\": \"下载服务器日志\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"集群名称\",\n                        \"name\": \"clusterName\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"世界名称\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"服务器日志文件\",\n                        \"schema\": {\n                            \"type\": \"file\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/level/server/log\": {\n            \"get\": {\n                \"description\": \"获取指定世界的服务器日志（默认最近100行）\",\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"log\"\n                ],\n                \"summary\": \"获取服务器日志\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"集群名称\",\n                        \"name\": \"clusterName\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"世界名称\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"返回日志行数，默认为100\",\n                        \"name\": \"lines\",\n                        \"in\": \"query\"\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"服务器日志列表\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"type\": \"array\",\n                                            \"items\": {\n                                                \"type\": \"string\"\n                                            }\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/log/stream\": {\n            \"get\": {\n                \"description\": \"获取指定世界的实时日志流 (SSE)\",\n                \"consumes\": [\n                    \"text/event-stream\"\n                ],\n                \"produces\": [\n                    \"text/event-stream\"\n                ],\n                \"tags\": [\n                    \"log\"\n                ],\n                \"summary\": \"服务器日志流\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"集群名称\",\n                        \"name\": \"clusterName\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"世界名称\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"SSE 格式的日志流\",\n                        \"schema\": {\n                            \"type\": \"string\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/start\": {\n            \"get\": {\n                \"description\": \"启动世界\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"game\"\n                ],\n                \"summary\": \"启动世界\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"世界名称\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/start/all\": {\n            \"get\": {\n                \"description\": \"启动所有世界\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"game\"\n                ],\n                \"summary\": \"启动所有世界\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/stop\": {\n            \"get\": {\n                \"description\": \"停止世界\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"game\"\n                ],\n                \"summary\": \"停止世界\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"世界名称\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/stop/all\": {\n            \"get\": {\n                \"description\": \"停止所有世界\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"game\"\n                ],\n                \"summary\": \"停止所有世界\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/system/info/stream\": {\n            \"get\": {\n                \"description\": \"获取服务器系统信息的实时流 (SSE)\",\n                \"consumes\": [\n                    \"text/event-stream\"\n                ],\n                \"produces\": [\n                    \"text/event-stream\"\n                ],\n                \"tags\": [\n                    \"game\"\n                ],\n                \"summary\": \"系统信息流\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"SSE 格式的系统信息流\",\n                        \"schema\": {\n                            \"type\": \"string\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/update\": {\n            \"get\": {\n                \"description\": \"更新游戏\",\n                \"tags\": [\n                    \"update\"\n                ],\n                \"summary\": \"更新游戏\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/init\": {\n            \"get\": {\n                \"description\": \"检查系统是否进行了首次初始化\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"user\"\n                ],\n                \"summary\": \"检查是否首次初始化\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"初始化系统首次用户信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"user\"\n                ],\n                \"summary\": \"初始化首次用户\",\n                \"parameters\": [\n                    {\n                        \"description\": \"用户信息\",\n                        \"name\": \"userInfo\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/login.UserInfo\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/kv\": {\n            \"get\": {\n                \"description\": \"获取kv值\",\n                \"tags\": [\n                    \"kv\"\n                ],\n                \"summary\": \"获取kv值\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"key\",\n                        \"name\": \"key\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"保存kv值\",\n                \"tags\": [\n                    \"kv\"\n                ],\n                \"summary\": \"保存kv值\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"key\",\n                        \"name\": \"key\",\n                        \"in\": \"formData\",\n                        \"required\": true\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"value\",\n                        \"name\": \"value\",\n                        \"in\": \"formData\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/mod\": {\n            \"get\": {\n                \"description\": \"获取已订阅的模组列表\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"获取我的mod列表\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/mod/modinfo\": {\n            \"put\": {\n                \"description\": \"批量更新所有已订阅模组的信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"批量更新模组信息\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"default\": \"zh\",\n                        \"description\": \"语言\",\n                        \"name\": \"lang\",\n                        \"in\": \"query\"\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"保存模组配置信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"保存模组配置文件\",\n                \"parameters\": [\n                    {\n                        \"description\": \"模组信息\",\n                        \"name\": \"data\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/mod.ModInfo\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"$ref\": \"#/definitions/mod.ModInfo\"\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/mod/modinfo/file\": {\n            \"post\": {\n                \"description\": \"手动添加模组配置文件\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"手动添加模组\",\n                \"parameters\": [\n                    {\n                        \"description\": \"模组信息\",\n                        \"name\": \"data\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"object\"\n                        }\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"default\": \"zh\",\n                        \"description\": \"语言\",\n                        \"name\": \"lang\",\n                        \"in\": \"query\"\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/mod/modinfo/{modId}\": {\n            \"get\": {\n                \"description\": \"根据modId获取模组配置文件内容\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"获取模组配置文件\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"模组ID\",\n                        \"name\": \"modId\",\n                        \"in\": \"path\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"$ref\": \"#/definitions/mod.ModInfo\"\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/mod/search\": {\n            \"get\": {\n                \"description\": \"搜索Steam创意工坊中的模组\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"搜索mod列表\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"搜索关键词\",\n                        \"name\": \"text\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"integer\",\n                        \"default\": 1,\n                        \"description\": \"页码\",\n                        \"name\": \"page\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"integer\",\n                        \"default\": 10,\n                        \"description\": \"每页数量\",\n                        \"name\": \"size\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"default\": \"zh\",\n                        \"description\": \"语言\",\n                        \"name\": \"lang\",\n                        \"in\": \"query\"\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/mod/setup/workshop\": {\n            \"delete\": {\n                \"description\": \"删除所有workshop模组文件\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"删除workshop文件\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/mod/ugc\": {\n            \"delete\": {\n                \"description\": \"删除UGC模组文件\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"删除UGC模组文件\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"世界名称\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"WorkshopID\",\n                        \"name\": \"workshopId\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/mod/ugc/acf\": {\n            \"get\": {\n                \"description\": \"获取UGC模组的ACF文件信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"获取UGC mod acf文件信息\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"世界名称\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/mod/{modId}\": {\n            \"get\": {\n                \"description\": \"根据modId获取模组详细信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"获取mod信息\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"模组ID\",\n                        \"name\": \"modId\",\n                        \"in\": \"path\",\n                        \"required\": true\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"default\": \"zh\",\n                        \"description\": \"语言\",\n                        \"name\": \"lang\",\n                        \"in\": \"query\"\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"put\": {\n                \"description\": \"根据modId更新模组\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"更新模组\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"模组ID\",\n                        \"name\": \"modId\",\n                        \"in\": \"path\",\n                        \"required\": true\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"default\": \"zh\",\n                        \"description\": \"语言\",\n                        \"name\": \"lang\",\n                        \"in\": \"query\"\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"delete\": {\n                \"description\": \"根据modId删除模组\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"删除模组\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"模组ID\",\n                        \"name\": \"modId\",\n                        \"in\": \"path\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/player/log\": {\n            \"get\": {\n                \"description\": \"分页查询玩家日志\",\n                \"tags\": [\n                    \"playerLog\"\n                ],\n                \"summary\": \"分页查询玩家日志\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"玩家名称\",\n                        \"name\": \"name\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"KuId\",\n                        \"name\": \"kuId\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"SteamId\",\n                        \"name\": \"steamId\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"角色\",\n                        \"name\": \"role\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"操作\",\n                        \"name\": \"action\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"IP地址\",\n                        \"name\": \"ip\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"integer\",\n                        \"default\": 1,\n                        \"description\": \"页码\",\n                        \"name\": \"page\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"integer\",\n                        \"default\": 10,\n                        \"description\": \"每页数量\",\n                        \"name\": \"size\",\n                        \"in\": \"query\"\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/player/log/delete\": {\n            \"post\": {\n                \"description\": \"删除玩家日志\",\n                \"tags\": [\n                    \"playerLog\"\n                ],\n                \"summary\": \"删除玩家日志\",\n                \"parameters\": [\n                    {\n                        \"description\": \"ID列表\",\n                        \"name\": \"ids\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"array\",\n                            \"items\": {\n                                \"type\": \"integer\"\n                            }\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/player/log/delete/all\": {\n            \"get\": {\n                \"description\": \"删除所有玩家\",\n                \"tags\": [\n                    \"playerLog\"\n                ],\n                \"summary\": \"删除所有玩家日志\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/user/changePassword\": {\n            \"post\": {\n                \"description\": \"修改密码\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"user\"\n                ],\n                \"summary\": \"修改密码\",\n                \"parameters\": [\n                    {\n                        \"description\": \"新密码\",\n                        \"name\": \"password\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"object\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/user/info\": {\n            \"get\": {\n                \"description\": \"获取用户信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"user\"\n                ],\n                \"summary\": \"获取用户信息\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"$ref\": \"#/definitions/login.UserInfo\"\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/user/login\": {\n            \"post\": {\n                \"description\": \"用户登录\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"user\"\n                ],\n                \"summary\": \"用户登录\",\n                \"parameters\": [\n                    {\n                        \"description\": \"用户信息\",\n                        \"name\": \"user\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/login.UserInfo\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/user/logout\": {\n            \"get\": {\n                \"description\": \"用户登出\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"user\"\n                ],\n                \"summary\": \"用户登出\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/user/update\": {\n            \"post\": {\n                \"description\": \"更新用户信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"user\"\n                ],\n                \"summary\": \"更新用户信息\",\n                \"parameters\": [\n                    {\n                        \"description\": \"用户信息\",\n                        \"name\": \"user\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"object\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/backup/restore\": {\n            \"get\": {\n                \"description\": \"从备份文件恢复游戏存档\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"恢复备份\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"备份文件名\",\n                        \"name\": \"backupName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        }\n    },\n    \"definitions\": {\n        \"dstConfig.DstConfig\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"backup\": {\n                    \"type\": \"string\"\n                },\n                \"beta\": {\n                    \"type\": \"integer\"\n                },\n                \"bin\": {\n                    \"type\": \"integer\"\n                },\n                \"cluster\": {\n                    \"type\": \"string\"\n                },\n                \"conf_dir\": {\n                    \"description\": \"存档相对位置\",\n                    \"type\": \"string\"\n                },\n                \"donot_starve_server_directory\": {\n                    \"type\": \"string\"\n                },\n                \"force_install_dir\": {\n                    \"type\": \"string\"\n                },\n                \"mod_download_path\": {\n                    \"type\": \"string\"\n                },\n                \"persistent_storage_root\": {\n                    \"description\": \"根目录位置\",\n                    \"type\": \"string\"\n                },\n                \"steamcmd\": {\n                    \"type\": \"string\"\n                },\n                \"ugc_directory\": {\n                    \"type\": \"string\"\n                }\n            }\n        },\n        \"game.DstPsAux\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"RSS\": {\n                    \"type\": \"string\"\n                },\n                \"VSZ\": {\n                    \"type\": \"string\"\n                },\n                \"cpuUage\": {\n                    \"type\": \"string\"\n                },\n                \"memUage\": {\n                    \"type\": \"string\"\n                }\n            }\n        },\n        \"gameConfig.ClusterIni\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"bind_ip\": {\n                    \"type\": \"string\"\n                },\n                \"cluster_description\": {\n                    \"type\": \"string\"\n                },\n                \"cluster_intention\": {\n                    \"type\": \"string\"\n                },\n                \"cluster_key\": {\n                    \"type\": \"string\"\n                },\n                \"cluster_language\": {\n                    \"type\": \"string\"\n                },\n                \"cluster_name\": {\n                    \"type\": \"string\"\n                },\n                \"cluster_password\": {\n                    \"type\": \"string\"\n                },\n                \"console_enabled\": {\n                    \"description\": \"[MISC]\",\n                    \"type\": \"boolean\"\n                },\n                \"game_mode\": {\n                    \"description\": \"[GAEMPLAY]\",\n                    \"type\": \"string\"\n                },\n                \"lan_only_cluster\": {\n                    \"description\": \"[NETWORK]\",\n                    \"type\": \"boolean\"\n                },\n                \"master_ip\": {\n                    \"type\": \"string\"\n                },\n                \"master_port\": {\n                    \"type\": \"integer\"\n                },\n                \"max_players\": {\n                    \"type\": \"integer\"\n                },\n                \"max_snapshots\": {\n                    \"type\": \"integer\"\n                },\n                \"offline_cluster\": {\n                    \"type\": \"boolean\"\n                },\n                \"pause_when_nobody\": {\n                    \"type\": \"boolean\"\n                },\n                \"pvp\": {\n                    \"type\": \"boolean\"\n                },\n                \"shard_enabled\": {\n                    \"description\": \"[SHARD]\",\n                    \"type\": \"boolean\"\n                },\n                \"steam_group_admins\": {\n                    \"type\": \"boolean\"\n                },\n                \"steam_group_id\": {\n                    \"description\": \"[STEAM]\",\n                    \"type\": \"string\"\n                },\n                \"steam_group_only\": {\n                    \"type\": \"boolean\"\n                },\n                \"tick_rate\": {\n                    \"type\": \"integer\"\n                },\n                \"vote_enabled\": {\n                    \"type\": \"boolean\"\n                },\n                \"vote_kick_enabled\": {\n                    \"type\": \"boolean\"\n                },\n                \"whitelist_slots\": {\n                    \"type\": \"integer\"\n                }\n            }\n        },\n        \"gameConfig.ClusterIniConfig\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"cluster\": {\n                    \"$ref\": \"#/definitions/gameConfig.ClusterIni\"\n                },\n                \"token\": {\n                    \"type\": \"string\"\n                }\n            }\n        },\n        \"gameConfig.HomeConfigVO\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"cavesMapData\": {\n                    \"type\": \"string\"\n                },\n                \"clusterDescription\": {\n                    \"type\": \"string\"\n                },\n                \"clusterIntention\": {\n                    \"type\": \"string\"\n                },\n                \"clusterName\": {\n                    \"type\": \"string\"\n                },\n                \"clusterPassword\": {\n                    \"type\": \"string\"\n                },\n                \"gameMode\": {\n                    \"type\": \"string\"\n                },\n                \"masterMapData\": {\n                    \"type\": \"string\"\n                },\n                \"maxPlayers\": {\n                    \"type\": \"integer\"\n                },\n                \"max_snapshots\": {\n                    \"type\": \"integer\"\n                },\n                \"modData\": {\n                    \"type\": \"string\"\n                },\n                \"pause_when_nobody\": {\n                    \"type\": \"boolean\"\n                },\n                \"pvp\": {\n                    \"type\": \"boolean\"\n                },\n                \"token\": {\n                    \"type\": \"string\"\n                },\n                \"type\": {\n                    \"type\": \"integer\"\n                },\n                \"vote_enabled\": {\n                    \"type\": \"boolean\"\n                }\n            }\n        },\n        \"handler.LevelStatus\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"Ps\": {\n                    \"$ref\": \"#/definitions/game.DstPsAux\"\n                },\n                \"isMaster\": {\n                    \"type\": \"boolean\"\n                },\n                \"levelName\": {\n                    \"type\": \"string\"\n                },\n                \"leveldataoverride\": {\n                    \"type\": \"string\"\n                },\n                \"modoverrides\": {\n                    \"type\": \"string\"\n                },\n                \"runVersion\": {\n                    \"type\": \"integer\"\n                },\n                \"serverIni\": {\n                    \"$ref\": \"#/definitions/levelConfig.ServerIni\"\n                },\n                \"status\": {\n                    \"type\": \"boolean\"\n                },\n                \"uuid\": {\n                    \"type\": \"string\"\n                }\n            }\n        },\n        \"levelConfig.LevelInfo\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"isMaster\": {\n                    \"type\": \"boolean\"\n                },\n                \"levelName\": {\n                    \"type\": \"string\"\n                },\n                \"leveldataoverride\": {\n                    \"type\": \"string\"\n                },\n                \"modoverrides\": {\n                    \"type\": \"string\"\n                },\n                \"runVersion\": {\n                    \"type\": \"integer\"\n                },\n                \"server_ini\": {\n                    \"$ref\": \"#/definitions/levelConfig.ServerIni\"\n                },\n                \"uuid\": {\n                    \"type\": \"string\"\n                }\n            }\n        },\n        \"levelConfig.ServerIni\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"authentication_port\": {\n                    \"description\": \"[STEAM]\",\n                    \"type\": \"integer\"\n                },\n                \"encode_user_path\": {\n                    \"description\": \"[ACCOUNT]\",\n                    \"type\": \"boolean\"\n                },\n                \"id\": {\n                    \"type\": \"integer\"\n                },\n                \"is_master\": {\n                    \"description\": \"[SHARD]\",\n                    \"type\": \"boolean\"\n                },\n                \"master_server_port\": {\n                    \"type\": \"integer\"\n                },\n                \"name\": {\n                    \"type\": \"string\"\n                },\n                \"server_port\": {\n                    \"description\": \"[NETWORK]\",\n                    \"type\": \"integer\"\n                }\n            }\n        },\n        \"login.UserInfo\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"displayName\": {\n                    \"type\": \"string\"\n                },\n                \"password\": {\n                    \"type\": \"string\"\n                },\n                \"photoURL\": {\n                    \"type\": \"string\"\n                },\n                \"username\": {\n                    \"type\": \"string\"\n                }\n            }\n        },\n        \"mod.ModInfo\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"author\": {\n                    \"type\": \"string\"\n                },\n                \"child\": {\n                    \"type\": \"array\",\n                    \"items\": {\n                        \"type\": \"string\"\n                    }\n                },\n                \"consumer_appid\": {\n                    \"type\": \"number\"\n                },\n                \"creator_appid\": {\n                    \"type\": \"number\"\n                },\n                \"desc\": {\n                    \"type\": \"string\"\n                },\n                \"file_url\": {\n                    \"type\": \"string\"\n                },\n                \"id\": {\n                    \"type\": \"string\"\n                },\n                \"img\": {\n                    \"type\": \"string\"\n                },\n                \"last_time\": {\n                    \"type\": \"number\"\n                },\n                \"name\": {\n                    \"type\": \"string\"\n                },\n                \"sub\": {\n                    \"type\": \"integer\"\n                },\n                \"time\": {\n                    \"type\": \"integer\"\n                },\n                \"v\": {\n                    \"type\": \"string\"\n                },\n                \"vote\": {\n                    \"type\": \"object\",\n                    \"properties\": {\n                        \"num\": {\n                            \"type\": \"integer\"\n                        },\n                        \"star\": {\n                            \"type\": \"integer\"\n                        }\n                    }\n                }\n            }\n        },\n        \"model.BackupSnapshot\": {\n            \"type\": \"object\"\n        },\n        \"response.Response\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"code\": {\n                    \"description\": \"提示代码\",\n                    \"type\": \"integer\"\n                },\n                \"data\": {\n                    \"description\": \"数据\"\n                },\n                \"msg\": {\n                    \"description\": \"提示信息\",\n                    \"type\": \"string\"\n                }\n            }\n        }\n    },\n    \"securityDefinitions\": {\n        \"BearerAuth\": {\n            \"description\": \"Type \\\"Bearer\\\" followed by a space and JWT token.\",\n            \"type\": \"apiKey\",\n            \"name\": \"Authorization\",\n            \"in\": \"header\"\n        }\n    }\n}`\n\n// SwaggerInfo holds exported Swagger Info so clients can modify it\nvar SwaggerInfo = &swag.Spec{\n\tVersion:          \"1.0\",\n\tHost:             \"localhost:8082\",\n\tBasePath:         \"/\",\n\tSchemes:          []string{},\n\tTitle:            \"DST Admin Go API\",\n\tDescription:      \"饥荒联机版服务器管理后台 API 文档\",\n\tInfoInstanceName: \"swagger\",\n\tSwaggerTemplate:  docTemplate,\n\tLeftDelim:        \"{{\",\n\tRightDelim:       \"}}\",\n}\n\nfunc init() {\n\tswag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)\n}\n"
  },
  {
    "path": "docs/swagger.json",
    "content": "{\n    \"swagger\": \"2.0\",\n    \"info\": {\n        \"description\": \"饥荒联机版服务器管理后台 API 文档\",\n        \"title\": \"DST Admin Go API\",\n        \"termsOfService\": \"http://swagger.io/terms/\",\n        \"contact\": {\n            \"name\": \"API Support\",\n            \"url\": \"https://github.com/carrot-hu23/dst-admin-go\"\n        },\n        \"license\": {\n            \"name\": \"Apache 2.0\",\n            \"url\": \"http://www.apache.org/licenses/LICENSE-2.0.html\"\n        },\n        \"version\": \"1.0\"\n    },\n    \"host\": \"localhost:8082\",\n    \"basePath\": \"/\",\n    \"paths\": {\n        \"/api/cluster/level\": {\n            \"get\": {\n                \"description\": \"获取指定世界的详细信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"level\"\n                ],\n                \"summary\": \"获取单个世界\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"世界名称\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"put\": {\n                \"description\": \"批量更新多个世界的配置信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"level\"\n                ],\n                \"summary\": \"批量更新世界\",\n                \"parameters\": [\n                    {\n                        \"description\": \"世界配置信息列表\",\n                        \"name\": \"levels\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"array\",\n                            \"items\": {\n                                \"$ref\": \"#/definitions/levelConfig.LevelInfo\"\n                            }\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"创建一个新的世界(等级)\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"level\"\n                ],\n                \"summary\": \"创建世界\",\n                \"parameters\": [\n                    {\n                        \"description\": \"世界配置信息\",\n                        \"name\": \"level\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/levelConfig.LevelInfo\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"delete\": {\n                \"description\": \"删除指定的世界\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"level\"\n                ],\n                \"summary\": \"删除世界\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"世界名称\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/dst/map/gen\": {\n            \"get\": {\n                \"description\": \"生成地图\",\n                \"tags\": [\n                    \"dstMap\"\n                ],\n                \"summary\": \"生成地图\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"levelName\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    },\n                    \"400\": {\n                        \"description\": \"Bad Request\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/dst/map/has/walrusHut/plains\": {\n            \"get\": {\n                \"description\": \"检测地图中是否有walrusHutPlains\",\n                \"tags\": [\n                    \"dstMap\"\n                ],\n                \"summary\": \"检测地图中是否有walrusHutPlains\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"levelName\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    },\n                    \"400\": {\n                        \"description\": \"Bad Request\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/dst/map/image\": {\n            \"get\": {\n                \"description\": \"获取地图图片\",\n                \"tags\": [\n                    \"dstMap\"\n                ],\n                \"summary\": \"获取地图图片\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"levelName\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    },\n                    \"400\": {\n                        \"description\": \"Bad Request\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/dst/map/player/session/file\": {\n            \"get\": {\n                \"description\": \"获取玩家存档文件\",\n                \"tags\": [\n                    \"dstMap\"\n                ],\n                \"summary\": \"获取玩家存档文件\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"levelName\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    },\n                    \"400\": {\n                        \"description\": \"Bad Request\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/dst/map/session/file\": {\n            \"get\": {\n                \"description\": \"获取存档文件\",\n                \"tags\": [\n                    \"dstMap\"\n                ],\n                \"summary\": \"获取存档文件\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"levelName\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    },\n                    \"400\": {\n                        \"description\": \"Bad Request\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/8level/status\": {\n            \"get\": {\n                \"description\": \"获取所有世界的运行状态信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"game\"\n                ],\n                \"summary\": \"获取服务器状态\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"type\": \"array\",\n                                            \"items\": {\n                                                \"$ref\": \"#/definitions/handler.LevelStatus\"\n                                            }\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/archive\": {\n            \"get\": {\n                \"description\": \"获取当前集群的游戏存档列表\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"game\"\n                ],\n                \"summary\": \"获取游戏存档列表\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/backup\": {\n            \"get\": {\n                \"description\": \"获取当前集群的所有备份文件列表\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"获取备份列表\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"put\": {\n                \"description\": \"重命名指定的备份文件\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"重命名备份\",\n                \"parameters\": [\n                    {\n                        \"description\": \"请求体\",\n                        \"name\": \"request\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"object\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"创建新的游戏存档备份\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"创建备份\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"备份名称\",\n                        \"name\": \"backupName\",\n                        \"in\": \"query\"\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"delete\": {\n                \"description\": \"删除指定的备份文件\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"删除备份\",\n                \"parameters\": [\n                    {\n                        \"description\": \"要删除的文件名列表\",\n                        \"name\": \"fileNames\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"array\",\n                            \"items\": {\n                                \"type\": \"string\"\n                            }\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/backup/download\": {\n            \"get\": {\n                \"description\": \"下载指定的备份文件\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"下载备份\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"备份文件名\",\n                        \"name\": \"backupName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/backup/snapshot/list\": {\n            \"get\": {\n                \"description\": \"获取当前集群的所有快照备份列表\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"获取快照列表\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/backup/snapshot/setting\": {\n            \"get\": {\n                \"description\": \"获取自动快照备份的设置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"获取快照设置\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"保存自动快照备份的设置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"保存快照设置\",\n                \"parameters\": [\n                    {\n                        \"description\": \"快照设置\",\n                        \"name\": \"setting\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/model.BackupSnapshot\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/backup/upload\": {\n            \"post\": {\n                \"description\": \"上传新的备份文件\",\n                \"consumes\": [\n                    \"multipart/form-data\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"上传备份\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/command\": {\n            \"post\": {\n                \"description\": \"运行命令\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"game\"\n                ],\n                \"summary\": \"运行命令\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"命令\",\n                        \"name\": \"command\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/config\": {\n            \"get\": {\n                \"description\": \"获取房间配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"gameConfig\"\n                ],\n                \"summary\": \"获取房间配置\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"$ref\": \"#/definitions/gameConfig.HomeConfigVO\"\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/config/adminlist\": {\n            \"get\": {\n                \"description\": \"获取房间 adminlist.txt 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"gameConfig\"\n                ],\n                \"summary\": \"获取房间 adminlist.txt 配置\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"type\": \"array\",\n                                            \"items\": {\n                                                \"type\": \"string\"\n                                            }\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"保存房间 adminlist.txt 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"gameConfig\"\n                ],\n                \"summary\": \"保存房间 adminlist.txt 配置\",\n                \"parameters\": [\n                    {\n                        \"description\": \"adminlist.txt 配置\",\n                        \"name\": \"list\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"array\",\n                            \"items\": {\n                                \"type\": \"string\"\n                            }\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/config/blacklist\": {\n            \"get\": {\n                \"description\": \"获取房间 blacklist.txt 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"gameConfig\"\n                ],\n                \"summary\": \"获取房间 blacklist.txt 配置\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"type\": \"array\",\n                                            \"items\": {\n                                                \"type\": \"string\"\n                                            }\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"保存房间 blacklist.txt 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"gameConfig\"\n                ],\n                \"summary\": \"保存房间 blacklist.txt 配置\",\n                \"parameters\": [\n                    {\n                        \"description\": \"blacklist.txt 配置\",\n                        \"name\": \"list\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"array\",\n                            \"items\": {\n                                \"type\": \"string\"\n                            }\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/config/clusterIni\": {\n            \"get\": {\n                \"description\": \"获取房间 cluster.ini 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"gameConfig\"\n                ],\n                \"summary\": \"获取房间 cluster.ini 配置\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"$ref\": \"#/definitions/gameConfig.ClusterIniConfig\"\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"保存房间 cluster.ini 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"gameConfig\"\n                ],\n                \"summary\": \"保存房间 cluster.ini 配置\",\n                \"parameters\": [\n                    {\n                        \"description\": \"cluster.ini 配置\",\n                        \"name\": \"config\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/gameConfig.ClusterIniConfig\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/config/whitelist\": {\n            \"get\": {\n                \"description\": \"获取房间 whitelist.txt 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"gameConfig\"\n                ],\n                \"summary\": \"获取房间 whitelist.txt 配置\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"type\": \"array\",\n                                            \"items\": {\n                                                \"type\": \"string\"\n                                            }\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"保存房间 whitelist.txt 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"gameConfig\"\n                ],\n                \"summary\": \"保存房间 whitelist.txt 配置\",\n                \"parameters\": [\n                    {\n                        \"description\": \"whitelist.txt 配置\",\n                        \"name\": \"list\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"array\",\n                            \"items\": {\n                                \"type\": \"string\"\n                            }\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/dst/config\": {\n            \"get\": {\n                \"description\": \"获取房间 dst 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"dstConfig\"\n                ],\n                \"summary\": \"获取房间 dst 配置\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"$ref\": \"#/definitions/dstConfig.DstConfig\"\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"保存房间 dst 配置\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"dstConfig\"\n                ],\n                \"summary\": \"保存房间 dst 配置\",\n                \"parameters\": [\n                    {\n                        \"description\": \"dst 配置\",\n                        \"name\": \"config\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/dstConfig.DstConfig\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/level/server/download\": {\n            \"get\": {\n                \"description\": \"下载指定世界的完整服务器日志文件\",\n                \"produces\": [\n                    \"application/octet-stream\"\n                ],\n                \"tags\": [\n                    \"log\"\n                ],\n                \"summary\": \"下载服务器日志\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"集群名称\",\n                        \"name\": \"clusterName\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"世界名称\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"服务器日志文件\",\n                        \"schema\": {\n                            \"type\": \"file\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/level/server/log\": {\n            \"get\": {\n                \"description\": \"获取指定世界的服务器日志（默认最近100行）\",\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"log\"\n                ],\n                \"summary\": \"获取服务器日志\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"集群名称\",\n                        \"name\": \"clusterName\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"世界名称\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"返回日志行数，默认为100\",\n                        \"name\": \"lines\",\n                        \"in\": \"query\"\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"服务器日志列表\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"type\": \"array\",\n                                            \"items\": {\n                                                \"type\": \"string\"\n                                            }\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/log/stream\": {\n            \"get\": {\n                \"description\": \"获取指定世界的实时日志流 (SSE)\",\n                \"consumes\": [\n                    \"text/event-stream\"\n                ],\n                \"produces\": [\n                    \"text/event-stream\"\n                ],\n                \"tags\": [\n                    \"log\"\n                ],\n                \"summary\": \"服务器日志流\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"集群名称\",\n                        \"name\": \"clusterName\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"世界名称\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"SSE 格式的日志流\",\n                        \"schema\": {\n                            \"type\": \"string\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/start\": {\n            \"get\": {\n                \"description\": \"启动世界\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"game\"\n                ],\n                \"summary\": \"启动世界\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"世界名称\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/start/all\": {\n            \"get\": {\n                \"description\": \"启动所有世界\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"game\"\n                ],\n                \"summary\": \"启动所有世界\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/stop\": {\n            \"get\": {\n                \"description\": \"停止世界\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"game\"\n                ],\n                \"summary\": \"停止世界\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"世界名称\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/stop/all\": {\n            \"get\": {\n                \"description\": \"停止所有世界\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"game\"\n                ],\n                \"summary\": \"停止所有世界\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/system/info/stream\": {\n            \"get\": {\n                \"description\": \"获取服务器系统信息的实时流 (SSE)\",\n                \"consumes\": [\n                    \"text/event-stream\"\n                ],\n                \"produces\": [\n                    \"text/event-stream\"\n                ],\n                \"tags\": [\n                    \"game\"\n                ],\n                \"summary\": \"系统信息流\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"SSE 格式的系统信息流\",\n                        \"schema\": {\n                            \"type\": \"string\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/game/update\": {\n            \"get\": {\n                \"description\": \"更新游戏\",\n                \"tags\": [\n                    \"update\"\n                ],\n                \"summary\": \"更新游戏\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/init\": {\n            \"get\": {\n                \"description\": \"检查系统是否进行了首次初始化\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"user\"\n                ],\n                \"summary\": \"检查是否首次初始化\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"初始化系统首次用户信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"user\"\n                ],\n                \"summary\": \"初始化首次用户\",\n                \"parameters\": [\n                    {\n                        \"description\": \"用户信息\",\n                        \"name\": \"userInfo\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/login.UserInfo\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/kv\": {\n            \"get\": {\n                \"description\": \"获取kv值\",\n                \"tags\": [\n                    \"kv\"\n                ],\n                \"summary\": \"获取kv值\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"key\",\n                        \"name\": \"key\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"保存kv值\",\n                \"tags\": [\n                    \"kv\"\n                ],\n                \"summary\": \"保存kv值\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"key\",\n                        \"name\": \"key\",\n                        \"in\": \"formData\",\n                        \"required\": true\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"value\",\n                        \"name\": \"value\",\n                        \"in\": \"formData\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/mod\": {\n            \"get\": {\n                \"description\": \"获取已订阅的模组列表\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"获取我的mod列表\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/mod/modinfo\": {\n            \"put\": {\n                \"description\": \"批量更新所有已订阅模组的信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"批量更新模组信息\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"default\": \"zh\",\n                        \"description\": \"语言\",\n                        \"name\": \"lang\",\n                        \"in\": \"query\"\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"post\": {\n                \"description\": \"保存模组配置信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"保存模组配置文件\",\n                \"parameters\": [\n                    {\n                        \"description\": \"模组信息\",\n                        \"name\": \"data\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/mod.ModInfo\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"$ref\": \"#/definitions/mod.ModInfo\"\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/mod/modinfo/file\": {\n            \"post\": {\n                \"description\": \"手动添加模组配置文件\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"手动添加模组\",\n                \"parameters\": [\n                    {\n                        \"description\": \"模组信息\",\n                        \"name\": \"data\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"object\"\n                        }\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"default\": \"zh\",\n                        \"description\": \"语言\",\n                        \"name\": \"lang\",\n                        \"in\": \"query\"\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/mod/modinfo/{modId}\": {\n            \"get\": {\n                \"description\": \"根据modId获取模组配置文件内容\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"获取模组配置文件\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"模组ID\",\n                        \"name\": \"modId\",\n                        \"in\": \"path\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"$ref\": \"#/definitions/mod.ModInfo\"\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/mod/search\": {\n            \"get\": {\n                \"description\": \"搜索Steam创意工坊中的模组\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"搜索mod列表\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"搜索关键词\",\n                        \"name\": \"text\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"integer\",\n                        \"default\": 1,\n                        \"description\": \"页码\",\n                        \"name\": \"page\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"integer\",\n                        \"default\": 10,\n                        \"description\": \"每页数量\",\n                        \"name\": \"size\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"default\": \"zh\",\n                        \"description\": \"语言\",\n                        \"name\": \"lang\",\n                        \"in\": \"query\"\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/mod/setup/workshop\": {\n            \"delete\": {\n                \"description\": \"删除所有workshop模组文件\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"删除workshop文件\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/mod/ugc\": {\n            \"delete\": {\n                \"description\": \"删除UGC模组文件\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"删除UGC模组文件\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"世界名称\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"WorkshopID\",\n                        \"name\": \"workshopId\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/mod/ugc/acf\": {\n            \"get\": {\n                \"description\": \"获取UGC模组的ACF文件信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"获取UGC mod acf文件信息\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"世界名称\",\n                        \"name\": \"levelName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/mod/{modId}\": {\n            \"get\": {\n                \"description\": \"根据modId获取模组详细信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"获取mod信息\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"模组ID\",\n                        \"name\": \"modId\",\n                        \"in\": \"path\",\n                        \"required\": true\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"default\": \"zh\",\n                        \"description\": \"语言\",\n                        \"name\": \"lang\",\n                        \"in\": \"query\"\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"put\": {\n                \"description\": \"根据modId更新模组\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"更新模组\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"模组ID\",\n                        \"name\": \"modId\",\n                        \"in\": \"path\",\n                        \"required\": true\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"default\": \"zh\",\n                        \"description\": \"语言\",\n                        \"name\": \"lang\",\n                        \"in\": \"query\"\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            },\n            \"delete\": {\n                \"description\": \"根据modId删除模组\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"mod\"\n                ],\n                \"summary\": \"删除模组\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"模组ID\",\n                        \"name\": \"modId\",\n                        \"in\": \"path\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/player/log\": {\n            \"get\": {\n                \"description\": \"分页查询玩家日志\",\n                \"tags\": [\n                    \"playerLog\"\n                ],\n                \"summary\": \"分页查询玩家日志\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"玩家名称\",\n                        \"name\": \"name\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"KuId\",\n                        \"name\": \"kuId\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"SteamId\",\n                        \"name\": \"steamId\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"角色\",\n                        \"name\": \"role\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"操作\",\n                        \"name\": \"action\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"IP地址\",\n                        \"name\": \"ip\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"integer\",\n                        \"default\": 1,\n                        \"description\": \"页码\",\n                        \"name\": \"page\",\n                        \"in\": \"query\"\n                    },\n                    {\n                        \"type\": \"integer\",\n                        \"default\": 10,\n                        \"description\": \"每页数量\",\n                        \"name\": \"size\",\n                        \"in\": \"query\"\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/player/log/delete\": {\n            \"post\": {\n                \"description\": \"删除玩家日志\",\n                \"tags\": [\n                    \"playerLog\"\n                ],\n                \"summary\": \"删除玩家日志\",\n                \"parameters\": [\n                    {\n                        \"description\": \"ID列表\",\n                        \"name\": \"ids\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"array\",\n                            \"items\": {\n                                \"type\": \"integer\"\n                            }\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/player/log/delete/all\": {\n            \"get\": {\n                \"description\": \"删除所有玩家\",\n                \"tags\": [\n                    \"playerLog\"\n                ],\n                \"summary\": \"删除所有玩家日志\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/user/changePassword\": {\n            \"post\": {\n                \"description\": \"修改密码\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"user\"\n                ],\n                \"summary\": \"修改密码\",\n                \"parameters\": [\n                    {\n                        \"description\": \"新密码\",\n                        \"name\": \"password\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"object\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/user/info\": {\n            \"get\": {\n                \"description\": \"获取用户信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"user\"\n                ],\n                \"summary\": \"获取用户信息\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"allOf\": [\n                                {\n                                    \"$ref\": \"#/definitions/response.Response\"\n                                },\n                                {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"data\": {\n                                            \"$ref\": \"#/definitions/login.UserInfo\"\n                                        }\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/user/login\": {\n            \"post\": {\n                \"description\": \"用户登录\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"user\"\n                ],\n                \"summary\": \"用户登录\",\n                \"parameters\": [\n                    {\n                        \"description\": \"用户信息\",\n                        \"name\": \"user\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/login.UserInfo\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/user/logout\": {\n            \"get\": {\n                \"description\": \"用户登出\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"user\"\n                ],\n                \"summary\": \"用户登出\",\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/api/user/update\": {\n            \"post\": {\n                \"description\": \"更新用户信息\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"user\"\n                ],\n                \"summary\": \"更新用户信息\",\n                \"parameters\": [\n                    {\n                        \"description\": \"用户信息\",\n                        \"name\": \"user\",\n                        \"in\": \"body\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"object\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        },\n        \"/backup/restore\": {\n            \"get\": {\n                \"description\": \"从备份文件恢复游戏存档\",\n                \"consumes\": [\n                    \"application/json\"\n                ],\n                \"produces\": [\n                    \"application/json\"\n                ],\n                \"tags\": [\n                    \"backup\"\n                ],\n                \"summary\": \"恢复备份\",\n                \"parameters\": [\n                    {\n                        \"type\": \"string\",\n                        \"description\": \"备份文件名\",\n                        \"name\": \"backupName\",\n                        \"in\": \"query\",\n                        \"required\": true\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"OK\",\n                        \"schema\": {\n                            \"$ref\": \"#/definitions/response.Response\"\n                        }\n                    }\n                }\n            }\n        }\n    },\n    \"definitions\": {\n        \"dstConfig.DstConfig\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"backup\": {\n                    \"type\": \"string\"\n                },\n                \"beta\": {\n                    \"type\": \"integer\"\n                },\n                \"bin\": {\n                    \"type\": \"integer\"\n                },\n                \"cluster\": {\n                    \"type\": \"string\"\n                },\n                \"conf_dir\": {\n                    \"description\": \"存档相对位置\",\n                    \"type\": \"string\"\n                },\n                \"donot_starve_server_directory\": {\n                    \"type\": \"string\"\n                },\n                \"force_install_dir\": {\n                    \"type\": \"string\"\n                },\n                \"mod_download_path\": {\n                    \"type\": \"string\"\n                },\n                \"persistent_storage_root\": {\n                    \"description\": \"根目录位置\",\n                    \"type\": \"string\"\n                },\n                \"steamcmd\": {\n                    \"type\": \"string\"\n                },\n                \"ugc_directory\": {\n                    \"type\": \"string\"\n                }\n            }\n        },\n        \"game.DstPsAux\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"RSS\": {\n                    \"type\": \"string\"\n                },\n                \"VSZ\": {\n                    \"type\": \"string\"\n                },\n                \"cpuUage\": {\n                    \"type\": \"string\"\n                },\n                \"memUage\": {\n                    \"type\": \"string\"\n                }\n            }\n        },\n        \"gameConfig.ClusterIni\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"bind_ip\": {\n                    \"type\": \"string\"\n                },\n                \"cluster_description\": {\n                    \"type\": \"string\"\n                },\n                \"cluster_intention\": {\n                    \"type\": \"string\"\n                },\n                \"cluster_key\": {\n                    \"type\": \"string\"\n                },\n                \"cluster_language\": {\n                    \"type\": \"string\"\n                },\n                \"cluster_name\": {\n                    \"type\": \"string\"\n                },\n                \"cluster_password\": {\n                    \"type\": \"string\"\n                },\n                \"console_enabled\": {\n                    \"description\": \"[MISC]\",\n                    \"type\": \"boolean\"\n                },\n                \"game_mode\": {\n                    \"description\": \"[GAEMPLAY]\",\n                    \"type\": \"string\"\n                },\n                \"lan_only_cluster\": {\n                    \"description\": \"[NETWORK]\",\n                    \"type\": \"boolean\"\n                },\n                \"master_ip\": {\n                    \"type\": \"string\"\n                },\n                \"master_port\": {\n                    \"type\": \"integer\"\n                },\n                \"max_players\": {\n                    \"type\": \"integer\"\n                },\n                \"max_snapshots\": {\n                    \"type\": \"integer\"\n                },\n                \"offline_cluster\": {\n                    \"type\": \"boolean\"\n                },\n                \"pause_when_nobody\": {\n                    \"type\": \"boolean\"\n                },\n                \"pvp\": {\n                    \"type\": \"boolean\"\n                },\n                \"shard_enabled\": {\n                    \"description\": \"[SHARD]\",\n                    \"type\": \"boolean\"\n                },\n                \"steam_group_admins\": {\n                    \"type\": \"boolean\"\n                },\n                \"steam_group_id\": {\n                    \"description\": \"[STEAM]\",\n                    \"type\": \"string\"\n                },\n                \"steam_group_only\": {\n                    \"type\": \"boolean\"\n                },\n                \"tick_rate\": {\n                    \"type\": \"integer\"\n                },\n                \"vote_enabled\": {\n                    \"type\": \"boolean\"\n                },\n                \"vote_kick_enabled\": {\n                    \"type\": \"boolean\"\n                },\n                \"whitelist_slots\": {\n                    \"type\": \"integer\"\n                }\n            }\n        },\n        \"gameConfig.ClusterIniConfig\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"cluster\": {\n                    \"$ref\": \"#/definitions/gameConfig.ClusterIni\"\n                },\n                \"token\": {\n                    \"type\": \"string\"\n                }\n            }\n        },\n        \"gameConfig.HomeConfigVO\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"cavesMapData\": {\n                    \"type\": \"string\"\n                },\n                \"clusterDescription\": {\n                    \"type\": \"string\"\n                },\n                \"clusterIntention\": {\n                    \"type\": \"string\"\n                },\n                \"clusterName\": {\n                    \"type\": \"string\"\n                },\n                \"clusterPassword\": {\n                    \"type\": \"string\"\n                },\n                \"gameMode\": {\n                    \"type\": \"string\"\n                },\n                \"masterMapData\": {\n                    \"type\": \"string\"\n                },\n                \"maxPlayers\": {\n                    \"type\": \"integer\"\n                },\n                \"max_snapshots\": {\n                    \"type\": \"integer\"\n                },\n                \"modData\": {\n                    \"type\": \"string\"\n                },\n                \"pause_when_nobody\": {\n                    \"type\": \"boolean\"\n                },\n                \"pvp\": {\n                    \"type\": \"boolean\"\n                },\n                \"token\": {\n                    \"type\": \"string\"\n                },\n                \"type\": {\n                    \"type\": \"integer\"\n                },\n                \"vote_enabled\": {\n                    \"type\": \"boolean\"\n                }\n            }\n        },\n        \"handler.LevelStatus\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"Ps\": {\n                    \"$ref\": \"#/definitions/game.DstPsAux\"\n                },\n                \"isMaster\": {\n                    \"type\": \"boolean\"\n                },\n                \"levelName\": {\n                    \"type\": \"string\"\n                },\n                \"leveldataoverride\": {\n                    \"type\": \"string\"\n                },\n                \"modoverrides\": {\n                    \"type\": \"string\"\n                },\n                \"runVersion\": {\n                    \"type\": \"integer\"\n                },\n                \"serverIni\": {\n                    \"$ref\": \"#/definitions/levelConfig.ServerIni\"\n                },\n                \"status\": {\n                    \"type\": \"boolean\"\n                },\n                \"uuid\": {\n                    \"type\": \"string\"\n                }\n            }\n        },\n        \"levelConfig.LevelInfo\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"isMaster\": {\n                    \"type\": \"boolean\"\n                },\n                \"levelName\": {\n                    \"type\": \"string\"\n                },\n                \"leveldataoverride\": {\n                    \"type\": \"string\"\n                },\n                \"modoverrides\": {\n                    \"type\": \"string\"\n                },\n                \"runVersion\": {\n                    \"type\": \"integer\"\n                },\n                \"server_ini\": {\n                    \"$ref\": \"#/definitions/levelConfig.ServerIni\"\n                },\n                \"uuid\": {\n                    \"type\": \"string\"\n                }\n            }\n        },\n        \"levelConfig.ServerIni\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"authentication_port\": {\n                    \"description\": \"[STEAM]\",\n                    \"type\": \"integer\"\n                },\n                \"encode_user_path\": {\n                    \"description\": \"[ACCOUNT]\",\n                    \"type\": \"boolean\"\n                },\n                \"id\": {\n                    \"type\": \"integer\"\n                },\n                \"is_master\": {\n                    \"description\": \"[SHARD]\",\n                    \"type\": \"boolean\"\n                },\n                \"master_server_port\": {\n                    \"type\": \"integer\"\n                },\n                \"name\": {\n                    \"type\": \"string\"\n                },\n                \"server_port\": {\n                    \"description\": \"[NETWORK]\",\n                    \"type\": \"integer\"\n                }\n            }\n        },\n        \"login.UserInfo\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"displayName\": {\n                    \"type\": \"string\"\n                },\n                \"password\": {\n                    \"type\": \"string\"\n                },\n                \"photoURL\": {\n                    \"type\": \"string\"\n                },\n                \"username\": {\n                    \"type\": \"string\"\n                }\n            }\n        },\n        \"mod.ModInfo\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"author\": {\n                    \"type\": \"string\"\n                },\n                \"child\": {\n                    \"type\": \"array\",\n                    \"items\": {\n                        \"type\": \"string\"\n                    }\n                },\n                \"consumer_appid\": {\n                    \"type\": \"number\"\n                },\n                \"creator_appid\": {\n                    \"type\": \"number\"\n                },\n                \"desc\": {\n                    \"type\": \"string\"\n                },\n                \"file_url\": {\n                    \"type\": \"string\"\n                },\n                \"id\": {\n                    \"type\": \"string\"\n                },\n                \"img\": {\n                    \"type\": \"string\"\n                },\n                \"last_time\": {\n                    \"type\": \"number\"\n                },\n                \"name\": {\n                    \"type\": \"string\"\n                },\n                \"sub\": {\n                    \"type\": \"integer\"\n                },\n                \"time\": {\n                    \"type\": \"integer\"\n                },\n                \"v\": {\n                    \"type\": \"string\"\n                },\n                \"vote\": {\n                    \"type\": \"object\",\n                    \"properties\": {\n                        \"num\": {\n                            \"type\": \"integer\"\n                        },\n                        \"star\": {\n                            \"type\": \"integer\"\n                        }\n                    }\n                }\n            }\n        },\n        \"model.BackupSnapshot\": {\n            \"type\": \"object\"\n        },\n        \"response.Response\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"code\": {\n                    \"description\": \"提示代码\",\n                    \"type\": \"integer\"\n                },\n                \"data\": {\n                    \"description\": \"数据\"\n                },\n                \"msg\": {\n                    \"description\": \"提示信息\",\n                    \"type\": \"string\"\n                }\n            }\n        }\n    },\n    \"securityDefinitions\": {\n        \"BearerAuth\": {\n            \"description\": \"Type \\\"Bearer\\\" followed by a space and JWT token.\",\n            \"type\": \"apiKey\",\n            \"name\": \"Authorization\",\n            \"in\": \"header\"\n        }\n    }\n}"
  },
  {
    "path": "docs/swagger.yaml",
    "content": "basePath: /\ndefinitions:\n  dstConfig.DstConfig:\n    properties:\n      backup:\n        type: string\n      beta:\n        type: integer\n      bin:\n        type: integer\n      cluster:\n        type: string\n      conf_dir:\n        description: 存档相对位置\n        type: string\n      donot_starve_server_directory:\n        type: string\n      force_install_dir:\n        type: string\n      mod_download_path:\n        type: string\n      persistent_storage_root:\n        description: 根目录位置\n        type: string\n      steamcmd:\n        type: string\n      ugc_directory:\n        type: string\n    type: object\n  game.DstPsAux:\n    properties:\n      RSS:\n        type: string\n      VSZ:\n        type: string\n      cpuUage:\n        type: string\n      memUage:\n        type: string\n    type: object\n  gameConfig.ClusterIni:\n    properties:\n      bind_ip:\n        type: string\n      cluster_description:\n        type: string\n      cluster_intention:\n        type: string\n      cluster_key:\n        type: string\n      cluster_language:\n        type: string\n      cluster_name:\n        type: string\n      cluster_password:\n        type: string\n      console_enabled:\n        description: '[MISC]'\n        type: boolean\n      game_mode:\n        description: '[GAEMPLAY]'\n        type: string\n      lan_only_cluster:\n        description: '[NETWORK]'\n        type: boolean\n      master_ip:\n        type: string\n      master_port:\n        type: integer\n      max_players:\n        type: integer\n      max_snapshots:\n        type: integer\n      offline_cluster:\n        type: boolean\n      pause_when_nobody:\n        type: boolean\n      pvp:\n        type: boolean\n      shard_enabled:\n        description: '[SHARD]'\n        type: boolean\n      steam_group_admins:\n        type: boolean\n      steam_group_id:\n        description: '[STEAM]'\n        type: string\n      steam_group_only:\n        type: boolean\n      tick_rate:\n        type: integer\n      vote_enabled:\n        type: boolean\n      vote_kick_enabled:\n        type: boolean\n      whitelist_slots:\n        type: integer\n    type: object\n  gameConfig.ClusterIniConfig:\n    properties:\n      cluster:\n        $ref: '#/definitions/gameConfig.ClusterIni'\n      token:\n        type: string\n    type: object\n  gameConfig.HomeConfigVO:\n    properties:\n      cavesMapData:\n        type: string\n      clusterDescription:\n        type: string\n      clusterIntention:\n        type: string\n      clusterName:\n        type: string\n      clusterPassword:\n        type: string\n      gameMode:\n        type: string\n      masterMapData:\n        type: string\n      max_snapshots:\n        type: integer\n      maxPlayers:\n        type: integer\n      modData:\n        type: string\n      pause_when_nobody:\n        type: boolean\n      pvp:\n        type: boolean\n      token:\n        type: string\n      type:\n        type: integer\n      vote_enabled:\n        type: boolean\n    type: object\n  handler.LevelStatus:\n    properties:\n      Ps:\n        $ref: '#/definitions/game.DstPsAux'\n      isMaster:\n        type: boolean\n      levelName:\n        type: string\n      leveldataoverride:\n        type: string\n      modoverrides:\n        type: string\n      runVersion:\n        type: integer\n      serverIni:\n        $ref: '#/definitions/levelConfig.ServerIni'\n      status:\n        type: boolean\n      uuid:\n        type: string\n    type: object\n  levelConfig.LevelInfo:\n    properties:\n      isMaster:\n        type: boolean\n      levelName:\n        type: string\n      leveldataoverride:\n        type: string\n      modoverrides:\n        type: string\n      runVersion:\n        type: integer\n      server_ini:\n        $ref: '#/definitions/levelConfig.ServerIni'\n      uuid:\n        type: string\n    type: object\n  levelConfig.ServerIni:\n    properties:\n      authentication_port:\n        description: '[STEAM]'\n        type: integer\n      encode_user_path:\n        description: '[ACCOUNT]'\n        type: boolean\n      id:\n        type: integer\n      is_master:\n        description: '[SHARD]'\n        type: boolean\n      master_server_port:\n        type: integer\n      name:\n        type: string\n      server_port:\n        description: '[NETWORK]'\n        type: integer\n    type: object\n  login.UserInfo:\n    properties:\n      displayName:\n        type: string\n      password:\n        type: string\n      photoURL:\n        type: string\n      username:\n        type: string\n    type: object\n  mod.ModInfo:\n    properties:\n      author:\n        type: string\n      child:\n        items:\n          type: string\n        type: array\n      consumer_appid:\n        type: number\n      creator_appid:\n        type: number\n      desc:\n        type: string\n      file_url:\n        type: string\n      id:\n        type: string\n      img:\n        type: string\n      last_time:\n        type: number\n      name:\n        type: string\n      sub:\n        type: integer\n      time:\n        type: integer\n      v:\n        type: string\n      vote:\n        properties:\n          num:\n            type: integer\n          star:\n            type: integer\n        type: object\n    type: object\n  model.BackupSnapshot:\n    type: object\n  response.Response:\n    properties:\n      code:\n        description: 提示代码\n        type: integer\n      data:\n        description: 数据\n      msg:\n        description: 提示信息\n        type: string\n    type: object\nhost: localhost:8082\ninfo:\n  contact:\n    name: API Support\n    url: https://github.com/carrot-hu23/dst-admin-go\n  description: 饥荒联机版服务器管理后台 API 文档\n  license:\n    name: Apache 2.0\n    url: http://www.apache.org/licenses/LICENSE-2.0.html\n  termsOfService: http://swagger.io/terms/\n  title: DST Admin Go API\n  version: \"1.0\"\npaths:\n  /api/cluster/level:\n    delete:\n      consumes:\n      - application/json\n      description: 删除指定的世界\n      parameters:\n      - description: 世界名称\n        in: query\n        name: levelName\n        required: true\n        type: string\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 删除世界\n      tags:\n      - level\n    get:\n      consumes:\n      - application/json\n      description: 获取指定世界的详细信息\n      parameters:\n      - description: 世界名称\n        in: query\n        name: levelName\n        required: true\n        type: string\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 获取单个世界\n      tags:\n      - level\n    post:\n      consumes:\n      - application/json\n      description: 创建一个新的世界(等级)\n      parameters:\n      - description: 世界配置信息\n        in: body\n        name: level\n        required: true\n        schema:\n          $ref: '#/definitions/levelConfig.LevelInfo'\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 创建世界\n      tags:\n      - level\n    put:\n      consumes:\n      - application/json\n      description: 批量更新多个世界的配置信息\n      parameters:\n      - description: 世界配置信息列表\n        in: body\n        name: levels\n        required: true\n        schema:\n          items:\n            $ref: '#/definitions/levelConfig.LevelInfo'\n          type: array\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 批量更新世界\n      tags:\n      - level\n  /api/dst/map/gen:\n    get:\n      description: 生成地图\n      parameters:\n      - description: levelName\n        in: query\n        name: levelName\n        required: true\n        type: string\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n        \"400\":\n          description: Bad Request\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 生成地图\n      tags:\n      - dstMap\n  /api/dst/map/has/walrusHut/plains:\n    get:\n      description: 检测地图中是否有walrusHutPlains\n      parameters:\n      - description: levelName\n        in: query\n        name: levelName\n        required: true\n        type: string\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n        \"400\":\n          description: Bad Request\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 检测地图中是否有walrusHutPlains\n      tags:\n      - dstMap\n  /api/dst/map/image:\n    get:\n      description: 获取地图图片\n      parameters:\n      - description: levelName\n        in: query\n        name: levelName\n        required: true\n        type: string\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n        \"400\":\n          description: Bad Request\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 获取地图图片\n      tags:\n      - dstMap\n  /api/dst/map/player/session/file:\n    get:\n      description: 获取玩家存档文件\n      parameters:\n      - description: levelName\n        in: query\n        name: levelName\n        required: true\n        type: string\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n        \"400\":\n          description: Bad Request\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 获取玩家存档文件\n      tags:\n      - dstMap\n  /api/dst/map/session/file:\n    get:\n      description: 获取存档文件\n      parameters:\n      - description: levelName\n        in: query\n        name: levelName\n        required: true\n        type: string\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n        \"400\":\n          description: Bad Request\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 获取存档文件\n      tags:\n      - dstMap\n  /api/game/8level/status:\n    get:\n      consumes:\n      - application/json\n      description: 获取所有世界的运行状态信息\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            allOf:\n            - $ref: '#/definitions/response.Response'\n            - properties:\n                data:\n                  items:\n                    $ref: '#/definitions/handler.LevelStatus'\n                  type: array\n              type: object\n      summary: 获取服务器状态\n      tags:\n      - game\n  /api/game/archive:\n    get:\n      consumes:\n      - application/json\n      description: 获取当前集群的游戏存档列表\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 获取游戏存档列表\n      tags:\n      - game\n  /api/game/backup:\n    delete:\n      consumes:\n      - application/json\n      description: 删除指定的备份文件\n      parameters:\n      - description: 要删除的文件名列表\n        in: body\n        name: fileNames\n        required: true\n        schema:\n          items:\n            type: string\n          type: array\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 删除备份\n      tags:\n      - backup\n    get:\n      consumes:\n      - application/json\n      description: 获取当前集群的所有备份文件列表\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 获取备份列表\n      tags:\n      - backup\n    post:\n      consumes:\n      - application/json\n      description: 创建新的游戏存档备份\n      parameters:\n      - description: 备份名称\n        in: query\n        name: backupName\n        type: string\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 创建备份\n      tags:\n      - backup\n    put:\n      consumes:\n      - application/json\n      description: 重命名指定的备份文件\n      parameters:\n      - description: 请求体\n        in: body\n        name: request\n        required: true\n        schema:\n          type: object\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 重命名备份\n      tags:\n      - backup\n  /api/game/backup/download:\n    get:\n      consumes:\n      - application/json\n      description: 下载指定的备份文件\n      parameters:\n      - description: 备份文件名\n        in: query\n        name: backupName\n        required: true\n        type: string\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 下载备份\n      tags:\n      - backup\n  /api/game/backup/snapshot/list:\n    get:\n      consumes:\n      - application/json\n      description: 获取当前集群的所有快照备份列表\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 获取快照列表\n      tags:\n      - backup\n  /api/game/backup/snapshot/setting:\n    get:\n      consumes:\n      - application/json\n      description: 获取自动快照备份的设置\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 获取快照设置\n      tags:\n      - backup\n    post:\n      consumes:\n      - application/json\n      description: 保存自动快照备份的设置\n      parameters:\n      - description: 快照设置\n        in: body\n        name: setting\n        required: true\n        schema:\n          $ref: '#/definitions/model.BackupSnapshot'\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 保存快照设置\n      tags:\n      - backup\n  /api/game/backup/upload:\n    post:\n      consumes:\n      - multipart/form-data\n      description: 上传新的备份文件\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 上传备份\n      tags:\n      - backup\n  /api/game/command:\n    post:\n      consumes:\n      - application/json\n      description: 运行命令\n      parameters:\n      - description: 命令\n        in: query\n        name: command\n        required: true\n        type: string\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 运行命令\n      tags:\n      - game\n  /api/game/config:\n    get:\n      consumes:\n      - application/json\n      description: 获取房间配置\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            allOf:\n            - $ref: '#/definitions/response.Response'\n            - properties:\n                data:\n                  $ref: '#/definitions/gameConfig.HomeConfigVO'\n              type: object\n      summary: 获取房间配置\n      tags:\n      - gameConfig\n  /api/game/config/adminlist:\n    get:\n      consumes:\n      - application/json\n      description: 获取房间 adminlist.txt 配置\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            allOf:\n            - $ref: '#/definitions/response.Response'\n            - properties:\n                data:\n                  items:\n                    type: string\n                  type: array\n              type: object\n      summary: 获取房间 adminlist.txt 配置\n      tags:\n      - gameConfig\n    post:\n      consumes:\n      - application/json\n      description: 保存房间 adminlist.txt 配置\n      parameters:\n      - description: adminlist.txt 配置\n        in: body\n        name: list\n        required: true\n        schema:\n          items:\n            type: string\n          type: array\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 保存房间 adminlist.txt 配置\n      tags:\n      - gameConfig\n  /api/game/config/blacklist:\n    get:\n      consumes:\n      - application/json\n      description: 获取房间 blacklist.txt 配置\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            allOf:\n            - $ref: '#/definitions/response.Response'\n            - properties:\n                data:\n                  items:\n                    type: string\n                  type: array\n              type: object\n      summary: 获取房间 blacklist.txt 配置\n      tags:\n      - gameConfig\n    post:\n      consumes:\n      - application/json\n      description: 保存房间 blacklist.txt 配置\n      parameters:\n      - description: blacklist.txt 配置\n        in: body\n        name: list\n        required: true\n        schema:\n          items:\n            type: string\n          type: array\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 保存房间 blacklist.txt 配置\n      tags:\n      - gameConfig\n  /api/game/config/clusterIni:\n    get:\n      consumes:\n      - application/json\n      description: 获取房间 cluster.ini 配置\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            allOf:\n            - $ref: '#/definitions/response.Response'\n            - properties:\n                data:\n                  $ref: '#/definitions/gameConfig.ClusterIniConfig'\n              type: object\n      summary: 获取房间 cluster.ini 配置\n      tags:\n      - gameConfig\n    post:\n      consumes:\n      - application/json\n      description: 保存房间 cluster.ini 配置\n      parameters:\n      - description: cluster.ini 配置\n        in: body\n        name: config\n        required: true\n        schema:\n          $ref: '#/definitions/gameConfig.ClusterIniConfig'\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 保存房间 cluster.ini 配置\n      tags:\n      - gameConfig\n  /api/game/config/whitelist:\n    get:\n      consumes:\n      - application/json\n      description: 获取房间 whitelist.txt 配置\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            allOf:\n            - $ref: '#/definitions/response.Response'\n            - properties:\n                data:\n                  items:\n                    type: string\n                  type: array\n              type: object\n      summary: 获取房间 whitelist.txt 配置\n      tags:\n      - gameConfig\n    post:\n      consumes:\n      - application/json\n      description: 保存房间 whitelist.txt 配置\n      parameters:\n      - description: whitelist.txt 配置\n        in: body\n        name: list\n        required: true\n        schema:\n          items:\n            type: string\n          type: array\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 保存房间 whitelist.txt 配置\n      tags:\n      - gameConfig\n  /api/game/dst/config:\n    get:\n      consumes:\n      - application/json\n      description: 获取房间 dst 配置\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            allOf:\n            - $ref: '#/definitions/response.Response'\n            - properties:\n                data:\n                  $ref: '#/definitions/dstConfig.DstConfig'\n              type: object\n      summary: 获取房间 dst 配置\n      tags:\n      - dstConfig\n    post:\n      consumes:\n      - application/json\n      description: 保存房间 dst 配置\n      parameters:\n      - description: dst 配置\n        in: body\n        name: config\n        required: true\n        schema:\n          $ref: '#/definitions/dstConfig.DstConfig'\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 保存房间 dst 配置\n      tags:\n      - dstConfig\n  /api/game/level/server/download:\n    get:\n      description: 下载指定世界的完整服务器日志文件\n      parameters:\n      - description: 集群名称\n        in: query\n        name: clusterName\n        type: string\n      - description: 世界名称\n        in: query\n        name: levelName\n        required: true\n        type: string\n      produces:\n      - application/octet-stream\n      responses:\n        \"200\":\n          description: 服务器日志文件\n          schema:\n            type: file\n      summary: 下载服务器日志\n      tags:\n      - log\n  /api/game/level/server/log:\n    get:\n      description: 获取指定世界的服务器日志（默认最近100行）\n      parameters:\n      - description: 集群名称\n        in: query\n        name: clusterName\n        type: string\n      - description: 世界名称\n        in: query\n        name: levelName\n        required: true\n        type: string\n      - description: 返回日志行数，默认为100\n        in: query\n        name: lines\n        type: string\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: 服务器日志列表\n          schema:\n            allOf:\n            - $ref: '#/definitions/response.Response'\n            - properties:\n                data:\n                  items:\n                    type: string\n                  type: array\n              type: object\n      summary: 获取服务器日志\n      tags:\n      - log\n  /api/game/log/stream:\n    get:\n      consumes:\n      - text/event-stream\n      description: 获取指定世界的实时日志流 (SSE)\n      parameters:\n      - description: 集群名称\n        in: query\n        name: clusterName\n        type: string\n      - description: 世界名称\n        in: query\n        name: levelName\n        required: true\n        type: string\n      produces:\n      - text/event-stream\n      responses:\n        \"200\":\n          description: SSE 格式的日志流\n          schema:\n            type: string\n      summary: 服务器日志流\n      tags:\n      - log\n  /api/game/start:\n    get:\n      consumes:\n      - application/json\n      description: 启动世界\n      parameters:\n      - description: 世界名称\n        in: query\n        name: levelName\n        required: true\n        type: string\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 启动世界\n      tags:\n      - game\n  /api/game/start/all:\n    get:\n      consumes:\n      - application/json\n      description: 启动所有世界\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 启动所有世界\n      tags:\n      - game\n  /api/game/stop:\n    get:\n      consumes:\n      - application/json\n      description: 停止世界\n      parameters:\n      - description: 世界名称\n        in: query\n        name: levelName\n        required: true\n        type: string\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 停止世界\n      tags:\n      - game\n  /api/game/stop/all:\n    get:\n      consumes:\n      - application/json\n      description: 停止所有世界\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 停止所有世界\n      tags:\n      - game\n  /api/game/system/info/stream:\n    get:\n      consumes:\n      - text/event-stream\n      description: 获取服务器系统信息的实时流 (SSE)\n      produces:\n      - text/event-stream\n      responses:\n        \"200\":\n          description: SSE 格式的系统信息流\n          schema:\n            type: string\n      summary: 系统信息流\n      tags:\n      - game\n  /api/game/update:\n    get:\n      description: 更新游戏\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 更新游戏\n      tags:\n      - update\n  /api/init:\n    get:\n      consumes:\n      - application/json\n      description: 检查系统是否进行了首次初始化\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 检查是否首次初始化\n      tags:\n      - user\n    post:\n      consumes:\n      - application/json\n      description: 初始化系统首次用户信息\n      parameters:\n      - description: 用户信息\n        in: body\n        name: userInfo\n        required: true\n        schema:\n          $ref: '#/definitions/login.UserInfo'\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 初始化首次用户\n      tags:\n      - user\n  /api/kv:\n    get:\n      description: 获取kv值\n      parameters:\n      - description: key\n        in: query\n        name: key\n        required: true\n        type: string\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 获取kv值\n      tags:\n      - kv\n    post:\n      description: 保存kv值\n      parameters:\n      - description: key\n        in: formData\n        name: key\n        required: true\n        type: string\n      - description: value\n        in: formData\n        name: value\n        required: true\n        type: string\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 保存kv值\n      tags:\n      - kv\n  /api/mod:\n    get:\n      consumes:\n      - application/json\n      description: 获取已订阅的模组列表\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 获取我的mod列表\n      tags:\n      - mod\n  /api/mod/{modId}:\n    delete:\n      consumes:\n      - application/json\n      description: 根据modId删除模组\n      parameters:\n      - description: 模组ID\n        in: path\n        name: modId\n        required: true\n        type: string\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 删除模组\n      tags:\n      - mod\n    get:\n      consumes:\n      - application/json\n      description: 根据modId获取模组详细信息\n      parameters:\n      - description: 模组ID\n        in: path\n        name: modId\n        required: true\n        type: string\n      - default: zh\n        description: 语言\n        in: query\n        name: lang\n        type: string\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 获取mod信息\n      tags:\n      - mod\n    put:\n      consumes:\n      - application/json\n      description: 根据modId更新模组\n      parameters:\n      - description: 模组ID\n        in: path\n        name: modId\n        required: true\n        type: string\n      - default: zh\n        description: 语言\n        in: query\n        name: lang\n        type: string\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 更新模组\n      tags:\n      - mod\n  /api/mod/modinfo:\n    post:\n      consumes:\n      - application/json\n      description: 保存模组配置信息\n      parameters:\n      - description: 模组信息\n        in: body\n        name: data\n        required: true\n        schema:\n          $ref: '#/definitions/mod.ModInfo'\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            allOf:\n            - $ref: '#/definitions/response.Response'\n            - properties:\n                data:\n                  $ref: '#/definitions/mod.ModInfo'\n              type: object\n      summary: 保存模组配置文件\n      tags:\n      - mod\n    put:\n      consumes:\n      - application/json\n      description: 批量更新所有已订阅模组的信息\n      parameters:\n      - default: zh\n        description: 语言\n        in: query\n        name: lang\n        type: string\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 批量更新模组信息\n      tags:\n      - mod\n  /api/mod/modinfo/{modId}:\n    get:\n      consumes:\n      - application/json\n      description: 根据modId获取模组配置文件内容\n      parameters:\n      - description: 模组ID\n        in: path\n        name: modId\n        required: true\n        type: string\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            allOf:\n            - $ref: '#/definitions/response.Response'\n            - properties:\n                data:\n                  $ref: '#/definitions/mod.ModInfo'\n              type: object\n      summary: 获取模组配置文件\n      tags:\n      - mod\n  /api/mod/modinfo/file:\n    post:\n      consumes:\n      - application/json\n      description: 手动添加模组配置文件\n      parameters:\n      - description: 模组信息\n        in: body\n        name: data\n        required: true\n        schema:\n          type: object\n      - default: zh\n        description: 语言\n        in: query\n        name: lang\n        type: string\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 手动添加模组\n      tags:\n      - mod\n  /api/mod/search:\n    get:\n      consumes:\n      - application/json\n      description: 搜索Steam创意工坊中的模组\n      parameters:\n      - description: 搜索关键词\n        in: query\n        name: text\n        type: string\n      - default: 1\n        description: 页码\n        in: query\n        name: page\n        type: integer\n      - default: 10\n        description: 每页数量\n        in: query\n        name: size\n        type: integer\n      - default: zh\n        description: 语言\n        in: query\n        name: lang\n        type: string\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 搜索mod列表\n      tags:\n      - mod\n  /api/mod/setup/workshop:\n    delete:\n      consumes:\n      - application/json\n      description: 删除所有workshop模组文件\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 删除workshop文件\n      tags:\n      - mod\n  /api/mod/ugc:\n    delete:\n      consumes:\n      - application/json\n      description: 删除UGC模组文件\n      parameters:\n      - description: 世界名称\n        in: query\n        name: levelName\n        required: true\n        type: string\n      - description: WorkshopID\n        in: query\n        name: workshopId\n        required: true\n        type: string\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 删除UGC模组文件\n      tags:\n      - mod\n  /api/mod/ugc/acf:\n    get:\n      consumes:\n      - application/json\n      description: 获取UGC模组的ACF文件信息\n      parameters:\n      - description: 世界名称\n        in: query\n        name: levelName\n        required: true\n        type: string\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 获取UGC mod acf文件信息\n      tags:\n      - mod\n  /api/player/log:\n    get:\n      description: 分页查询玩家日志\n      parameters:\n      - description: 玩家名称\n        in: query\n        name: name\n        type: string\n      - description: KuId\n        in: query\n        name: kuId\n        type: string\n      - description: SteamId\n        in: query\n        name: steamId\n        type: string\n      - description: 角色\n        in: query\n        name: role\n        type: string\n      - description: 操作\n        in: query\n        name: action\n        type: string\n      - description: IP地址\n        in: query\n        name: ip\n        type: string\n      - default: 1\n        description: 页码\n        in: query\n        name: page\n        type: integer\n      - default: 10\n        description: 每页数量\n        in: query\n        name: size\n        type: integer\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 分页查询玩家日志\n      tags:\n      - playerLog\n  /api/player/log/delete:\n    post:\n      description: 删除玩家日志\n      parameters:\n      - description: ID列表\n        in: body\n        name: ids\n        required: true\n        schema:\n          items:\n            type: integer\n          type: array\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 删除玩家日志\n      tags:\n      - playerLog\n  /api/player/log/delete/all:\n    get:\n      description: 删除所有玩家\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 删除所有玩家日志\n      tags:\n      - playerLog\n  /api/user/changePassword:\n    post:\n      consumes:\n      - application/json\n      description: 修改密码\n      parameters:\n      - description: 新密码\n        in: body\n        name: password\n        required: true\n        schema:\n          type: object\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 修改密码\n      tags:\n      - user\n  /api/user/info:\n    get:\n      consumes:\n      - application/json\n      description: 获取用户信息\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            allOf:\n            - $ref: '#/definitions/response.Response'\n            - properties:\n                data:\n                  $ref: '#/definitions/login.UserInfo'\n              type: object\n      summary: 获取用户信息\n      tags:\n      - user\n  /api/user/login:\n    post:\n      consumes:\n      - application/json\n      description: 用户登录\n      parameters:\n      - description: 用户信息\n        in: body\n        name: user\n        required: true\n        schema:\n          $ref: '#/definitions/login.UserInfo'\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 用户登录\n      tags:\n      - user\n  /api/user/logout:\n    get:\n      consumes:\n      - application/json\n      description: 用户登出\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 用户登出\n      tags:\n      - user\n  /api/user/update:\n    post:\n      consumes:\n      - application/json\n      description: 更新用户信息\n      parameters:\n      - description: 用户信息\n        in: body\n        name: user\n        required: true\n        schema:\n          type: object\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 更新用户信息\n      tags:\n      - user\n  /backup/restore:\n    get:\n      consumes:\n      - application/json\n      description: 从备份文件恢复游戏存档\n      parameters:\n      - description: 备份文件名\n        in: query\n        name: backupName\n        required: true\n        type: string\n      produces:\n      - application/json\n      responses:\n        \"200\":\n          description: OK\n          schema:\n            $ref: '#/definitions/response.Response'\n      summary: 恢复备份\n      tags:\n      - backup\nsecurityDefinitions:\n  BearerAuth:\n    description: Type \"Bearer\" followed by a space and JWT token.\n    in: header\n    name: Authorization\n    type: apiKey\nswagger: \"2.0\"\n"
  },
  {
    "path": "go.mod",
    "content": "module dst-admin-go\n\ngo 1.23.0\n\ntoolchain go1.24.7\n\nrequire (\n\tgithub.com/gin-contrib/sessions v1.0.1\n\tgithub.com/gin-gonic/gin v1.10.0\n\tgithub.com/glebarez/sqlite v1.8.0\n\tgithub.com/go-ini/ini v1.67.0\n\tgithub.com/hpcloud/tail v1.0.0\n\tgithub.com/shirou/gopsutil v3.21.11+incompatible\n\tgithub.com/swaggo/files v1.0.1\n\tgithub.com/swaggo/gin-swagger v1.6.1\n\tgithub.com/swaggo/swag v1.16.6\n\tgithub.com/yuin/gopher-lua v1.1.0\n\tgolang.org/x/text v0.23.0\n\tgopkg.in/yaml.v3 v3.0.1\n\tgorm.io/gorm v1.25.8\n)\n\nrequire (\n\tgithub.com/KyleBanks/depth v1.2.1 // indirect\n\tgithub.com/PuerkitoBio/purell v1.1.1 // indirect\n\tgithub.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect\n\tgithub.com/bytedance/sonic v1.11.6 // indirect\n\tgithub.com/bytedance/sonic/loader v0.1.1 // indirect\n\tgithub.com/cloudwego/base64x v0.1.4 // indirect\n\tgithub.com/cloudwego/iasm v0.2.0 // indirect\n\tgithub.com/dustin/go-humanize v1.0.1 // indirect\n\tgithub.com/fsnotify/fsnotify v1.6.0 // indirect\n\tgithub.com/gabriel-vasile/mimetype v1.4.3 // indirect\n\tgithub.com/gin-contrib/gzip v1.0.1 // indirect\n\tgithub.com/gin-contrib/sse v0.1.0 // indirect\n\tgithub.com/glebarez/go-sqlite v1.21.1 // indirect\n\tgithub.com/go-ole/go-ole v1.2.6 // indirect\n\tgithub.com/go-openapi/jsonpointer v0.19.5 // indirect\n\tgithub.com/go-openapi/jsonreference v0.19.6 // indirect\n\tgithub.com/go-openapi/spec v0.20.4 // indirect\n\tgithub.com/go-openapi/swag v0.19.15 // indirect\n\tgithub.com/go-playground/locales v0.14.1 // indirect\n\tgithub.com/go-playground/universal-translator v0.18.1 // indirect\n\tgithub.com/go-playground/validator/v10 v10.20.0 // indirect\n\tgithub.com/goccy/go-json v0.10.2 // indirect\n\tgithub.com/google/uuid v1.3.0 // indirect\n\tgithub.com/gorilla/context v1.1.2 // indirect\n\tgithub.com/gorilla/securecookie v1.1.2 // indirect\n\tgithub.com/gorilla/sessions v1.2.2 // indirect\n\tgithub.com/jinzhu/inflection v1.0.0 // indirect\n\tgithub.com/jinzhu/now v1.1.5 // indirect\n\tgithub.com/josharian/intern v1.0.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/klauspost/cpuid/v2 v2.2.7 // indirect\n\tgithub.com/leodido/go-urn v1.4.0 // indirect\n\tgithub.com/mailru/easyjson v0.7.6 // indirect\n\tgithub.com/mattn/go-isatty v0.0.20 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.2 // indirect\n\tgithub.com/pelletier/go-toml/v2 v2.2.2 // indirect\n\tgithub.com/quasoft/memstore v0.0.0-20191010062613-2bce066d2b0b // indirect\n\tgithub.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect\n\tgithub.com/tklauser/go-sysconf v0.3.11 // indirect\n\tgithub.com/tklauser/numcpus v0.6.0 // indirect\n\tgithub.com/twitchyliquid64/golang-asm v0.15.1 // indirect\n\tgithub.com/ugorji/go/codec v1.2.12 // indirect\n\tgithub.com/yusufpapurcu/wmi v1.2.2 // indirect\n\tgolang.org/x/arch v0.8.0 // indirect\n\tgolang.org/x/crypto v0.36.0 // indirect\n\tgolang.org/x/mod v0.17.0 // indirect\n\tgolang.org/x/net v0.38.0 // indirect\n\tgolang.org/x/sys v0.31.0 // indirect\n\tgolang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect\n\tgoogle.golang.org/protobuf v1.34.1 // indirect\n\tgopkg.in/fsnotify.v1 v1.4.7 // indirect\n\tgopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect\n\tgopkg.in/yaml.v2 v2.4.0 // indirect\n\tmodernc.org/libc v1.22.6 // indirect\n\tmodernc.org/mathutil v1.5.0 // indirect\n\tmodernc.org/memory v1.5.0 // indirect\n\tmodernc.org/sqlite v1.22.1 // indirect\n)\n"
  },
  {
    "path": "go.sum",
    "content": "github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=\ngithub.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=\ngithub.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI=\ngithub.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=\ngithub.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=\ngithub.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=\ngithub.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=\ngithub.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=\ngithub.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=\ngithub.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=\ngithub.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=\ngithub.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=\ngithub.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=\ngithub.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=\ngithub.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=\ngithub.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=\ngithub.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY=\ngithub.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw=\ngithub.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=\ngithub.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=\ngithub.com/gin-contrib/gzip v1.0.1 h1:HQ8ENHODeLY7a4g1Au/46Z92bdGFl74OhxcZble9WJE=\ngithub.com/gin-contrib/gzip v1.0.1/go.mod h1:njt428fdUNRvjuJf16tZMYZ2Yl+WQB53X5wmhDwXvC4=\ngithub.com/gin-contrib/sessions v1.0.1 h1:3hsJyNs7v7N8OtelFmYXFrulAf6zSR7nW/putcPEHxI=\ngithub.com/gin-contrib/sessions v1.0.1/go.mod h1:ouxSFM24/OgIud5MJYQJLpy6AwxQ5EYO9yLhbtObGkM=\ngithub.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=\ngithub.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=\ngithub.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=\ngithub.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=\ngithub.com/glebarez/go-sqlite v1.21.1 h1:7MZyUPh2XTrHS7xNEHQbrhfMZuPSzhkm2A1qgg0y5NY=\ngithub.com/glebarez/go-sqlite v1.21.1/go.mod h1:ISs8MF6yk5cL4n/43rSOmVMGJJjHYr7L2MbZZ5Q4E2E=\ngithub.com/glebarez/sqlite v1.8.0 h1:02X12E2I/4C1n+v90yTqrjRa8yuo7c3KeHI3FRznCvc=\ngithub.com/glebarez/sqlite v1.8.0/go.mod h1:bpET16h1za2KOOMb8+jCp6UBP/iahDpfPQqSaYLTLx8=\ngithub.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=\ngithub.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=\ngithub.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=\ngithub.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=\ngithub.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=\ngithub.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY=\ngithub.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=\ngithub.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs=\ngithub.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns=\ngithub.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M=\ngithub.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I=\ngithub.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=\ngithub.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM=\ngithub.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ=\ngithub.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=\ngithub.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=\ngithub.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=\ngithub.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=\ngithub.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=\ngithub.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=\ngithub.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=\ngithub.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=\ngithub.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=\ngithub.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=\ngithub.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=\ngithub.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=\ngithub.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=\ngithub.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=\ngithub.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=\ngithub.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/gorilla/context v1.1.2 h1:WRkNAv2uoa03QNIc1A6u4O7DAGMUVoopZhkiXWA2V1o=\ngithub.com/gorilla/context v1.1.2/go.mod h1:KDPwT9i/MeWHiLl90fuTgrt4/wPcv75vFAZLaOOcbxM=\ngithub.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=\ngithub.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=\ngithub.com/gorilla/sessions v1.2.2 h1:lqzMYz6bOfvn2WriPUjNByzeXIlVzURcPmgMczkmTjY=\ngithub.com/gorilla/sessions v1.2.2/go.mod h1:ePLdVu+jbEgHH+KWw8I1z2wqd0BAdAQh/8LRvBeoNcQ=\ngithub.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=\ngithub.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=\ngithub.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=\ngithub.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=\ngithub.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=\ngithub.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=\ngithub.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=\ngithub.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=\ngithub.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=\ngithub.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=\ngithub.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=\ngithub.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=\ngithub.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=\ngithub.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=\ngithub.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=\ngithub.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=\ngithub.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=\ngithub.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA=\ngithub.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=\ngithub.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=\ngithub.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=\ngithub.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=\ngithub.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=\ngithub.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/quasoft/memstore v0.0.0-20191010062613-2bce066d2b0b h1:aUNXCGgukb4gtY99imuIeoh8Vr0GSwAlYxPAhqZrpFc=\ngithub.com/quasoft/memstore v0.0.0-20191010062613-2bce066d2b0b/go.mod h1:wTPjTepVu7uJBYgZ0SdWHQlIas582j6cn2jgk4DDdlg=\ngithub.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=\ngithub.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=\ngithub.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=\ngithub.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI=\ngithub.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=\ngithub.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=\ngithub.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=\ngithub.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=\ngithub.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=\ngithub.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=\ngithub.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=\ngithub.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=\ngithub.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=\ngithub.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=\ngithub.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE=\ngithub.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg=\ngithub.com/swaggo/gin-swagger v1.6.1 h1:Ri06G4gc9N4t4k8hekMigJ9zKTFSlqj/9paAQCQs7cY=\ngithub.com/swaggo/gin-swagger v1.6.1/go.mod h1:LQ+hJStHakCWRiK/YNYtJOu4mR2FP+pxLnILT/qNiTw=\ngithub.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=\ngithub.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=\ngithub.com/tklauser/go-sysconf v0.3.11 h1:89WgdJhk5SNwJfu+GKyYveZ4IaJ7xAkecBo+KdJV0CM=\ngithub.com/tklauser/go-sysconf v0.3.11/go.mod h1:GqXfhXY3kiPa0nAXPDIQIWzJbMCB7AmcWpGR8lSZfqI=\ngithub.com/tklauser/numcpus v0.6.0 h1:kebhY2Qt+3U6RNK7UqpYNA+tJ23IBEGKkB7JQBfDYms=\ngithub.com/tklauser/numcpus v0.6.0/go.mod h1:FEZLMke0lhOUG6w2JadTzp0a+Nl8PF/GFkQ5UVIcaL4=\ngithub.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=\ngithub.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=\ngithub.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=\ngithub.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=\ngithub.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=\ngithub.com/yuin/gopher-lua v1.1.0 h1:BojcDhfyDWgU2f2TOzYK/g5p2gxMrku8oupLDqlnSqE=\ngithub.com/yuin/gopher-lua v1.1.0/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=\ngithub.com/yusufpapurcu/wmi v1.2.2 h1:KBNDSne4vP5mbSWnJbO+51IMOXJB67QiYCSBrubbPRg=\ngithub.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=\ngolang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=\ngolang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=\ngolang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=\ngolang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=\ngolang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=\ngolang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=\ngolang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=\ngolang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=\ngolang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=\ngolang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=\ngolang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=\ngolang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=\ngolang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM=\ngolang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=\ngolang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=\ngolang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=\ngolang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=\ngolang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw=\ngolang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=\ngolang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=\ngolang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=\ngolang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=\ngolang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=\ngolang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=\ngolang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=\ngolang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=\ngolang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=\ngolang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=\ngolang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=\ngolang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=\ngolang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=\ngolang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=\ngolang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=\ngolang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=\ngolang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=\ngolang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg=\ngolang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=\ngolang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=\ngoogle.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=\ngoogle.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=\ngopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=\ngopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=\ngopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=\ngopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=\ngopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=\ngopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=\ngopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=\ngopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\ngopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\ngorm.io/gorm v1.25.8 h1:WAGEZ/aEcznN4D03laj8DKnehe1e9gYQAjW8xyPRdeo=\ngorm.io/gorm v1.25.8/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=\nmodernc.org/libc v1.22.6 h1:cbXU8R+A6aOjRuhsFh3nbDWXO/Hs4ClJRXYB11KmPDo=\nmodernc.org/libc v1.22.6/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY=\nmodernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=\nmodernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=\nmodernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds=\nmodernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=\nmodernc.org/sqlite v1.22.1 h1:P2+Dhp5FR1RlVRkQ3dDfCiv3Ok8XPxqpe70IjYVA9oE=\nmodernc.org/sqlite v1.22.1/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk=\nnullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=\nrsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=\n"
  },
  {
    "path": "internal/api/handler/backup_handler.go",
    "content": "package handler\n\nimport (\n\t\"dst-admin-go/internal/database\"\n\t\"dst-admin-go/internal/model\"\n\t\"dst-admin-go/internal/pkg/context\"\n\t\"dst-admin-go/internal/pkg/response\"\n\t\"dst-admin-go/internal/service/backup\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype BackupHandler struct {\n\tbackupService *backup.BackupService\n}\n\nfunc NewBackupHandler(backupService *backup.BackupService) *BackupHandler {\n\treturn &BackupHandler{\n\t\tbackupService: backupService,\n\t}\n}\n\nfunc (h *BackupHandler) RegisterRoute(router *gin.RouterGroup) {\n\trouter.GET(\"/api/game/backup\", h.GetBackupList)\n\trouter.POST(\"/api/game/backup\", h.CreateBackup)\n\trouter.DELETE(\"/api/game/backup\", h.DeleteBackup)\n\trouter.PUT(\"/api/game/backup\", h.RenameBackup)\n\trouter.GET(\"/api/game/backup/download\", h.DownloadBackup)\n\trouter.POST(\"/api/game/backup/upload\", h.UploadBackup)\n\trouter.GET(\"/backup/restore\", h.RestoreBackup)\n\trouter.POST(\"/api/game/backup/snapshot/setting\", h.SaveBackupSnapshotsSetting)\n\trouter.GET(\"/api/game/backup/snapshot/setting\", h.GetBackupSnapshotsSetting)\n\trouter.GET(\"/api/game/backup/snapshot/list\", h.BackupSnapshotsList)\n}\n\n// DeleteBackup 删除备份\n// @Summary 删除备份\n// @Description 删除指定的备份文件\n// @Tags backup\n// @Accept json\n// @Produce json\n// @Param fileNames body []string true \"要删除的文件名列表\"\n// @Success 200 {object} response.Response\n// @Router /api/game/backup [delete]\nfunc (h *BackupHandler) DeleteBackup(ctx *gin.Context) {\n\tvar body struct {\n\t\tFileNames []string `json:\"fileNames\"`\n\t}\n\tif err := ctx.BindJSON(&body); err != nil {\n\t\treturn\n\t}\n\th.backupService.DeleteBackup(ctx, body.FileNames)\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"delete backups success\",\n\t\tData: nil,\n\t})\n}\n\n// DownloadBackup 下载备份\n// @Summary 下载备份\n// @Description 下载指定的备份文件\n// @Tags backup\n// @Accept json\n// @Produce json\n// @Param backupName query string true \"备份文件名\"\n// @Success 200 {object} response.Response\n// @Router /api/game/backup/download [get]\nfunc (h *BackupHandler) DownloadBackup(ctx *gin.Context) {\n\th.backupService.DownloadBackup(ctx)\n}\n\n// GetBackupList 获取备份列表\n// @Summary 获取备份列表\n// @Description 获取当前集群的所有备份文件列表\n// @Tags backup\n// @Accept json\n// @Produce json\n// @Success 200 {object} response.Response\n// @Router /api/game/backup [get]\nfunc (h *BackupHandler) GetBackupList(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"get backup list success\",\n\t\tData: h.backupService.GetBackupList(clusterName),\n\t})\n}\n\n// RenameBackup 重命名备份\n// @Summary 重命名备份\n// @Description 重命名指定的备份文件\n// @Tags backup\n// @Accept json\n// @Produce json\n// @Param request body object true \"请求体\" schema-example({\"fileName\": \"old_name\", \"newName\": \"new_name\"})\n// @Success 200 {object} response.Response\n// @Router /api/game/backup [put]\nfunc (h *BackupHandler) RenameBackup(ctx *gin.Context) {\n\n\tvar body struct {\n\t\tFileName string `json:\"fileName\"`\n\t\tNewName  string `json:\"newName\"`\n\t}\n\tif err := ctx.BindJSON(&body); err != nil {\n\t\treturn\n\t}\n\th.backupService.RenameBackup(ctx, body.FileName, body.NewName)\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"rename backup success\",\n\t\tData: nil,\n\t})\n}\n\n// RestoreBackup 恢复备份\n// @Summary 恢复备份\n// @Description 从备份文件恢复游戏存档\n// @Tags backup\n// @Accept json\n// @Produce json\n// @Param backupName query string true \"备份文件名\"\n// @Success 200 {object} response.Response\n// @Router /backup/restore [get]\nfunc (h *BackupHandler) RestoreBackup(ctx *gin.Context) {\n\tbackupName := ctx.Query(\"backupName\")\n\n\th.backupService.RestoreBackup(ctx, backupName)\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"restore backup success\",\n\t\tData: nil,\n\t})\n}\n\n// UploadBackup 上传备份\n// @Summary 上传备份\n// @Description 上传新的备份文件\n// @Tags backup\n// @Accept multipart/form-data\n// @Produce json\n// @Success 200 {object} response.Response\n// @Router /api/game/backup/upload [post]\nfunc (h *BackupHandler) UploadBackup(ctx *gin.Context) {\n\n\th.backupService.UploadBackup(ctx)\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"upload backup success\",\n\t\tData: nil,\n\t})\n}\n\n// CreateBackup 创建备份\n// @Summary 创建备份\n// @Description 创建新的游戏存档备份\n// @Tags backup\n// @Accept json\n// @Produce json\n// @Param backupName query string false \"备份名称\"\n// @Success 200 {object} response.Response\n// @Router /api/game/backup [post]\nfunc (h *BackupHandler) CreateBackup(ctx *gin.Context) {\n\tvar body struct {\n\t\tBackupName string `json:\"backupName\"`\n\t}\n\tif err := ctx.ShouldBind(&body); err != nil {\n\t\tbody.BackupName = \"\"\n\t}\n\tclusterName := context.GetClusterName(ctx)\n\th.backupService.CreateBackup(clusterName, body.BackupName)\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"create backup success\",\n\t\tData: nil,\n\t})\n}\n\n// SaveBackupSnapshotsSetting 保存快照设置\n// @Summary 保存快照设置\n// @Description 保存自动快照备份的设置\n// @Tags backup\n// @Accept json\n// @Produce json\n// @Param setting body model.BackupSnapshot true \"快照设置\"\n// @Success 200 {object} response.Response\n// @Router /api/game/backup/snapshot/setting [post]\nfunc (h *BackupHandler) SaveBackupSnapshotsSetting(ctx *gin.Context) {\n\n\tvar backupSnapshot model.BackupSnapshot\n\tvar oldBackupSnapshot model.BackupSnapshot\n\terr := ctx.ShouldBind(&backupSnapshot)\n\tif err != nil {\n\t\tlog.Panicln(\"参数错误\", err)\n\t}\n\tdb := database.Db\n\tdb.First(&oldBackupSnapshot)\n\n\toldBackupSnapshot.Enable = backupSnapshot.Enable\n\toldBackupSnapshot.Interval = backupSnapshot.Interval\n\toldBackupSnapshot.MaxSnapshots = backupSnapshot.MaxSnapshots\n\toldBackupSnapshot.IsCSave = backupSnapshot.IsCSave\n\n\tdb.Save(&oldBackupSnapshot)\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: oldBackupSnapshot,\n\t})\n}\n\n// GetBackupSnapshotsSetting 获取快照设置\n// @Summary 获取快照设置\n// @Description 获取自动快照备份的设置\n// @Tags backup\n// @Accept json\n// @Produce json\n// @Success 200 {object} response.Response\n// @Router /api/game/backup/snapshot/setting [get]\nfunc (h *BackupHandler) GetBackupSnapshotsSetting(ctx *gin.Context) {\n\n\tvar oldBackupSnapshot model.BackupSnapshot\n\tdb := database.Db\n\tdb.First(&oldBackupSnapshot)\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: oldBackupSnapshot,\n\t})\n}\n\n// BackupSnapshotsList 获取快照列表\n// @Summary 获取快照列表\n// @Description 获取当前集群的所有快照备份列表\n// @Tags backup\n// @Accept json\n// @Produce json\n// @Success 200 {object} response.Response\n// @Router /api/game/backup/snapshot/list [get]\nfunc (h *BackupHandler) BackupSnapshotsList(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\n\tvar snapshotBackupList []backup.BackupInfo\n\tbackupList := h.backupService.GetBackupList(clusterName)\n\tfor i := range backupList {\n\t\tname := backupList[i].FileName\n\t\tif strings.HasPrefix(name, \"(snapshot)\") && strings.Contains(name, clusterName) {\n\t\t\tsnapshotBackupList = append(snapshotBackupList, backupList[i])\n\t\t}\n\t}\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: snapshotBackupList,\n\t})\n}\n"
  },
  {
    "path": "internal/api/handler/dst_api_handler.go",
    "content": "package handler\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype DstHomeDetailParam struct {\n\tRowId  string `json:\"rowId\"`\n\tRegion string `json:\"region\"`\n}\n\nfunc NewDstHomeDetailParam() *DstHomeDetailParam {\n\treturn &DstHomeDetailParam{}\n}\n\ntype DstHomeServerParam struct {\n\tPage           int    `json:\"page\"`\n\tPaginate       int    `json:\"paginate\"`\n\tSortType       string `json:\"sort_type\"`\n\tSortWay        int    `json:\"sort_way\"`\n\tSearch_type    int    `json:\"search_type\"`\n\tSearch_content string `json:\"search_content\"`\n\tMode           string `json:\"mode\"`\n\tMod            int    `json:\"mod\"`\n\tSeason         string `json:\"season\"`\n\tPvp            int    `json:\"pvp\"`\n\tPassword       int    `json:\"password\"`\n\tWorld          int    `json:\"world\"`\n\tPlayerpercent  string `json:\"playerpercent\"`\n}\n\nfunc NewDstHomeServerParam() *DstHomeServerParam {\n\treturn &DstHomeServerParam{}\n}\n\ntype DstApiHandler struct {\n}\n\nfunc NewDstApiHandler() *DstApiHandler {\n\treturn &DstApiHandler{}\n}\n\nfunc (h *DstApiHandler) RegisterRoute(router *gin.RouterGroup) {\n\n\trouter.POST(\"/api/dst/home/server\", h.GetDstHomeServerList)\n\trouter.POST(\"/api/dst/home/server/detail\", h.GetDstHomeDetailList)\n\n\trouter.GET(\"/api/dst/home/server2\", h.GetDstHomeServerList2)\n\trouter.GET(\"/api/dst/home/server/detail2\", h.GetDstHomeDetailList2)\n\t// 配置路由\n\trouter.Any(\"/api/dst-static/*filepath\", h.GiteeProxy)\n\n}\n\n// 获取第三方饥荒服务器\nfunc (h *DstApiHandler) GetDstHomeServerList(c *gin.Context) {\n\n\t// response, err := http.Get(\"https://dst.liuyh.com/index/serverlist/getserverlist.html\")\n\t// if err != nil || response.StatusCode != http.StatusOK {\n\t// \tc.Status(http.StatusServiceUnavailable)\n\t// \treturn\n\t// }\n\n\tparam := NewDstHomeServerParam()\n\terr := c.ShouldBind(param)\n\tif err != nil {\n\t\tlog.Println(\"参数解析错误\", err)\n\t}\n\n\tquery_data := map[string]any{}\n\tquery_data[\"page\"] = param.Page\n\tquery_data[\"paginate\"] = param.Paginate\n\tquery_data[\"sort_type\"] = param.SortType\n\tquery_data[\"sort_way\"] = param.SortWay\n\tquery_data[\"search_type\"] = param.Search_type\n\tif param.Search_content != \"\" {\n\t\tquery_data[\"search_content\"] = param.Search_content\n\t}\n\tif param.Mode != \"\" {\n\t\tquery_data[\"mode\"] = param.Mode\n\t}\n\tif param.Season != \"\" {\n\t\tquery_data[\"season\"] = param.Season\n\t}\n\tif param.Pvp != -1 {\n\t\tquery_data[\"pvp\"] = param.Pvp\n\t}\n\tif param.Mod != -1 {\n\t\tquery_data[\"mod\"] = param.Mod\n\t}\n\tif param.Password != -1 {\n\t\tquery_data[\"password\"] = param.Password\n\t}\n\tif param.World != -1 {\n\t\tquery_data[\"world\"] = param.World\n\t}\n\tif param.Playerpercent != \"\" {\n\t\tquery_data[\"playerpercent\"] = param.Playerpercent\n\t}\n\n\tbytesData, err := json.Marshal(query_data)\n\tlog.Println(\"param\", string(bytesData))\n\n\tif err != nil {\n\t\tlog.Println(\"josn 解析异常\")\n\t}\n\n\tb_reader := bytes.NewReader(bytesData)\n\n\turl := \"http://dst.liuyh.com/index/serverlist/getserverlist.html\"\n\treq, _ := http.NewRequest(\"POST\", url, b_reader)\n\t// 比如说设置个token\n\treq.Header.Set(\"X-Requested-With\", \"XMLHttpRequest\")\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tresponse, err := (&http.Client{}).Do(req)\n\tif err != nil || response.StatusCode != http.StatusOK {\n\t\tc.Status(http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\n\treader := response.Body\n\tcontentLength := response.ContentLength\n\tcontentType := response.Header.Get(\"Content-Type\")\n\n\textraHeaders := map[string]string{\n\t\t//\"Content-Disposition\": `attachment; filename=\"gopher.png\"`,\n\t\t\"X-Requested-With\": \"XMLHttpRequest\",\n\t}\n\n\tc.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)\n}\n\n// 获取第三方饥荒服务器详情\nfunc (h *DstApiHandler) GetDstHomeDetailList(c *gin.Context) {\n\n\tparam := NewDstHomeDetailParam()\n\terr := c.ShouldBind(param)\n\tif err != nil {\n\t\tlog.Println(\"参数解析错误\", err)\n\t}\n\n\tbytesData, err := json.Marshal(param)\n\tif err != nil {\n\t\tlog.Println(\"josn 解析异常\")\n\t}\n\n\tb_reader := bytes.NewReader(bytesData)\n\n\turl := \"http://dst.liuyh.com/index/serverlist/getserverdetail.html\"\n\treq, _ := http.NewRequest(\"POST\", url, b_reader)\n\t// 比如说设置个token\n\treq.Header.Set(\"X-Requested-With\", \"XMLHttpRequest\")\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tresponse, err := (&http.Client{}).Do(req)\n\tif err != nil || response.StatusCode != http.StatusOK {\n\t\tc.Status(http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\n\treader := response.Body\n\tcontentLength := response.ContentLength\n\tcontentType := response.Header.Get(\"Content-Type\")\n\n\textraHeaders := map[string]string{\n\t\t//\"Content-Disposition\": `attachment; filename=\"gopher.png\"`,\n\t\t\"X-Requested-With\": \"XMLHttpRequest\",\n\t}\n\n\tc.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)\n}\n\nfunc (h *DstApiHandler) GetDstHomeServerList2(ctx *gin.Context) {\n\n\toriginalURL := \"https://api.dstserverlist.top/api/list\"\n\tu, err := url.Parse(originalURL)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to parse URL:\", err)\n\t\treturn\n\t}\n\n\t// 构建参数\n\tparams := url.Values{}\n\tparams.Add(\"page\", ctx.DefaultQuery(\"current\", \"1\"))\n\tparams.Add(\"pageCount\", ctx.DefaultQuery(\"pageSize\", \"10\"))\n\tparams.Add(\"name\", ctx.Query(\"Name\"))\n\n\t// 将参数编码为查询字符串\n\tqueryString := params.Encode()\n\n\t// 将查询字符串附加到原始URL\n\tu.RawQuery = queryString\n\n\t// 获取新的URL字符串\n\tnewURL := u.String()\n\n\treq, _ := http.NewRequest(\"POST\", newURL, nil)\n\t// 比如说设置个token\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tresponse, err := (&http.Client{}).Do(req)\n\tif err != nil || response.StatusCode != http.StatusOK {\n\t\tctx.Status(http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\n\treader := response.Body\n\tcontentLength := response.ContentLength\n\tcontentType := response.Header.Get(\"Content-Type\")\n\n\textraHeaders := map[string]string{\n\t\t//\"Content-Disposition\": `attachment; filename=\"gopher.png\"`,\n\t\t//\"X-Requested-With\": \"XMLHttpRequest\",\n\t}\n\tctx.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)\n\n}\n\nfunc (h *DstApiHandler) GetDstHomeDetailList2(ctx *gin.Context) {\n\n\toriginalURL := \"https://api.dstserverlist.top/api/details/\" + ctx.Query(\"rowId\")\n\n\treq, _ := http.NewRequest(\"POST\", originalURL, nil)\n\t// 比如说设置个token\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tresponse, err := (&http.Client{}).Do(req)\n\tif err != nil || response.StatusCode != http.StatusOK {\n\t\tctx.Status(http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\n\treader := response.Body\n\tcontentLength := response.ContentLength\n\tcontentType := response.Header.Get(\"Content-Type\")\n\n\textraHeaders := map[string]string{\n\t\t//\"Content-Disposition\": `attachment; filename=\"gopher.png\"`,\n\t\t//\"X-Requested-With\": \"XMLHttpRequest\",\n\t}\n\tctx.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)\n\n}\n\nfunc (h *DstApiHandler) GiteeProxy(c *gin.Context) {\n\t// 获取路径参数\n\tfilePath := c.Param(\"filepath\")\n\n\t// 处理路径前缀的斜杠（Gin 的路径参数会保留斜杠）\n\tif len(filePath) > 0 && filePath[0] == '/' {\n\t\tfilePath = filePath[1:]\n\t}\n\n\t// 构建目标 URL\n\ttargetURL := \"https://gitee.com/hhhuhu23/dst-static/raw/master/\" + filePath\n\n\t// 创建带超时的 HTTP 客户端\n\tclient := &http.Client{\n\t\tTimeout: 10 * time.Second,\n\t}\n\n\t// 创建代理请求\n\treq, err := http.NewRequest(c.Request.Method, targetURL, c.Request.Body)\n\tif err != nil {\n\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{\n\t\t\t\"error\": \"Failed to create request\",\n\t\t})\n\t\treturn\n\t}\n\n\t// 复制请求头\n\tfor key, values := range c.Request.Header {\n\t\tfor _, value := range values {\n\t\t\t// 排除 Host 头，避免影响转发\n\t\t\tif key == \"Host\" || key == \"Referer\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treq.Header.Add(key, value)\n\t\t}\n\t}\n\n\t// 发送请求\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tc.AbortWithStatusJSON(http.StatusBadGateway, gin.H{\n\t\t\t\"error\": \"Failed to fetch resource\",\n\t\t})\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\t// 设置 CORS 头\n\tc.Header(\"Access-Control-Allow-Origin\", \"*\")\n\tc.Header(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, DELETE, OPTIONS\")\n\tc.Header(\"Access-Control-Allow-Headers\", \"Origin, Content-Type\")\n\n\t// 复制响应头\n\tfor key, values := range resp.Header {\n\t\tfor _, value := range values {\n\t\t\tc.Header(key, value)\n\t\t}\n\t}\n\n\t// 设置状态码\n\tc.Status(resp.StatusCode)\n\n\t// 复制响应体\n\tif _, err := io.Copy(c.Writer, resp.Body); err != nil {\n\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{\n\t\t\t\"error\": \"Failed to stream response\",\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "internal/api/handler/dst_config_handler.go",
    "content": "package handler\n\nimport (\n\t\"dst-admin-go/internal/collect\"\n\t\"dst-admin-go/internal/pkg/context\"\n\t\"dst-admin-go/internal/pkg/response\"\n\t\"dst-admin-go/internal/service/archive\"\n\t\"dst-admin-go/internal/service/dstConfig\"\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype DstConfigHandler struct {\n\tdstConfig dstConfig.Config\n\tarchive   *archive.PathResolver\n}\n\nfunc NewDstConfigHandler(dstConfig dstConfig.Config, archive *archive.PathResolver) *DstConfigHandler {\n\treturn &DstConfigHandler{\n\t\tdstConfig: dstConfig,\n\t\tarchive:   archive,\n\t}\n}\n\nfunc (h *DstConfigHandler) RegisterRoute(router *gin.RouterGroup) {\n\trouter.GET(\"api/dst/config\", h.GetDstConfig)\n\trouter.POST(\"api/dst/config\", h.SaveDstConfig)\n}\n\n// GetDstConfig 获取房间 dst 配置 swagger 注释\n// @Summary 获取房间 dst 配置\n// @Description 获取房间 dst 配置\n// @Tags dstConfig\n// @Accept json\n// @Produce json\n// @Success 200 {object} response.Response{data=dstConfig.DstConfig}\n// @Router /api/game/dst/config [get]\nfunc (h *DstConfigHandler) GetDstConfig(ctx *gin.Context) {\n\n\tclusterName := context.GetClusterName(ctx)\n\n\tconfig, err := h.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\tctx.JSON(http.StatusOK, response.Response{\n\t\t\tCode: 500,\n\t\t\tMsg:  \"failed to get dst config: \" + err.Error(),\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: config,\n\t})\n}\n\n// SaveDstConfig 保存房间 dst 配置 swagger 注释\n// @Summary 保存房间 dst 配置\n// @Description 保存房间 dst 配置\n// @Tags dstConfig\n// @Accept json\n// @Produce json\n// @Param config body dstConfig.DstConfig true \"dst 配置\"\n// @Success 200 {object} response.Response\n// @Router /api/game/dst/config [post]\nfunc (h *DstConfigHandler) SaveDstConfig(ctx *gin.Context) {\n\tconfig := dstConfig.DstConfig{}\n\tif err := ctx.ShouldBindJSON(&config); err != nil {\n\t\tctx.JSON(400, gin.H{\"error\": \"Invalid request body\"})\n\t\treturn\n\t}\n\terr := h.dstConfig.SaveDstConfig(context.GetClusterName(ctx), config)\n\tif err != nil {\n\t\tctx.JSON(http.StatusOK, response.Response{\n\t\t\tCode: 500,\n\t\t\tMsg:  \"failed to save dst config: \" + err.Error(),\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\tclusterPath := h.archive.ClusterPath(config.Cluster)\n\tcollect.Collector.ReCollect(clusterPath, config.Cluster)\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"DstConfig saved successfully\",\n\t\tData: nil,\n\t})\n}\n"
  },
  {
    "path": "internal/api/handler/dst_map_handler.go",
    "content": "package handler\n\nimport (\n\t\"dst-admin-go/internal/pkg/context\"\n\t\"dst-admin-go/internal/pkg/response\"\n\t\"dst-admin-go/internal/pkg/utils/fileUtils\"\n\t\"dst-admin-go/internal/service/archive\"\n\t\"dst-admin-go/internal/service/dstMap\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype DstMapHandler struct {\n\tgenerator       *dstMap.DSTMapGenerator\n\tarchiveResolver *archive.PathResolver\n}\n\nfunc NewDstMapHandler(archiveResolver *archive.PathResolver, generator *dstMap.DSTMapGenerator) *DstMapHandler {\n\treturn &DstMapHandler{\n\t\tarchiveResolver: archiveResolver,\n\t\tgenerator:       generator,\n\t}\n}\n\nfunc (d *DstMapHandler) RegisterRoute(router *gin.RouterGroup) {\n\trouter.GET(\"/api/dst/map/gen\", d.GenDstMap)\n\trouter.GET(\"/api/dst/map/image\", d.GetDstMapImage)\n\trouter.GET(\"/api/dst/map/has/walrusHut/plains\", d.HasWalrusHutPlains)\n\trouter.GET(\"/api/dst/map/session/file\", d.GetSessionFile)\n\trouter.GET(\"/api/dst/map/player/session/file\", d.GetPlayerSessionFile)\n}\n\n// GenDstMap 生成地图 生成 swagger 文档注释\n// @Summary 生成地图\n// @Description 生成地图\n// @Tags dstMap\n// @Param levelName query string true \"levelName\"\n// @Success 200 {object} response.Response\n// @Failure 400 {object} response.Response\n// @Router /api/dst/map/gen [get]\nfunc (d *DstMapHandler) GenDstMap(ctx *gin.Context) {\n\n\tlevelName := ctx.Query(\"levelName\")\n\tif levelName == \"\" {\n\t\tctx.JSON(http.StatusBadRequest, response.Response{\n\t\t\tCode: 400,\n\t\t\tMsg:  \"levelName 参数不能为空\",\n\t\t})\n\t\treturn\n\t}\n\tclusterName := context.GetClusterName(ctx)\n\tclusterPath := d.archiveResolver.ClusterPath(clusterName)\n\toutputImage := filepath.Join(clusterPath, \"dst_map_\"+levelName+\".jpg\")\n\tsessionPath := filepath.Join(clusterPath, levelName, \"save\", \"session\")\n\tfilePath, err := findLatestMetaFile(sessionPath)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tlog.Println(\"生成地图\", filePath, outputImage)\n\theight, width, err := dstMap.ExtractDimensions(filePath)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\terr = d.generator.GenerateMap(\n\t\tfilePath,\n\t\toutputImage,\n\t\theight,\n\t\twidth,\n\t)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: nil,\n\t})\n}\n\n// GetDstMapImage 获取地图图片 获取 swagger 文档注释\n// @Summary 获取地图图片\n// @Description 获取地图图片\n// @Tags dstMap\n// @Param levelName query string true \"levelName\"\n// @Success 200 {object} response.Response\n// @Failure 400 {object} response.Response\n// @Router /api/dst/map/image [get]\nfunc (d *DstMapHandler) GetDstMapImage(ctx *gin.Context) {\n\n\tlevelName := ctx.Query(\"levelName\")\n\tif levelName == \"\" {\n\t\tctx.JSON(http.StatusBadRequest, response.Response{\n\t\t\tCode: 400,\n\t\t\tMsg:  \"levelName 参数不能为空\",\n\t\t})\n\t\treturn\n\t}\n\n\tclusterName := context.GetClusterName(ctx)\n\tclusterPath := d.archiveResolver.ClusterPath(clusterName)\n\n\toutputImage := filepath.Join(clusterPath, \"dst_map_\"+levelName+\".jpg\")\n\tlog.Println(outputImage)\n\t// 使用 Gin 提供的文件传输方法返回图片\n\tctx.File(outputImage)\n\tctx.Header(\"Content-Type\", \"image/png\")\n\n}\n\n// HasWalrusHutPlains 检测地图中是否有walrusHutPlains 获取 swagger 文档注释\n// @Summary 检测地图中是否有walrusHutPlains\n// @Description 检测地图中是否有walrusHutPlains\n// @Tags dstMap\n// @Param levelName query string true \"levelName\"\n// @Success 200 {object} response.Response\n// @Failure 400 {object} response.Response\n// @Router /api/dst/map/has/walrusHut/plains [get]\nfunc (d *DstMapHandler) HasWalrusHutPlains(ctx *gin.Context) {\n\n\tlevelName := ctx.Query(\"levelName\")\n\tif levelName == \"\" {\n\t\tctx.JSON(http.StatusBadRequest, response.Response{\n\t\t\tCode: 400,\n\t\t\tMsg:  \"levelName 参数不能为空\",\n\t\t})\n\t\treturn\n\t}\n\n\tclusterName := context.GetClusterName(ctx)\n\tclusterPath := d.archiveResolver.ClusterPath(clusterName)\n\n\tsessionPath := filepath.Join(clusterPath, levelName, \"save\", \"session\")\n\tfilePath, err := findLatestMetaFile(sessionPath)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tfile, err := fileUtils.ReadFile(filePath)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\thasWalrusHutPlains := strings.Contains(file, \"WalrusHut_Plains\")\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: hasWalrusHutPlains,\n\t})\n\n}\n\n// GetSessionFile 获取存档文件 获取 swagger 文档注释\n// @Summary 获取存档文件\n// @Description 获取存档文件\n// @Tags dstMap\n// @Param levelName query string true \"levelName\"\n// @Success 200 {object} response.Response\n// @Failure 400 {object} response.Response\n// @Router /api/dst/map/session/file [get]\nfunc (d *DstMapHandler) GetSessionFile(ctx *gin.Context) {\n\n\tclusterName := context.GetClusterName(ctx)\n\tclusterPath := d.archiveResolver.ClusterPath(clusterName)\n\n\tlevelName := ctx.Query(\"levelName\")\n\tif levelName == \"\" {\n\t\tctx.JSON(http.StatusBadRequest, response.Response{\n\t\t\tCode: 400,\n\t\t\tMsg:  \"levelName 参数不能为空\",\n\t\t})\n\t\treturn\n\t}\n\tsessionPath := filepath.Join(clusterPath, levelName, \"save\", \"session\")\n\tfilePath, err := findLatestMetaFile(sessionPath)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tfile, err := fileUtils.ReadFile(filePath)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: file,\n\t})\n\n}\n\n// GetPlayerSessionFile 获取玩家存档文件 获取 swagger 文档\n// @Summary 获取玩家存档文件\n// @Description 获取玩家存档文件\n// @Tags dstMap\n// @Param levelName query string true \"levelName\"\n// @Success 200 {object} response.Response\n// @Failure 400 {object} response.Response\n// @Router /api/dst/map/player/session/file [get]\nfunc (d *DstMapHandler) GetPlayerSessionFile(ctx *gin.Context) {\n\n\tclusterName := context.GetClusterName(ctx)\n\tclusterPath := d.archiveResolver.ClusterPath(clusterName)\n\n\tlevelName := ctx.Query(\"levelName\")\n\tkuId := ctx.Query(\"kuId\")\n\tif levelName == \"\" || kuId == \"\" {\n\t\tctx.JSON(http.StatusBadRequest, response.Response{\n\t\t\tCode: 400,\n\t\t\tMsg:  \"levelName or kuId 参数不能为空\",\n\t\t})\n\t\treturn\n\t}\n\n\tbaseSessionFile := filepath.Join(clusterPath, levelName, \"save\", \"session\")\n\tlatestMetaFile, err2 := findLatestMetaFile(baseSessionFile)\n\tif err2 != nil {\n\t\tctx.JSON(http.StatusBadRequest, response.Response{\n\t\t\tCode: 400,\n\t\t\tMsg:  err2.Error(),\n\t\t})\n\t\treturn\n\t}\n\tsessionID := extractSessionID(latestMetaFile)\n\tsessionPath := filepath.Join(baseSessionFile, sessionID, kuId+\"_\")\n\tlog.Println(sessionPath)\n\tfilePath, err := findLatestPlayerFile(sessionPath)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tlog.Println(filePath)\n\tfile, err := fileUtils.ReadFile(filePath)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: file,\n\t})\n\n}\n\nfunc findLatestPlayerFile(directory string) (string, error) {\n\t// 检查指定目录是否存在\n\t_, err := os.Stat(directory)\n\tif os.IsNotExist(err) {\n\t\treturn \"\", fmt.Errorf(\"目录不存在：%s\", directory)\n\t}\n\n\t// 用于存储最新的.meta文件路径和其修改时间\n\tvar latestFile string\n\tvar latestFileTime time.Time\n\n\t// 获取指定目录下所有的文件\n\tfiles, err := ioutil.ReadDir(directory)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"读取目录失败：%s\", err)\n\t}\n\tfor _, file := range files {\n\t\t// 检查文件是否是文件\n\t\tif !file.IsDir() {\n\t\t\t// 获取文件的修改时间\n\t\t\tmodifiedTime := file.ModTime()\n\t\t\t// 如果找到的文件的修改时间比当前最新的.meta文件的修改时间更晚，则更新最新的.meta文件路径和修改时间\n\t\t\tif modifiedTime.After(latestFileTime) {\n\t\t\t\tlatestFile = filepath.Join(directory, file.Name())\n\t\t\t\tlatestFileTime = modifiedTime\n\t\t\t}\n\t\t}\n\t}\n\n\tif latestFile == \"\" {\n\t\treturn \"\", fmt.Errorf(\"未找到文件\")\n\t}\n\n\treturn latestFile, nil\n}\n\nfunc extractSessionPrefix(sessionFile string) string {\n\tparts := strings.Split(sessionFile, \"/\")\n\tif len(parts) >= 2 {\n\t\treturn parts[0] + \"/\" + parts[1]\n\t}\n\treturn sessionFile\n}\n\nconst sessionPrefix = \"/save/session/\"\n\n// extractSessionID 提取 /save/session/ 后的第一个路径段（如 925F2AFB73839B9E）\nfunc extractSessionID(p string) string {\n\t// 找到 \"/save/session/\" 的起始位置\n\ti := strings.Index(p, sessionPrefix)\n\t// 由于题目保证一定存在，可直接跳过错误检查\n\trest := p[i+len(sessionPrefix):]\n\t// 取第一个 '/' 之前的部分（即 session ID）\n\tif j := strings.Index(rest, \"/\"); j != -1 {\n\t\treturn rest[:j]\n\t}\n\t// 理论上不会走到这里（因为后面还有子目录如 /0000000002），但为安全起见：\n\treturn rest // 整个剩余部分（如路径恰好以 ID 结尾）\n}\n\nfunc findLatestMetaFile(directory string) (string, error) {\n\t// 检查指定目录是否存在\n\t_, err := os.Stat(directory)\n\tif os.IsNotExist(err) {\n\t\treturn \"\", fmt.Errorf(\"目录不存在：%s\", directory)\n\t}\n\n\t// 获取指定目录下一级的所有子目录\n\tsubdirs, err := ioutil.ReadDir(directory)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"读取目录失败：%s\", err)\n\t}\n\n\t// 用于存储最新的.meta文件路径和其修改时间\n\tvar latestMetaFile string\n\tvar latestMetaFileTime time.Time\n\n\tfor _, subdir := range subdirs {\n\t\t// 检查子目录是否是目录\n\t\tif subdir.IsDir() {\n\t\t\tsubdirPath := filepath.Join(directory, subdir.Name())\n\n\t\t\t// 获取子目录下的所有文件\n\t\t\tfiles, err := ioutil.ReadDir(subdirPath)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"读取子目录失败：%s\", err)\n\t\t\t}\n\n\t\t\tfor _, file := range files {\n\t\t\t\t// 检查文件是否是.meta文件\n\t\t\t\tif !file.IsDir() && filepath.Ext(file.Name()) != \".meta\" {\n\t\t\t\t\t// 获取文件的修改时间\n\t\t\t\t\tmodifiedTime := file.ModTime()\n\n\t\t\t\t\t// 如果找到的文件的修改时间比当前最新的.meta文件的修改时间更晚，则更新最新的.meta文件路径和修改时间\n\t\t\t\t\tif modifiedTime.After(latestMetaFileTime) {\n\t\t\t\t\t\tlatestMetaFile = filepath.Join(subdirPath, file.Name())\n\t\t\t\t\t\tlatestMetaFileTime = modifiedTime\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif latestMetaFile == \"\" {\n\t\treturn \"\", fmt.Errorf(\"未找到文件\")\n\t}\n\n\treturn latestMetaFile, nil\n}\n"
  },
  {
    "path": "internal/api/handler/game_config_handler.go",
    "content": "package handler\n\nimport (\n\t\"dst-admin-go/internal/pkg/context\"\n\t\"dst-admin-go/internal/pkg/response\"\n\t\"dst-admin-go/internal/service/gameConfig\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype GameConfigHandler struct {\n\tgameConfig *gameConfig.GameConfig\n}\n\nfunc NewGameConfigHandler(gameConfig *gameConfig.GameConfig) *GameConfigHandler {\n\treturn &GameConfigHandler{\n\t\tgameConfig: gameConfig,\n\t}\n}\n\nfunc (p *GameConfigHandler) RegisterRoute(router *gin.RouterGroup) {\n\trouter.GET(\"/api/game/8level/clusterIni\", p.GetClusterIni)\n\trouter.POST(\"/api/game/8level/clusterIni\", p.SaveClusterIni)\n\trouter.GET(\"/api/game/8level/adminilist\", p.GetAdminList)\n\trouter.POST(\"/api/game/8level/adminilist\", p.SaveAdminList)\n\trouter.GET(\"/api/game/8level/blacklist\", p.GetBlackList)\n\trouter.POST(\"/api/game/8level/blacklist\", p.SaveBlackList)\n\trouter.GET(\"/api/game/8level/whitelist\", p.GetWhithList)\n\trouter.POST(\"/api/game/8level/whitelist\", p.SaveWhithList)\n\n\trouter.GET(\"/api/game/config\", p.GetConfig)\n\trouter.POST(\"/api/game/config\", p.SaveConfig)\n}\n\n// GetClusterIni 获取房间 cluster.ini 配置 swagger 注释\n// @Summary 获取房间 cluster.ini 配置\n// @Description 获取房间 cluster.ini 配置\n// @Tags gameConfig\n// @Accept json\n// @Produce json\n// @Success 200 {object} response.Response{data=gameConfig.ClusterIniConfig}\n// @Router /api/game/config/clusterIni [get]\nfunc (p *GameConfigHandler) GetClusterIni(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\tconfig, err := p.gameConfig.GetClusterIniConfig(clusterName)\n\tif err != nil {\n\t\tctx.JSON(500, response.Response{\n\t\t\tCode: http.StatusInternalServerError,\n\t\t\tMsg:  err.Error(),\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\tctx.JSON(200, response.Response{\n\t\tCode: http.StatusOK,\n\t\tMsg:  \"success\",\n\t\tData: config,\n\t})\n}\n\n// SaveClusterIni 保存房间 cluster.ini 配置 swagger 注释\n// @Summary 保存房间 cluster.ini 配置\n// @Description 保存房间 cluster.ini 配置\n// @Tags gameConfig\n// @Accept json\n// @Produce json\n// @Param config body gameConfig.ClusterIniConfig true \"cluster.ini 配置\"\n// @Success 200 {object} response.Response\n// @Router /api/game/config/clusterIni [post]\nfunc (p *GameConfigHandler) SaveClusterIni(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\tvar config gameConfig.ClusterIniConfig\n\tif err := ctx.ShouldBindJSON(&config); err != nil {\n\t\tctx.JSON(400, response.Response{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMsg:  \"Invalid request body\",\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\terr := p.gameConfig.SaveClusterIniConfig(clusterName, &config)\n\tif err != nil {\n\t\tctx.JSON(500, response.Response{\n\t\t\tCode: http.StatusInternalServerError,\n\t\t\tMsg:  err.Error(),\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\tctx.JSON(200, response.Response{\n\t\tCode: http.StatusOK,\n\t\tMsg:  \"success\",\n\t\tData: nil,\n\t})\n}\n\n// GetAdminList 获取房间 adminlist.txt 配置 swagger 注释\n// @Summary 获取房间 adminlist.txt 配置\n// @Description 获取房间 adminlist.txt 配置\n// @Tags gameConfig\n// @Accept json\n// @Produce json\n// @Success 200 {object} response.Response{data=[]string}\n// @Router /api/game/config/adminlist [get]\nfunc (p *GameConfigHandler) GetAdminList(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\tlist, err := p.gameConfig.GetAdminList(clusterName)\n\tif err != nil {\n\t\tctx.JSON(500, response.Response{\n\t\t\tCode: http.StatusInternalServerError,\n\t\t\tMsg:  err.Error(),\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\tctx.JSON(200, response.Response{\n\t\tCode: http.StatusOK,\n\t\tMsg:  \"success\",\n\t\tData: list,\n\t})\n}\n\n// SaveAdminList 保存房间 adminlist.txt 配置 swagger 注释\n// @Summary 保存房间 adminlist.txt 配置\n// @Description 保存房间 adminlist.txt 配置\n// @Tags gameConfig\n// @Accept json\n// @Produce json\n// @Param list body []string true \"adminlist.txt 配置\"\n// @Success 200 {object} response.Response\n// @Router /api/game/config/adminlist [post]\nfunc (p *GameConfigHandler) SaveAdminList(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\tvar payload struct {\n\t\tList []string `json:\"adminlist\"`\n\t}\n\tif err := ctx.ShouldBindJSON(&payload); err != nil {\n\t\tctx.JSON(400, response.Response{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMsg:  \"Invalid request body\",\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\terr := p.gameConfig.SaveAdminList(clusterName, payload.List)\n\tif err != nil {\n\t\tctx.JSON(500, response.Response{\n\t\t\tCode: http.StatusInternalServerError,\n\t\t\tMsg:  err.Error(),\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\tctx.JSON(200, response.Response{\n\t\tCode: http.StatusOK,\n\t\tMsg:  \"success\",\n\t\tData: nil,\n\t})\n}\n\n// GetBlackList 获取房间 blacklist.txt 配置 swagger 注释\n// @Summary 获取房间 blacklist.txt 配置\n// @Description 获取房间 blacklist.txt 配置\n// @Tags gameConfig\n// @Accept json\n// @Produce json\n// @Success 200 {object} response.Response{data=[]string}\n// @Router /api/game/config/blacklist [get]\nfunc (p *GameConfigHandler) GetBlackList(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\tlist, err := p.gameConfig.GetBlackList(clusterName)\n\tif err != nil {\n\t\tctx.JSON(500, response.Response{\n\t\t\tCode: http.StatusInternalServerError,\n\t\t\tMsg:  err.Error(),\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\tctx.JSON(200, response.Response{\n\t\tCode: http.StatusOK,\n\t\tMsg:  \"success\",\n\t\tData: list,\n\t})\n}\n\n// SaveBlackList 保存房间 blacklist.txt 配置 swagger 注释\n// @Summary 保存房间 blacklist.txt 配置\n// @Description 保存房间 blacklist.txt 配置\n// @Tags gameConfig\n// @Accept json\n// @Produce json\n// @Param list body []string true \"blacklist.txt 配置\"\n// @Success 200 {object} response.Response\n// @Router /api/game/config/blacklist [post]\nfunc (p *GameConfigHandler) SaveBlackList(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\tvar payload struct {\n\t\tList []string `json:\"blacklist\"`\n\t}\n\tif err := ctx.ShouldBindJSON(&payload); err != nil {\n\t\tctx.JSON(400, response.Response{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMsg:  \"Invalid request body\",\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\terr := p.gameConfig.SaveBlackList(clusterName, payload.List)\n\tif err != nil {\n\t\tctx.JSON(500, response.Response{\n\t\t\tCode: http.StatusInternalServerError,\n\t\t\tMsg:  err.Error(),\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\tctx.JSON(200, response.Response{\n\t\tCode: http.StatusOK,\n\t\tMsg:  \"success\",\n\t\tData: nil,\n\t})\n}\n\n// GetWhithList 获取房间 whitelist.txt 配置 swagger 注释\n// @Summary 获取房间 whitelist.txt 配置\n// @Description 获取房间 whitelist.txt 配置\n// @Tags gameConfig\n// @Accept json\n// @Produce json\n// @Success 200 {object} response.Response{data=[]string}\n// @Router /api/game/config/whitelist [get]\nfunc (p *GameConfigHandler) GetWhithList(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\tlist, err := p.gameConfig.GetWhithList(clusterName)\n\tif err != nil {\n\t\tctx.JSON(500, response.Response{\n\t\t\tCode: http.StatusInternalServerError,\n\t\t\tMsg:  err.Error(),\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\tctx.JSON(200, response.Response{\n\t\tCode: http.StatusOK,\n\t\tMsg:  \"success\",\n\t\tData: list,\n\t})\n}\n\n// SaveWhithList 保存房间 whitelist.txt 配置 swagger 注释\n// @Summary 保存房间 whitelist.txt 配置\n// @Description 保存房间 whitelist.txt 配置\n// @Tags gameConfig\n// @Accept json\n// @Produce json\n// @Param list body []string true \"whitelist.txt 配置\"\n// @Success 200 {object} response.Response\n// @Router /api/game/config/whitelist [post]\nfunc (p *GameConfigHandler) SaveWhithList(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\tvar payload struct {\n\t\tList []string `json:\"whitelist\"`\n\t}\n\tif err := ctx.ShouldBindJSON(&payload); err != nil {\n\t\tctx.JSON(400, response.Response{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMsg:  \"Invalid request body\",\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\terr := p.gameConfig.SaveWhithList(clusterName, payload.List)\n\tif err != nil {\n\t\tctx.JSON(500, response.Response{\n\t\t\tCode: http.StatusInternalServerError,\n\t\t\tMsg:  err.Error(),\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\tctx.JSON(200, response.Response{\n\t\tCode: http.StatusOK,\n\t\tMsg:  \"success\",\n\t\tData: nil,\n\t})\n\n}\n\n// GetConfig 获取房间配置 swagger 注释\n// @Summary 获取房间配置\n// @Description 获取房间配置\n// @Tags gameConfig\n// @Accept json\n// @Produce json\n// @Success 200 {object} response.Response{data=gameConfig.HomeConfigVO}\n// @Router /api/game/config [get]\nfunc (p *GameConfigHandler) GetConfig(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\tconfig, err := p.gameConfig.GetHomeConfig(clusterName)\n\tif err != nil {\n\t\tctx.JSON(200, response.Response{\n\t\t\tCode: 500,\n\t\t\tMsg:  err.Error(),\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\tctx.JSON(200, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: config,\n\t})\n}\n\nfunc (p *GameConfigHandler) SaveConfig(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\tconfig := gameConfig.HomeConfigVO{}\n\terr := ctx.ShouldBind(&config)\n\tif err != nil {\n\t\tctx.JSON(http.StatusBadRequest, response.Response{\n\t\t\tCode: 400,\n\t\t\tMsg:  \"Invalid request body\",\n\t\t})\n\t\treturn\n\t}\n\tlog.Println(config)\n\tp.gameConfig.SaveConfig(clusterName, config)\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"save dst server config success\",\n\t})\n}\n"
  },
  {
    "path": "internal/api/handler/game_handler.go",
    "content": "package handler\n\nimport (\n\t\"dst-admin-go/internal/middleware\"\n\t\"dst-admin-go/internal/pkg/context\"\n\t\"dst-admin-go/internal/pkg/response\"\n\t\"dst-admin-go/internal/pkg/utils/shellUtils\"\n\t\"dst-admin-go/internal/pkg/utils/systemUtils\"\n\t\"dst-admin-go/internal/service/archive\"\n\t\"dst-admin-go/internal/service/game\"\n\t\"dst-admin-go/internal/service/gameArchive\"\n\t\"dst-admin-go/internal/service/level\"\n\t\"dst-admin-go/internal/service/levelConfig\"\n\t\"encoding/json\"\n\t\"log\"\n\t\"net/http\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype GameHandler struct {\n\tprocess          game.Process\n\tlevel            *level.LevelService\n\tgameArchive      *gameArchive.GameArchive\n\tlevelConfigUtils *levelConfig.LevelConfigUtils\n\tarchive          *archive.PathResolver\n}\n\nfunc NewGameHandler(process game.Process, levelService *level.LevelService, gameArchive *gameArchive.GameArchive, levelConfigUtils *levelConfig.LevelConfigUtils, archive *archive.PathResolver) *GameHandler {\n\treturn &GameHandler{\n\t\tprocess:          process,\n\t\tlevel:            levelService,\n\t\tgameArchive:      gameArchive,\n\t\tlevelConfigUtils: levelConfigUtils,\n\t\tarchive:          archive,\n\t}\n}\n\nfunc (p *GameHandler) RegisterRoute(router *gin.RouterGroup) {\n\trouter.GET(\"/api/game/8level/start\", p.Start, middleware.StartBeforeMiddleware(p.archive, p.levelConfigUtils))\n\trouter.GET(\"/api/game/8level/stop\", p.Stop)\n\trouter.GET(\"/api/game/8level/start/all\", p.StartAll, middleware.StartBeforeMiddleware(p.archive, p.levelConfigUtils))\n\trouter.GET(\"/api/game/8level/stop/all\", p.StopAll)\n\trouter.POST(\"/api/game/8level/command\", p.Command)\n\trouter.GET(\"/api/game/8level/status\", p.Status)\n\trouter.GET(\"/api/game/archive\", p.GameArchive)\n\trouter.GET(\"/api/game/system/info/stream\", p.SystemInfoStream)\n}\n\n// Stop 停止世界 swagger 注释\n// @Summary 停止世界\n// @Description 停止世界\n// @Tags game\n// @Accept json\n// @Produce json\n// @Param levelName query string true \"世界名称\"\n// @Success 200 {object} response.Response\n// @Router /api/game/stop [get]\nfunc (p *GameHandler) Stop(ctx *gin.Context) {\n\n\tclusterName := context.GetClusterName(ctx)\n\tlevelName := ctx.Query(\"levelName\")\n\tif levelName == \"\" {\n\t\tctx.JSON(400, response.Response{Code: 400, Msg: \"levelName query parameter is required\"})\n\t\treturn\n\t}\n\terr := p.process.Stop(clusterName, levelName)\n\tif err != nil {\n\t\tctx.JSON(http.StatusOK, response.Response{Code: 500, Msg: \"failed to stop game server: \" + err.Error()})\n\t} else {\n\t\tctx.JSON(http.StatusOK, response.Response{Code: 200, Msg: \"success\"})\n\t}\n}\n\n// Start 启动世界 swagger 注释\n// @Summary 启动世界\n// @Description 启动世界\n// @Tags game\n// @Accept json\n// @Produce json\n// @Param levelName query string true \"世界名称\"\n// @Success 200 {object} response.Response\n// @Router /api/game/start [get]\nfunc (p *GameHandler) Start(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\tlevelName := ctx.Query(\"levelName\")\n\tif levelName == \"\" {\n\t\tctx.JSON(400, response.Response{Code: 400, Msg: \"levelName query parameter is required\"})\n\t\treturn\n\t}\n\terr := p.process.Start(clusterName, levelName)\n\tif err != nil {\n\t\tctx.JSON(http.StatusOK, response.Response{Code: 500, Msg: \"failed to start game server: \" + err.Error()})\n\t} else {\n\t\tctx.JSON(http.StatusOK, response.Response{Code: 200, Msg: \"success\"})\n\t}\n}\n\n// StartAll 启动所有世界 swagger 注释\n// @Summary 启动所有世界\n// @Description 启动所有世界\n// @Tags game\n// @Accept json\n// @Produce json\n// @Success 200 {object} response.Response\n// @Router /api/game/start/all [get]\nfunc (p *GameHandler) StartAll(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\terr := p.process.StartAll(clusterName)\n\tif err != nil {\n\t\tctx.JSON(http.StatusOK, response.Response{Code: 500, Msg: \"failed to start all game servers: \" + err.Error()})\n\t} else {\n\t\tctx.JSON(http.StatusOK, response.Response{Code: 200, Msg: \"success\"})\n\t}\n}\n\n// StopAll 停止所有世界 swagger 注释\n// @Summary 停止所有世界\n// @Description 停止所有世界\n// @Tags game\n// @Accept json\n// @Produce json\n// @Success 200 {object} response.Response\n// @Router /api/game/stop/all [get]\nfunc (p *GameHandler) StopAll(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\terr := p.process.StopAll(clusterName)\n\tif err != nil {\n\t\tctx.JSON(http.StatusOK, response.Response{Code: 500, Msg: \"failed to stop all game servers: \" + err.Error()})\n\t} else {\n\t\tctx.JSON(http.StatusOK, response.Response{Code: 200, Msg: \"success\"})\n\t}\n}\n\n// Command 运行命令 swagger 注释\n// @Summary 运行命令\n// @Description 运行命令\n// @Tags game\n// @Accept json\n// @Produce json\n// @Param command query string true \"命令\"\n// @Success 200 {object} response.Response\n// @Router /api/game/command [post]\nfunc (p *GameHandler) Command(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\ttype payload struct {\n\t\tCommand   string `json:\"command\"`\n\t\tLevelName string `json:\"levelName\"`\n\t}\n\tvar command payload\n\tif err := ctx.ShouldBindJSON(&command); err != nil {\n\t\tctx.JSON(400, response.Response{Code: 400, Msg: \"Invalid request body\"})\n\t\treturn\n\t}\n\tif command.LevelName == \"\" {\n\t\tctx.JSON(400, response.Response{Code: 400, Msg: \"levelName query parameter is required\"})\n\t\treturn\n\t}\n\tstatus, err := p.process.Status(clusterName, command.LevelName)\n\tif !status {\n\t\tctx.JSON(http.StatusOK, response.Response{Code: 200, Msg: \"game server is not running\"})\n\t\treturn\n\t}\n\terr = p.process.Command(clusterName, command.LevelName, command.Command)\n\tif err != nil {\n\t\tctx.JSON(http.StatusOK, response.Response{Code: 500, Msg: \"failed to run command: \" + err.Error()})\n\t\treturn\n\t}\n\tctx.JSON(http.StatusOK, response.Response{Code: 200, Msg: \"success\"})\n}\n\ntype LevelStatus struct {\n\tPs                game.DstPsAux         `json:\"Ps\"`\n\tRunVersion        int64                 `json:\"runVersion\"`\n\tStatus            bool                  `json:\"status\"`\n\tIsMaster          bool                  `json:\"isMaster\"`\n\tLevelName         string                `json:\"levelName\"`\n\tUuid              string                `json:\"uuid\"`\n\tLeveldataoverride string                `json:\"leveldataoverride\"`\n\tModoverrides      string                `json:\"modoverrides\"`\n\tServerIni         levelConfig.ServerIni `json:\"serverIni\"`\n}\n\n// Status 获取服务器状态\n// @Summary 获取服务器状态\n// @Description 获取所有世界的运行状态信息\n// @Tags game\n// @Accept json\n// @Produce json\n// @Success 200 {object} response.Response{data=[]LevelStatus}\n// @Router /api/game/8level/status [get]\nfunc (p *GameHandler) Status(ctx *gin.Context) {\n\n\tclusterName := context.GetClusterName(ctx)\n\tlevelList := p.level.GetLevelList(clusterName)\n\tlength := len(levelList)\n\tresult := make([]LevelStatus, length)\n\n\tif runtime.GOOS == \"windows\" {\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(length)\n\t\tfor i := range levelList {\n\t\t\tgo func(index int) {\n\t\t\t\tdefer func() {\n\t\t\t\t\twg.Done()\n\t\t\t\t\tif r := recover(); r != nil {\n\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t\tlevelItem := levelList[index]\n\t\t\t\tps := p.process.PsAuxSpecified(clusterName, levelItem.Uuid)\n\t\t\t\tstatus, _ := p.process.Status(clusterName, levelItem.Uuid)\n\t\t\t\tresult[index] = LevelStatus{\n\t\t\t\t\tPs:                ps,\n\t\t\t\t\tStatus:            status,\n\t\t\t\t\tRunVersion:        levelItem.RunVersion,\n\t\t\t\t\tLevelName:         levelItem.LevelName,\n\t\t\t\t\tIsMaster:          levelItem.IsMaster,\n\t\t\t\t\tUuid:              levelItem.Uuid,\n\t\t\t\t\tLeveldataoverride: levelItem.Leveldataoverride,\n\t\t\t\t\tModoverrides:      levelItem.Modoverrides,\n\t\t\t\t\tServerIni:         levelItem.ServerIni,\n\t\t\t\t}\n\t\t\t}(i)\n\t\t}\n\t\twg.Wait()\n\t\tctx.JSON(http.StatusOK, response.Response{\n\t\t\tCode: 200,\n\t\t\tMsg:  \"success\",\n\t\t\tData: result,\n\t\t})\n\t} else {\n\t\tfor i := range levelList {\n\t\t\tlevelItem := levelList[i]\n\t\t\tresult[i] = LevelStatus{\n\t\t\t\tStatus:            false,\n\t\t\t\tRunVersion:        levelItem.RunVersion,\n\t\t\t\tLevelName:         levelItem.LevelName,\n\t\t\t\tIsMaster:          levelItem.IsMaster,\n\t\t\t\tUuid:              levelItem.Uuid,\n\t\t\t\tLeveldataoverride: levelItem.Leveldataoverride,\n\t\t\t\tModoverrides:      levelItem.Modoverrides,\n\t\t\t\tServerIni:         levelItem.ServerIni,\n\t\t\t}\n\t\t}\n\n\t\tcmd := \"ps -aux | grep -v grep | grep -v tail | grep -v SCREEN | grep \" + clusterName + \" |awk '{print $3, $4, $5, $6,$16}'\"\n\t\tinfo, err := shellUtils.Shell(cmd)\n\t\tif err != nil {\n\t\t\tlog.Println(cmd + \" error: \" + err.Error())\n\t\t} else {\n\t\t\tlines := strings.Split(info, \"\\n\")\n\t\t\tfor lineIndex := range lines {\n\t\t\t\tdstPsVo := game.DstPsAux{}\n\t\t\t\tarr := strings.Split(lines[lineIndex], \" \")\n\t\t\t\tif len(arr) > 4 {\n\t\t\t\t\tdstPsVo.CpuUage = strings.Replace(arr[0], \"\\n\", \"\", -1)\n\t\t\t\t\tdstPsVo.MemUage = strings.Replace(arr[1], \"\\n\", \"\", -1)\n\t\t\t\t\tdstPsVo.VSZ = strings.Replace(arr[2], \"\\n\", \"\", -1)\n\t\t\t\t\tdstPsVo.RSS = strings.Replace(arr[3], \"\\n\", \"\", -1)\n\t\t\t\t\tfor i := range result {\n\t\t\t\t\t\tlevelName := result[i].Uuid\n\t\t\t\t\t\tif strings.Contains(arr[4], levelName) {\n\t\t\t\t\t\t\tresult[i].Ps = dstPsVo\n\t\t\t\t\t\t\tresult[i].Status = true\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t\tctx.JSON(http.StatusOK, response.Response{\n\t\t\tCode: 200,\n\t\t\tMsg:  \"success\",\n\t\t\tData: result,\n\t\t})\n\t}\n}\n\n// GameArchive 获取游戏存档列表\n// @Summary 获取游戏存档列表\n// @Description 获取当前集群的游戏存档列表\n// @Tags game\n// @Accept json\n// @Produce json\n// @Success 200 {object} response.Response{gameArchive.GameArchiveInfo}\n// @Router /api/game/archive [get]\nfunc (p *GameHandler) GameArchive(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\tarchiveInfo := p.gameArchive.GetGameArchive(clusterName)\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: archiveInfo,\n\t})\n}\n\n// SystemInfoStream 系统信息流\n// @Summary 系统信息流\n// @Description 获取服务器系统信息的实时流 (SSE)\n// @Tags game\n// @Accept text/event-stream\n// @Produce text/event-stream\n// @Success 200 {string} string \"SSE 格式的系统信息流\"\n// @Router /api/game/system/info/stream [get]\nfunc (p *GameHandler) SystemInfoStream(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\n\t// 设置SSE响应头\n\tctx.Header(\"Content-Type\", \"text/event-stream\")\n\tctx.Header(\"Cache-Control\", \"no-cache\")\n\tctx.Header(\"Connection\", \"keep-alive\")\n\tctx.Header(\"X-Accel-Buffering\", \"no\")\n\n\t// 创建一个ticker,每2秒推送一次数据\n\tticker := time.NewTicker(2 * time.Second)\n\tdefer ticker.Stop()\n\n\t// 使用context来检测客户端断开连接\n\tclientGone := ctx.Request.Context().Done()\n\n\t// 立即发送第一次数据\n\tp.sendSystemInfoData(ctx, clusterName)\n\n\tfor {\n\t\tselect {\n\t\tcase <-clientGone:\n\t\t\tlog.Println(\"Client disconnected from system info stream\")\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tp.sendSystemInfoData(ctx, clusterName)\n\t\t}\n\t}\n}\n\nfunc (p *GameHandler) sendSystemInfoData(ctx *gin.Context, clusterName string) {\n\tsystemInfo := p.GetSystemInfo(clusterName)\n\n\t// 构造响应数据\n\tresponse := response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: systemInfo,\n\t}\n\n\t// 将数据序列化为JSON\n\tdata, err := json.Marshal(response)\n\tif err != nil {\n\t\tlog.Println(\"Failed to marshal system info data:\", err)\n\t\treturn\n\t}\n\n\t// 发送SSE数据\n\tctx.SSEvent(\"message\", string(data))\n\tctx.Writer.Flush()\n}\n\ntype SystemInfo struct {\n\tHostInfo      *systemUtils.HostInfo `json:\"host\"`\n\tCpuInfo       *systemUtils.CpuInfo  `json:\"cpu\"`\n\tMemInfo       *systemUtils.MemInfo  `json:\"mem\"`\n\tDiskInfo      *systemUtils.DiskInfo `json:\"disk\"`\n\tPanelMemUsage uint64                `json:\"panelMemUsage\"`\n\tPanelCpuUsage float64               `json:\"panelCpuUsage\"`\n}\n\nfunc (p *GameHandler) GetSystemInfo(clusterName string) *SystemInfo {\n\tvar wg sync.WaitGroup\n\twg.Add(5)\n\n\tdashboardVO := SystemInfo{}\n\tgo func() {\n\t\tdefer func() {\n\t\t\twg.Done()\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tlog.Println(r)\n\t\t\t}\n\t\t}()\n\t\tdashboardVO.HostInfo = systemUtils.GetHostInfo()\n\t}()\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\twg.Done()\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tlog.Println(r)\n\t\t\t}\n\t\t}()\n\t\tdashboardVO.CpuInfo = systemUtils.GetCpuInfo()\n\t}()\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\twg.Done()\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tlog.Println(r)\n\t\t\t}\n\t\t}()\n\t\tdashboardVO.MemInfo = systemUtils.GetMemInfo()\n\t}()\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\twg.Done()\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tlog.Println(r)\n\t\t\t}\n\t\t}()\n\t\tdashboardVO.DiskInfo = systemUtils.GetDiskInfo()\n\t}()\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\twg.Done()\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tlog.Println(r)\n\t\t\t}\n\t\t}()\n\t\tvar m runtime.MemStats\n\t\truntime.ReadMemStats(&m)\n\t\tdashboardVO.PanelMemUsage = m.Alloc / 1024 // 将字节转换为MB\n\t}()\n\n\twg.Wait()\n\treturn &dashboardVO\n}\n"
  },
  {
    "path": "internal/api/handler/kv_handler.go",
    "content": "package handler\n\nimport (\n\t\"dst-admin-go/internal/model\"\n\t\"dst-admin-go/internal/pkg/response\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"gorm.io/gorm\"\n)\n\ntype KvHandler struct {\n\tdb *gorm.DB\n}\n\nfunc NewKvHandler(db *gorm.DB) *KvHandler {\n\treturn &KvHandler{\n\t\tdb: db,\n\t}\n}\n\nfunc (i *KvHandler) RegisterRoute(router *gin.RouterGroup) {\n\trouter.GET(\"/api/kv\", i.GetKv)\n\trouter.POST(\"/api/kv\", i.SaveKv)\n}\n\n// GetKv 生成 swagger 文档注释\n// @Summary 获取kv值\n// @Description 获取kv值\n// @Tags kv\n// @Param key query string true \"key\"\n// @Success 200 {object} response.Response\n// @Router /api/kv [get]\nfunc (i *KvHandler) GetKv(ctx *gin.Context) {\n\n\tkey := ctx.Query(\"key\")\n\tdb := i.db\n\tkv := model.KV{}\n\tdb.Where(\"key = ?\", key).Find(&kv)\n\t//if kv.Value != \"Y\" {\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: kv.Value,\n\t})\n}\n\n// SaveKv 生成 swagger 文档注释\n// @Summary 保存kv值\n// @Description 保存kv值\n// @Tags kv\n// @Param key formData string true \"key\"\n// @Param value formData string true \"value\"\n// @Success 200 {object} response.Response\n// @Router /api/kv [post]\nfunc (i *KvHandler) SaveKv(ctx *gin.Context) {\n\n\tkv := model.KV{}\n\terr := ctx.ShouldBind(&kv)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tdb := i.db\n\toldKv := model.KV{}\n\tdb.Where(\"key = ?\", kv.Key).Find(&oldKv)\n\tif oldKv.ID == 0 {\n\t\tdb.Create(&kv)\n\t} else {\n\t\toldKv.Value = kv.Value\n\t\tdb.Save(&oldKv)\n\t}\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: kv.Value,\n\t})\n}\n"
  },
  {
    "path": "internal/api/handler/level_handler.go",
    "content": "package handler\n\nimport (\n\t\"dst-admin-go/internal/pkg/context\"\n\t\"dst-admin-go/internal/pkg/response\"\n\t\"dst-admin-go/internal/service/level\"\n\t\"dst-admin-go/internal/service/levelConfig\"\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype LevelHandler struct {\n\tlevelService *level.LevelService\n}\n\nfunc NewLevelHandler(levelService *level.LevelService) *LevelHandler {\n\treturn &LevelHandler{\n\t\tlevelService: levelService,\n\t}\n}\n\nfunc (h *LevelHandler) RegisterRoute(router *gin.RouterGroup) {\n\tlevel := router.Group(\"/api/cluster/level\")\n\t{\n\t\tlevel.GET(\"\", h.GetLevelList)\n\t\tlevel.POST(\"\", h.CreateLevel)\n\t\tlevel.DELETE(\"\", h.DeleteLevel)\n\t\tlevel.PUT(\"\", h.UpdateLevels)\n\t}\n}\n\n// GetLevelList 获取世界列表\n// @Summary 获取世界列表\n// @Description 获取当前集群的所有世界(等级)列表\n// @Tags level\n// @Accept json\n// @Produce json\n// @Success 200 {object} response.Response{data=[]levelConfig.LevelInfo}\n// @Router /api/cluster/level [get]\nfunc (h *LevelHandler) GetLevelList(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\tlevels := h.levelService.GetLevelList(clusterName)\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"get level list success\",\n\t\tData: levels,\n\t})\n}\n\n// UpdateLevel 更新世界\n// @Summary 更新世界\n// @Description 更新指定世界的配置信息\n// @Tags level\n// @Accept json\n// @Produce json\n// @Param level body levelConfig.LevelInfo true \"世界配置信息\"\n// @Success 200 {object} response.Response\n// @Router /api/cluster/level [put]\nfunc (h *LevelHandler) UpdateLevel(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\n\tvar world levelConfig.LevelInfo\n\tif err := ctx.BindJSON(&world); err != nil {\n\t\tctx.JSON(http.StatusOK, response.Response{\n\t\t\tCode: 400,\n\t\t\tMsg:  \"invalid request\",\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\n\terr := h.levelService.UpdateLevel(clusterName, &world)\n\tif err != nil {\n\t\tctx.JSON(http.StatusOK, response.Response{\n\t\t\tCode: 500,\n\t\t\tMsg:  \"update level failed\",\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"update level success\",\n\t\tData: nil,\n\t})\n}\n\n// CreateLevel 创建世界\n// @Summary 创建世界\n// @Description 创建一个新的世界(等级)\n// @Tags level\n// @Accept json\n// @Produce json\n// @Param level body levelConfig.LevelInfo true \"世界配置信息\"\n// @Success 200 {object} response.Response\n// @Router /api/cluster/level [post]\nfunc (h *LevelHandler) CreateLevel(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\n\tvar world levelConfig.LevelInfo\n\tif err := ctx.BindJSON(&world); err != nil {\n\t\tctx.JSON(http.StatusOK, response.Response{\n\t\t\tCode: 400,\n\t\t\tMsg:  \"invalid request\",\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\n\terr := h.levelService.CreateLevel(clusterName, &world)\n\tif err != nil {\n\t\tctx.JSON(http.StatusOK, response.Response{\n\t\t\tCode: 500,\n\t\t\tMsg:  \"create level failed\",\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"create level success\",\n\t\tData: world,\n\t})\n}\n\n// DeleteLevel 删除世界\n// @Summary 删除世界\n// @Description 删除指定的世界\n// @Tags level\n// @Accept json\n// @Produce json\n// @Param levelName query string true \"世界名称\"\n// @Success 200 {object} response.Response\n// @Router /api/cluster/level [delete]\nfunc (h *LevelHandler) DeleteLevel(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\tlevelName := ctx.Query(\"levelName\")\n\n\terr := h.levelService.DeleteLevel(clusterName, levelName)\n\tif err != nil {\n\t\tctx.JSON(http.StatusOK, response.Response{\n\t\t\tCode: 500,\n\t\t\tMsg:  \"delete level failed\",\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"delete level success\",\n\t\tData: nil,\n\t})\n}\n\n// UpdateLevels 批量更新世界\n// @Summary 批量更新世界\n// @Description 批量更新多个世界的配置信息\n// @Tags level\n// @Accept json\n// @Produce json\n// @Param levels body []levelConfig.LevelInfo true \"世界配置信息列表\"\n// @Success 200 {object} response.Response\n// @Router /api/cluster/level [put]\nfunc (h *LevelHandler) UpdateLevels(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\tvar payload struct {\n\t\tLevels []levelConfig.LevelInfo `json:\"levels\"`\n\t}\n\tif err := ctx.BindJSON(&payload); err != nil {\n\t\tctx.JSON(http.StatusOK, response.Response{\n\t\t\tCode: 400,\n\t\t\tMsg:  \"invalid request\",\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\n\terr := h.levelService.UpdateLevels(clusterName, payload.Levels)\n\tif err != nil {\n\t\tctx.JSON(http.StatusOK, response.Response{\n\t\t\tCode: 500,\n\t\t\tMsg:  \"update levels failed\",\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"update levels success\",\n\t\tData: nil,\n\t})\n}\n"
  },
  {
    "path": "internal/api/handler/level_log_handler.go",
    "content": "package handler\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"context\"\n\tclusterContext \"dst-admin-go/internal/pkg/context\"\n\t\"dst-admin-go/internal/pkg/response\"\n\t\"dst-admin-go/internal/pkg/utils/fileUtils\"\n\t\"dst-admin-go/internal/service/archive\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype LevelLogHandler struct {\n\tarchive *archive.PathResolver\n}\n\nfunc NewLevelLogHandler(archive *archive.PathResolver) *LevelLogHandler {\n\treturn &LevelLogHandler{\n\t\tarchive: archive,\n\t}\n}\nfunc (h *LevelLogHandler) RegisterRoute(router *gin.RouterGroup) {\n\trouter.GET(\"/api/game/log/stream\", h.Stream)\n\trouter.GET(\"/api/game/level/server/log\", h.GetServerLog)\n\trouter.GET(\"/api/game/level/server/download\", h.DownloadServerLog)\n}\n\n// Stream 服务器日志流\n// @Summary 服务器日志流\n// @Description 获取指定世界的实时日志流 (SSE)\n// @Tags log\n// @Accept text/event-stream\n// @Produce text/event-stream\n// @Param clusterName query string false \"集群名称\"\n// @Param levelName query string true \"世界名称\"\n// @Success 200 {string} string \"SSE 格式的日志流\"\n// @Router /api/game/log/stream [get]\nfunc (h *LevelLogHandler) Stream(c *gin.Context) {\n\tclusterName := clusterContext.GetClusterName(c)\n\tlevelName := c.Query(\"levelName\")\n\tif clusterName == \"\" || levelName == \"\" {\n\t\tc.JSON(400, gin.H{\"error\": \"cluster and level required\"})\n\t\treturn\n\t}\n\n\tw := c.Writer\n\tflusher, ok := w.(http.Flusher)\n\tif !ok {\n\t\tc.JSON(500, gin.H{\"error\": \"streaming unsupported\"})\n\t\treturn\n\t}\n\n\t// SSE headers\n\tw.Header().Set(\"Content-Type\", \"text/event-stream\")\n\tw.Header().Set(\"Cache-Control\", \"no-cache\")\n\tw.Header().Set(\"Connection\", \"keep-alive\")\n\tw.Header().Set(\"X-Accel-Buffering\", \"no\") // nginx\n\n\tctx := c.Request.Context()\n\n\t// 1️⃣ snapshot\n\tserverLogPath := h.archive.ServerLogPath(clusterName, levelName)\n\tlines, err := reader.Snapshot(serverLogPath, 100)\n\tif err != nil {\n\t\tc.JSON(500, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\tfor _, line := range lines {\n\t\twriteSSE(w, \"log\", line)\n\t}\n\tflusher.Flush()\n\n\t// 2️⃣ follow\n\tch, cancel, err := reader.Follow(serverLogPath)\n\tif err != nil {\n\t\twriteSSE(w, \"error\", err.Error())\n\t\tflusher.Flush()\n\t\treturn\n\t}\n\tdefer cancel()\n\n\theartbeat := time.NewTicker(15 * time.Second)\n\tdefer heartbeat.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\n\t\tcase line, ok := <-ch:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\twriteSSE(w, \"log\", line)\n\t\t\tflusher.Flush()\n\n\t\tcase <-heartbeat.C:\n\t\t\twriteSSE(w, \"ping\", \"\")\n\t\t\tflusher.Flush()\n\t\t}\n\t}\n}\n\n// GetServerLog 获取服务器日志 swagger 注释\n// @Summary 获取服务器日志\n// @Description 获取指定世界的服务器日志（默认最近100行）\n// @Tags log\n// @Produce application/json\n// @Param clusterName query string false \"集群名称\"\n// @Param levelName query string true \"世界名称\"\n// @Param lines query string false \"返回日志行数，默认为100\"\n// @Success 200 {object} response.Response{data=[]string} \"服务器日志列表\"\n// @Router /api/game/level/server/log [get]\nfunc (h *LevelLogHandler) GetServerLog(ctx *gin.Context) {\n\tclusterName := clusterContext.GetClusterName(ctx)\n\tlevelName := ctx.Query(\"levelName\")\n\tlines := ctx.DefaultQuery(\"lines\", \"100\")\n\tif clusterName == \"\" || levelName == \"\" {\n\t\tctx.JSON(400, gin.H{\"error\": \"cluster and level required\"})\n\t\treturn\n\t}\n\tserverLogPath := h.archive.ServerLogPath(clusterName, levelName)\n\tlinesInt, err := strconv.Atoi(lines)\n\tif err != nil {\n\t\tctx.JSON(400, gin.H{\"error\": \"lines must be a number\"})\n\t\treturn\n\t}\n\tread, err := fileUtils.ReverseRead(serverLogPath, uint(linesInt))\n\tif err != nil {\n\t\tctx.JSON(200, response.Response{\n\t\t\tCode: 500,\n\t\t\tMsg:  \"failed to read server log: \" + err.Error(),\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\tctx.JSON(200, response.Response{\n\t\tCode: 200,\n\t\tData: read,\n\t\tMsg:  \"success\",\n\t})\n}\n\n// DownloadServerLog 下载服务器日志 swagger 注释\n// @Summary 下载服务器日志\n// @Description 下载指定世界的完整服务器日志文件\n// @Tags log\n// @Produce application/octet-stream\n// @Param clusterName query string false \"集群名称\"\n// @Param levelName query string true \"世界名称\"\n// @Success 200 {file} file \"服务器日志文件\"\n// @Router /api/game/level/server/download [get]\nfunc (h *LevelLogHandler) DownloadServerLog(ctx *gin.Context) {\n\tclusterName := clusterContext.GetClusterName(ctx)\n\tlevelName := ctx.Query(\"levelName\")\n\tif clusterName == \"\" || levelName == \"\" {\n\t\tctx.JSON(400, gin.H{\"error\": \"cluster and level required\"})\n\t\treturn\n\t}\n\tserverLogPath := h.archive.ServerLogPath(clusterName, levelName)\n\tctx.Header(\"Content-Type\", \"application/octet-stream\")\n\tctx.Header(\"Content-Disposition\", \"attachment; filename=\"+\"server_log.txt\")\n\tctx.Header(\"Content-Transfer-Encoding\", \"binary\")\n\tctx.File(serverLogPath)\n}\n\nfunc writeSSE(w io.Writer, event, data string) {\n\tif event != \"\" {\n\t\tfmt.Fprintf(w, \"event: %s\\n\", event)\n\t}\n\n\t// data 可能包含换行，必须逐行写\n\tscanner := bufio.NewScanner(strings.NewReader(data))\n\tfor scanner.Scan() {\n\t\tfmt.Fprintf(w, \"data: %s\\n\", scanner.Text())\n\t}\n\n\tfmt.Fprint(w, \"\\n\")\n}\n\nvar reader = NewFileLogReader()\n\ntype FileLogReader struct {\n\tinterval time.Duration\n}\n\nfunc NewFileLogReader() *FileLogReader {\n\treturn &FileLogReader{\n\t\tinterval: time.Second,\n\t}\n}\n\nfunc (r *FileLogReader) Snapshot(\n\tserverLogPath string,\n\tn int,\n) ([]string, error) {\n\n\tpath := serverLogPath\n\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tstat, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar (\n\t\tsize   = stat.Size()\n\t\toffset = size\n\t\tlines  []string\n\t\tbuf    []byte\n\t)\n\n\tfor offset > 0 && len(lines) < n {\n\t\treadSize := int64(4096)\n\t\tif offset < readSize {\n\t\t\treadSize = offset\n\t\t}\n\n\t\toffset -= readSize\n\t\tchunk := make([]byte, readSize)\n\n\t\t_, err := f.ReadAt(chunk, offset)\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tbuf = append(chunk, buf...)\n\n\t\tfor {\n\t\t\tidx := bytes.LastIndexByte(buf, '\\n')\n\t\t\tif idx < 0 {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tline := strings.TrimRight(string(buf[idx+1:]), \"\\r\")\n\t\t\tlines = append(lines, line)\n\t\t\tbuf = buf[:idx]\n\n\t\t\tif len(lines) >= n {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// 反转\n\tfor i, j := 0, len(lines)-1; i < j; i, j = i+1, j-1 {\n\t\tlines[i], lines[j] = lines[j], lines[i]\n\t}\n\n\treturn lines, nil\n}\n\nfunc (r *FileLogReader) Follow(\n\tserverLogPath string,\n) (<-chan string, func(), error) {\n\n\tpath := serverLogPath\n\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstat, err := f.Stat()\n\tif err != nil {\n\t\tf.Close()\n\t\treturn nil, nil, err\n\t}\n\n\tout := make(chan string, 100)\n\tctx, cancel := context.WithCancel(context.Background())\n\n\toffset := stat.Size()\n\n\tgo func() {\n\t\tdefer close(out)\n\t\tdefer f.Close()\n\n\t\treader := bufio.NewReader(f)\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase <-time.After(r.interval):\n\t\t\t\tstat, err := f.Stat()\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// 文件被 truncate\n\t\t\t\tif stat.Size() < offset {\n\t\t\t\t\toffset = 0\n\t\t\t\t\tf.Seek(0, io.SeekStart)\n\t\t\t\t\treader.Reset(f)\n\t\t\t\t}\n\n\t\t\t\tif stat.Size() == offset {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tf.Seek(offset, io.SeekStart)\n\t\t\t\treader.Reset(f)\n\n\t\t\t\tfor {\n\t\t\t\t\tline, err := reader.ReadString('\\n')\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\toffset += int64(len(line))\n\t\t\t\t\tout <- strings.TrimRight(line, \"\\r\\n\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn out, cancel, nil\n}\n"
  },
  {
    "path": "internal/api/handler/login_handler.go",
    "content": "package handler\n\nimport (\n\t\"dst-admin-go/internal/database\"\n\t\"dst-admin-go/internal/model\"\n\t\"dst-admin-go/internal/pkg/response\"\n\t\"dst-admin-go/internal/pkg/utils/fileUtils\"\n\t\"dst-admin-go/internal/service/login\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"gorm.io/gorm\"\n)\n\nconst (\n\tPasswordPath = \"./password.txt\"\n)\n\ntype LoginHandler struct {\n\tloginService *login.LoginService\n}\n\nfunc NewLoginHandler(loginService *login.LoginService) *LoginHandler {\n\treturn &LoginHandler{\n\t\tloginService: loginService,\n\t}\n}\n\nfunc (h *LoginHandler) RegisterRoute(router *gin.RouterGroup) {\n\trouter.GET(\"/api/user\", h.GetUserInfo)\n\trouter.POST(\"/api/login\", h.Login)\n\trouter.GET(\"/api/logout\", h.Logout)\n\trouter.POST(\"/api/change/password\", h.ChangePassword)\n\trouter.POST(\"/api/user\", h.UpdateUserInfo)\n\trouter.GET(\"/api/init\", h.CheckIsFirst)\n\trouter.POST(\"/api/init\", h.InitFirst)\n}\n\n// GetUserInfo 获取用户信息\n// @Summary 获取用户信息\n// @Description 获取用户信息\n// @Tags user\n// @Accept json\n// @Produce json\n// @Success 200 {object} response.Response{data=login.UserInfo}\n// @Router /api/user/info [get]\nfunc (h *LoginHandler) GetUserInfo(ctx *gin.Context) {\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"Init user success\",\n\t\tData: h.loginService.GetUserInfo(),\n\t})\n}\n\n// Login 用户登录\n// @Summary 用户登录\n// @Description 用户登录\n// @Tags user\n// @Accept json\n// @Produce json\n// @Param user body login.UserInfo true \"用户信息\"\n// @Success 200 {object} response.Response\n// @Router /api/user/login [post]\nfunc (h *LoginHandler) Login(ctx *gin.Context) {\n\tvar userInfo login.UserInfo\n\terr := ctx.ShouldBind(&userInfo)\n\tif err != nil {\n\t\tctx.JSON(http.StatusBadRequest, response.Response{\n\t\t\tCode: 400,\n\t\t\tMsg:  \"Invalid request body: \" + err.Error(),\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\n\tresponse := h.loginService.Login(userInfo, ctx)\n\tctx.JSON(http.StatusOK, response)\n}\n\n// Logout 用户登出\n// @Summary 用户登出\n// @Description 用户登出\n// @Tags user\n// @Accept json\n// @Produce json\n// @Success 200 {object} response.Response\n// @Router /api/user/logout [get]\nfunc (h *LoginHandler) Logout(ctx *gin.Context) {\n\th.loginService.Logout(ctx)\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"Logout success\",\n\t\tData: nil,\n\t})\n}\n\n// ChangePassword 修改密码\n// @Summary 修改密码\n// @Description 修改密码\n// @Tags user\n// @Accept json\n// @Produce json\n// @Param password body object true \"新密码\"\n// @Success 200 {object} response.Response\n// @Router /api/user/changePassword [post]\nfunc (h *LoginHandler) ChangePassword(ctx *gin.Context) {\n\tvar body struct {\n\t\tNewPassword string `json:\"newPassword\"`\n\t}\n\tif err := ctx.BindJSON(&body); err != nil {\n\t\tctx.JSON(http.StatusBadRequest, response.Response{\n\t\t\tCode: 400,\n\t\t\tMsg:  \"Invalid request body: \" + err.Error(),\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\tresponse := h.loginService.ChangePassword(body.NewPassword)\n\n\tctx.JSON(http.StatusOK, response)\n}\n\n// UpdateUserInfo 更新用户信息\n// @Summary 更新用户信息\n// @Description 更新用户信息\n// @Tags user\n// @Accept json\n// @Produce json\n// @Param user body object true \"用户信息\"\n// @Success 200 {object} response.Response\n// @Router /api/user/update [post]\nfunc (h *LoginHandler) UpdateUserInfo(ctx *gin.Context) {\n\tvar body struct {\n\t\tUsername    string `json:\"username\"`\n\t\tDisplayName string `json:\"displayName\"`\n\t\tPhotoURL    string `json:\"photoURL\"`\n\t\tPassword    string `json:\"password\"`\n\t}\n\tif err := ctx.BindJSON(&body); err != nil {\n\t\tctx.JSON(http.StatusBadRequest, response.Response{\n\t\t\tCode: 400,\n\t\t\tMsg:  \"Invalid request body: \" + err.Error(),\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\terr := fileUtils.WriterLnFile(PasswordPath, []string{\n\t\t\"username = \" + body.Username,\n\t\t\"password = \" + body.Password,\n\t\t\"displayName=\" + body.DisplayName,\n\t\t\"photoURL=\" + body.PhotoURL,\n\t})\n\tif err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, response.Response{\n\t\t\tCode: 500,\n\t\t\tMsg:  \"修改用户信息失败: \" + err.Error(),\n\t\t\tData: nil,\n\t\t})\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"Update user info success\",\n\t\tData: nil,\n\t})\n}\n\n// InitFirst 初始化首次用户\n// @Summary 初始化首次用户\n// @Description 初始化系统首次用户信息\n// @Tags user\n// @Accept json\n// @Produce json\n// @Param userInfo body login.UserInfo true \"用户信息\"\n// @Success 200 {object} response.Response\n// @Router /api/init [post]\nfunc (h *LoginHandler) InitFirst(ctx *gin.Context) {\n\tdb := database.Db\n\tkv := model.KV{}\n\tdb.Where(\"key = 'FIRST_INIT'\").First(&kv)\n\tif kv.Value == \"TRUE\" || fileUtils.Exists(\"./first\") {\n\t\tlog.Panicln(\"非法请求\")\n\t}\n\tvar payload struct {\n\t\tUserInfo login.UserInfo `json:\"userInfo\"`\n\t}\n\terr := ctx.BindJSON(&payload)\n\tif err != nil {\n\t\tctx.JSON(http.StatusBadRequest, response.Response{\n\t\t\tCode: 400,\n\t\t\tMsg:  \"Invalid request body: \" + err.Error(),\n\t\t\tData: nil,\n\t\t})\n\t}\n\t// 事务\n\t// 记录已经初始化\n\t// 保存用户信息\n\terr = db.Transaction(func(tx *gorm.DB) error {\n\t\ttx.Create(&model.KV{Key: \"FIRST_INIT\", Value: \"TRUE\"})\n\t\th.loginService.InitUserInfo(payload.UserInfo)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, response.Response{\n\t\t\tCode: 500,\n\t\t\tMsg:  \"初始化失败: \" + err.Error(),\n\t\t\tData: nil,\n\t\t})\n\t}\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: nil,\n\t})\n}\n\n// CheckIsFirst 检查是否首次初始化\n// @Summary 检查是否首次初始化\n// @Description 检查系统是否进行了首次初始化\n// @Tags user\n// @Accept json\n// @Produce json\n// @Success 200 {object} response.Response\n// @Router /api/init [get]\nfunc (h *LoginHandler) CheckIsFirst(ctx *gin.Context) {\n\n\texist := false\n\tdb := database.Db\n\tkv := model.KV{}\n\tdb.Where(\"key = 'FIRST_INIT'\").First(&kv)\n\tif kv.Value == \"TRUE\" {\n\t\texist = true\n\t} else {\n\t\texist = fileUtils.Exists(\"./first\")\n\t}\n\n\tcode := 200\n\tmsg := \"is first\"\n\tif exist {\n\t\tcode = 400\n\t\tmsg = \"is not first\"\n\t}\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: code,\n\t\tMsg:  msg,\n\t\tData: nil,\n\t})\n}\n"
  },
  {
    "path": "internal/api/handler/mod_handler.go",
    "content": "package handler\n\nimport (\n\t\"dst-admin-go/internal/model\"\n\t\"dst-admin-go/internal/pkg/context\"\n\t\"dst-admin-go/internal/pkg/response\"\n\t\"dst-admin-go/internal/service/dstConfig\"\n\t\"dst-admin-go/internal/service/mod\"\n\t\"encoding/json\"\n\t\"log\"\n\t\"strconv\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype ModHandler struct {\n\tmodService *mod.ModService\n\tdstConfig  dstConfig.Config\n}\n\nfunc NewModHandler(modService *mod.ModService, dstConfig dstConfig.Config) *ModHandler {\n\treturn &ModHandler{\n\t\tmodService: modService,\n\t\tdstConfig:  dstConfig,\n\t}\n}\n\nfunc (h *ModHandler) RegisterRoute(router *gin.RouterGroup) {\n\tmodGroup := router.Group(\"/api/mod\")\n\t{\n\t\tmodGroup.GET(\"/search\", h.SearchModList)\n\t\tmodGroup.GET(\"/:modId\", h.GetModInfo)\n\t\tmodGroup.PUT(\"/:modId\", h.UpdateMod)\n\t\tmodGroup.GET(\"\", h.GetMyModList)\n\t\tmodGroup.DELETE(\"/:modId\", h.DeleteMod)\n\t\tmodGroup.DELETE(\"/setup/workshop\", h.DeleteSetupWorkshop)\n\t\tmodGroup.GET(\"/modinfo/:modId\", h.GetModInfoFile)\n\t\tmodGroup.POST(\"/modinfo\", h.SaveModInfoFile)\n\t\tmodGroup.POST(\"/modinfo/file\", h.AddModInfoFile)\n\t\tmodGroup.PUT(\"/modinfo\", h.UpdateAllModInfos)\n\t\tmodGroup.GET(\"/ugc/acf\", h.GetUgcModAcf)\n\t\tmodGroup.DELETE(\"/ugc\", h.DeleteUgcModFile)\n\t}\n}\n\n// SearchModList 搜索mod列表\n// @Summary 搜索mod列表\n// @Description 搜索Steam创意工坊中的模组\n// @Tags mod\n// @Accept json\n// @Produce json\n// @Param text query string false \"搜索关键词\"\n// @Param page query int false \"页码\" default(1)\n// @Param size query int false \"每页数量\" default(10)\n// @Param lang query string false \"语言\" default(zh)\n// @Success 200 {object} response.Response{}\n// @Router /api/mod/search [get]\nfunc (h *ModHandler) SearchModList(ctx *gin.Context) {\n\ttext := ctx.Query(\"text\")\n\tpage, _ := strconv.Atoi(ctx.DefaultQuery(\"page\", \"1\"))\n\tsize, _ := strconv.Atoi(ctx.DefaultQuery(\"size\", \"10\"))\n\tlang := ctx.DefaultQuery(\"lang\", \"zh\")\n\n\tdata, err := h.modService.SearchModList(text, page, size, lang)\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"搜索mod失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tresponse.OkWithData(data, ctx)\n}\n\n// GetModInfo 获取mod信息\n// @Summary 获取mod信息\n// @Description 根据modId获取模组详细信息\n// @Tags mod\n// @Accept json\n// @Produce json\n// @Param modId path string true \"模组ID\"\n// @Param lang query string false \"语言\" default(zh)\n// @Success 200 {object} response.Response\n// @Router /api/mod/{modId} [get]\nfunc (h *ModHandler) GetModInfo(ctx *gin.Context) {\n\tmodId := ctx.Param(\"modId\")\n\tlang := ctx.DefaultQuery(\"lang\", \"zh\")\n\tclusterName := context.GetClusterName(ctx)\n\tmodinfo, err := h.modService.SubscribeModByModId(clusterName, modId, lang)\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"模组下载失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tvar modConfig map[string]interface{}\n\t_ = json.Unmarshal([]byte(modinfo.ModConfig), &modConfig)\n\n\tmodData := map[string]interface{}{\n\t\t\"auth\":          modinfo.Auth,\n\t\t\"consumer_id\":   modinfo.ConsumerAppid,\n\t\t\"creator_appid\": modinfo.CreatorAppid,\n\t\t\"description\":   modinfo.Description,\n\t\t\"file_url\":      modinfo.FileUrl,\n\t\t\"modid\":         modinfo.Modid,\n\t\t\"img\":           modinfo.Img,\n\t\t\"last_time\":     modinfo.LastTime,\n\t\t\"name\":          modinfo.Name,\n\t\t\"v\":             modinfo.V,\n\t\t\"mod_config\":    modConfig,\n\t\t\"update\":        modinfo.Update,\n\t}\n\n\tresponse.OkWithData(modData, ctx)\n}\n\n// GetMyModList 获取我的mod列表\n// @Summary 获取我的mod列表\n// @Description 获取已订阅的模组列表\n// @Tags mod\n// @Accept json\n// @Produce json\n// @Success 200 {object} response.Response\n// @Router /api/mod [get]\nfunc (h *ModHandler) GetMyModList(ctx *gin.Context) {\n\tmodInfos, err := h.modService.GetMyModList()\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"获取模组列表失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tvar modDataList []map[string]interface{}\n\tfor _, modinfo := range modInfos {\n\t\tvar modConfig map[string]interface{}\n\t\t_ = json.Unmarshal([]byte(modinfo.ModConfig), &modConfig)\n\n\t\tmodData := map[string]interface{}{\n\t\t\t\"auth\":          modinfo.Auth,\n\t\t\t\"consumer_id\":   modinfo.ConsumerAppid,\n\t\t\t\"creator_appid\": modinfo.CreatorAppid,\n\t\t\t\"description\":   modinfo.Description,\n\t\t\t\"file_url\":      modinfo.FileUrl,\n\t\t\t\"modid\":         modinfo.Modid,\n\t\t\t\"img\":           modinfo.Img,\n\t\t\t\"last_time\":     modinfo.LastTime,\n\t\t\t\"name\":          modinfo.Name,\n\t\t\t\"v\":             modinfo.V,\n\t\t\t\"mod_config\":    modConfig,\n\t\t\t\"update\":        modinfo.Update,\n\t\t}\n\t\tmodDataList = append(modDataList, modData)\n\t}\n\n\tresponse.OkWithData(modDataList, ctx)\n}\n\n// UpdateAllModInfos 批量更新模组信息\n// @Summary 批量更新模组信息\n// @Description 批量更新所有已订阅模组的信息\n// @Tags mod\n// @Accept json\n// @Produce json\n// @Param lang query string false \"语言\" default(zh)\n// @Success 200 {object} response.Response\n// @Router /api/mod/modinfo [put]\nfunc (h *ModHandler) UpdateAllModInfos(ctx *gin.Context) {\n\n\tclusterName := context.GetClusterName(ctx)\n\tlang := ctx.DefaultQuery(\"lang\", \"zh\")\n\n\terr := h.modService.UpdateAllModInfos(clusterName, lang)\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"更新失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tresponse.OkWithMessage(\"更新成功\", ctx)\n}\n\n// DeleteMod 删除模组\n// @Summary 删除模组\n// @Description 根据modId删除模组\n// @Tags mod\n// @Accept json\n// @Produce json\n// @Param modId path string true \"模组ID\"\n// @Success 200 {object} response.Response\n// @Router /api/mod/{modId} [delete]\nfunc (h *ModHandler) DeleteMod(ctx *gin.Context) {\n\tmodId := ctx.Param(\"modId\")\n\tclusterName := context.GetClusterName(ctx)\n\n\terr := h.modService.DeleteMod(clusterName, modId)\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"删除失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tresponse.OkWithData(modId, ctx)\n}\n\n// DeleteSetupWorkshop 删除workshop文件\n// @Summary 删除workshop文件\n// @Description 删除所有workshop模组文件\n// @Tags mod\n// @Accept json\n// @Produce json\n// @Success 200 {object} response.Response\n// @Router /api/mod/setup/workshop [delete]\nfunc (h *ModHandler) DeleteSetupWorkshop(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\n\terr := h.modService.DeleteSetupWorkshop(clusterName)\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"删除失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tresponse.OkWithMessage(\"删除成功\", ctx)\n}\n\n// GetModInfoFile 获取模组配置文件\n// @Summary 获取模组配置文件\n// @Description 根据modId获取模组配置文件内容\n// @Tags mod\n// @Accept json\n// @Produce json\n// @Param modId path string true \"模组ID\"\n// @Success 200 {object} response.Response{data=mod.ModInfo}\n// @Router /api/mod/modinfo/{modId} [get]\nfunc (h *ModHandler) GetModInfoFile(ctx *gin.Context) {\n\tmodId := ctx.Param(\"modId\")\n\n\tmodInfo, err := h.modService.GetModByModId(modId)\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"获取模组信息失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tresponse.OkWithData(modInfo, ctx)\n}\n\n// SaveModInfoFile 保存模组配置文件\n// @Summary 保存模组配置文件\n// @Description 保存模组配置信息\n// @Tags mod\n// @Accept json\n// @Produce json\n// @Param data body mod.ModInfo true \"模组信息\"\n// @Success 200 {object} response.Response{data=mod.ModInfo}\n// @Router /api/mod/modinfo [post]\nfunc (h *ModHandler) SaveModInfoFile(ctx *gin.Context) {\n\tvar modInfo model.ModInfo\n\terr := ctx.ShouldBindJSON(&modInfo)\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"参数解析失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\terr = h.modService.SaveModInfo(&modInfo)\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"保存失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tresponse.OkWithData(modInfo, ctx)\n}\n\n// UpdateMod 更新模组\n// @Summary 更新模组\n// @Description 根据modId更新模组\n// @Tags mod\n// @Accept json\n// @Produce json\n// @Param modId path string true \"模组ID\"\n// @Param lang query string false \"语言\" default(zh)\n// @Success 200 {object} response.Response\n// @Router /api/mod/{modId} [put]\nfunc (h *ModHandler) UpdateMod(ctx *gin.Context) {\n\tmodId := ctx.Param(\"modId\")\n\tclusterName := context.GetClusterName(ctx)\n\tlang := ctx.DefaultQuery(\"lang\", \"zh\")\n\n\t// 删除旧数据\n\terr := h.modService.DeleteMod(clusterName, modId)\n\tif err != nil {\n\t\tlog.Println(\"删除旧模组失败:\", err)\n\t}\n\n\t// 重新下载\n\tmodinfo, err := h.modService.SubscribeModByModId(clusterName, modId, lang)\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"模组更新失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tvar modConfig map[string]interface{}\n\t_ = json.Unmarshal([]byte(modinfo.ModConfig), &modConfig)\n\n\tmodData := map[string]interface{}{\n\t\t\"auth\":          modinfo.Auth,\n\t\t\"consumer_id\":   modinfo.ConsumerAppid,\n\t\t\"creator_appid\": modinfo.CreatorAppid,\n\t\t\"description\":   modinfo.Description,\n\t\t\"file_url\":      modinfo.FileUrl,\n\t\t\"modid\":         modinfo.Modid,\n\t\t\"img\":           modinfo.Img,\n\t\t\"last_time\":     modinfo.LastTime,\n\t\t\"name\":          modinfo.Name,\n\t\t\"v\":             modinfo.V,\n\t\t\"mod_config\":    modConfig,\n\t\t\"update\":        modinfo.Update,\n\t}\n\n\tresponse.OkWithData(modData, ctx)\n}\n\n// AddModInfoFile 手动添加模组\n// @Summary 手动添加模组\n// @Description 手动添加模组配置文件\n// @Tags mod\n// @Accept json\n// @Produce json\n// @Param data body object true \"模组信息\" example({\"workshopId\":\"123456\",\"modinfo\":\"模组配置内容\"})\n// @Param lang query string false \"语言\" default(zh)\n// @Success 200 {object} response.Response\n// @Router /api/mod/modinfo/file [post]\nfunc (h *ModHandler) AddModInfoFile(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\tlang := ctx.DefaultQuery(\"lang\", \"zh\")\n\n\tvar payload struct {\n\t\tWorkshopId string `json:\"workshopId\"`\n\t\tModinfo    string `json:\"modinfo\"`\n\t}\n\n\terr := ctx.ShouldBindJSON(&payload)\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"参数解析失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tif payload.WorkshopId == \"\" {\n\t\tresponse.FailWithMessage(\"workshopId不能为空\", ctx)\n\t\treturn\n\t}\n\n\t// 获取配置\n\tconfig, err := h.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"获取配置失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\terr = h.modService.AddModInfo(clusterName, lang, payload.WorkshopId, payload.Modinfo, config.Mod_download_path)\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"添加模组失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tresponse.OkWithMessage(\"添加成功\", ctx)\n}\n\n// GetUgcModAcf 获取UGC mod acf文件信息\n// @Summary 获取UGC mod acf文件信息\n// @Description 获取UGC模组的ACF文件信息\n// @Tags mod\n// @Accept json\n// @Produce json\n// @Param levelName query string true \"世界名称\"\n// @Success 200 {object} response.Response\n// @Router /api/mod/ugc/acf [get]\nfunc (h *ModHandler) GetUgcModAcf(ctx *gin.Context) {\n\n\tlevelName := ctx.Query(\"levelName\")\n\tclusterName := context.GetClusterName(ctx)\n\n\tworkshopItemDetails, err := h.modService.GetUgcModInfo(clusterName, levelName)\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"获取UGC模组信息失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tresponse.OkWithData(workshopItemDetails, ctx)\n}\n\n// DeleteUgcModFile 删除UGC模组文件\n// @Summary 删除UGC模组文件\n// @Description 删除UGC模组文件\n// @Tags mod\n// @Accept json\n// @Produce json\n// @Param levelName query string true \"世界名称\"\n// @Param workshopId query string true \"WorkshopID\"\n// @Success 200 {object} response.Response\n// @Router /api/mod/ugc [delete]\nfunc (h *ModHandler) DeleteUgcModFile(ctx *gin.Context) {\n\tclusterName := context.GetClusterName(ctx)\n\tlevelName := ctx.Query(\"levelName\")\n\tworkshopId := ctx.Query(\"workshopId\")\n\n\terr := h.modService.DeleteUgcModFile(clusterName, levelName, workshopId)\n\tif err != nil {\n\t\tresponse.FailWithMessage(\"删除失败: \"+err.Error(), ctx)\n\t\treturn\n\t}\n\n\tresponse.OkWithMessage(\"删除成功\", ctx)\n}\n"
  },
  {
    "path": "internal/api/handler/player_handler.go",
    "content": "package handler\n\nimport (\n\t\"dst-admin-go/internal/pkg/context\"\n\t\"dst-admin-go/internal/service/game\"\n\t\"dst-admin-go/internal/service/player\"\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype PlayerHandler struct {\n\tplayerService *player.PlayerService\n\tgameProcess   game.Process\n}\n\nfunc NewPlayerHandler(playerService *player.PlayerService, gameProcess game.Process) *PlayerHandler {\n\treturn &PlayerHandler{\n\t\tplayerService: playerService,\n\t\tgameProcess:   gameProcess,\n\t}\n}\n\nfunc (p *PlayerHandler) GetPlayerList(ctx *gin.Context) {\n\n\tclusterName := context.GetClusterName(ctx)\n\n\tctx.JSON(http.StatusOK, gin.H{\n\t\t\"code\": 200,\n\t\t\"msg\":  \"success\",\n\t\t\"data\": p.playerService.GetPlayerList(clusterName, \"Master\", p.gameProcess),\n\t})\n}\n\nfunc (p *PlayerHandler) GetPlayerAllList(ctx *gin.Context) {\n\n\tclusterName := context.GetClusterName(ctx)\n\n\tctx.JSON(http.StatusOK, gin.H{\n\t\t\"code\": 200,\n\t\t\"msg\":  \"success\",\n\t\t\"data\": p.playerService.GetPlayerAllList(clusterName, p.gameProcess),\n\t})\n}\n\nfunc (p *PlayerHandler) RegisterRoute(router *gin.RouterGroup) {\n\tplayer := router.Group(\"/api/game/8level/players\")\n\t{\n\t\tplayer.GET(\"\", p.GetPlayerList)\n\t\tplayer.GET(\"/all\", p.GetPlayerAllList)\n\t}\n}\n"
  },
  {
    "path": "internal/api/handler/player_log_handler.go",
    "content": "package handler\n\nimport (\n\t\"dst-admin-go/internal/database\"\n\t\"dst-admin-go/internal/model\"\n\t\"dst-admin-go/internal/pkg/response\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"strconv\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype PlayerLogHandler struct {\n}\n\nfunc NewPlayerLogHandler() *PlayerLogHandler {\n\treturn &PlayerLogHandler{}\n}\n\nfunc (l *PlayerLogHandler) RegisterRoute(router *gin.RouterGroup) {\n\trouter.GET(\"/api/player/log\", l.PlayerLogQueryPage)\n\trouter.POST(\"/api/player/log/delete\", l.DeletePlayerLog)\n\trouter.GET(\"/api/player/log/delete/all\", l.DeletePlayerLogAll)\n}\n\n// PlayerLogQueryPage 生成 swagger 文档注释\n// @Summary 分页查询玩家日志\n// @Description 分页查询玩家日志\n// @Tags playerLog\n// @Param name query string false \"玩家名称\"\n// @Param kuId query string false \"KuId\"\n// @Param steamId query string false \"SteamId\"\n// @Param role query string false \"角色\"\n// @Param action query string false \"操作\"\n// @Param ip query string false \"IP地址\"\n// @Param page query int false \"页码\" default(1)\n// @Param size query int false \"每页数量\" default(10)\n// @Success 200 {object} response.Response\n// @Router /api/player/log [get]\nfunc (l *PlayerLogHandler) PlayerLogQueryPage(ctx *gin.Context) {\n\n\t//获取查询参数\n\t//name := ctx.Query(\"name\")\n\t//kuId := ctx.Query(\"kuId\")\n\t//steamId := ctx.Query(\"steamId\")\n\t//role := ctx.Query(\"role\")\n\t//action := ctx.Query(\"action\")\n\n\tpage, _ := strconv.Atoi(ctx.DefaultQuery(\"page\", \"1\"))\n\tsize, _ := strconv.Atoi(ctx.DefaultQuery(\"size\", \"10\"))\n\n\tif page <= 0 {\n\t\tpage = 1\n\t}\n\tif size < 0 {\n\t\tsize = 10\n\t}\n\n\tdb := database.Db\n\tdb2 := database.Db\n\tif name, isExist := ctx.GetQuery(\"name\"); isExist {\n\t\tdb = db.Where(\"name LIKE ?\", \"%\"+name+\"%\")\n\t\tdb2 = db2.Where(\"name LIKE ?\", \"%\"+name+\"%\")\n\t}\n\tif kuId, isExist := ctx.GetQuery(\"kuId\"); isExist {\n\t\tdb = db.Where(\"ku_id LIKE ?\", \"%\"+kuId+\"%\")\n\t\tdb2 = db2.Where(\"ku_id LIKE ?\", \"%\"+kuId+\"%\")\n\t}\n\tif steamId, isExist := ctx.GetQuery(\"steamId\"); isExist {\n\t\tdb = db.Where(\"steamId LIKE ?\", \"%\"+steamId+\"%\")\n\t\tdb2 = db2.Where(\"steamId LIKE ?\", \"%\"+steamId+\"%\")\n\t}\n\tif role, isExist := ctx.GetQuery(\"role\"); isExist {\n\t\tdb = db.Where(\"role LIKE ?\", \"%\"+role+\"%\")\n\t\tdb2 = db2.Where(\"role LIKE ?\", \"%\"+role+\"%\")\n\t}\n\tif action, isExist := ctx.GetQuery(\"action\"); isExist {\n\t\tdb = db.Where(\"action LIKE ?\", \"%\"+action+\"%\")\n\t\tdb2 = db2.Where(\"action LIKE ?\", \"%\"+action+\"%\")\n\t}\n\tif ip, isExist := ctx.GetQuery(\"ip\"); isExist {\n\t\tdb = db.Where(\"ip LIKE ?\", \"%\"+ip+\"%\")\n\t\tdb2 = db2.Where(\"ip LIKE ?\", \"%\"+ip+\"%\")\n\t}\n\n\tdb = db.Order(\"created_at desc\").Limit(size).Offset((page - 1) * size)\n\n\tplayerLogs := make([]model.PlayerLog, 0)\n\n\tif err := db.Find(&playerLogs).Error; err != nil {\n\t\tfmt.Println(err.Error())\n\t}\n\n\tvar total int64\n\tdb2.Model(&model.PlayerLog{}).Count(&total)\n\n\ttotalPages := total / int64(size)\n\tif total%int64(size) != 0 {\n\t\ttotalPages++\n\t}\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: response.Page{\n\t\t\tData:       playerLogs,\n\t\t\tPage:       page,\n\t\t\tSize:       size,\n\t\t\tTotal:      total,\n\t\t\tTotalPages: totalPages,\n\t\t},\n\t})\n\n}\n\n// DeletePlayerLog 删除玩家日志\n// @Summary 删除玩家日志\n// @Description 删除玩家日志\n// @Tags playerLog\n// @Param ids body []int64 true \"ID列表\"\n// @Success 200 {object} response.Response\n// @Router /api/player/log/delete [post]\nfunc (l *PlayerLogHandler) DeletePlayerLog(ctx *gin.Context) {\n\tvar payload struct {\n\t\tIds []int64 `json:\"ids\"`\n\t}\n\terr := ctx.ShouldBind(&payload)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tdb := database.Db\n\n\tdb.Delete(&model.PlayerLog{}, payload.Ids)\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: nil,\n\t})\n}\n\n// DeletePlayerLogAll 删除所有玩家日志\n// @Summary 删除所有玩家日志\n// @Description 删除所有玩家\n// @Tags playerLog\n// @Success 200 {object} response.Response\n// @Router /api/player/log/delete/all [get]\nfunc (l *PlayerLogHandler) DeletePlayerLogAll(ctx *gin.Context) {\n\n\tdb := database.Db\n\tdb.Delete(&model.PlayerLog{})\n\n\t// 删除所有记录\n\tresult := db.Where(\"1 = 1\").Delete(&model.PlayerLog{})\n\n\tif result.Error != nil {\n\t\tlog.Panicln(result.Error)\n\t}\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: nil,\n\t})\n}\n"
  },
  {
    "path": "internal/api/handler/statistics_handler.go",
    "content": "package handler\n\nimport (\n\t\"dst-admin-go/internal/database\"\n\t\"dst-admin-go/internal/model\"\n\t\"dst-admin-go/internal/pkg/response\"\n\t\"dst-admin-go/internal/pkg/utils\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype StatisticsHandler struct {\n}\n\nfunc NewStatisticsHandler() *StatisticsHandler {\n\treturn &StatisticsHandler{}\n}\n\ntype UserStatistics struct {\n\tCount int       `json:\"y\"`\n\tDate  time.Time `json:\"x\"`\n}\n\ntype TopStatistics struct {\n\tId         int    `json:\"id\"`\n\tCount      int    `json:\"count\"`\n\tName       string `json:\"name\"`\n\tKuId       string `json:\"kuId\"`\n\tSteamId    string `json:\"steamId\"`\n\tRole       string `json:\"role\"`\n\tActionDesc string `json:\"actionDesc\"`\n\tCreatedAt  string `json:\"createdAt\"`\n}\n\ntype RoleRateStatistics struct {\n\tRole  string `json:\"role\"`\n\tCount int    `json:\"count\"`\n}\n\nfunc findStamp(stamp int64, data []UserStatistics) *UserStatistics {\n\tfor _, d := range data {\n\t\tunix := utils.Bod(d.Date).UnixMilli()\n\t\tif unix == stamp {\n\t\t\treturn &d\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *StatisticsHandler) RegisterRoute(router *gin.RouterGroup) {\n\n\trouter.GET(\"/api/statistics/active/user\", s.CountActiveUser)\n\trouter.GET(\"/api/statistics/top/death\", s.TopDeaths)\n\trouter.GET(\"/api/statistics/top/login\", s.TopUserLoginimes)\n\trouter.GET(\"/api/statistics/top/active\", s.TopUserActiveTimes)\n\trouter.GET(\"/api/statistics/rate/role\", s.CountRoleRate)\n\trouter.GET(\"/api/statistics/regenerate\", s.LastThNRegenerate)\n\n}\n\nfunc (s *StatisticsHandler) CountActiveUser(ctx *gin.Context) {\n\n\tunit := ctx.Query(\"unit\")\n\tstartDate := startDate(ctx)\n\tendDate := endDate(ctx)\n\tlog.Println(\"unit\", unit, \"startTime\", startDate, \"endTime\", endDate)\n\n\tdb := database.Db\n\tvar data1 []UserStatistics\n\tvar data2 []UserStatistics\n\tvar stamps []int64\n\t//database.Raw(\"select count(distinct name), day(create_at) from player_logs  where create_at between ? and ? group by month(create_at), day(create_at)\", \"2023-02-25T16:24:33.2960449+08:00\", \"2023-02-25T15:59:15.5348647+08:00\").Scan(&data)\n\tif unit == \"MONTH\" {\n\t\tdb.Raw(\"select count(distinct name) as count,created_at as date from player_logs where created_at between ? and ? group by strftime('%Y',created_at),strftime('%m',created_at)\", startDate, endDate).Scan(&data1)\n\t\tdb.Raw(\"select count(name) as count,created_at as date from player_logs where created_at between ? and ? and action like '[JoinAnnouncement]' group by strftime('%Y',created_at),strftime('%m',created_at)\", startDate, endDate).Scan(&data2)\n\t}\n\tif unit == \"DAY\" {\n\t\tsql1 := `\n\t\tselect\n\t\t\tcount(distinct name) as count,created_at as date\n\t\tfrom player_logs\n\t\twhere created_at between ? and ?\n\t\tgroup by strftime('%m',created_at),strftime('%d',created_at)\n\t\t`\n\t\tsql2 := `\n\t\tselect\n\t\t\tcount(name) as count,created_at as date\n\t\tfrom player_logs\n\t\twhere created_at between ? and ? and action like '[JoinAnnouncement]'\n\t\tgroup by strftime('%m',created_at),strftime('%d',created_at)\n\t\t`\n\t\tdb.Raw(sql1, startDate, endDate).Scan(&data1)\n\t\tdb.Raw(sql2, startDate, endDate).Scan(&data2)\n\n\t\t// database.Raw(\"select count(distinct name) as count,created_at as date from player_logs where action like '[JoinAnnouncement]' group by strftime('%m',created_at),strftime('%d',created_at)\").Scan(&data1)\n\t\t// database.Raw(\"select count(name) as count,created_at as date from player_logs where action like '[JoinAnnouncement]' group by strftime('%m',created_at),strftime('%d',created_at)\").Scan(&data2)\n\n\t\tstamps = utils.Get_stamp_day(startDate, endDate)\n\t}\n\n\tvar axis struct {\n\t\tX  []int64 `json:\"x\"`\n\t\tY1 []int   `json:\"y1\"`\n\t\tY2 []int   `json:\"y2\"`\n\t}\n\tlog.Println(\"data1\", data1)\n\tlog.Println(\"data1\", data2)\n\t//填充数据\n\t// var stamp []int64;\n\tfor _, stamp := range stamps {\n\t\taxis.X = append(axis.X, stamp)\n\n\t\tif d := findStamp(stamp, data1); d != nil {\n\t\t\taxis.Y1 = append(axis.Y1, d.Count)\n\t\t} else {\n\t\t\taxis.Y1 = append(axis.Y1, 0)\n\t\t}\n\t\tif d := findStamp(stamp, data2); d != nil {\n\t\t\taxis.Y2 = append(axis.Y2, d.Count)\n\t\t} else {\n\t\t\taxis.Y2 = append(axis.Y2, 0)\n\t\t}\n\t}\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: axis,\n\t})\n}\n\nfunc (s *StatisticsHandler) CountLoginUser(ctx *gin.Context) {\n\n\tunit := ctx.Query(\"unit\")\n\tstartDate := startDate(ctx)\n\tendDate := endDate(ctx)\n\tfmt.Println(\"unit\", unit, \"startTime\", startDate, \"endTime\", endDate)\n\n\tdb := database.Db\n\tvar data []UserStatistics\n\tif unit == \"MONTH\" {\n\t\tdb.Raw(\"select count(name) as count,created_at as date from player_logs where created_at between ? and ? group by strftime('%Y',created_at),strftime('%m',created_at)\", startDate, endDate).Scan(&data)\n\t}\n\tif unit == \"DAY\" {\n\t\tdb.Raw(\"select count(name) as count,created_at as date from player_logs where created_at between ? and ? group by strftime('%m',created_at),strftime('%d',created_at)\", startDate, endDate).Scan(&data)\n\t}\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: data,\n\t})\n}\n\nfunc (s *StatisticsHandler) TopUserActiveTimes(ctx *gin.Context) {\n\tN := ctx.Query(\"N\")\n\n\t// startTime, _ := time.Parse(\"2006-01-02T15:04:05.000Z\", startDate)\n\t// endTime, _ := time.Parse(\"2006-01-02T15:04:05.000Z\", endDate)\n\n\tstartDate := startDate(ctx)\n\tendDate := endDate(ctx)\n\n\tfmt.Println(\"N\", N, \"startTime\", startDate, \"endTime\", endDate)\n\n\tdb := database.Db\n\n\t//本天，本周，本月\n\tvar data []TopStatistics\n\tsql := `\n\tselect \n\t\tmax(id) as id,count(name) as count, name, ku_id, steam_id, role, action_desc, created_at\n\tfrom player_logs\n\twhere created_at between ? and ? and action like '[JoinAnnouncement]'\n\tgroup by name order by count(id) DESC limit ?\n\t`\n\tdb.Raw(sql, startDate, endDate, N).Scan(&data)\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: data,\n\t})\n}\n\nfunc (s *StatisticsHandler) TopUserLoginimes(ctx *gin.Context) {\n\tN := ctx.Query(\"N\")\n\tstartDate := startDate(ctx)\n\tendDate := endDate(ctx)\n\n\tfmt.Println(\"N\", N, \"startDate\", startDate, \"endDate\", endDate)\n\n\tdb := database.Db\n\n\t//本天，本周，本月\n\tvar data []TopStatistics\n\tsql := `\n\tselect \n\t\tmax(p.id) as id,count(p.name) as count, p.name, c.ku_id, c.steam_id, role, action_desc, p.created_at\n\tfrom player_logs p\n\tleft join connects c on p.name = c.name\n\twhere p.created_at between ? and ? and p.action like '[JoinAnnouncement]' \n\tgroup by p.name order by count(p.id) DESC limit ?\n\t`\n\tdb.Raw(sql, startDate, endDate, N).Scan(&data)\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: data,\n\t})\n}\n\nfunc (s *StatisticsHandler) TopDeaths(ctx *gin.Context) {\n\n\tN := ctx.Query(\"N\")\n\tstartDate := startDate(ctx)\n\tendDate := endDate(ctx)\n\n\tfmt.Println(\"N\", N, \"startDate\", startDate, \"endDate\", endDate)\n\n\tdb := database.Db\n\n\t//本天，本周，本月\n\tvar data []TopStatistics\n\tsql := `\n\tselect \n\t\tmax(id) as id, count(id) as count, name, ku_id, steam_id, role, action_desc, created_at\n\tfrom player_logs\n\twhere created_at between ? and ? and action like '[DeathAnnouncement]'\n\tgroup by name order by count(id) DESC limit ?\n\t`\n\tdb.Raw(sql, startDate, endDate, N).Scan(&data)\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: data,\n\t})\n}\n\nfunc (s *StatisticsHandler) CountRoleRate(ctx *gin.Context) {\n\tstartDate := startDate(ctx)\n\tendDate := endDate(ctx)\n\n\tdb := database.Db\n\n\t//本天，本周，本月\n\tvar data []RoleRateStatistics\n\tsql := `\n\tselect \n\t\trole as role, count(distinct name) as count\n\tfrom player_logs\n\twhere role != '' and created_at between ? and ?\n\tgroup by role\n\t`\n\tdb.Raw(sql, startDate, endDate).Scan(&data)\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: data,\n\t})\n}\n\nfunc startDate(ctx *gin.Context) time.Time {\n\tvar date time.Time\n\tif t, isExist := ctx.GetQuery(\"startDate\"); isExist {\n\t\tdate, _ = time.Parse(\"2006-01-02T15:04:05.000Z\", t)\n\t}\n\treturn date\n}\n\nfunc endDate(ctx *gin.Context) time.Time {\n\tvar date time.Time\n\tif t, isExist := ctx.GetQuery(\"endDate\"); isExist {\n\t\tdate, _ = time.Parse(\"2006-01-02T15:04:05.000Z\", t)\n\t}\n\treturn date\n}\n\nfunc (s *StatisticsHandler) LastThNRegenerate(ctx *gin.Context) {\n\n\tN := ctx.Query(\"N\")\n\tdb := database.Db\n\n\t//本天，本周，本月\n\tvar data []model.Regenerate\n\tsql := `\n\tselect * from regenerates order by created_at DESC limit ?\n\t`\n\tdb.Raw(sql, N).Scan(&data)\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: data,\n\t})\n}\n"
  },
  {
    "path": "internal/api/handler/update.go",
    "content": "package handler\n\nimport (\n\t\"dst-admin-go/internal/pkg/context\"\n\t\"dst-admin-go/internal/pkg/response\"\n\t\"dst-admin-go/internal/service/update\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype UpdateHandler struct {\n\tupdateService update.Update\n}\n\nfunc NewUpdateHandler(update update.Update) *UpdateHandler {\n\treturn &UpdateHandler{\n\t\tupdateService: update,\n\t}\n}\n\nfunc (h *UpdateHandler) RegisterRoute(router *gin.RouterGroup) {\n\trouter.GET(\"/api/game/update\", h.Update)\n}\n\n// Update 生成 swagger 文档注释\n// @Summary 更新游戏\n// @Description 更新游戏\n// @Tags update\n// @Success 200 {object} response.Response\n// @Router /api/game/update [get]\nfunc (h *UpdateHandler) Update(ctx *gin.Context) {\n\n\tclusterName := context.GetClusterName(ctx)\n\n\terr := h.updateService.Update(clusterName)\n\tif err != nil {\n\t\tlog.Panicln(\"更新游戏失败: \", err)\n\t}\n\n\tctx.JSON(http.StatusOK, response.Response{\n\t\tCode: 200,\n\t\tMsg:  \"update dst success\",\n\t\tData: nil,\n\t})\n}\n"
  },
  {
    "path": "internal/api/router.go",
    "content": "package api\n\nimport (\n\t\"dst-admin-go/internal/api/handler\"\n\t\"dst-admin-go/internal/collect\"\n\t\"dst-admin-go/internal/config\"\n\t\"dst-admin-go/internal/middleware\"\n\t\"dst-admin-go/internal/service/archive\"\n\t\"dst-admin-go/internal/service/backup\"\n\t\"dst-admin-go/internal/service/dstConfig\"\n\t\"dst-admin-go/internal/service/dstMap\"\n\t\"dst-admin-go/internal/service/game\"\n\t\"dst-admin-go/internal/service/gameArchive\"\n\t\"dst-admin-go/internal/service/gameConfig\"\n\t\"dst-admin-go/internal/service/level\"\n\t\"dst-admin-go/internal/service/levelConfig\"\n\t\"dst-admin-go/internal/service/login\"\n\t\"dst-admin-go/internal/service/mod\"\n\t\"dst-admin-go/internal/service/player\"\n\t\"dst-admin-go/internal/service/update\"\n\t\"time\"\n\n\t\"github.com/gin-contrib/sessions\"\n\t\"github.com/gin-contrib/sessions/memstore\"\n\t\"github.com/gin-gonic/gin\"\n\tswaggerFiles \"github.com/swaggo/files\"\n\t\"github.com/swaggo/gin-swagger\"\n\n\t\"gorm.io/gorm\"\n)\n\nfunc NewRoute(cfg *config.Config, db *gorm.DB) *gin.Engine {\n\tapp := gin.Default()\n\tstore := memstore.NewStore([]byte(\"secret\"))\n\tstore.Options(sessions.Options{\n\t\tPath:     \"/\",\n\t\tMaxAge:   int(60 * 24 * 7 * time.Minute.Seconds()),\n\t\tHttpOnly: true,\n\t})\n\tapp.Use(sessions.Sessions(\"token\", store))\n\tapp.Use(middleware.Recover)\n\n\tapp.GET(\"/hello\", func(ctx *gin.Context) {\n\t\tctx.String(200, \"Hello! Dont starve together\")\n\t})\n\t// Swagger UI\n\tapp.GET(\"/swagger/*any\", ginSwagger.WrapHandler(swaggerFiles.Handler))\n\tRegisterStaticFile(app)\n\tRegister(cfg, db, app.Group(\"\"))\n\treturn app\n}\n\nfunc initCollectors(archive *archive.PathResolver, dstConfigService dstConfig.Config) {\n\tgetDstConfig, err := dstConfigService.GetDstConfig(\"MyDediServer\")\n\tif err != nil {\n\t\treturn\n\t}\n\tclusterName := getDstConfig.Cluster\n\tnewCollect := collect.NewCollect(archive.ClusterPath(clusterName), clusterName)\n\tcollect.Collector = newCollect\n\tcollect.Collector.StartCollect()\n}\n\nfunc RegisterStaticFile(app *gin.Engine) {\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t}\n\t}()\n\tapp.Use(func(context *gin.Context) {\n\t\tcontext.Writer.Header().Set(\"Cache-Control\", \"public, max-age=30672000\")\n\t})\n\tapp.LoadHTMLGlob(\"dist/index.html\") // 添加入口index.html\n\t//r.LoadHTMLFiles(\"dist//*\") // 添加资源路径\n\tapp.Static(\"/assets\", \"./dist/assets\")\n\tapp.Static(\"/misc\", \"./dist/misc\")\n\tapp.Static(\"/static/js\", \"./dist/static/js\")                         // 添加资源路径\n\tapp.Static(\"/static/css\", \"./dist/static/css\")                       // 添加资源路径\n\tapp.Static(\"/static/img\", \"./dist/static/img\")                       // 添加资源路径\n\tapp.Static(\"/static/fonts\", \"./dist/static/fonts\")                   // 添加资源路径\n\tapp.Static(\"/static/media\", \"./dist/static/media\")                   // 添加资源路径\n\tapp.StaticFile(\"/favicon.ico\", \"./dist/favicon.ico\")                 // 添加资源路径\n\tapp.StaticFile(\"/asset-manifest.json\", \"./dist/asset-manifest.json\") // 添加资源路径\n\tapp.StaticFile(\"/\", \"./dist/index.html\")\n}\n\nfunc Register(cfg *config.Config, db *gorm.DB, router *gin.RouterGroup) {\n\n\t// service\n\tdstConfigService := dstConfig.NewDstConfig(db)\n\tupdateService := update.NewUpdateService(dstConfigService)\n\tresolverService, _ := archive.NewPathResolver(dstConfigService)\n\tloginService := login.NewLoginService(cfg)\n\tlevelConfigUtils := levelConfig.NewLevelConfigUtils(resolverService)\n\tgameProcess := game.NewGame(dstConfigService, levelConfigUtils)\n\n\tgameConfigService := gameConfig.NewGameConfig(resolverService, levelConfigUtils)\n\tbackupService := backup.NewBackupService(resolverService, dstConfigService, gameProcess)\n\tlevelService := level.NewLevelService(gameProcess, dstConfigService, resolverService, levelConfigUtils)\n\tplayerService := player.NewPlayerService(resolverService)\n\tgameArchiveService := gameArchive.NewGameArchive(gameConfigService, levelService, resolverService)\n\tmodService := mod.NewModService(db, dstConfigService, resolverService)\n\n\tdstMapGenerator := dstMap.NewDSTMapGenerator()\n\n\t// init\n\tinitCollectors(resolverService, dstConfigService)\n\n\t//  handler\n\tupdateHandler := handler.NewUpdateHandler(updateService)\n\tgameHandler := handler.NewGameHandler(gameProcess, levelService, gameArchiveService, levelConfigUtils, resolverService)\n\tgameConfigHandler := handler.NewGameConfigHandler(gameConfigService)\n\tdstConfigHandler := handler.NewDstConfigHandler(dstConfigService, resolverService)\n\tloginHandler := handler.NewLoginHandler(loginService)\n\tbackupHandler := handler.NewBackupHandler(backupService)\n\tlevelHandler := handler.NewLevelHandler(levelService)\n\tplayerHandler := handler.NewPlayerHandler(playerService, gameProcess)\n\tlevelLogHandler := handler.NewLevelLogHandler(resolverService)\n\tkvHandler := handler.NewKvHandler(db)\n\tdstApiHandler := handler.NewDstApiHandler()\n\tdstMapHandler := handler.NewDstMapHandler(resolverService, dstMapGenerator)\n\tplayerLogHandler := handler.NewPlayerLogHandler()\n\tstatisticsHandler := handler.NewStatisticsHandler()\n\tmodHandler := handler.NewModHandler(modService, dstConfigService)\n\n\t// 中间件\n\trouter.Use(middleware.Authentication(loginService))\n\trouter.Use(middleware.ClusterMiddleware(dstConfigService))\n\n\t//  route\n\tupdateHandler.RegisterRoute(router)\n\tgameHandler.RegisterRoute(router)\n\tgameConfigHandler.RegisterRoute(router)\n\tdstConfigHandler.RegisterRoute(router)\n\tloginHandler.RegisterRoute(router)\n\tbackupHandler.RegisterRoute(router)\n\tlevelHandler.RegisterRoute(router)\n\tplayerHandler.RegisterRoute(router)\n\tlevelLogHandler.RegisterRoute(router)\n\tkvHandler.RegisterRoute(router)\n\tdstApiHandler.RegisterRoute(router)\n\tdstMapHandler.RegisterRoute(router)\n\tplayerLogHandler.RegisterRoute(router)\n\tstatisticsHandler.RegisterRoute(router)\n\tmodHandler.RegisterRoute(router)\n\n}\n"
  },
  {
    "path": "internal/collect/collect.go",
    "content": "package collect\n\nimport (\n\t\"dst-admin-go/internal/database\"\n\t\"dst-admin-go/internal/model\"\n\t\"fmt\"\n\t\"log\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/hpcloud/tail\"\n)\n\nvar Collector *Collect\n\ntype Collect struct {\n\tstate             chan int\n\tstop              chan bool\n\tseverLogList      []string\n\tserverChatLogList []string\n\tlength            int\n\tclusterName       string\n}\n\nfunc NewCollect(baseLogPath string, clusterName string) *Collect {\n\tcollect := &Collect{\n\t\tstate: make(chan int, 1),\n\t\tseverLogList: []string{\n\t\t\tfilepath.Join(baseLogPath, \"Master\", \"server_log.txt\"),\n\t\t},\n\t\tserverChatLogList: []string{\n\t\t\tfilepath.Join(baseLogPath, \"Master\", \"server_chat_log.txt\"),\n\t\t},\n\t\tstop:        make(chan bool, 2),\n\t\tlength:      2,\n\t\tclusterName: clusterName,\n\t}\n\tcollect.state <- 1\n\treturn collect\n}\n\nfunc (c *Collect) Stop() {\n\tclose(c.stop)\n}\n\nfunc (c *Collect) ReCollect(baseLogPath, clusterName string) {\n\tfor i := 0; i < c.length; i++ {\n\t\tc.stop <- true\n\t}\n\tc.severLogList = []string{\n\t\tfilepath.Join(baseLogPath, \"Master\", \"server_log.txt\"),\n\t}\n\tc.serverChatLogList = []string{\n\t\tfilepath.Join(baseLogPath, \"Master\", \"server_chat_log.txt\"),\n\t}\n\tc.clusterName = clusterName\n\tc.state <- 1\n}\n\nfunc (c *Collect) StartCollect() {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-c.state:\n\t\t\t\t// 采集\n\t\t\t\tfor _, s := range c.severLogList {\n\t\t\t\t\tgo c.tailServeLog(s)\n\t\t\t\t}\n\t\t\t\tfor _, s := range c.serverChatLogList {\n\t\t\t\t\tgo c.tailServerChatLog(s)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\ttime.Sleep(5 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc (c *Collect) parseSpawnRequestLog(text string) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.Printf(\"Spawn request Log text: %s\\n\", text)\n\t\t\tlog.Printf(\"玩家角色日志解析异常: %v\\n\", r)\n\t\t}\n\t}()\n\n\t// 捕获 (1)时间, (2)动作, (3)角色, (4)玩家名\n\tre := regexp.MustCompile(`^\\[([^\\]]+)\\]:\\s*(.*?):\\s*(\\w+)\\s*from\\s*(.+)$`)\n\tmatches := re.FindStringSubmatch(text)\n\n\tif len(matches) != 5 {\n\t\t// 如果日志格式不匹配，直接退出\n\t\tlog.Printf(\"Spawn request 日志格式不匹配: %s\\n\", text)\n\t\treturn\n\t}\n\n\tt := matches[1] // 00:37:41\n\t// action := matches[2] // Spawn request\n\trole := matches[3] // winona\n\tname := strings.TrimSpace(matches[4])\n\n\tspawn := model.Spawn{Name: name, Role: role, Time: t, ClusterName: c.clusterName}\n\tif err := database.Db.Create(&spawn).Error; err != nil {\n\t\tlog.Printf(\"插入玩家 Spawn 日志失败: %v\\n\", err)\n\t}\n}\n\nfunc (c *Collect) parseRegenerateLog(text string) {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tlog.Println(\"Generating 日志解析异常:\", err)\n\t\t}\n\t}()\n\n\tregenerate := model.Regenerate{\n\t\tClusterName: c.clusterName,\n\t}\n\tdatabase.Db.Create(&regenerate)\n}\n\nfunc (c *Collect) parseNewIncomingLog(lines []string) {\n\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tlog.Println(\"new incoming 日志解析异常:\", err)\n\t\t}\n\t}()\n\tconnect := model.Connect{}\n\tlog.Println(\"len:\", len(lines), lines)\n\tfor i, line := range lines {\n\t\tif i == 1 {\n\t\t\t// 解析 ip\n\t\t\tstr := strings.Split(line, \" \")\n\t\t\tif len(str) < 5 {\n\t\t\t\tlog.Println(\"ip 解析错误: \", line)\n\t\t\t\tconnect.Ip = \"\"\n\t\t\t} else {\n\t\t\t\tvar ip string\n\t\t\t\tif strings.Contains(line, \"[LAN]\") {\n\t\t\t\t\tip = str[5]\n\t\t\t\t} else {\n\t\t\t\t\tip = str[4]\n\t\t\t\t}\n\t\t\t\tconnect.Ip = ip\n\t\t\t\tfmt.Println(\"ip\", ip)\n\t\t\t}\n\t\t}\n\t\tif i == 2 {\n\t\t\t// 解析 ip\n\t\t}\n\t\tif i == 3 {\n\t\t\t// 解析 KuId 和 用户名\n\t\t\tstr := strings.Split(line, \" \")\n\t\t\tif len(str) <= 4 {\n\t\t\t\tlog.Println(\"kuid 解析错误: \", line)\n\t\t\t} else {\n\t\t\t\tku := str[3]\n\t\t\t\tku = ku[1 : len(ku)-1]\n\t\t\t\tname := str[4]\n\t\t\t\tconnect.Name = name\n\t\t\t\tconnect.KuId = ku\n\t\t\t\tfmt.Println(\"ku\", ku, \"name\", name)\n\t\t\t}\n\t\t}\n\t\tif i == 4 {\n\t\t\t// 解析 steamId\n\t\t\tstr := strings.Split(line, \" \")\n\t\t\tif len(str) < 4 {\n\t\t\t\tlog.Println(\"steamid 解析错误: \", line)\n\t\t\t} else {\n\t\t\t\tsteamId := str[4]\n\t\t\t\tsteamId = steamId[1 : len(steamId)-1]\n\t\t\t\tfmt.Println(\"steamId\", steamId)\n\t\t\t\tconnect.SteamId = steamId\n\t\t\t\tconnect.ClusterName = c.clusterName\n\t\t\t}\n\t\t}\n\t\tif strings.Contains(line, \"Resuming user:\") {\n\t\t\t// 解析 session file path\n\t\t\tstr := strings.Split(line, \" \")\n\t\t\tlog.Println(len(str), lines)\n\t\t\t//[00:14:37]: Resuming user: session/7477D5E4A0424844/KU_Mt-zrX8K_\n\t\t\tif len(str) < 4 {\n\t\t\t\tlog.Println(\"session file path 解析错误: \", line)\n\t\t\t} else {\n\t\t\t\tname := str[3]\n\t\t\t\tname = strings.Replace(name, \"session/\", \"\", -1)\n\t\t\t\tconnect.SessionFile = name\n\t\t\t}\n\t\t}\n\t\t// [03:19:10]: Serializing user: session/D480EA2CEF7633C0/KU_Mt-zrX8K_/0000000005\n\t\tif strings.Contains(line, \"Serializing user:\") {\n\t\t\t// 解析 session file path\n\t\t\tstr := strings.Split(line, \" \")\n\t\t\tlog.Println(len(str), lines)\n\t\t\t//[00:14:37]: Resuming user: session/7477D5E4A0424844/KU_Mt-zrX8K_\n\t\t\tif len(str) < 4 {\n\t\t\t\tlog.Println(\"session file path 解析错误: \", line)\n\t\t\t} else {\n\t\t\t\tname := str[3]\n\t\t\t\tname = strings.Replace(name, \"session/\", \"\", -1)\n\t\t\t\tconnect.SessionFile = name\n\t\t\t}\n\n\t\t}\n\t}\n\tdatabase.Db.Create(&connect)\n}\n\nfunc (c *Collect) tailServeLog(fileName string) {\n\n\tlog.Println(\"开始采集 path:\", fileName)\n\tconfig := tail.Config{\n\t\tReOpen:    true,                                 // 重新打开\n\t\tFollow:    true,                                 // 是否跟随\n\t\tLocation:  &tail.SeekInfo{Offset: 0, Whence: 2}, // 从文件的哪个地方开始读\n\t\tMustExist: false,                                // 文件不存在不报错\n\t\tPoll:      true,\n\t}\n\ttails, err := tail.TailFile(fileName, config)\n\tif err != nil {\n\t\tlog.Println(\"文件监听失败\", err)\n\t}\n\tvar (\n\t\twhich        = 0\n\t\tisNewConnect = false\n\t\tincoming     []string\n\t)\n\tfor {\n\t\tselect {\n\t\tcase line, ok := <-tails.Lines:\n\t\t\tif !ok {\n\t\t\t\tlog.Println(\"文件读取失败\", err)\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t} else {\n\t\t\t\ttext := line.Text\n\t\t\t\tif find := strings.Contains(text, \"Spawn request\"); find {\n\t\t\t\t\tc.parseSpawnRequestLog(text)\n\t\t\t\t} else if find := strings.Contains(text, \"# Generating\"); find {\n\t\t\t\t\tc.parseRegenerateLog(text)\n\t\t\t\t} else if find := strings.Contains(text, \"New incoming connection\"); find {\n\t\t\t\t\tisNewConnect = true\n\t\t\t\t}\n\t\t\t\t// 获取接下来的五条数据\n\t\t\t\tif isNewConnect {\n\t\t\t\t\tincoming = append(incoming, text)\n\t\t\t\t\twhich++\n\t\t\t\t\tif which > 10 {\n\t\t\t\t\t\tisNewConnect = false\n\t\t\t\t\t\twhich = 0\n\t\t\t\t\t\tc.parseNewIncomingLog(incoming)\n\t\t\t\t\t\tincoming = []string{}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-c.stop:\n\t\t\t// 结束监听\n\t\t\terr := tails.Stop()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"tail log 结束失败\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (c *Collect) parseChatLog(text string) {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tlog.Println(\"玩家行为日志解析异常:\", err)\n\t\t}\n\t}()\n\t//[00:00:55]: [Join Announcement] 猜猜我是谁\n\tif strings.Contains(text, \"[Join Announcement]\") {\n\t\tc.parseJoin(text)\n\t}\n\t//[00:02:28]: [Leave Announcement] 猜猜我是谁\n\tif strings.Contains(text, \"[Leave Announcement]\") {\n\t\tc.parseLeave(text)\n\t}\n\t//[00:02:17]: [Death Announcement] 猜猜我是谁 死于： 采摘的红蘑菇。她变成了可怕的鬼魂！\n\tif strings.Contains(text, \"[Death Announcement]\") {\n\t\tc.parseDeath(text)\n\t}\n\t//[00:02:37]: [Resurrect Announcement] 猜猜我是谁 复活自： TMIP 控制台.\n\tif strings.Contains(text, \"[Resurrect Announcement]\") {\n\t\tc.parseResurrect(text)\n\t}\n\t//[00:03:16]: [Say] (KU_Mt-zrX8K) 猜猜我是谁: 你好啊\n\tif strings.Contains(text, \"[Say]\") {\n\t\tc.parseSay(text)\n\t}\n\t//[10:01:42]: [Announcement] 欢迎访客歪比巴卜，游玩\n\tif strings.Contains(text, \"[Announcement]\") {\n\t\tc.parseAnnouncement(text)\n\t}\n}\n\nfunc (c *Collect) parseSay(text string) {\n\tfmt.Println(text)\n\n\t// 正则解析日志\n\tre := regexp.MustCompile(`\\[(.*?)\\]: (\\[.*?\\]) \\((.*?)\\) (.*?): (.*)`)\n\tmatches := re.FindStringSubmatch(text)\n\tif len(matches) != 6 {\n\t\tfmt.Println(\"无法解析日志:\", text, matches)\n\t\treturn\n\t}\n\n\t// 时间\n\tt := matches[1]\n\t// [Say]\n\taction := matches[2]\n\tkuId := matches[3]\n\t// 玩家名字，可包含空格\n\tname := matches[4]\n\tactionDesc := matches[5]\n\n\t// 获取玩家角色和连接信息\n\tspawn := c.getSpawnRole(name)\n\tconnect := c.getConnectInfo(name)\n\n\tplayerLog := model.PlayerLog{\n\t\tName:        name,\n\t\tRole:        spawn.Role,\n\t\tAction:      action,\n\t\tActionDesc:  actionDesc,\n\t\tTime:        t,\n\t\tIp:          connect.Ip,\n\t\tKuId:        kuId,\n\t\tSteamId:     connect.SteamId,\n\t\tClusterName: c.clusterName,\n\t}\n\n\t// 保存到数据库，并打印错误\n\tif err := database.Db.Create(&playerLog).Error; err != nil {\n\t\tfmt.Println(\"插入玩家日志失败:\", err)\n\t}\n}\n\nfunc (c *Collect) parseResurrect(text string) {\n\tc.parseDeath(text)\n}\n\nfunc (c *Collect) parseDeath(text string) {\n\tfmt.Println(text)\n\n\t// 正则表达式 (1)时间, (2)动作, (3)剩余所有内容\n\tre := regexp.MustCompile(`^\\[([^\\]]+)\\]:\\s*(\\[[^\\]]+\\])\\s*(.*)$`)\n\tmatches := re.FindStringSubmatch(text)\n\tif len(matches) != 4 {\n\t\tlog.Println(\"无法解析 Announcement Log (正则不匹配):\", text)\n\t\treturn\n\t}\n\n\tt := matches[1]\n\taction := matches[2]\n\t// 擦屁股\n\taction = strings.ReplaceAll(action, \" \", \"\")\n\trest := strings.TrimSpace(matches[3]) // 名字 + 描述 整体\n\n\tvar name string\n\tvar actionDesc string\n\n\t// 死亡/复活的分隔符列表 (支持中英文)\n\t// 关键：在 Death Announce 和 Resurrect Announce 之间寻找共同的分隔模式\n\t// 中文：死于： / 复活自：\n\t// 英文：died from / resurrected from / revived by\n\tannouncementWords := []string{\n\t\t\"死于：\", \"died from\", \"was killed by\", \"starved\", \"suicide\", // 死亡\n\t\t\"复活自：\", \"resurrected from\", \"revived by\", // 复活\n\t}\n\n\tsplitIndex := -1\n\tfor _, word := range announcementWords {\n\t\t// 查找分隔符\n\t\tidx := strings.Index(rest, word)\n\t\tif idx > splitIndex { // 找到最靠前的已知分隔符\n\t\t\tsplitIndex = idx\n\t\t\t// 找到后立即退出循环，因为第一个匹配就是名字和描述的边界\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif splitIndex != -1 {\n\t\t// 找到了分隔符：分割 rest\n\t\tname = strings.TrimSpace(rest[:splitIndex])\n\t\tactionDesc = strings.TrimSpace(rest[splitIndex:])\n\t} else {\n\t\t// 未找到已知分隔符，假设整个 rest 都是名字，描述为空 (适用于名字很长，或系统消息)\n\t\tname = rest\n\t\tactionDesc = \"\"\n\t\tfmt.Println(\"Announcement Log 未找到分隔符，将全部分配给 Name:\", name)\n\t}\n\n\tspawn := c.getSpawnRole(name)\n\tconnect := c.getConnectInfo(name)\n\tfmt.Println(connect)\n\n\tplayerLog := model.PlayerLog{\n\t\tName:        name,\n\t\tRole:        spawn.Role,\n\t\tAction:      action,\n\t\tActionDesc:  actionDesc,\n\t\tTime:        t,\n\t\tIp:          connect.Ip,\n\t\tKuId:        connect.KuId,\n\t\tSteamId:     connect.SteamId,\n\t\tClusterName: c.clusterName,\n\t}\n\n\tif err := database.Db.Create(&playerLog).Error; err != nil {\n\t\tfmt.Println(\"插入玩家日志失败:\", err)\n\t}\n}\n\nfunc (c *Collect) parseLeave(text string) {\n\tc.parseJoin(text)\n}\n\nfunc (c *Collect) parseJoin(text string) {\n\tfmt.Println(text)\n\n\t// 正则表达式：捕获 (1)时间, (2)动作, (3)玩家名\n\tre := regexp.MustCompile(`^\\[([^\\]]+)\\]:\\s*(\\[[^\\]]+\\])\\s*(.+)$`)\n\tmatches := re.FindStringSubmatch(text)\n\n\t// 预期匹配 4 组：[完整匹配, 时间, 动作, 玩家名]\n\tif len(matches) != 4 {\n\t\tlog.Println(\"无法解析 Join Log (正则不匹配):\", text)\n\t\treturn\n\t}\n\n\t// 捕获结果\n\tt := matches[1]      // 时间: 00:01:43\n\taction := matches[2] // 动作: [Join Announcement]\n\t// 擦屁股\n\taction = strings.ReplaceAll(action, \" \", \"\")\n\t// 玩家名字是捕获组 3，使用 strings.TrimSpace 确保名字前后没有多余空格\n\tname := strings.TrimSpace(matches[3])\n\n\tspawn := c.getSpawnRole(name)\n\tconnect := c.getConnectInfo(name)\n\n\tplayerLog := model.PlayerLog{\n\t\tName:        name,\n\t\tRole:        spawn.Role,\n\t\tAction:      action,\n\t\tTime:        t,\n\t\tIp:          connect.Ip,\n\t\tKuId:        connect.KuId,\n\t\tSteamId:     connect.SteamId,\n\t\tClusterName: c.clusterName,\n\t}\n\n\t// 保存到数据库，并打印错误\n\tif err := database.Db.Create(&playerLog).Error; err != nil {\n\t\tfmt.Println(\"插入玩家日志失败:\", err)\n\t}\n}\n\nfunc (c *Collect) tailServerChatLog(fileName string) {\n\tlog.Println(\"开始采集 path:\", fileName)\n\tconfig := tail.Config{\n\t\tReOpen:    true,                                 // 重新打开\n\t\tFollow:    true,                                 // 是否跟随\n\t\tLocation:  &tail.SeekInfo{Offset: 0, Whence: 2}, // 从文件的哪个地方开始读\n\t\tMustExist: false,                                // 文件不存在不报错\n\t\tPoll:      true,\n\t}\n\ttails, err := tail.TailFile(fileName, config)\n\tif err != nil {\n\t\tlog.Println(\"文件监听失败\", err)\n\t}\n\tfor {\n\t\tselect {\n\t\tcase line, ok := <-tails.Lines:\n\t\t\tif !ok {\n\t\t\t\tlog.Println(\"文件读取失败\", err)\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t} else {\n\t\t\t\ttext := line.Text\n\t\t\t\tc.parseChatLog(text)\n\t\t\t}\n\t\tcase <-c.stop:\n\t\t\t// 结束监听\n\t\t\terr := tails.Stop()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"tail log 结束失败\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (c *Collect) getSpawnRole(name string) *model.Spawn {\n\tspawn := new(model.Spawn)\n\tdatabase.Db.Where(\"name LIKE ? and cluster_name = ?\", \"%\"+name+\"%\", c.clusterName).Last(spawn)\n\treturn spawn\n}\n\nfunc (c *Collect) getConnectInfo(name string) *model.Connect {\n\tconnect := new(model.Connect)\n\tdatabase.Db.Where(\"name LIKE ? and cluster_name = ?\", \"%\"+name+\"%\", c.clusterName).Last(connect)\n\treturn connect\n}\n\nfunc (c *Collect) parseAnnouncement(text string) {\n\tfmt.Println(text)\n\n\t// 正则解析日志\n\tre := regexp.MustCompile(`\\[(.*?)\\]: (\\[Announcement\\]) (.*)`)\n\tmatches := re.FindStringSubmatch(text)\n\t// 无法解析宣告日志: 00:55:21 Announcement test\n\tif len(matches) != 4 {\n\t\tfmt.Println(\"无法解析宣告日志:\", text, matches)\n\t\treturn\n\t}\n\n\t// 时间\n\tt := matches[1]\n\t// [Announcement]\n\taction := matches[2]\n\t// 宣告的内容\n\tactionDesc := matches[3]\n\n\tplayerLog := model.PlayerLog{\n\t\tName:        \"-\",\n\t\tRole:        \"-\",\n\t\tAction:      action,\n\t\tActionDesc:  actionDesc,\n\t\tTime:        t,\n\t\tIp:          \"-\",\n\t\tKuId:        \"-\",\n\t\tSteamId:     \"-\",\n\t\tClusterName: c.clusterName,\n\t}\n\n\t// 保存到数据库，并打印错误\n\tif err := database.Db.Create(&playerLog).Error; err != nil {\n\t\tfmt.Println(\"插入玩家日志失败:\", err)\n\t}\n}\n"
  },
  {
    "path": "internal/collect/collect_map.go",
    "content": "package collect\n\nimport (\n\t\"dst-admin-go/internal/service/archive\"\n\t\"sync\"\n)\n\nvar CollectorMap *CollectMap\n\ntype CollectMap struct {\n\tcache   sync.Map\n\tarchive *archive.PathResolver\n}\n\nfunc NewCollectMap() *CollectMap {\n\treturn &CollectMap{\n\t\tcache: sync.Map{},\n\t}\n}\n\nfunc (cm *CollectMap) AddNewCollect(clusterName string, baseLogPath string) {\n\t_, ok := cm.cache.Load(clusterName)\n\tif !ok {\n\t\tcollect := NewCollect(baseLogPath, clusterName)\n\t\tcollect.StartCollect()\n\t\tcm.cache.Store(clusterName, collect)\n\t}\n}\n\nfunc (cm *CollectMap) RemoveCollect(clusterName string) {\n\tvalue, loaded := cm.cache.LoadAndDelete(clusterName)\n\tif loaded {\n\t\tvalue.(*Collect).Stop()\n\t}\n}\n"
  },
  {
    "path": "internal/config/config.go",
    "content": "package config\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\ntype Config struct {\n\tBindAddress       string `yaml:\"bindAddress\"`\n\tPort              string `yaml:\"port\"`\n\tPath              string `yaml:\"path\"`\n\tDb                string `yaml:\"database\"`\n\tSteamAPIKey       string `yaml:\"steamAPIKey\"`\n\tFlag              string `yaml:\"flag\"`\n\tWanIP             string `yaml:\"wanip\"`\n\tWhiteAdminIP      string `yaml:\"whiteadminip\"`\n\tToken             string `yaml:\"token\"`\n\tAutoUpdateModinfo struct {\n\t\tEnable              bool `yaml:\"enable\"`\n\t\tCheckInterval       int  `yaml:\"checkInterval\"`\n\t\tUpdateCheckInterval int  `yaml:\"updateCheckInterval\"`\n\t} `yaml:\"autoUpdateModinfo\"`\n}\n\nconst (\n\tConfigPath  = \"./config.yml\"\n\tDefaultPort = \"8083\"\n)\n\nvar Cfg *Config\n\nfunc Load() *Config {\n\tyamlFile, err := ioutil.ReadFile(ConfigPath)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t}\n\tvar c *Config\n\terr = yaml.Unmarshal(yamlFile, &c)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t}\n\tif c.Port == \"\" {\n\t\tc.Port = DefaultPort\n\t}\n\tif c.AutoUpdateModinfo.UpdateCheckInterval == 0 {\n\t\tc.AutoUpdateModinfo.UpdateCheckInterval = 10\n\t}\n\tif c.AutoUpdateModinfo.CheckInterval == 0 {\n\t\tc.AutoUpdateModinfo.CheckInterval = 5\n\t}\n\tCfg = c\n\treturn c\n}\n"
  },
  {
    "path": "internal/database/sqlite.go",
    "content": "package database\n\nimport (\n\t\"dst-admin-go/internal/config\"\n\t\"dst-admin-go/internal/model\"\n\t\"log\"\n\n\t\"github.com/glebarez/sqlite\"\n\t\"gorm.io/gorm\"\n\t\"gorm.io/gorm/logger\"\n)\n\nvar Db *gorm.DB\n\nfunc InitDB(config *config.Config) *gorm.DB {\n\tdb, err := gorm.Open(sqlite.Open(config.Db), &gorm.Config{\n\t\tLogger: logger.Default.LogMode(logger.Silent),\n\t})\n\tif err != nil {\n\t\tpanic(\"failed to connect database\")\n\t}\n\tDb = db\n\terr = db.AutoMigrate(\n\t\t&model.Spawn{},\n\t\t&model.PlayerLog{},\n\t\t&model.Connect{},\n\t\t&model.Regenerate{},\n\t\t&model.ModInfo{},\n\t\t&model.Cluster{},\n\t\t&model.JobTask{},\n\t\t&model.AutoCheck{},\n\t\t&model.Announce{},\n\t\t&model.WebLink{},\n\t\t&model.BackupSnapshot{},\n\t\t&model.LogRecord{},\n\t\t&model.KV{},\n\t)\n\tif err != nil {\n\t\tlog.Println(\"AutoMigrate error\", err)\n\t}\n\treturn db\n}\n"
  },
  {
    "path": "internal/middleware/auth.go",
    "content": "package middleware\n\nimport (\n\t\"dst-admin-go/internal/service/login\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/gin-contrib/sessions\"\n\t\"github.com/gin-gonic/gin\"\n)\n\nvar (\n\twhitelist = []string{\"/api/login\", \"/api/logout\", \"/ws\", \"/api/dst-static\", \"/api/init\", \"/api/install/steamcmd\"}\n)\n\nfunc apiFilter(s []string, str string) bool {\n\t//开放不是 /api 开头接口\n\tif !strings.Contains(str, \"/api\") {\n\t\treturn true\n\t}\n\tfor _, v := range s {\n\t\tif v == str {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\nfunc Authentication(loginService *login.LoginService) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tpath := c.Request.URL.Path\n\t\tif apiFilter(whitelist, path) {\n\t\t\tc.Next()\n\t\t\treturn\n\t\t}\n\t\tsession := sessions.Default(c)\n\t\tusername := session.Get(\"username\")\n\t\tlog.Println(\"username:\", username)\n\t\tif username == nil {\n\t\t\tif loginService.IsWhiteIP(c) {\n\t\t\t\tloginService.DirectLogin(c)\n\t\t\t\tlog.Println(\"white ip login\", c.ClientIP())\n\t\t\t\tc.Next()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tc.AbortWithStatus(http.StatusUnauthorized)\n\t\t} else {\n\t\t\tc.Next()\n\t\t}\n\t}\n}\n\nfunc SseHeadersMiddleware() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tc.Writer.Header().Set(\"Content-Type\", \"text/event-stream\")\n\t\tc.Writer.Header().Set(\"Cache-Control\", \"no-cache\")\n\t\tc.Writer.Header().Set(\"Connection\", \"keep-alive\")\n\t\tc.Writer.Header().Set(\"Transfer-Encoding\", \"chunked\")\n\t\tc.Next()\n\t}\n}\n"
  },
  {
    "path": "internal/middleware/cluster.go",
    "content": "package middleware\n\nimport (\n\t\"dst-admin-go/internal/pkg/response\"\n\t\"dst-admin-go/internal/service/dstConfig\"\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nconst (\n\tclusterNameKey = \"cluster_name\"\n\tdstConfigKey   = \"dst_config\"\n)\n\n// ClusterMiddleware 从 HTTP Header 解析 cluster 名称并加载配置到 context\nfunc ClusterMiddleware(dstConfigService dstConfig.Config) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\n\t\tpath := c.Request.URL.Path\n\t\tif apiFilter(whitelist, path) {\n\t\t\tc.Next()\n\t\t\treturn\n\t\t}\n\n\t\t// 从 Header 获取集群名称\n\t\tclusterName := c.GetHeader(\"Cluster\")\n\n\t\t// 查询集群配置\n\t\tconfig, err := dstConfigService.GetDstConfig(clusterName)\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusNotFound, response.Response{\n\t\t\t\tCode: 500,\n\t\t\t\tMsg:  \"集群配置不存在: \" + clusterName,\n\t\t\t})\n\t\t\tc.Abort()\n\t\t\treturn\n\t\t}\n\n\t\t// 将集群名称和配置注入到 context\n\t\tc.Set(clusterNameKey, config.Cluster)\n\t\tc.Set(dstConfigKey, config)\n\n\t\tc.Next()\n\t}\n}\n"
  },
  {
    "path": "internal/middleware/error.go",
    "content": "package middleware\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"runtime/debug\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc Recover(c *gin.Context) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\t//打印错误堆栈信息\n\t\t\tlog.Printf(\"panic: %v\\n\", r)\n\t\t\tdebug.PrintStack()\n\t\t\t//封装通用json返回\n\t\t\t//c.JSON(http.StatusOK, Result.Fail(errorToString(r)))\n\t\t\t//Result.Fail不是本例的重点，因此用下面代码代替\n\t\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\t\"code\": \"500\",\n\t\t\t\t\"msg\":  errorToString(r),\n\t\t\t\t\"data\": nil,\n\t\t\t})\n\t\t\t//终止后续接口调用，不加的话recover到异常后，还会继续执行接口里后续代码\n\t\t\tc.Abort()\n\t\t}\n\t}()\n\t//加载完 defer recover，继续后续接口调用\n\tc.Next()\n}\n\n// recover错误，转string\nfunc errorToString(r interface{}) string {\n\tswitch v := r.(type) {\n\tcase error:\n\t\treturn v.Error()\n\tdefault:\n\t\treturn r.(string)\n\t}\n}\n"
  },
  {
    "path": "internal/middleware/start_before.go",
    "content": "package middleware\n\nimport (\n\t\"dst-admin-go/internal/pkg/context\"\n\t\"dst-admin-go/internal/pkg/utils/fileUtils\"\n\t\"dst-admin-go/internal/service/archive\"\n\t\"dst-admin-go/internal/service/levelConfig\"\n\t\"log\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc StartBeforeMiddleware(archive *archive.PathResolver, levelConfigUtils *levelConfig.LevelConfigUtils) gin.HandlerFunc {\n\treturn func(ctx *gin.Context) {\n\t\tmakeRunVersion(ctx, archive, levelConfigUtils)\n\t\tcustomcommandsFile(ctx, archive, levelConfigUtils)\n\t}\n}\n\nfunc copyOsFile() {\n\n}\n\nfunc customcommandsFile(ctx *gin.Context, archive *archive.PathResolver, levelConfigUtils *levelConfig.LevelConfigUtils) {\n\tclusterName := context.GetClusterName(ctx)\n\tconfig, _ := levelConfigUtils.GetLevelConfig(clusterName)\n\tfor _, item := range config.LevelList {\n\t\tlevelName := item.File\n\t\tlevelPath := archive.LevelPath(clusterName, levelName)\n\t\tpath := filepath.Join(levelPath, \"customcommands.lua\")\n\t\t_ = fileUtils.CreateFileIfNotExists(path)\n\t\tcustomcommands, _ := fileUtils.ReadFile(\"./static/customcommands.lua\")\n\t\tfileUtils.WriterTXT(path, customcommands)\n\t}\n}\n\nfunc makeRunVersion(ctx *gin.Context, archive *archive.PathResolver, levelConfigUtils *levelConfig.LevelConfigUtils) {\n\tclusterName := context.GetClusterName(ctx)\n\tversion, _ := archive.GetLocalDstVersion(clusterName)\n\turlPath := ctx.Request.URL.Path\n\tconfig, err := levelConfigUtils.GetLevelConfig(clusterName)\n\tif strings.Contains(urlPath, \"all\") {\n\t\tif err == nil {\n\t\t\tfor i := range config.LevelList {\n\t\t\t\tconfig.LevelList[i].RunVersion = version\n\t\t\t\tconfig.LevelList[i].Version = version\n\t\t\t}\n\t\t}\n\t} else {\n\t\tlevelName := ctx.Query(\"levelName\")\n\t\tif err == nil {\n\t\t\tfor i := range config.LevelList {\n\t\t\t\tif config.LevelList[i].File == levelName {\n\t\t\t\t\tconfig.LevelList[i].RunVersion = version\n\t\t\t\t\tconfig.LevelList[i].Version = version\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\terr = levelConfigUtils.SaveLevelConfig(clusterName, config)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}\n"
  },
  {
    "path": "internal/model/LogRecord.go",
    "content": "package model\n\nimport \"gorm.io/gorm\"\n\ntype Action int\n\nconst (\n\tRUN Action = iota\n\tSTOP\n\tNORMAL\n)\n\ntype LogRecord struct {\n\tgorm.Model\n\tAction      Action `json:\"action\"`\n\tClusterName string `json:\"clusterName\"`\n\tLevelName   string `json:\"levelName\"`\n}\n"
  },
  {
    "path": "internal/model/announce.go",
    "content": "package model\n\nimport \"gorm.io/gorm\"\n\ntype Announce struct {\n\tgorm.Model\n\tEnable       bool   `json:\"enable\"`\n\tFrequency    int64  `json:\"frequency\"`\n\tInterval     int64  `json:\"interval\"`\n\tIntervalUnit string `json:\"intervalUnit\"`\n\tMethod       string `json:\"method\"`\n\tContent      string `json:\"content\"`\n}\n"
  },
  {
    "path": "internal/model/autoCheck.go",
    "content": "package model\n\nimport \"gorm.io/gorm\"\n\ntype AutoCheck struct {\n\tgorm.Model\n\tName         string `json:\"name\"`\n\tClusterName  string `json:\"clusterName\"`\n\tLevelName    string `json:\"levelName\"`\n\tUuid         string `json:\"uuid\"`\n\tEnable       int    `json:\"enable\"`\n\tAnnouncement string `json:\"announcement\"`\n\tTimes        int    `json:\"times\"`\n\tSleep        int    `json:\"sleep\"`\n\tInterval     int    `json:\"interval\"`\n\tCheckType    string `json:\"checkType\"`\n}\n"
  },
  {
    "path": "internal/model/backup.go",
    "content": "package model\n\nimport \"gorm.io/gorm\"\n\ntype Backup struct {\n\tgorm.Model\n\tName        string `json:\"name\"`\n\tDescription string `json:\"description\"`\n\tPath        string `json:\"Path\"`\n\tSize        string `json:\"size\"`\n\tDays        string `json:\"days\"`\n\tSeason      bool   `json:\"season\"`\n}\n"
  },
  {
    "path": "internal/model/backupSnapshot.go",
    "content": "package model\n\nimport \"gorm.io/gorm\"\n\ntype BackupSnapshot struct {\n\tgorm.Model\n\tName         string `json:\"name\"`\n\tInterval     int    `json:\"interval\"`\n\tMaxSnapshots int    `json:\"maxSnapshots\"`\n\tEnable       int    `json:\"enable\"`\n\tIsCSave      int    `json:\"isCSave\"`\n}\n"
  },
  {
    "path": "internal/model/cluster.go",
    "content": "package model\n\nimport \"gorm.io/gorm\"\n\ntype Cluster struct {\n\tgorm.Model\n\tClusterName     string `gorm:\"uniqueIndex\" json:\"clusterName\"`\n\tDescription     string `json:\"description\"`\n\tSteamCmd        string `json:\"steamcmd\"`\n\tForceInstallDir string `json:\"force_install_dir\"`\n\tBackup          string `json:\"backup\"`\n\tModDownloadPath string `json:\"mod_download_path\"`\n\tUuid            string `json:\"uuid\"`\n\tBeta            int    `json:\"beta\"`\n\tBin             int    `json:\"bin\"`\n\n\tUgc_directory           string `json:\"ugc_directory\"`\n\tPersistent_storage_root string `json:\"persistent_storage_root\"`\n\tConf_dir                string `json:\"conf_dir\"`\n}\n"
  },
  {
    "path": "internal/model/connect.go",
    "content": "package model\n\nimport \"gorm.io/gorm\"\n\ntype Connect struct {\n\tgorm.Model\n\tIp          string\n\tName        string\n\tKuId        string\n\tSteamId     string\n\tTime        string\n\tClusterName string\n\tSessionFile string\n}\n"
  },
  {
    "path": "internal/model/jobTask.go",
    "content": "package model\n\nimport \"gorm.io/gorm\"\n\ntype JobTask struct {\n\tgorm.Model\n\tClusterName  string `json:\"clusterName\"`\n\tLevelName    string `json:\"levelName\"`\n\tUuid         string `json:\"uuid\"`\n\tCron         string `json:\"cron\"`\n\tCategory     string `json:\"category\"`\n\tComment      string `json:\"comment\"`\n\tAnnouncement string `json:\"announcement\"`\n\tSleep        int    `json:\"sleep\"`\n\tTimes        int    `json:\"times\"`\n\tScript       int    `json:\"script\"`\n}\n"
  },
  {
    "path": "internal/model/kv.go",
    "content": "package model\n\nimport \"gorm.io/gorm\"\n\ntype KV struct {\n\tgorm.Model\n\tKey   string `json:\"key\"`\n\tValue string `json:\"value\"`\n}\n"
  },
  {
    "path": "internal/model/modInfo.go",
    "content": "package model\n\nimport \"gorm.io/gorm\"\n\ntype ModInfo struct {\n\tgorm.Model\n\tAuth          string  `json:\"auth\"`\n\tConsumerAppid float64 `json:\"consumer_appid\"`\n\tCreatorAppid  float64 `json:\"creator_appid\"`\n\tDescription   string  `json:\"description\"`\n\tFileUrl       string  `json:\"file_url\"`\n\tModid         string  `json:\"modid\"`\n\tImg           string  `json:\"img\"`\n\tLastTime      float64 `json:\"last_time\"`\n\tModConfig     string  `gorm:\"TYPE:json\" json:\"mod_config\"`\n\tName          string  `json:\"name\"`\n\tV             string  `json:\"v\"`\n\tUpdate        bool    `json:\"update\"`\n}\n"
  },
  {
    "path": "internal/model/modKv.go",
    "content": "package model\n\nimport \"gorm.io/gorm\"\n\ntype ModKV struct {\n\tgorm.Model\n\tUserId  string `json:\"userId\"`\n\tModId   int    `json:\"modId\"`\n\tConfig  string `json:\"config\"`\n\tVersion string `json:\"version\"`\n}\n"
  },
  {
    "path": "internal/model/model.go",
    "content": "// Package model defines the data models used by the application.\npackage model\n"
  },
  {
    "path": "internal/model/playerLog.go",
    "content": "package model\n\nimport \"gorm.io/gorm\"\n\ntype PlayerLog struct {\n\tgorm.Model\n\tName        string `json:\"name\"`\n\tRole        string `json:\"role\"`\n\tKuId        string `json:\"kuId\"`\n\tSteamId     string `json:\"steamId\"`\n\tTime        string `json:\"time\"`\n\tAction      string `json:\"action\"`\n\tActionDesc  string `json:\"actionDesc\"`\n\tIp          string `json:\"ip\"`\n\tClusterName string `json:\"clusterName\"`\n}\n"
  },
  {
    "path": "internal/model/regenerate.go",
    "content": "package model\n\nimport \"gorm.io/gorm\"\n\ntype Regenerate struct {\n\tgorm.Model\n\tClusterName string `json:\"clusterName\"`\n}\n"
  },
  {
    "path": "internal/model/spawnRole.go",
    "content": "package model\n\nimport \"gorm.io/gorm\"\n\ntype Spawn struct {\n\tgorm.Model\n\tName        string\n\tRole        string\n\tTime        string\n\tClusterName string\n}\n"
  },
  {
    "path": "internal/model/webLink.go",
    "content": "package model\n\nimport \"gorm.io/gorm\"\n\ntype WebLink struct {\n\tgorm.Model\n\tTitle  string `json:\"title\"`\n\tUrl    string `json:\"url\"`\n\tWidth  string `json:\"width\"`\n\tHeight string `json:\"height\"`\n}\n"
  },
  {
    "path": "internal/pkg/context/cluster.go",
    "content": "package context\n\nimport (\n\t\"dst-admin-go/internal/service/dstConfig\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nconst (\n\tclusterNameKey = \"cluster_name\"\n\tdstConfigKey   = \"dst_config\"\n)\n\n// GetClusterName 从 gin.Context 获取集群名称\n// 需要配合 ClusterMiddleware 使用\nfunc GetClusterName(c *gin.Context) string {\n\tif value, exists := c.Get(clusterNameKey); exists {\n\t\tif clusterName, ok := value.(string); ok {\n\t\t\treturn clusterName\n\t\t}\n\t}\n\treturn \"\"\n}\n\n// GetDstConfig 从 gin.Context 获取 DstConfig 对象\n// 需要配合 ClusterMiddleware 使用\nfunc GetDstConfig(c *gin.Context) *dstConfig.DstConfig {\n\tif value, exists := c.Get(dstConfigKey); exists {\n\t\tif config, ok := value.(dstConfig.DstConfig); ok {\n\t\t\treturn &config\n\t\t}\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "internal/pkg/response/response.go",
    "content": "package response\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype Response struct {\n\tCode int         `json:\"code\"` //提示代码\n\tMsg  string      `json:\"msg\"`  //提示信息\n\tData interface{} `json:\"data\"` //数据\n}\n\ntype Page struct {\n\tData       interface{} `json:\"data\"`\n\tTotal      int64       `json:\"total\"`\n\tTotalPages int64       `json:\"totalPages\"`\n\tPage       int         `json:\"page\"`\n\tSize       int         `json:\"size\"`\n}\n\n// OkWithData 成功响应带数据\nfunc OkWithData(data interface{}, ctx *gin.Context) {\n\tctx.JSON(http.StatusOK, Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: data,\n\t})\n}\n\n// OkWithMessage 成功响应带消息\nfunc OkWithMessage(message string, ctx *gin.Context) {\n\tctx.JSON(http.StatusOK, Response{\n\t\tCode: 200,\n\t\tMsg:  message,\n\t\tData: nil,\n\t})\n}\n\n// FailWithMessage 失败响应带消息\nfunc FailWithMessage(message string, ctx *gin.Context) {\n\tctx.JSON(http.StatusOK, Response{\n\t\tCode: 500,\n\t\tMsg:  message,\n\t\tData: nil,\n\t})\n}\n\n// OkWithPage 成功响应带分页数据\nfunc OkWithPage(data interface{}, total, page, size int64, ctx *gin.Context) {\n\ttotalPages := (total + size - 1) / size\n\tctx.JSON(http.StatusOK, Response{\n\t\tCode: 200,\n\t\tMsg:  \"success\",\n\t\tData: Page{\n\t\t\tData:       data,\n\t\t\tTotal:      total,\n\t\t\tTotalPages: totalPages,\n\t\t\tPage:       int(page),\n\t\t\tSize:       int(size),\n\t\t},\n\t})\n}\n"
  },
  {
    "path": "internal/pkg/utils/collectionUtils/collectionUtils.go",
    "content": "package collectionUtils\n\nimport \"log\"\n\nfunc ToSet(list []string) []string {\n\n\tvar m = map[string]string{}\n\tvar set []string\n\n\tfor i, _ := range list {\n\t\tkey := list[i]\n\t\tlog.Println(\"key\", key)\n\t\t_, ok := m[key]\n\t\tif !ok {\n\t\t\tm[key] = key\n\t\t\tset = append(set, key)\n\t\t}\n\t}\n\treturn set\n}\n"
  },
  {
    "path": "internal/pkg/utils/dateUtils.go",
    "content": "package utils\n\nimport (\n\t\"time\"\n)\n\nfunc Bod(t time.Time) time.Time {\n\tyear, month, day := t.Date()\n\treturn time.Date(year, month, day, 0, 0, 0, 0, t.Location())\n}\n\nfunc Truncate(t time.Time) time.Time {\n\treturn t.Truncate(24 * time.Hour)\n}\n\nfunc Get_stamp_day(start_time, end_time time.Time) (args []int64) {\n\n\tt1 := Bod(start_time)\n\tt2 := Bod(end_time)\n\n\tsInt := t1.UnixMilli() - 8*60*60*1000\n\teInt := t2.UnixMilli() - 8*60*60*1000\n\n\targs = append(args, sInt)\n\tfor {\n\t\tsInt += 86400 * 1000\n\t\tif sInt > eInt {\n\t\t\treturn\n\t\t}\n\t\targs = append(args, sInt)\n\t}\n}\n\nfunc Get_stamp_month(start_time, end_time time.Time) (args []int64) {\n\n\tt1 := Bod(start_time)\n\tt2 := Bod(end_time)\n\n\tsInt := t1.Unix()\n\teInt := t2.Unix()\n\targs = append(args, sInt)\n\tfor {\n\t\tsInt += 2592000000\n\t\tif sInt > eInt {\n\t\t\treturn\n\t\t}\n\t\targs = append(args, sInt)\n\t}\n}\n"
  },
  {
    "path": "internal/pkg/utils/dstUtils/dstUtils.go",
    "content": "package dstUtils\n\nimport (\n\t\"bytes\"\n\t\"dst-admin-go/internal/pkg/utils/fileUtils\"\n\t\"dst-admin-go/internal/service/dstConfig\"\n\t\"io/ioutil\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strings\"\n\ttextTemplate \"text/template\"\n)\n\nfunc EscapePath(path string) string {\n\tif runtime.GOOS == \"windows\" {\n\t\treturn path\n\t}\n\t// 在这里添加需要转义的特殊字符\n\tescapedChars := []string{\" \", \"'\", \"(\", \")\"}\n\tfor _, char := range escapedChars {\n\t\tpath = strings.ReplaceAll(path, char, \"\\\\\"+char)\n\t}\n\treturn path\n}\n\nfunc WorkshopIds(content string) []string {\n\tvar workshopIds []string\n\n\tre := regexp.MustCompile(\"\\\"workshop-\\\\w[-\\\\w+]*\\\"\")\n\tworkshops := re.FindAllString(content, -1)\n\n\tfor _, workshop := range workshops {\n\t\tworkshop = strings.Replace(workshop, \"\\\"\", \"\", -1)\n\t\tsplit := strings.Split(workshop, \"-\")\n\t\tworkshopId := strings.TrimSpace(split[1])\n\t\tworkshopIds = append(workshopIds, workshopId)\n\t}\n\treturn workshopIds\n}\n\nfunc DedicatedServerModsSetup(dstConfig dstConfig.DstConfig, modConfig string) error {\n\tif modConfig != \"\" {\n\t\tvar serverModSetup []string\n\t\tworkshopIds := WorkshopIds(modConfig)\n\t\tfor _, workshopId := range workshopIds {\n\t\t\tserverModSetup = append(serverModSetup, \"ServerModSetup(\\\"\"+workshopId+\"\\\")\")\n\t\t}\n\t\tmodSetupPath := GetModSetup2(dstConfig)\n\t\tmods, err := fileUtils.ReadLnFile(modSetupPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar newServerModSetup []string\n\t\tfor i := range serverModSetup {\n\t\t\tvar notFind = true\n\t\t\tfor j := range mods {\n\t\t\t\tif serverModSetup[i] == mods[j] {\n\t\t\t\t\tnotFind = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif notFind {\n\t\t\t\tnewServerModSetup = append(newServerModSetup, serverModSetup[i])\n\t\t\t}\n\t\t}\n\t\tnewServerModSetup = append(newServerModSetup, mods...)\n\t\terr = fileUtils.WriterLnFile(modSetupPath, newServerModSetup)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GetModSetup2(dstConfig dstConfig.DstConfig) string {\n\treturn filepath.Join(dstConfig.Force_install_dir, \"mods\", \"dedicated_server_mods_setup.lua\")\n}\n\nfunc ParseTemplate(templatePath string, data interface{}) string {\n\n\t// 读取文件内容\n\tcontent, err := ioutil.ReadFile(templatePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// 创建模板对象\n\ttmpl, err := textTemplate.New(\"myTemplate\").Parse(string(content))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// 执行模板并保存结果到字符串\n\tbuf := new(bytes.Buffer)\n\terr = tmpl.Execute(buf, data)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn buf.String()\n\n}\n"
  },
  {
    "path": "internal/pkg/utils/envUtils.go",
    "content": "package utils\n\nimport \"runtime\"\n\nfunc IsWindow() bool {\n\tos := runtime.GOOS\n\treturn os == \"windows\"\n}\n"
  },
  {
    "path": "internal/pkg/utils/fileUtils/fileUtls.go",
    "content": "package fileUtils\n\nimport (\n\t\"bufio\"\n\t\"dst-admin-go/internal/pkg/utils/systemUtils\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n)\n\nfunc Exists(path string) bool {\n\t_, err := os.Stat(path)\n\tif err != nil {\n\t\treturn os.IsExist(err)\n\t}\n\treturn true\n}\n\nfunc IsDir(path string) bool {\n\ts, err := os.Stat(path)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn s.IsDir()\n}\n\nfunc IsFile(path string) bool {\n\treturn !IsDir(path)\n}\n\nfunc CreateDir(dirName string) bool {\n\tif dirName == \"\" {\n\t\treturn false\n\t}\n\tif Exists(dirName) {\n\t\treturn false\n\t}\n\terr := os.MkdirAll(dirName, 0755)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc CreateFile(fileName string) error {\n\tf, err := os.Create(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\treturn err\n}\n\nfunc WriterTXT(filename, content string) error {\n\t// 写入文件\n\t// 判断文件是否存在\n\tvar file *os.File\n\tif _, err := os.Stat(filename); os.IsNotExist(err) {\n\n\t\tfile, err = os.Create(filename)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\n\t} else {\n\t\t//O_APPEND\n\t\tfile, err = os.OpenFile(filename, os.O_RDWR|os.O_TRUNC, 0666)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tdefer file.Close()\n\n\tw := bufio.NewWriter(file)\n\t_, err2 := w.WriteString(content)\n\tif err2 != nil {\n\t\treturn err2\n\t}\n\tw.Flush()\n\tfile.Sync()\n\treturn nil\n\n}\n\nfunc ReadLnFile(filePath string) ([]string, error) {\n\n\t//打开文件\n\tfi, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer fi.Close()\n\n\tbuf := bufio.NewScanner(fi)\n\t// 循环读取\n\tvar lineArr []string\n\tfor {\n\t\tif !buf.Scan() {\n\t\t\tbreak //文件读完了,退出for\n\t\t}\n\t\tline := buf.Text() //获取每一行\n\t\tlineArr = append(lineArr, line)\n\t}\n\n\treturn lineArr, nil\n}\n\nfunc ReadFile(filePath string) (string, error) {\n\n\tdata, err := os.ReadFile(filePath)\n\tif err != nil {\n\t\tfmt.Println(\"File reading error: \", err)\n\t\treturn \"\", err\n\t}\n\treturn string(data), err\n}\n\nfunc WriterLnFile(filename string, lines []string) error {\n\n\tvar file *os.File\n\tif _, err := os.Stat(filename); os.IsNotExist(err) {\n\n\t\tfile, err = os.Create(filename)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\n\t} else {\n\t\t//O_APPEND\n\t\tfile, err = os.OpenFile(filename, os.O_RDWR|os.O_TRUNC, 0666)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tdefer file.Close()\n\tw := bufio.NewWriter(file)\n\tfor _, v := range lines {\n\t\tfmt.Fprintln(w, v)\n\t}\n\treturn w.Flush()\n}\n\nfunc ReverseRead(filename string, lineNum uint) ([]string, error) {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\t//获取文件大小\n\tfs, err := file.Stat()\n\tfileSize := fs.Size()\n\n\tvar offset int64 = -1   //偏移量，初始化为-1，若为0则会读到EOF\n\tchar := make([]byte, 1) //用于读取单个字节\n\tlineStr := \"\"           //存放一行的数据\n\tbuff := make([]string, 0, 100)\n\tfor (-offset) <= fileSize {\n\t\t//通过Seek函数从末尾移动游标然后每次读取一个字节\n\t\tfile.Seek(offset, io.SeekEnd)\n\t\t_, err := file.Read(char)\n\t\tif err != nil {\n\t\t\treturn buff, err\n\t\t}\n\t\tif char[0] == '\\n' {\n\t\t\t// offset--  //windows跳过'\\r'\n\t\t\tlineNum-- //到此读取完一行\n\t\t\tbuff = append(buff, lineStr)\n\t\t\tlineStr = \"\"\n\t\t\tif lineNum == 0 {\n\t\t\t\treturn buff, nil\n\t\t\t}\n\t\t} else {\n\t\t\tlineStr = string(char) + lineStr\n\t\t}\n\t\toffset--\n\t}\n\tbuff = append(buff, lineStr)\n\treturn buff, nil\n}\n\nfunc DeleteFile(path string) error {\n\terr := os.Remove(path)\n\tif err != nil {\n\t\tlog.Printf(\"remove \"+path+\" : %v\\n\", err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc DeleteDir(path string) error {\n\thome, err := systemUtils.Home()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif path == filepath.Join(home, \".klei/DoNotStarveTogether\") {\n\t\treturn errors.New(\".klei/DoNotStarveTogether not allow to delete\")\n\t}\n\terr = os.RemoveAll(path)\n\tif err != nil {\n\t\tlog.Printf(\"remove err \"+path+\" : %v\\n\", err)\n\t}\n\treturn err\n}\n\nfunc Rename(filePath, newName string) (err error) {\n\terr = os.Rename(filePath, newName)\n\treturn\n}\n\nfunc FindWorldDirs(rootPath string) ([]string, error) {\n\tvar dirs []string\n\n\t// 遍历目录并列出满足条件的目录\n\terr := filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// 如果是目录且名称包含 master 或 caves（不区分大小写）\n\t\tif info.IsDir() && (strings.Contains(strings.ToLower(info.Name()), \"master\") || strings.Contains(strings.ToLower(info.Name()), \"caves\")) {\n\t\t\tdirs = append(dirs, path)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn dirs, nil\n}\n\nfunc ListDirectories(root string) ([]string, error) {\n\tvar dirs []string\n\n\terr := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif info.IsDir() {\n\t\t\tdirs = append(dirs, path)\n\t\t}\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsort.Slice(dirs, func(i, j int) bool {\n\t\tfi, err := os.Stat(dirs[i])\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tfj, err := os.Stat(dirs[j])\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\treturn fi.ModTime().Before(fj.ModTime())\n\t})\n\n\treturn dirs, nil\n}\n\nfunc CreateFileIfNotExists(path string) error {\n\n\t// 检查文件是否存在\n\t_, err := os.Stat(path)\n\tif err == nil {\n\t\t// 文件已经存在，直接返回\n\t\treturn nil\n\t}\n\tif !os.IsNotExist(err) {\n\t\t// 其他错误，返回错误信息\n\t\treturn err\n\t}\n\n\t// 创建文件所在的目录\n\tdir := filepath.Dir(path)\n\terr = os.MkdirAll(dir, 0755)\n\tif err != nil {\n\t\t// 创建目录失败，返回错误信息\n\t\treturn err\n\t}\n\n\t// 创建文件\n\t_, err = os.Create(path)\n\tif err != nil {\n\t\t// 创建文件失败，返回错误信息\n\t\treturn err\n\t}\n\n\t// 创建成功，返回 nil\n\treturn nil\n}\n\nfunc CreateDirIfNotExists(filepath string) {\n\tif !Exists(filepath) {\n\t\tCreateDir(filepath)\n\t}\n}\n\nfunc Copy(srcPath, outFileDir string) error {\n\n\tsrcInfo, err := os.Stat(srcPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// 如果源文件是目录，则递归复制目录\n\tif srcInfo.IsDir() {\n\t\t// 创建目标目录（如果不存在）\n\t\terr = os.MkdirAll(outFileDir, srcInfo.Mode())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// 遍历源目录中的所有文件和子目录，并递归复制它们\n\t\tsrcDir, err := os.Open(srcPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer srcDir.Close()\n\n\t\tfiles, err := srcDir.Readdir(-1)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, file := range files {\n\t\t\tsrcFilePath := filepath.Join(srcPath, file.Name())\n\t\t\toutFilePath := filepath.Join(outFileDir, filepath.Base(srcPath))\n\t\t\terr = Copy(srcFilePath, outFilePath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n\n\treturn copyHelper(srcPath, outFileDir)\n}\n\nfunc copyHelper(srcPath, outFileDir string) error {\n\t// 打开源文件\n\tsrcFile, err := os.Open(srcPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer srcFile.Close()\n\n\t// 创建目标目录（如果不存在）\n\terr = os.MkdirAll(outFileDir, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// 创建目标文件\n\toutFilePath := filepath.Join(outFileDir, filepath.Base(srcPath))\n\toutFile, err := os.Create(outFilePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer outFile.Close()\n\n\t// 复制数据\n\t_, err = io.Copy(outFile, srcFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "internal/pkg/utils/luaUtils/luaUtils.go",
    "content": "package luaUtils\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"reflect\"\n\n\tlua \"github.com/yuin/gopher-lua\"\n)\n\ntype Clock struct {\n\tTotalTimeInPhase     int     `lua:\"totaltimeinphase\"`\n\tCycles               int     `lua:\"cycles\"`\n\tPhase                string  `lua:\"phase\"`\n\tRemainingTimeInPhase float64 `lua:\"remainingtimeinphase\"`\n\tMooomPhaseCycle      int     `lua:\"mooomphasecycle\"`\n\tSegs                 Segs    `lua:\"segs\"`\n}\n\ntype Segs struct {\n\tNight int `lua:\"night\"`\n\tDay   int `lua:\"day\"`\n\tDusk  int `lua:\"dusk\"`\n}\n\ntype IsRandom struct {\n\tSummer bool `lua:\"summer\"`\n\tAutumn bool `lua:\"autumn\"`\n\tSpring bool `lua:\"spring\"`\n\tWinter bool `lua:\"winter\"`\n}\n\ntype Lengths struct {\n\tSummer int `lua:\"summer\"`\n\tAutumn int `lua:\"autumn\"`\n\tSpring int `lua:\"spring\"`\n\tWinter int `lua:\"winter\"`\n}\n\ntype Seasons struct {\n\tPremode               bool                   `lua:\"premode\"`\n\tSeason                string                 `lua:\"season\"`\n\tElapsedDaysInSeason   int                    `lua:\"elapseddaysinseason\"`\n\tIsRandom              IsRandom               `lua:\"israndom\"`\n\tLengths               Lengths                `lua:\"lengths\"`\n\tRemainingDaysInSeason int                    `lua:\"remainingdaysinseason\"`\n\tMode                  string                 `lua:\"mode\"`\n\tTotalDaysInSeason     int                    `lua:\"totaldaysinseason\"`\n\tSegs                  map[string]interface{} `lua:\"segs\"`\n}\n\ntype Data struct {\n\tClock   Clock   `lua:\"clock\"`\n\tSeasons Seasons `lua:\"seasons\"`\n}\n\nfunc mapTableToStruct(table *lua.LTable, v reflect.Value) error {\n\tt := v.Type()\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tfieldType := t.Field(i)\n\t\ttag := fieldType.Tag.Get(\"lua\")\n\t\tif tag == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tvalue := table.RawGetString(tag)\n\t\tif value == lua.LNil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfieldValue := v.Field(i)\n\t\tswitch fieldValue.Kind() {\n\t\tcase reflect.Struct:\n\t\t\tif err := mapTableToStruct(value.(*lua.LTable), fieldValue); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase reflect.Map:\n\t\t\tmapType := fieldValue.Type()\n\t\t\tkeyType := mapType.Key()\n\t\t\tvalueType := mapType.Elem()\n\t\t\tmapValue := reflect.MakeMap(mapType)\n\n\t\t\ttableValue, ok := value.(*lua.LTable)\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"expected lua.LTable, got %T\", value)\n\t\t\t}\n\n\t\t\ttableValue.ForEach(func(key, value lua.LValue) {\n\t\t\t\tmapKey := reflect.New(keyType).Elem()\n\t\t\t\terr := luaValueToValue(key, mapKey)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tmapValue := reflect.New(valueType).Elem()\n\t\t\t\terr = luaValueToValue(value, mapValue)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tmapValue.Set(mapValue)\n\t\t\t})\n\n\t\t\tfieldValue.Set(mapValue)\n\t\tdefault:\n\t\t\tif err := luaValueToValue(value, fieldValue); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc luaValueToValue(lv lua.LValue, v reflect.Value) error {\n\tswitch v.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\tif lv.Type() != lua.LTNumber {\n\t\t\treturn fmt.Errorf(\"expected lua.LNumber, got %T\", lv)\n\t\t}\n\t\tv.SetInt(int64(lv.(lua.LNumber)))\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\tif lv.Type() != lua.LTNumber {\n\t\t\treturn fmt.Errorf(\"expected lua.LNumber, got %T\", lv)\n\t\t}\n\t\tv.SetUint(uint64(lv.(lua.LNumber)))\n\tcase reflect.Float32, reflect.Float64:\n\t\tif lv.Type() != lua.LTNumber {\n\t\t\treturn fmt.Errorf(\"expected lua.LNumber, got %T\", lv)\n\t\t}\n\t\tv.SetFloat(float64(lv.(lua.LNumber)))\n\tcase reflect.Bool:\n\t\tif lv.Type() != lua.LTBool {\n\t\t\treturn fmt.Errorf(\"expected lua.LBool, got %T\", lv)\n\t\t}\n\t\tv.SetBool(bool(lv.(lua.LBool)))\n\tcase reflect.String:\n\t\tif lv.Type() != lua.LTString {\n\t\t\treturn fmt.Errorf(\"expected lua.LString, got %T\", lv)\n\t\t}\n\t\tv.SetString(string(lv.(lua.LString)))\n\tcase reflect.Map:\n\t\tif lv.Type() != lua.LTTable {\n\t\t\treturn fmt.Errorf(\"expected lua.LTable, got %T\", lv)\n\t\t}\n\n\t\tmapType := v.Type()\n\t\tkeyType := mapType.Key()\n\t\tvalueType := mapType.Elem()\n\t\tmapValue := reflect.MakeMap(mapType)\n\n\t\ttable := lv.(*lua.LTable)\n\t\ttable.ForEach(func(key, value lua.LValue) {\n\t\t\tmapKey := reflect.New(keyType).Elem()\n\t\t\terr := luaValueToValue(key, mapKey)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tmapValue := reflect.New(valueType).Elem()\n\t\t\terr = luaValueToValue(value, mapValue)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tmapValue.Set(mapValue)\n\t\t})\n\n\t\tv.Set(mapValue)\n\tdefault:\n\t\treturn fmt.Errorf(\"unsupported kind: %v\", v.Kind())\n\t}\n\n\treturn nil\n}\n\nfunc mapTableToMap(table *lua.LTable, m map[string]interface{}) {\n\ttable.ForEach(func(key, value lua.LValue) {\n\t\tkeyStr := key.String()\n\n\t\tswitch value.Type() {\n\t\tcase lua.LTTable:\n\t\t\tnestedTable := value.(*lua.LTable)\n\t\t\tnestedMap := map[string]interface{}{}\n\t\t\tmapTableToMap(nestedTable, nestedMap)\n\t\t\tm[keyStr] = nestedMap\n\t\tcase lua.LTNumber:\n\t\t\tm[keyStr] = float64(value.(lua.LNumber))\n\t\tcase lua.LTString:\n\t\t\tm[keyStr] = string(value.(lua.LString))\n\t\tcase lua.LTBool:\n\t\t\tm[keyStr] = bool(value.(lua.LBool))\n\t\tdefault:\n\t\t\tm[keyStr] = nil\n\t\t}\n\t})\n}\n\nfunc LuaTable2Map(script string) (map[string]interface{}, error) {\n\tL := lua.NewState()\n\tdefer L.Close()\n\n\terr := L.DoString(script)\n\tif err != nil {\n\t\treturn map[string]interface{}{}, err\n\t}\n\ttable := L.Get(-1)\n\tL.Pop(1)\n\tdata := map[string]interface{}{}\n\tmapTableToMap(table.(*lua.LTable), data)\n\treturn data, nil\n}\n\nfunc LuaTable2Struct(script string, v reflect.Value) error {\n\tL := lua.NewState()\n\tdefer L.Close()\n\n\terr := L.DoString(script)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\n\ttable := L.Get(-1)\n\tL.Pop(1)\n\n\terr = mapTableToStruct(table.(*lua.LTable), v)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "internal/pkg/utils/shellUtils/shellUitls.go",
    "content": "package shellUtils\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\n\t\"golang.org/x/text/encoding/simplifiedchinese\"\n)\n\nfunc ExecuteCommandInWin(command string) (string, error) {\n\tcmd := exec.Command(\"cmd\", \"/C\", command)\n\toutput, err := cmd.Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(output), nil\n}\n\n// ExecuteCommand 执行给定的 Shell 命令，并返回输出和错误（如果有的话）。\nfunc ExecuteCommand(command string) (string, error) {\n\tcmd := exec.Command(\"sh\", \"-c\", command)\n\tvar out bytes.Buffer\n\tvar stderr bytes.Buffer\n\tcmd.Stdout = &out\n\tcmd.Stderr = &stderr\n\terr := cmd.Run()\n\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"run command error: %v, ERROR: %s\", err, stderr.String())\n\t}\n\tif stderr.String() != \"\" {\n\t\treturn \"\", fmt.Errorf(\"exec command error: %s\", stderr.String())\n\t}\n\treturn out.String(), nil\n}\n\n// 执行shell命令\nfunc Shell(cmd string) (res string, err error) {\n\t//var execCmd *exec.Cmd\n\t//if runtime.GOOS == \"windows\" {\n\t//\texecCmd = exec.Command(\"cmd.exe\", \"/c\", cmd)\n\t//} else {\n\t//\texecCmd = exec.Command(\"bash\", \"-c\", cmd)\n\t//}\n\t//var (\n\t//\tstdout bytes.Buffer\n\t//\tstderr bytes.Buffer\n\t//)\n\t//\n\t//execCmd.Stdout = &stdout\n\t//execCmd.Stderr = &stderr\n\t//err = execCmd.Run()\n\t//if err != nil {\n\t//\tlog.Println(\"error: \" + err.Error())\n\t//}\n\t//\n\t//output := ConvertByte2String(stderr.Bytes(), GB18030)\n\t//errput := ConvertByte2String(stdout.Bytes(), GB18030)\n\t////res = fmt.Sprintf(\"Output:\\n%s\\nError:\\n%s\", stdout.String(), stderr.String())\n\t//\n\t//// log.Printf(\"shell exec: %s \\nOutput:\\n%s\\nError:\\n%s\", cmd, output, errput)\n\t//if errput != \"\" {\n\t//\tlog.Printf(\"shell exec: %s Error:\\n%s\", cmd, errput)\n\t//}\n\t//if output != \"\" {\n\t//\tlog.Printf(\"shell exec: %s nOutput:\\n%s\", cmd, output)\n\t//}\n\t//\n\t//return stdout.String(), err\n\n\treturn ExecuteCommand(cmd)\n}\n\ntype Charset string\n\nconst (\n\tUTF8    = Charset(\"UTF-8\")\n\tGB18030 = Charset(\"GB18030\")\n)\n\nfunc ConvertByte2String(byte []byte, charset Charset) string {\n\n\tvar str string\n\tswitch charset {\n\tcase GB18030:\n\t\tdecodeBytes, _ := simplifiedchinese.GB18030.NewDecoder().Bytes(byte)\n\t\tstr = string(decodeBytes)\n\tcase UTF8:\n\t\tfallthrough\n\tdefault:\n\t\tstr = string(byte)\n\t}\n\treturn str\n}\n\nfunc Chmod(filePath string) error {\n\t// 获取文件的当前权限\n\tfileInfo, err := os.Stat(filePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// 添加可执行权限\n\tnewMode := fileInfo.Mode() | 0100\n\n\t// 更改文件权限\n\terr = os.Chmod(filePath, newMode)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "internal/pkg/utils/systemUtils/SystemUtils.go",
    "content": "package systemUtils\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"os/exec\"\n\t\"os/user\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com/shirou/gopsutil/cpu\"\n\t\"github.com/shirou/gopsutil/disk\"\n\t\"github.com/shirou/gopsutil/host\"\n\t\"github.com/shirou/gopsutil/mem\"\n)\n\n// Home returns the home directory for the executing user.\n//\n// This uses an OS-specific method for discovering the home directory.\n// An error is returned if a home directory cannot be detected.\nfunc Home() (string, error) {\n\tuser, err := user.Current()\n\tif nil == err {\n\t\treturn user.HomeDir, nil\n\t}\n\n\t// cross compile support\n\n\tif runtime.GOOS == \"windows\" {\n\t\treturn homeWindows()\n\t}\n\n\t// Unix-like system, so just assume Unix\n\treturn homeUnix()\n}\n\nfunc HomePath() string {\n\thome, err := Home()\n\tif err != nil {\n\t\tpanic(\"Home path error: \" + err.Error())\n\t}\n\treturn home\n}\n\nfunc homeUnix() (string, error) {\n\t// First prefer the HOME environmental variable\n\tif home := os.Getenv(\"HOME\"); home != \"\" {\n\t\treturn home, nil\n\t}\n\n\t// If that fails, try the shell\n\tvar stdout bytes.Buffer\n\tcmd := exec.Command(\"sh\", \"-c\", \"eval echo ~$USER\")\n\tcmd.Stdout = &stdout\n\tif err := cmd.Run(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresult := strings.TrimSpace(stdout.String())\n\tif result == \"\" {\n\t\treturn \"\", errors.New(\"blank output when reading home directory\")\n\t}\n\n\treturn result, nil\n}\n\nfunc homeWindows() (string, error) {\n\tdrive := os.Getenv(\"HOMEDRIVE\")\n\tpath := os.Getenv(\"HOMEPATH\")\n\thome := drive + path\n\tif drive == \"\" || path == \"\" {\n\t\thome = os.Getenv(\"USERPROFILE\")\n\t}\n\tif home == \"\" {\n\t\treturn \"\", errors.New(\"HOMEDRIVE, HOMEPATH, and USERPROFILE are blank\")\n\t}\n\n\treturn home, nil\n}\n\ntype HostInfo struct {\n\tOs         string `json:\"os\"`\n\tHostName   string `json:\"hostname\"`\n\tPlatform   string `json:\"platform\"`\n\tKernelArch string `json:\"kernelArch\"`\n}\n\ntype MemInfo struct {\n\tTotal       uint64  `json:\"total\"`\n\tAvailable   uint64  `json:\"available\"`\n\tUsed        uint64  `json:\"used\"`\n\tUsedPercent float64 `json:\"usedPercent\"`\n}\n\ntype CpuInfo struct {\n\tCores          int       `json:\"cores\"`\n\tCpuPercent     []float64 `json:\"cpuPercent\"`\n\tCpuUsedPercent float64   `json:\"cpuUsedPercent\"`\n\tCpuUsed        float64   `json:\"cpuUsed\"`\n}\n\ntype DiskInfo struct {\n\tDevices []deviceInfo `json:\"devices\"`\n}\ntype deviceInfo struct {\n\tDevice      string  `json:\"device\"`\n\tMountpoint  string  `json:\"mountpoint\"`\n\tFstype      string  `json:\"fstype\"`\n\tOpts        string  `json:\"opts\"`\n\tTotal       uint64  `json:\"total\"`\n\tUsage       float64 `json:\"usage\"`\n\tInodesUsage float64 `json:\"inodesUsage\"`\n}\n\nfunc GetDiskInfo() *DiskInfo {\n\t//info, _ := disk.IOCounters() //所有硬盘的io信息\n\tdiskPart, err := disk.Partitions(false)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\t// fmt.Println(diskPart)\n\tvar devices []deviceInfo\n\n\tfor _, dp := range diskPart {\n\t\tdevice := deviceInfo{\n\t\t\tDevice:     dp.Device,\n\t\t\tMountpoint: dp.Mountpoint,\n\t\t\tFstype:     dp.Fstype,\n\t\t\tOpts:       dp.Opts,\n\t\t}\n\n\t\tdiskUsed, _ := disk.Usage(dp.Mountpoint)\n\t\t// fmt.Printf(\"分区总大小: %d MB \\n\", diskUsed.Total/1024/1024)\n\t\t// fmt.Printf(\"分区使用率: %.3f %% \\n\", diskUsed.UsedPercent)\n\t\t// fmt.Printf(\"分区inode使用率: %.3f %% \\n\", diskUsed.InodesUsedPercent)\n\t\tdevice.Total = diskUsed.Total / 1024 / 1024\n\t\tdevice.Usage = diskUsed.UsedPercent\n\t\tdevice.InodesUsage = diskUsed.InodesUsedPercent\n\t\tdevices = append(devices, device)\n\t}\n\treturn &DiskInfo{\n\t\tDevices: devices,\n\t}\n}\n\nfunc GetCpuInfo() *CpuInfo {\n\tcpuInfo := &CpuInfo{}\n\tcpuPercent, _ := cpu.Percent(0, false)\n\tcpuInfo.Cores, _ = cpu.Counts(true)\n\tif len(cpuPercent) == 1 {\n\t\tcpuInfo.CpuUsedPercent = cpuPercent[0]\n\t\tcpuInfo.CpuUsed = cpuInfo.CpuUsedPercent * 0.01 * float64(cpuInfo.Cores)\n\t}\n\tcpuInfo.CpuPercent, _ = cpu.Percent(0, true)\n\treturn cpuInfo\n}\n\nfunc GetHostInfo() *HostInfo {\n\tinfo, _ := host.Info()\n\n\treturn &HostInfo{\n\t\tOs:         info.OS,\n\t\tHostName:   info.Hostname,\n\t\tPlatform:   info.Platform,\n\t\tKernelArch: info.KernelArch,\n\t}\n}\n\nfunc GetMemInfo() *MemInfo {\n\tv, _ := mem.VirtualMemory()\n\n\t// almost every return value is a struct\n\t//fmt.Printf(\"Total: %v, Free:%v, UsedPercent:%f%%\\n\", v.Total, v.Free, v.UsedPercent)\n\t// convert to JSON. String() is also implemented\n\t//fmt.Println(v)\n\n\treturn &MemInfo{\n\t\tTotal:       v.Total,\n\t\tAvailable:   v.Available,\n\t\tUsed:        v.Used,\n\t\tUsedPercent: v.UsedPercent,\n\t}\n}\n\nfunc GetPublicIP() (string, error) {\n\tresp, err := http.Get(\"https://api.ipify.org/\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\tip, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(ip), nil\n}\n"
  },
  {
    "path": "internal/pkg/utils/zip/zip.go",
    "content": "package zip\n\nimport (\n\t\"archive/zip\"\n\t\"errors\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nfunc zipDir(dirPath string, zipWriter *zip.Writer, basePath string) error {\n\tfileInfos, err := os.ReadDir(dirPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, fileInfo := range fileInfos {\n\t\tpath := filepath.Join(dirPath, fileInfo.Name())\n\t\tif fileInfo.IsDir() {\n\t\t\terr := zipDir(path, zipWriter, basePath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tfile, err := os.Open(path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer file.Close()\n\n\t\t\trelPath, err := filepath.Rel(basePath, path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tzipEntry, err := zipWriter.Create(filepath.ToSlash(relPath))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t_, err = io.Copy(zipEntry, file)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc Zip(sourceDir, targetZip string) error {\n\tzipFile, err := os.Create(targetZip)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer zipFile.Close()\n\n\tzipWriter := zip.NewWriter(zipFile)\n\tdefer zipWriter.Close()\n\n\tbasePath := filepath.Dir(sourceDir)\n\n\terr = zipDir(sourceDir, zipWriter, basePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc Unzip(zipFile, destDir string) error {\n\treader, err := zip.OpenReader(zipFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer reader.Close()\n\n\tfor _, file := range reader.File {\n\t\tpath := filepath.Join(destDir, file.Name)\n\n\t\tif file.FileInfo().IsDir() {\n\t\t\terr = os.MkdirAll(path, os.ModePerm)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\terr = os.MkdirAll(filepath.Dir(path), os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tzipEntry, err := file.Open()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer zipEntry.Close()\n\n\t\ttargetFile, err := os.Create(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer targetFile.Close()\n\n\t\t_, err = io.Copy(targetFile, zipEntry)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc Unzip3(source, destination string) error {\n\treader, err := zip.OpenReader(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer reader.Close()\n\n\tvar clusterIniPath string\n\tfor _, file := range reader.File {\n\t\tif strings.HasSuffix(file.Name, \"cluster.ini\") {\n\t\t\tclusterIniPath = file.Name\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif clusterIniPath == \"\" {\n\t\treturn errors.New(\"压缩包中缺少 cluster.ini 文件\")\n\t}\n\n\tclusterPath := filepath.Dir(clusterIniPath)\n\tclusterPath = strings.TrimSuffix(clusterPath, \"/\")\n\tclusterPath = strings.TrimSuffix(clusterPath, \"\\\\\")\n\tlog.Println(\"clusterPath\", clusterPath)\n\tfor _, file := range reader.File {\n\t\t// 获取相对路径\n\t\trelativePath := strings.TrimPrefix(file.Name, clusterPath)\n\t\trelativePath = strings.TrimPrefix(relativePath, \"/\")\n\t\trelativePath = strings.TrimPrefix(relativePath, \"\\\\\")\n\n\t\textractedFilePath := filepath.Join(destination, relativePath)\n\t\tlog.Println(\"extractedFilePath\", extractedFilePath)\n\t\tif file.FileInfo().IsDir() {\n\t\t\tos.MkdirAll(extractedFilePath, os.ModePerm)\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := os.MkdirAll(filepath.Dir(extractedFilePath), os.ModePerm); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\twriter, err := os.Create(extractedFilePath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer writer.Close()\n\n\t\treader, err := file.Open()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer reader.Close()\n\n\t\tif _, err := io.Copy(writer, reader); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n//func Unzip3(source, destination string) error {\n//\treader, err := zip.OpenReader(source)\n//\tif err != nil {\n//\t\treturn err\n//\t}\n//\tdefer reader.Close()\n//\n//\tfor _, file := range reader.File {\n//\t\tfilePath := filepath.Join(destination, file.Name)\n//\t\tif file.FileInfo().IsDir() {\n//\t\t\tos.MkdirAll(filePath, os.ModePerm)\n//\t\t\tcontinue\n//\t\t}\n//\n//\t\tif err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {\n//\t\t\treturn err\n//\t\t}\n//\n//\t\twriter, err := os.Create(filePath)\n//\t\tif err != nil {\n//\t\t\treturn err\n//\t\t}\n//\t\tdefer writer.Close()\n//\n//\t\treader, err := file.Open()\n//\t\tif err != nil {\n//\t\t\treturn err\n//\t\t}\n//\t\tdefer reader.Close()\n//\n//\t\tif _, err := io.Copy(writer, reader); err != nil {\n//\t\t\treturn err\n//\t\t}\n//\t}\n//\n//\treturn nil\n//}\n\nfunc Unzip2(zipFile, destDir, newName string) error {\n\tr, err := zip.OpenReader(zipFile)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tdefer r.Close()\n\n\tfor _, f := range r.File {\n\n\t\tif f.Name == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tparts := strings.Split(f.Name, string(filepath.Separator)) // 使用路径分隔符拆分路径\n\t\textractedFilePath := \"\"\n\t\tif newName == parts[0] {\n\t\t\tparts = parts[1:]                  // 去掉第一个部分，即一级目录\n\t\t\tnewPath := filepath.Join(parts...) // 组合新的路径\n\t\t\t// 构建解压后的文件路径\n\t\t\textractedFilePath = filepath.Join(destDir, newName, newPath)\n\t\t} else {\n\t\t\textractedFilePath = filepath.Join(destDir, newName, f.Name)\n\t\t}\n\n\t\tlog.Println(\">>> \", f.Name, extractedFilePath)\n\t\tif f.FileInfo().IsDir() {\n\t\t\t// 创建目录\n\t\t\tos.MkdirAll(extractedFilePath, os.ModePerm)\n\t\t\tcontinue\n\t\t}\n\n\t\t// 创建解压后的文件\n\t\tif err := os.MkdirAll(filepath.Dir(extractedFilePath), os.ModePerm); err != nil {\n\t\t\treturn err\n\t\t}\n\t\toutFile, err := os.OpenFile(extractedFilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn err\n\t\t}\n\t\tdefer outFile.Close()\n\n\t\t// 打开压缩文件中的文件\n\t\trc, err := f.Open()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn err\n\t\t}\n\t\tdefer rc.Close()\n\n\t\t// 将压缩文件中的内容复制到解压文件中\n\t\t_, err = io.Copy(outFile, rc)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "internal/service/archive/path_resolver.go",
    "content": "package archive\n\nimport (\n\t\"dst-admin-go/internal/pkg/utils/fileUtils\"\n\t\"dst-admin-go/internal/service/dstConfig\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype PathResolver struct {\n\thomePath  string\n\tdstConfig dstConfig.Config\n}\n\nfunc NewPathResolver(dstConfig dstConfig.Config) (*PathResolver, error) {\n\thome, err := os.UserHomeDir()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &PathResolver{\n\t\thomePath:  home,\n\t\tdstConfig: dstConfig,\n\t}, nil\n}\n\nfunc (r *PathResolver) KleiBasePath(clusterName string) string {\n\tconfig, err := r.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tpersistentStorageRoot := config.Persistent_storage_root\n\tconfDir := config.Conf_dir\n\tif persistentStorageRoot != \"\" {\n\t\tif confDir == \"\" {\n\t\t\tconfDir = \"DoNotStarveTogether\"\n\t\t}\n\t\tkleiDstPath := filepath.Join(persistentStorageRoot, confDir)\n\t\treturn kleiDstPath\n\t}\n\n\tif runtime.GOOS == \"windows\" {\n\t\treturn filepath.Join(\n\t\t\tr.homePath,\n\t\t\t\"Documents\",\n\t\t\t\"klei\",\n\t\t\t\"DoNotStarveTogether\",\n\t\t)\n\t}\n\n\treturn filepath.Join(\n\t\tr.homePath,\n\t\t\".klei\",\n\t\t\"DoNotStarveTogether\",\n\t)\n}\n\nfunc (r *PathResolver) ClusterPath(cluster string) string {\n\treturn filepath.Join(\n\t\tr.KleiBasePath(cluster),\n\t\tcluster,\n\t)\n}\n\nfunc (r *PathResolver) LevelPath(cluster, level string) string {\n\treturn filepath.Join(\n\t\tr.ClusterPath(cluster),\n\t\tlevel,\n\t)\n}\n\nfunc (r *PathResolver) DataFilePath(\n\tcluster,\n\tlevel,\n\tfileName string,\n) string {\n\n\treturn filepath.Join(\n\t\tr.LevelPath(cluster, level),\n\t\tfileName,\n\t)\n}\n\nfunc (r *PathResolver) ClusterIniPath(clusterName string) string {\n\treturn filepath.Join(r.KleiBasePath(clusterName), clusterName, \"cluster.ini\")\n}\n\nfunc (r *PathResolver) ClusterTokenPath(clusterName string) string {\n\treturn filepath.Join(r.KleiBasePath(clusterName), clusterName, \"cluster_token.txt\")\n}\n\nfunc (r *PathResolver) AdminlistPath(clusterName string) string {\n\treturn filepath.Join(r.KleiBasePath(clusterName), clusterName, \"adminlist.txt\")\n}\n\nfunc (r *PathResolver) BlocklistPath(clusterName string) string {\n\treturn filepath.Join(r.KleiBasePath(clusterName), clusterName, \"blocklist.txt\")\n}\nfunc (r *PathResolver) BlacklistPath(clusterName string) string {\n\treturn filepath.Join(r.KleiBasePath(clusterName), clusterName, \"blocklist.txt\")\n}\n\nfunc (r *PathResolver) WhitelistPath(clusterName string) string {\n\treturn filepath.Join(r.KleiBasePath(clusterName), clusterName, \"whitelist.txt\")\n}\n\nfunc (r *PathResolver) ModoverridesPath(clusterName, levelName string) string {\n\treturn filepath.Join(r.KleiBasePath(clusterName), clusterName, levelName, \"modoverrides.lua\")\n}\n\nfunc (r *PathResolver) LeveldataoverridePath(clusterName, levelName string) string {\n\treturn filepath.Join(r.KleiBasePath(clusterName), clusterName, levelName, \"leveldataoverride.lua\")\n}\n\nfunc (r *PathResolver) ServerIniPath(clusterName string, levelName string) string {\n\treturn filepath.Join(r.KleiBasePath(clusterName), clusterName, levelName, \"server.ini\")\n}\n\nfunc (r *PathResolver) ServerLogPath(cluster string, levelName string) string {\n\treturn filepath.Join(r.LevelPath(cluster, levelName), \"server_log.txt\")\n}\n\nfunc (r *PathResolver) GetUgcWorkshopModPath(clusterName, levelName, workshopId string) string {\n\t// dstConfig := dstConfigUtils.GetDstConfig()\n\tconfig, _ := r.dstConfig.GetDstConfig(clusterName)\n\tworkshopModPath := \"\"\n\tif config.Ugc_directory != \"\" {\n\t\tworkshopModPath = filepath.Join(r.GetUgcModPath(clusterName), \"content\", \"322330\", workshopId)\n\t} else {\n\t\tworkshopModPath = filepath.Join(config.Force_install_dir, \"ugc_mods\", clusterName, levelName, \"content\", \"322330\", workshopId)\n\t}\n\treturn workshopModPath\n}\n\nfunc (r *PathResolver) GetUgcModPath(clusterName string) string {\n\tconfig, _ := r.dstConfig.GetDstConfig(clusterName)\n\tugcModPath := \"\"\n\tif config.Ugc_directory != \"\" {\n\t\tugcModPath = config.Ugc_directory\n\t} else {\n\t\tugcModPath = filepath.Join(config.Force_install_dir, \"ugc_mods\")\n\t}\n\treturn ugcModPath\n}\n\nfunc (r *PathResolver) GetUgcAcfPath(clusterName, levelName string) string {\n\tugcModPath := r.GetUgcModPath(clusterName)\n\tconfig, _ := r.dstConfig.GetDstConfig(clusterName)\n\tp := \"\"\n\tif config.Ugc_directory == \"\" {\n\t\tp = filepath.Join(ugcModPath, clusterName, levelName, \"appworkshop_322330.acf\")\n\t} else {\n\t\tp = filepath.Join(ugcModPath, \"appworkshop_322330.acf\")\n\t}\n\treturn p\n}\n\nfunc (r *PathResolver) GetModSetup(clusterName string) string {\n\tcluster, _ := r.dstConfig.GetDstConfig(clusterName)\n\tdstServerPath := cluster.Force_install_dir\n\tif r.IsBeta(clusterName) {\n\t\tdstServerPath = dstServerPath + \"-beta\"\n\t}\n\treturn filepath.Join(dstServerPath, \"mods\", \"dedicated_server_mods_setup.lua\")\n}\n\nfunc (r *PathResolver) IsBeta(clusterName string) bool {\n\tconfig, err := r.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn config.Beta == 1\n}\n\nfunc (r *PathResolver) GetLocalDstVersion(clusterName string) (int64, error) {\n\tdstConfig, err := r.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdstInstallDir := dstConfig.Force_install_dir\n\tif dstConfig.Beta == 1 {\n\t\tdstInstallDir = dstInstallDir + \"-beta\"\n\t}\n\tversionTextPath := filepath.Join(dstInstallDir, \"version.txt\")\n\treturn r.dstVersion(versionTextPath)\n}\n\nfunc (r *PathResolver) GetLastDstVersion() (int64, error) {\n\turl := \"http://ver.tugos.cn/getLocalVersion\"\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tbody, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\ts := string(body)\n\tveriosn, err := strconv.Atoi(s)\n\tif err != nil {\n\t\tveriosn = 0\n\t}\n\treturn int64(veriosn), nil\n}\n\nfunc (r *PathResolver) dstVersion(versionTextPath string) (int64, error) {\n\t// 使用filepath.Clean确保路径格式正确\n\tcleanPath := filepath.Clean(versionTextPath)\n\n\t// 使用filepath.Abs获取绝对路径\n\tabsPath, err := filepath.Abs(cleanPath)\n\tif err != nil {\n\t\tlog.Println(\"Error getting absolute path:\", err)\n\t\treturn 0, err\n\t}\n\t// 打印绝对路径\n\tlog.Println(\"Absolute Path:\", absPath)\n\n\tversion, err := fileUtils.ReadFile(versionTextPath)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn 0, err\n\t}\n\tversion = strings.Replace(version, \"\\r\", \"\", -1)\n\tversion = strings.Replace(version, \"\\n\", \"\", -1)\n\tl, err := strconv.ParseInt(version, 10, 64)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn 0, err\n\t}\n\treturn l, nil\n}\n"
  },
  {
    "path": "internal/service/backup/backup_service.go",
    "content": "package backup\n\nimport (\n\t\"dst-admin-go/internal/database\"\n\t\"dst-admin-go/internal/model\"\n\t\"dst-admin-go/internal/pkg/context\"\n\t\"dst-admin-go/internal/pkg/utils/dstUtils\"\n\t\"dst-admin-go/internal/pkg/utils/fileUtils\"\n\t\"dst-admin-go/internal/pkg/utils/shellUtils\"\n\t\"dst-admin-go/internal/pkg/utils/zip\"\n\t\"dst-admin-go/internal/service/archive\"\n\t\"dst-admin-go/internal/service/dstConfig\"\n\t\"dst-admin-go/internal/service/game\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype BackupService struct {\n\tarchive     *archive.PathResolver\n\tdstConfig   dstConfig.Config\n\tgameProcess game.Process\n}\n\ntype BackupInfo struct {\n\tFileName   string    `json:\"fileName\"`\n\tFileSize   int64     `json:\"fileSize\"`\n\tCreateTime time.Time `json:\"createTime\"`\n\tTime       int64     `json:\"time\"`\n}\n\ntype BackupSnapshot struct {\n\tEnable       int `json:\"enable\"`\n\tInterval     int `json:\"interval\"`\n\tMaxSnapshots int `json:\"maxSnapshots\"`\n\tIsCSave      int `json:\"isCSave\"`\n}\n\nfunc NewBackupService(archive *archive.PathResolver, dstConfig dstConfig.Config, gameProcess game.Process) *BackupService {\n\treturn &BackupService{\n\t\tarchive:     archive,\n\t\tdstConfig:   dstConfig,\n\t\tgameProcess: gameProcess,\n\t}\n}\n\nfunc (b *BackupService) GetBackupList(clusterName string) []BackupInfo {\n\tconfig, err := b.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\tlog.Println(\"failed to get dst config:\", err)\n\t\treturn []BackupInfo{}\n\t}\n\tbackupPath := config.Backup\n\tvar backupList []BackupInfo\n\n\tif !fileUtils.Exists(backupPath) {\n\t\treturn backupList\n\t}\n\t//获取文件或目录相关信息\n\tfileInfoList, err := ioutil.ReadDir(backupPath)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\n\tfor _, file := range fileInfoList {\n\t\tif file.IsDir() {\n\t\t\tcontinue\n\t\t}\n\t\tsuffix := filepath.Ext(file.Name())\n\t\tif suffix == \".zip\" || suffix == \".tar\" {\n\t\t\tbackup := BackupInfo{\n\t\t\t\tFileName:   file.Name(),\n\t\t\t\tFileSize:   file.Size(),\n\t\t\t\tCreateTime: file.ModTime(),\n\t\t\t\tTime:       file.ModTime().Unix(),\n\t\t\t}\n\t\t\tbackupList = append(backupList, backup)\n\t\t}\n\t}\n\n\treturn backupList\n\n}\n\nfunc (b *BackupService) RenameBackup(ctx *gin.Context, fileName, newName string) {\n\tclusterName := context.GetClusterName(ctx)\n\tconfig, err := b.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\tlog.Println(\"failed to get dst config:\", err)\n\t\treturn\n\t}\n\tbackupPath := config.Backup\n\terr = fileUtils.Rename(filepath.Join(backupPath, fileName), filepath.Join(backupPath, newName))\n\tif err != nil {\n\t\treturn\n\t}\n}\n\nfunc (b *BackupService) DeleteBackup(ctx *gin.Context, fileNames []string) {\n\n\tclusterName := context.GetClusterName(ctx)\n\tconfig, err := b.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\tlog.Println(\"failed to get dst config:\", err)\n\t\treturn\n\t}\n\tbackupPath := config.Backup\n\tfor _, fileName := range fileNames {\n\t\tfilePath := filepath.Join(backupPath, fileName)\n\t\tif !fileUtils.Exists(filePath) {\n\t\t\tcontinue\n\t\t}\n\t\terr := fileUtils.DeleteFile(filePath)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n}\n\nfunc (b *BackupService) RestoreBackup(ctx *gin.Context, backupName string) {\n\n\tclusterName := context.GetClusterName(ctx)\n\tconfig, err := b.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\tlog.Println(\"failed to get dst config:\", err)\n\t\treturn\n\t}\n\n\tfilePath := filepath.Join(config.Backup, backupName)\n\tclusterPath := filepath.Join(b.archive.ClusterPath(clusterName))\n\terr = fileUtils.DeleteDir(clusterPath)\n\tif err != nil {\n\t\tlog.Panicln(\"删除失败,\", clusterPath, err)\n\t}\n\tlog.Println(\"正在恢复存档\", filePath, filepath.Join(b.archive.KleiBasePath(clusterName)))\n\n\t// err = zip.Unzip2(filePath, filepath.Join(constant.HOME_PATH, \".klei/DoNotStarveTogether\"), cluster.ClusterName)\n\terr = zip.Unzip3(filePath, clusterPath)\n\tif err != nil {\n\t\tlog.Panicln(\"解压失败,\", filePath, clusterPath, err)\n\t}\n\t// 安装mod\n\tmodoverride, err := fileUtils.ReadFile(b.archive.ModoverridesPath(clusterName, \"Master\"))\n\tif err != nil {\n\t\tlog.Println(\"读取模组失败\", err)\n\t}\n\tconfig, err = b.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t}\n\terr = dstUtils.DedicatedServerModsSetup(config, modoverride)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t}\n}\n\nfunc (b *BackupService) CreateBackup(clusterName, backupName string) {\n\n\tconfig, err := b.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\tlog.Println(\"failed to get dst config:\", err)\n\t\treturn\n\t}\n\tbackupPath := config.Backup\n\n\t// 执行 CSave 命令\n\terr = b.gameProcess.Command(clusterName, \"Master\", \"c_save()\")\n\tif err != nil {\n\t\tlog.Println(\"CSave command error:\", err)\n\t}\n\n\t// 等待保存完成\n\ttime.Sleep(2 * time.Second)\n\n\tsrc := b.archive.ClusterPath(clusterName)\n\tif !fileUtils.Exists(backupPath) {\n\t\tlog.Panicln(\"backup path is not exists\")\n\t}\n\tif backupName == \"\" {\n\t\tbackupName = b.GenGameBackUpName(clusterName)\n\t}\n\tdst := filepath.Join(backupPath, backupName)\n\tlog.Println(\"src\", src, dst)\n\terr = zip.Zip(src, dst)\n\tif err != nil {\n\t\tlog.Panicln(\"create backup error\", err)\n\t}\n\tlog.Println(\"创建备份成功\")\n}\n\nfunc (b *BackupService) DownloadBackup(c *gin.Context) {\n\tfileName := c.Query(\"fileName\")\n\n\tclusterName := c.GetHeader(\"level\")\n\tconfig, err := b.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\tlog.Println(\"failed to get dst config:\", err)\n\t\treturn\n\t}\n\n\tfilePath := filepath.Join(config.Backup, fileName)\n\t//打开文件\n\t_, err = os.Open(filePath)\n\t//非空处理\n\tif err != nil {\n\t\tlog.Panicln(\"download filePath error\", err)\n\t}\n\tc.Header(\"Content-Type\", \"application/octet-stream\")\n\tc.Header(\"Content-Disposition\", \"attachment; filename=\"+fileName)\n\tc.Header(\"Content-Transfer-Encoding\", \"binary\")\n\t// c.Header(\"Content-Length\", strconv.FormatInt(f.Size(), 10))\n\tc.File(filePath)\n}\n\nfunc (b *BackupService) UploadBackup(c *gin.Context) {\n\t// 单文件\n\tfile, _ := c.FormFile(\"file\")\n\tlog.Println(file.Filename)\n\n\tclusterName := context.GetClusterName(c)\n\tconfig, err := b.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\tlog.Println(\"failed to get dst config:\", err)\n\t\treturn\n\t}\n\tdst := filepath.Join(config.Backup, file.Filename)\n\n\tif fileUtils.Exists(dst) {\n\t\tlog.Panicln(\"backup is existed\")\n\t}\n\n\t// 上传文件至指定的完整文件路径\n\terr = c.SaveUploadedFile(file, dst)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// c.String(http.StatusOK, fmt.Sprintf(\"'%s' uploaded!\", file.Filename))\n\n}\n\nfunc (b *BackupService) ScheduleBackupSnapshots() {\n\tlog.Println(\"开始创建快照\")\n\tfor {\n\t\tdb := database.Db\n\t\tsnapshot := model.BackupSnapshot{}\n\t\tdb.First(&snapshot)\n\t\tif snapshot.Enable == 1 {\n\t\t\tif snapshot.Interval == 0 {\n\t\t\t\tsnapshot.Interval = 8\n\t\t\t}\n\t\t\tif snapshot.MaxSnapshots == 0 {\n\t\t\t\tsnapshot.MaxSnapshots = 6\n\t\t\t}\n\t\t\ttime.Sleep(time.Duration(snapshot.Interval) * time.Minute)\n\n\t\t\t// 定时创建备份,每隔 x 分钟备份一次\n\t\t\t// Get the first available cluster config (or \"MyCluster\" as default)\n\t\t\tclusterName := \"MyCluster\"\n\t\t\tconfig, err := b.dstConfig.GetDstConfig(clusterName)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"failed to get dst config for snapshot:\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif config.Cluster != \"\" {\n\t\t\t\tsnapshotPrefix := \"(snapshot)\"\n\t\t\t\tif snapshot.IsCSave == 1 {\n\t\t\t\t\t// 执行 CSave 命令\n\t\t\t\t\terr := b.gameProcess.Command(config.Cluster, \"Master\", \"c_save()\")\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Println(\"CSave command error:\", err)\n\t\t\t\t\t}\n\t\t\t\t\t// 等待保存完成\n\t\t\t\t\ttime.Sleep(2 * time.Second)\n\t\t\t\t}\n\t\t\t\tb.CreateSnapshotBackup(snapshotPrefix, config.Cluster)\n\t\t\t\t// 删除快照\n\t\t\t\tb.DeleteBackupSnapshots(snapshotPrefix, snapshot.MaxSnapshots, config.Cluster, config.Backup)\n\t\t\t}\n\t\t} else {\n\t\t\ttime.Sleep(1 * time.Minute)\n\t\t}\n\t}\n}\n\nfunc sumMd5(filePath string) string {\n\t// find save -type f -exec md5sum {} \\; | awk '{print $1}' | sort | md5sum\n\tcomamd := \"find \" + filePath + \" -type f -exec md5sum {} \\\\; | awk '{print $1}' | sort | md5sum\"\n\tinfo, err := shellUtils.ExecuteCommand(comamd)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn info\n}\n\nfunc (b *BackupService) CreateSnapshotBackup(prefix, clusterName string) {\n\n\tconfig, err := b.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\tlog.Println(\"failed to get dst config:\", err)\n\t\treturn\n\t}\n\n\tsnapshotMd5FilePath := \"./snapshotMd5\"\n\tfileUtils.CreateFileIfNotExists(snapshotMd5FilePath)\n\n\tsrc := b.archive.ClusterPath(clusterName)\n\tdst := filepath.Join(config.Backup, b.GenBackUpSnapshotName(prefix, clusterName))\n\tlog.Println(\"[Snapshot]正在定时创建游戏备份\", \"src: \", src, \"dst: \", dst)\n\terr = zip.Zip(src, dst)\n\tif err != nil {\n\t\tlog.Println(\"[Snapshot]create backup error\", err)\n\t}\n}\n\nfunc (b *BackupService) DeleteBackupSnapshots(prefix string, maxSnapshots int, clusterName, backupPath string) {\n\n\tlog.Println(\"[Snapshot]正在删除快照备份\", \"maxSnapshots\", maxSnapshots, \"clusterName: \", clusterName)\n\n\tbackupList := b.GetBackupList(clusterName)\n\tvar newBackupList []BackupInfo\n\tfor i := range backupList {\n\t\tname := backupList[i].FileName\n\t\tif strings.HasPrefix(name, prefix) {\n\t\t\tnewBackupList = append(newBackupList, backupList[i])\n\t\t}\n\t}\n\tif len(newBackupList) > maxSnapshots {\n\t\tdeleteBackupList := newBackupList[:len(newBackupList)-maxSnapshots]\n\t\tfor i := range deleteBackupList {\n\t\t\tfilePath := filepath.Join(backupPath, deleteBackupList[i].FileName)\n\t\t\tlog.Println(\"删除快照备份\", filePath)\n\t\t\tif !fileUtils.Exists(filePath) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terr := fileUtils.DeleteFile(filePath)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nfunc (b *BackupService) backupPath() string {\n\t// dstConfig := dstConfigUtils.GetDstConfig()\n\t// backupPath := dstConfig.Backup\n\t// if !fileUtils.Exists(backupPath) {\n\t// \tlog.Panicln(\"backup path is not exists\")\n\t// }\n\t// return backupPath\n\treturn \"\"\n}\n\nvar SeasonMap = map[string]string{\n\t\"spring\": \"春天\",\n\t\"summer\": \"夏天\",\n\t\"autumn\": \"秋天\",\n\t\"winter\": \"冬天\",\n}\n\n// GenGameBackUpName 备份名称增加存档信息如  猜猜我是谁的世界-10天-spring-1-20-2023071415\nfunc (b *BackupService) GenGameBackUpName(clusterName string) string {\n\t// 简化实现，使用时间戳和集群名称\n\tbackupName := time.Now().Format(\"2006年01月02日15点04分05秒\") + \"_\" + clusterName + \".zip\"\n\n\treturn backupName\n}\n\nfunc (b *BackupService) GenBackUpSnapshotName(prefix, clusterName string) string {\n\tbackupName := b.GenGameBackUpName(clusterName)\n\tbackupName = prefix + backupName\n\treturn backupName\n}\n"
  },
  {
    "path": "internal/service/dstConfig/dst_config.go",
    "content": "package dstConfig\n\ntype DstConfig struct {\n\tSteamcmd                   string `json:\"steamcmd\"`\n\tForce_install_dir          string `json:\"force_install_dir\"`\n\tDoNotStarveServerDirectory string `json:\"donot_starve_server_directory\"`\n\tCluster                    string `json:\"cluster\"`\n\tBackup                     string `json:\"backup\"`\n\tMod_download_path          string `json:\"mod_download_path\"`\n\tBin                        int    `json:\"bin\"`\n\tBeta                       int    `json:\"beta\"`\n\n\tUgc_directory string `json:\"ugc_directory\"`\n\t// 根目录位置\n\tPersistent_storage_root string `json:\"persistent_storage_root\"`\n\t// 存档相对位置\n\tConf_dir string `json:\"conf_dir\"`\n}\n\ntype Config interface {\n\tGetDstConfig(clusterName string) (DstConfig, error)\n\tSaveDstConfig(clusterName string, config DstConfig) error\n}\n"
  },
  {
    "path": "internal/service/dstConfig/factory.go",
    "content": "package dstConfig\n\nimport (\n\t\"gorm.io/gorm\"\n)\n\nfunc NewDstConfig(db *gorm.DB) Config {\n\tdstConfig := NewOneDstConfig(db)\n\treturn &dstConfig\n}\n"
  },
  {
    "path": "internal/service/dstConfig/one_dst_config.go",
    "content": "package dstConfig\n\nimport (\n\t\"dst-admin-go/internal/pkg/utils/fileUtils\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gorm.io/gorm\"\n)\n\nconst dst_config_path = \"./dst_config\"\n\ntype OneDstConfig struct {\n\tdb *gorm.DB\n}\n\nfunc NewOneDstConfig(db *gorm.DB) OneDstConfig {\n\treturn OneDstConfig{\n\t\tdb: db,\n\t}\n}\n\nfunc (o *OneDstConfig) kleiBasePath(config DstConfig) string {\n\n\thome, _ := os.UserHomeDir()\n\n\tpersistentStorageRoot := config.Persistent_storage_root\n\tconfDir := config.Conf_dir\n\tif persistentStorageRoot != \"\" {\n\t\tif confDir == \"\" {\n\t\t\tconfDir = \"DoNotStarveTogether\"\n\t\t}\n\t\tkleiDstPath := filepath.Join(persistentStorageRoot, confDir)\n\t\treturn kleiDstPath\n\t}\n\tif runtime.GOOS == \"windows\" {\n\t\treturn filepath.Join(\n\t\t\thome,\n\t\t\t\"Documents\",\n\t\t\t\"klei\",\n\t\t\t\"DoNotStarveTogether\",\n\t\t)\n\t}\n\n\treturn filepath.Join(\n\t\thome,\n\t\t\".klei\",\n\t\t\"DoNotStarveTogether\",\n\t)\n}\n\nfunc (o *OneDstConfig) GetDstConfig(clusterName string) (DstConfig, error) {\n\tdstConfig := DstConfig{}\n\n\t//判断是否存在，不存在创建一个\n\tif !fileUtils.Exists(dst_config_path) {\n\t\tif err := fileUtils.CreateFile(dst_config_path); err != nil {\n\t\t\treturn dstConfig, err\n\t\t}\n\t}\n\tdata, err := fileUtils.ReadLnFile(dst_config_path)\n\tif err != nil {\n\t\treturn dstConfig, err\n\t}\n\tfor _, value := range data {\n\t\tif value == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\t// TODO 这里解析有问题，如果路径含有 steamcmd 就会存在问题\n\t\tif strings.Contains(value, \"steamcmd=\") {\n\t\t\tsplit := strings.Split(value, \"=\")\n\t\t\tif len(split) > 1 {\n\t\t\t\ts := strings.TrimSpace(split[1])\n\t\t\t\tdstConfig.Steamcmd = strings.Replace(s, \"\\\\n\", \"\", -1)\n\t\t\t}\n\t\t}\n\t\tif strings.Contains(value, \"force_install_dir=\") {\n\t\t\tsplit := strings.Split(value, \"=\")\n\t\t\tif len(split) > 1 {\n\t\t\t\ts := strings.TrimSpace(split[1])\n\t\t\t\tdstConfig.Force_install_dir = strings.Replace(s, \"\\\\n\", \"\", -1)\n\t\t\t}\n\t\t}\n\t\tif strings.Contains(value, \"donot_starve_server_directory=\") {\n\t\t\tsplit := strings.Split(value, \"=\")\n\t\t\tif len(split) > 1 {\n\t\t\t\ts := strings.TrimSpace(split[1])\n\t\t\t\tdstConfig.DoNotStarveServerDirectory = strings.Replace(s, \"\\\\n\", \"\", -1)\n\t\t\t}\n\t\t}\n\t\tif strings.Contains(value, \"persistent_storage_root=\") {\n\t\t\tsplit := strings.Split(value, \"=\")\n\t\t\tif len(split) > 1 {\n\t\t\t\ts := strings.TrimSpace(split[1])\n\t\t\t\tdstConfig.Persistent_storage_root = strings.Replace(s, \"\\\\n\", \"\", -1)\n\t\t\t}\n\t\t}\n\t\tif strings.Contains(value, \"cluster=\") {\n\t\t\tsplit := strings.Split(value, \"=\")\n\t\t\tif len(split) > 1 {\n\t\t\t\ts := strings.TrimSpace(split[1])\n\t\t\t\tdstConfig.Cluster = strings.Replace(s, \"\\\\n\", \"\", -1)\n\t\t\t}\n\t\t}\n\t\tif strings.Contains(value, \"backup=\") {\n\t\t\tsplit := strings.Split(value, \"=\")\n\t\t\tif len(split) > 1 {\n\t\t\t\ts := strings.TrimSpace(split[1])\n\t\t\t\tdstConfig.Backup = strings.Replace(s, \"\\\\n\", \"\", -1)\n\t\t\t}\n\t\t}\n\t\tif strings.Contains(value, \"mod_download_path=\") {\n\t\t\tsplit := strings.Split(value, \"=\")\n\t\t\tif len(split) > 1 {\n\t\t\t\ts := strings.TrimSpace(split[1])\n\t\t\t\tdstConfig.Mod_download_path = strings.Replace(s, \"\\\\n\", \"\", -1)\n\t\t\t}\n\t\t}\n\t\tif strings.Contains(value, \"bin=\") {\n\t\t\tsplit := strings.Split(value, \"=\")\n\t\t\tif len(split) > 1 {\n\t\t\t\ts := strings.TrimSpace(split[1])\n\t\t\t\tbin, _ := strconv.ParseInt(strings.Replace(s, \"\\\\n\", \"\", -1), 10, 64)\n\t\t\t\tdstConfig.Bin = int(bin)\n\t\t\t}\n\t\t}\n\t\tif strings.Contains(value, \"beta=\") {\n\t\t\tsplit := strings.Split(value, \"=\")\n\t\t\tif len(split) > 1 {\n\t\t\t\ts := strings.TrimSpace(split[1])\n\t\t\t\tbeta, _ := strconv.ParseInt(strings.Replace(s, \"\\\\n\", \"\", -1), 10, 64)\n\t\t\t\tdstConfig.Beta = int(beta)\n\t\t\t}\n\t\t}\n\t\tif strings.Contains(value, \"ugc_directory=\") {\n\t\t\tsplit := strings.Split(value, \"=\")\n\t\t\tif len(split) > 1 {\n\t\t\t\ts := strings.TrimSpace(split[1])\n\t\t\t\tdstConfig.Ugc_directory = strings.Replace(s, \"\\\\n\", \"\", -1)\n\t\t\t}\n\t\t}\n\t\tif strings.Contains(value, \"conf_dir=\") {\n\t\t\tsplit := strings.Split(value, \"=\")\n\t\t\tif len(split) > 1 {\n\t\t\t\ts := strings.TrimSpace(split[1])\n\t\t\t\tdstConfig.Conf_dir = strings.Replace(s, \"\\\\n\", \"\", -1)\n\t\t\t}\n\t\t}\n\t}\n\t// 设置默认值\n\tif dstConfig.Cluster == \"\" {\n\t\tdstConfig.Cluster = \"Cluster1\"\n\t}\n\tif dstConfig.Backup == \"\" {\n\t\tdefaultPath := filepath.Join(o.kleiBasePath(dstConfig), \"backup\")\n\t\tfileUtils.CreateDirIfNotExists(defaultPath)\n\t\tdstConfig.Backup = defaultPath\n\t}\n\tif dstConfig.Mod_download_path == \"\" {\n\t\tdefaultPath := filepath.Join(o.kleiBasePath(dstConfig), \"mod_config_download\")\n\t\tfileUtils.CreateDirIfNotExists(defaultPath)\n\t\tdstConfig.Mod_download_path = defaultPath\n\t}\n\tif dstConfig.Bin == 0 {\n\t\tdstConfig.Bin = 32\n\t}\n\treturn dstConfig, nil\n}\n\nfunc (o *OneDstConfig) SaveDstConfig(clusterName string, dstConfig DstConfig) error {\n\toldDstConfig, err := o.GetDstConfig(clusterName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif dstConfig.Steamcmd == \"\" {\n\t\tdstConfig.Steamcmd = oldDstConfig.Steamcmd\n\t}\n\tif dstConfig.Force_install_dir == \"\" {\n\t\tdstConfig.Force_install_dir = oldDstConfig.Force_install_dir\n\t}\n\tif dstConfig.Cluster == \"\" {\n\t\tdstConfig.Cluster = oldDstConfig.Cluster\n\t}\n\tif dstConfig.Backup == \"\" {\n\t\tdstConfig.Backup = oldDstConfig.Backup\n\t}\n\tif dstConfig.Mod_download_path == \"\" {\n\t\tdstConfig.Mod_download_path = oldDstConfig.Mod_download_path\n\t}\n\n\terr = fileUtils.WriterLnFile(dst_config_path, []string{\n\t\t\"steamcmd=\" + dstConfig.Steamcmd,\n\t\t\"force_install_dir=\" + dstConfig.Force_install_dir,\n\t\t\"donot_starve_server_directory=\" + dstConfig.DoNotStarveServerDirectory,\n\t\t\"ugc_directory=\" + dstConfig.Ugc_directory,\n\t\t\"conf_dir=\" + dstConfig.Conf_dir,\n\t\t\"persistent_storage_root=\" + dstConfig.Persistent_storage_root,\n\t\t\"cluster=\" + dstConfig.Cluster,\n\t\t\"backup=\" + dstConfig.Backup,\n\t\t\"mod_download_path=\" + dstConfig.Mod_download_path,\n\t\t\"bin=\" + strconv.Itoa(dstConfig.Bin),\n\t\t\"beta=\" + strconv.Itoa(dstConfig.Beta),\n\t})\n\treturn err\n}\n"
  },
  {
    "path": "internal/service/dstMap/dst_map.go",
    "content": "package dstMap\n\nimport (\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"image\"\n\t\"image/color\"\n\t\"image/png\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"regexp\"\n)\n\n// Color 定义一个RGB颜色\ntype Color struct {\n\tR, G, B uint8\n\tName    string\n}\n\n// DSTMapGenerator 存储地图生成器的状态\ntype DSTMapGenerator struct {\n\ttileColors   map[int]Color\n\tentityColors map[string]color.Color\n}\n\n// NewDSTMapGenerator 创建新的地图生成器实例\nfunc NewDSTMapGenerator() *DSTMapGenerator {\n\tg := &DSTMapGenerator{\n\t\ttileColors:   make(map[int]Color),\n\t\tentityColors: make(map[string]color.Color),\n\t}\n\n\t// 初始化tile颜色映射\n\tg.tileColors = map[int]Color{\n\t\t0:   {42, 42, 42, \"地表虚空\"},\n\t\t1:   {42, 42, 44, \"一个虚空\"},\n\t\t2:   {80, 76, 65, \"卵石路\"},\n\t\t3:   {90, 105, 104, \"矿石区\"},\n\t\t4:   {117, 107, 85, \"无地皮\"},\n\t\t5:   {144, 125, 89, \"热带草原地皮\"},\n\t\t6:   {48, 67, 39, \"长草地皮\"},\n\t\t7:   {40, 47, 18, \"森林地皮\"},\n\t\t8:   {81, 28, 194, \"沼泽地皮\"},\n\t\t9:   {0, 0, 7, \"空\"},\n\t\t10:  {85, 69, 48, \"木地板\"},\n\t\t11:  {64, 75, 116, \"地毯地板\"},\n\t\t12:  {115, 133, 201, \"棋盘地板\"},\n\t\t13:  {139, 131, 115, \"鸟粪地皮\"},\n\t\t14:  {74, 65, 77, \"蓝真菌\"},\n\t\t15:  {67, 70, 32, \"黏滑地皮\"},\n\t\t16:  {75, 75, 73, \"洞穴岩石地皮\"},\n\t\t17:  {66, 49, 30, \"泥泞地皮\"},\n\t\t18:  {115, 113, 107, \"远古地皮\"},\n\t\t19:  {86, 86, 81, \"仿远古地皮\"},\n\t\t20:  {74, 61, 84, \"远古瓷砖\"},\n\t\t21:  {66, 50, 76, \"仿远古瓷砖\"},\n\t\t22:  {39, 38, 39, \"远古雕砖\"},\n\t\t23:  {34, 35, 34, \"仿远古雕砖\"},\n\t\t24:  {70, 44, 43, \"红真菌\"},\n\t\t25:  {62, 76, 61, \"绿真菌\"},\n\t\t26:  {42, 42, 44, \"空\"},\n\t\t27:  {42, 42, 44, \"空\"},\n\t\t28:  {42, 42, 44, \"空\"},\n\t\t29:  {42, 42, 44, \"空\"},\n\t\t30:  {91, 62, 14, \"落叶林地皮\"},\n\t\t31:  {117, 86, 46, \"沙漠地皮\"},\n\t\t32:  {31, 27, 27, \"龙鳞地皮\"},\n\t\t33:  {128, 128, 128, \"崩溃\"},\n\t\t34:  {128, 128, 128, \"崩溃\"},\n\t\t35:  {47, 44, 47, \"暴食沼泽\"},\n\t\t36:  {158, 104, 105, \"粉桦树林【暴食】\"},\n\t\t37:  {137, 113, 113, \"粉【暴食】\"},\n\t\t38:  {81, 97, 100, \"蓝长草【暴食】\"},\n\t\t39:  {66, 58, 49, \"耕地地皮\"},\n\t\t40:  {42, 42, 44, \"空\"},\n\t\t41:  {119, 113, 97, \"白【暴食】\"},\n\t\t42:  {84, 108, 107, \"岩石海滩\"},\n\t\t43:  {67, 133, 142, \"月球环形山\"},\n\t\t44:  {154, 146, 186, \"贝壳海滩\"},\n\t\t45:  {138, 96, 73, \"远古石刻\"},\n\t\t46:  {66, 86, 82, \"变异真菌地皮\"},\n\t\t47:  {61, 57, 46, \"耕地地皮\"},\n\t\t48:  {42, 42, 44, \"空\"},\n\t\t200: {0, 0, 11, \"深渊\"},\n\t\t201: {18, 66, 73, \"浅海\"},\n\t\t202: {18, 66, 73, \"浅海海岸\"},\n\t\t203: {7, 46, 61, \"中海\"},\n\t\t204: {1, 32, 46, \"深海\"},\n\t\t205: {6, 54, 81, \"盐矿海岸\"},\n\t\t206: {6, 54, 81, \"盐矿海岸\"},\n\t\t207: {0, 24, 26, \"危险海\"},\n\t\t208: {189, 193, 198, \"水中木\"},\n\t\t247: {42, 42, 44, \"空\"},\n\t}\n\n\t// 初始化实体颜色映射\n\tg.entityColors = map[string]color.Color{\n\t\t\"evergreen\":     color.RGBA{0, 100, 0, 255},\n\t\t\"deciduoustree\": color.RGBA{34, 139, 34, 255},\n\t\t\"rock1\":         color.RGBA{128, 128, 128, 255},\n\t\t\"rock2\":         color.RGBA{169, 169, 169, 255},\n\t\t\"sapling\":       color.RGBA{144, 238, 144, 255},\n\t\t\"grass\":         color.RGBA{124, 252, 0, 255},\n\t\t\"berrybush\":     color.RGBA{255, 0, 0, 255},\n\t\t\"berrybush2\":    color.RGBA{220, 20, 60, 255},\n\t\t\"spiderden\":     color.RGBA{128, 0, 128, 255},\n\t\t\"pond\":          color.RGBA{0, 191, 255, 255},\n\t\t\"rabbithole\":    color.RGBA{139, 69, 19, 255},\n\t\t\"cave\":          color.RGBA{105, 105, 105, 255},\n\t\t\"reeds\":         color.RGBA{189, 183, 107, 255},\n\t\t\"marsh_tree\":    color.RGBA{85, 107, 47, 255},\n\t\t\"marsh_bush\":    color.RGBA{107, 142, 35, 255},\n\t\t\"carrot\":        color.RGBA{255, 140, 0, 255},\n\t\t\"flower\":        color.RGBA{255, 192, 203, 255},\n\t\t\"wormhole\":      color.RGBA{138, 43, 226, 255},\n\t\t\"pighouse\":      color.RGBA{255, 160, 122, 255},\n\t\t\"mound\":         color.RGBA{160, 82, 45, 255},\n\t\t\"ruins\":         color.RGBA{119, 136, 153, 255},\n\t\t\"fireflies\":     color.RGBA{255, 255, 0, 255},\n\t}\n\n\treturn g\n}\n\n// ReadSaveFile 读取存档文件\nfunc (g *DSTMapGenerator) ReadSaveFile(filePath string) (string, error) {\n\tcontent, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"读取文件失败: %v\", err)\n\t}\n\n\t// 使用正则表达式提取地图数据\n\tre := regexp.MustCompile(`tiles=\"([^\"]+)\"`)\n\tmatches := re.FindSubmatch(content)\n\tif len(matches) < 2 {\n\t\treturn \"\", fmt.Errorf(\"无法在存档中找到地图数据\")\n\t}\n\n\tbase64Data := string(matches[1])\n\tfmt.Printf(\"提取的base64数据长度: %d\\n\", len(base64Data))\n\treturn base64Data, nil\n}\n\nfunc RestoreTileId(original int, colors map[int]Color) int {\n\thigh := original >> 8\n\tlow := original & 0xFF\n\n\t// 1) 直接用 high（正常情形：tile 存为 high<<8）\n\tif _, ok := colors[high]; ok {\n\t\treturn high\n\t}\n\n\t// 2) 尝试 high-1\n\tif high > 0 {\n\t\tif _, ok := colors[high-1]; ok {\n\t\t\treturn high - 1\n\t\t}\n\t}\n\n\t// 3) ocean 等大型 ID 区间的保守尝试（0xC8 = 200）\n\t//    如果 high 在 0xC8..0xFF 范围，优先把它当作 200+ 值尝试映射\n\tif high >= 0xC8 && high <= 0xFF {\n\t\tcand := 200 + (high - 0xC8)\n\t\tif _, ok := colors[cand]; ok {\n\t\t\treturn cand\n\t\t}\n\t}\n\n\t// 4) 其它情况：如果低字节不为0，有可能这不是简单的 high<<8 编码，\n\t//    你可以在此加入额外规则；暂时返回 0（或你想要的默认）\n\t_ = low // 如果以后需要可利用 low 做更精细的判断\n\treturn 0\n}\n\n// DecodeMapData 解码地图数据\nfunc (g *DSTMapGenerator) DecodeMapData(tilesBase64 string) ([]int, error) {\n\ttileBytes, err := base64.StdEncoding.DecodeString(tilesBase64)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"base64解码失败: %v\", err)\n\t}\n\n\t// 处理文件头\n\tdataStart := 0\n\tif len(tileBytes) > 5 && string(tileBytes[:5]) == \"VRSTN\" {\n\t\tdataStart = 5\n\t\tfor dataStart < len(tileBytes) && tileBytes[dataStart] == 0 {\n\t\t\tdataStart++\n\t\t}\n\t}\n\n\ttileBytes = tileBytes[dataStart:]\n\tif len(tileBytes)%2 != 0 {\n\t\ttileBytes = tileBytes[:len(tileBytes)-1]\n\t}\n\n\t// 解码tile IDs\n\ttileIds := make([]int, 0, len(tileBytes)/2)\n\tfor i := 0; i < len(tileBytes); i += 2 {\n\t\tif i+1 >= len(tileBytes) {\n\t\t\tbreak\n\t\t}\n\t\ttileId := (int(tileBytes[i+1]) << 8) | int(tileBytes[i])\n\t\ttileId = RestoreTileId(tileId, g.tileColors)\n\t\ttileIds = append(tileIds, tileId)\n\t}\n\n\t// 打印分布情况\n\ttileCounts := make(map[int]int)\n\tfor _, id := range tileIds {\n\t\ttileCounts[id]++\n\t}\n\n\ttotal := len(tileIds)\n\tfmt.Println(\"\\n瓦片分布情况:\")\n\tfor id, count := range tileCounts {\n\t\tpercentage := float64(count) / float64(total) * 100\n\t\tif percentage > 0.01 {\n\t\t\tfmt.Printf(\"瓦片ID %d: %d 个 (%.2f%%)\\n\", id, count, percentage)\n\t\t}\n\t}\n\n\treturn tileIds, nil\n}\n\n// CreateMapImage 创建地图图像\nfunc (g *DSTMapGenerator) CreateMapImage(tileIds []int, width, height, scale int) *image.RGBA {\n\timg := image.NewRGBA(image.Rect(0, 0, width*scale, height*scale))\n\n\t// 填充地形颜色\n\tfor y := 0; y < height; y++ {\n\t\tfor x := 0; x < width; x++ {\n\t\t\tidx := y*width + x\n\t\t\tif idx >= len(tileIds) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttileId := tileIds[idx]\n\t\t\ttileColor, exists := g.tileColors[tileId]\n\t\t\tif !exists {\n\t\t\t\t// 使用默认颜色 (黑色)\n\t\t\t\ttileColor = Color{0, 0, 0, \"未知地形\"}\n\t\t\t}\n\n\t\t\t// 翻转X坐标\n\t\t\tflippedX := width - x - 1\n\n\t\t\t// 按 scale 填充方块\n\t\t\tfor dy := 0; dy < scale; dy++ {\n\t\t\t\tfor dx := 0; dx < scale; dx++ {\n\t\t\t\t\timg.Set(flippedX*scale+dx, y*scale+dy, color.RGBA{\n\t\t\t\t\t\tR: tileColor.R,\n\t\t\t\t\t\tG: tileColor.G,\n\t\t\t\t\t\tB: tileColor.B,\n\t\t\t\t\t\tA: 255,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn img\n}\n\n// GenerateMap 生成完整的地图\nfunc (g *DSTMapGenerator) GenerateMap(saveFilePath, outputPath string, width, height int) error {\n\t// 读取并解码地图数据\n\ttilesBase64, err := g.ReadSaveFile(saveFilePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttileIds, err := g.DecodeMapData(tilesBase64)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// 确保生成的图像为指定的宽度和高度\n\tfmt.Printf(\"生成的地图尺寸: %dx%d\\n\", width, height)\n\n\t// 创建地图图像\n\timg := g.CreateMapImage(tileIds, width, height, 16)\n\n\t// 保存图像\n\tf, err := os.Create(outputPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"创建输出文件失败: %v\", err)\n\t}\n\tdefer f.Close()\n\n\tif err := png.Encode(f, img); err != nil {\n\t\treturn fmt.Errorf(\"保存图像失败: %v\", err)\n\t}\n\n\tfmt.Printf(\"地图已保存到: %s\\n\", outputPath)\n\treturn nil\n}\n\n// ExtractDimensions 从文件中读取并提取 height 和 width\nfunc ExtractDimensions(filePath string) (int, int, error) {\n\t// 读取文件内容\n\tdata, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\n\t// 将文件内容转换为字符串\n\tinput := string(data)\n\n\t// 定义正则表达式\n\theightRegex := regexp.MustCompile(`height=(\\d+)`)\n\twidthRegex := regexp.MustCompile(`width=(\\d+)`)\n\n\t// 查找匹配\n\theightMatch := heightRegex.FindStringSubmatch(input)\n\twidthMatch := widthRegex.FindStringSubmatch(input)\n\n\t// 返回结果\n\tvar height, width int\n\tif len(heightMatch) > 1 {\n\t\tfmt.Sscanf(heightMatch[1], \"%d\", &height)\n\t} else {\n\t\theight = 0 // 未找到时返回 0\n\t}\n\n\tif len(widthMatch) > 1 {\n\t\tfmt.Sscanf(widthMatch[1], \"%d\", &width)\n\t} else {\n\t\twidth = 0 // 未找到时返回 0\n\t}\n\n\treturn height, width, nil\n}\n\n// WalrusHut_Plains\nfunc main() {\n\tfilePath := \"save/session/50D0753A78BF681E/0000000004\"\n\theight, width, err := ExtractDimensions(filePath)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t\treturn\n\t}\n\tgenerator := NewDSTMapGenerator()\n\terr = generator.GenerateMap(\n\t\tfilePath,\n\t\t\"dst_map.png\",\n\t\theight, // 指定宽度\n\t\twidth,  // 指定高度\n\t)\n\tif err != nil {\n\t\tfmt.Printf(\"生成地图时出错: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n"
  },
  {
    "path": "internal/service/dstPath/dst_path.go",
    "content": "package dstPath\n\nimport (\n\t\"dst-admin-go/internal/service/dstConfig\"\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n)\n\ntype DstPath interface {\n\tUpdateCommand(clusterName string) (string, error)\n}\n\nfunc EscapePath(path string) string {\n\tif runtime.GOOS == \"windows\" {\n\t\treturn path\n\t}\n\t// 在这里添加需要转义的特殊字符\n\tescapedChars := []string{\" \", \"'\", \"(\", \")\"}\n\tfor _, char := range escapedChars {\n\t\tpath = strings.ReplaceAll(path, char, \"\\\\\"+char)\n\t}\n\treturn path\n}\n\nfunc GetBaseUpdateCmd(cluster dstConfig.DstConfig) string {\n\tsteamCmdPath := cluster.Steamcmd\n\tdstInstallDir := cluster.Force_install_dir\n\tif cluster.Beta == 1 {\n\t\tdstInstallDir = dstInstallDir + \"-beta\"\n\t}\n\t// 确保路径是跨平台兼容的\n\tdstInstallDir = filepath.Clean(EscapePath(dstInstallDir))\n\tsteamCmdPath = filepath.Clean(steamCmdPath)\n\n\t// 构建基本命令\n\tbaseCmd := \"+login anonymous +force_install_dir %s +app_update 343050\"\n\tif cluster.Beta == 1 {\n\t\tbaseCmd += \" -beta updatebeta\"\n\t}\n\tbaseCmd += \" validate +quit\"\n\tbaseCmd = fmt.Sprintf(baseCmd, dstInstallDir)\n\treturn baseCmd\n}\n"
  },
  {
    "path": "internal/service/dstPath/linux_dst.go",
    "content": "package dstPath\n\nimport (\n\t\"dst-admin-go/internal/pkg/utils/fileUtils\"\n\t\"dst-admin-go/internal/service/dstConfig\"\n\t\"fmt\"\n\t\"path/filepath\"\n)\n\ntype LinuxDstPath struct {\n\tdstConfig dstConfig.Config\n}\n\nfunc NewLinuxDstPath(dstConfig dstConfig.Config) *LinuxDstPath {\n\treturn &LinuxDstPath{dstConfig: dstConfig}\n}\n\nfunc (d LinuxDstPath) UpdateCommand(clusterName string) (string, error) {\n\tcluster, err := d.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsteamCmdPath := cluster.Steamcmd\n\tbaseCmd := GetBaseUpdateCmd(cluster)\n\tvar cmd string\n\tsteamCmdScript := filepath.Join(steamCmdPath, \"steamcmd.sh\")\n\tif cluster.Bin == 86 {\n\t\tcmd = fmt.Sprintf(\"cd %s ; box86 ./linux32/steamcmd %s\", steamCmdPath, baseCmd)\n\t} else {\n\t\tif fileUtils.Exists(steamCmdScript) {\n\t\t\tcmd = fmt.Sprintf(\"cd %s ; ./steamcmd.sh %s\", steamCmdPath, baseCmd)\n\t\t} else {\n\t\t\tcmd = fmt.Sprintf(\"cd %s ; ./steamcmd %s\", steamCmdPath, baseCmd)\n\t\t}\n\t}\n\treturn cmd, nil\n}\n"
  },
  {
    "path": "internal/service/dstPath/window_dst.go",
    "content": "package dstPath\n\nimport (\n\t\"dst-admin-go/internal/service/dstConfig\"\n\t\"fmt\"\n)\n\ntype WindowDstPath struct {\n\tdstConfig dstConfig.Config\n}\n\nfunc NewWindowDst(dstConfig dstConfig.Config) *WindowDstPath {\n\treturn &WindowDstPath{dstConfig: dstConfig}\n}\n\nfunc (d WindowDstPath) UpdateCommand(clusterName string) (string, error) {\n\tcluster, err := d.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsteamCmdPath := cluster.Steamcmd\n\tbaseCmd := GetBaseUpdateCmd(cluster)\n\n\tvar cmd string\n\tcmd = fmt.Sprintf(\"cd /d %s && Start steamcmd.exe %s\", steamCmdPath, baseCmd)\n\treturn cmd, nil\n}\n"
  },
  {
    "path": "internal/service/game/factory.go",
    "content": "package game\n\nimport (\n\t\"dst-admin-go/internal/service/dstConfig\"\n\t\"dst-admin-go/internal/service/levelConfig\"\n\t\"runtime\"\n)\n\nfunc NewGame(dstConfig dstConfig.Config, levelConfigUtils *levelConfig.LevelConfigUtils) Process {\n\tif runtime.GOOS == \"windows\" {\n\t\treturn NewWindowProcess(&dstConfig, levelConfigUtils)\n\t}\n\treturn NewLinuxProcess(dstConfig, levelConfigUtils)\n}\n"
  },
  {
    "path": "internal/service/game/linux_process.go",
    "content": "package game\n\nimport (\n\t\"dst-admin-go/internal/pkg/utils/dstUtils\"\n\t\"dst-admin-go/internal/pkg/utils/shellUtils\"\n\t\"dst-admin-go/internal/service/dstConfig\"\n\t\"dst-admin-go/internal/service/levelConfig\"\n\t\"log\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype LinuxProcess struct {\n\tdstConfig        dstConfig.Config\n\tlevelConfigUtils *levelConfig.LevelConfigUtils\n\tmu               sync.Mutex // 保护启动/停止操作，防止并发执行\n}\n\nfunc NewLinuxProcess(dstConfig dstConfig.Config, levelConfigUtils *levelConfig.LevelConfigUtils) *LinuxProcess {\n\treturn &LinuxProcess{\n\t\tdstConfig:        dstConfig,\n\t\tlevelConfigUtils: levelConfigUtils,\n\t}\n}\n\nfunc (p *LinuxProcess) SessionName(clusterName, levelName string) string {\n\treturn \"DST_8level_\" + levelName + \"_\" + clusterName\n}\n\nfunc (p *LinuxProcess) Start(clusterName, levelName string) error {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\terr := p.stop(clusterName, levelName)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn p.launchLevel(clusterName, levelName)\n}\n\nfunc (p *LinuxProcess) launchLevel(clusterName, levelName string) error {\n\tcluster, err := p.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbin := cluster.Bin\n\tdstInstallDir := cluster.Force_install_dir\n\tif cluster.Beta == 1 {\n\t\tdstInstallDir = dstInstallDir + \"-beta\"\n\t}\n\tugcDirectory := cluster.Ugc_directory\n\tpersistent_storage_root := cluster.Persistent_storage_root\n\tconf_dir := cluster.Conf_dir\n\tvar startCmd = \"\"\n\n\tdstInstallDir = dstUtils.EscapePath(dstInstallDir)\n\tlog.Println(dstInstallDir)\n\tsessionName := p.SessionName(clusterName, levelName)\n\tif bin == 64 {\n\t\tstartCmd = \"cd \" + dstInstallDir + \"/bin64 ; screen -d -m -S \\\"\" + sessionName + \"\\\"  ./dontstarve_dedicated_server_nullrenderer_x64 -console -cluster \" + clusterName + \" -shard \" + levelName\n\t} else if bin == 100 {\n\t\tstartCmd = \"cd \" + dstInstallDir + \"/bin64 ; screen -d -m -S \\\"\" + sessionName + \"\\\"  ./dontstarve_dedicated_server_nullrenderer_x64_luajit -console -cluster \" + clusterName + \" -shard \" + levelName\n\t} else if bin == 86 {\n\t\tstartCmd = \"cd \" + dstInstallDir + \"/bin64 ; screen -d -m -S \\\"\" + sessionName + \"\\\" box86 ./dontstarve_dedicated_server_nullrenderer_x64 -console -cluster \" + clusterName + \" -shard \" + levelName\n\t} else if bin == 2664 {\n\t\tstartCmd = \"cd \" + dstInstallDir + \"/bin64 ; screen -d -m -S \\\"\" + sessionName + \"\\\" box64 ./dontstarve_dedicated_server_nullrenderer_x64 -console -cluster \" + clusterName + \" -shard \" + levelName\n\t} else {\n\t\tstartCmd = \"cd \" + dstInstallDir + \"/bin ; screen -d -m -S \\\"\" + sessionName + \"\\\"  ./dontstarve_dedicated_server_nullrenderer -console -cluster \" + clusterName + \" -shard \" + levelName\n\t}\n\n\tif ugcDirectory != \"\" {\n\t\tstartCmd += \" -ugc_directory \" + ugcDirectory\n\t}\n\tif persistent_storage_root != \"\" {\n\t\tstartCmd += \" -persistent_storage_root \" + persistent_storage_root\n\t}\n\tif conf_dir != \"\" {\n\t\tstartCmd += \" -conf_dir \" + conf_dir\n\t}\n\tstartCmd += \"  ;\"\n\tlog.Println(\"正在启动世界\", \"cluster: \", clusterName, \"level: \", levelName, \"command: \", startCmd)\n\t_, err = shellUtils.Shell(startCmd)\n\treturn err\n}\n\nfunc (p *LinuxProcess) shutdownLevel(clusterName, levelName string) error {\n\tok, err := p.Status(clusterName, levelName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !ok {\n\t\treturn nil\n\t}\n\tshell := \"screen -S \\\"\" + p.SessionName(clusterName, levelName) + \"\\\" -p 0 -X stuff \\\"c_shutdown(true)\\\\n\\\"\"\n\tlog.Println(\"正在shutdown世界\", \"cluster: \", clusterName, \"level: \", levelName, \"command: \", shell)\n\t_, err = shellUtils.Shell(shell)\n\treturn err\n}\n\nfunc (p *LinuxProcess) killLevel(clusterName, level string) error {\n\n\tif ok, err := p.Status(clusterName, level); err != nil || !ok {\n\t\treturn nil\n\t}\n\tcmd := \" ps -ef | grep -v grep | grep -v tail |grep '\" + clusterName + \"'|grep \" + level + \" |sed -n '1P'|awk '{print $2}' |xargs kill -9\"\n\tlog.Println(\"正在kill世界\", \"cluster: \", clusterName, \"level: \", level, \"command: \", cmd)\n\t_, err := shellUtils.Shell(cmd)\n\treturn err\n}\n\nfunc (p *LinuxProcess) Stop(clusterName, levelName string) error {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\treturn p.stop(clusterName, levelName)\n}\n\n// stop 内部实现，不加锁，供 Start 等方法内部调用\nfunc (p *LinuxProcess) stop(clusterName, levelName string) error {\n\tp.shutdownLevel(clusterName, levelName)\n\ttime.Sleep(3 * time.Second)\n\n\tif ok, err := p.Status(clusterName, levelName); err == nil && ok {\n\t\tvar i uint8 = 1\n\t\tfor {\n\t\t\tif ok, err := p.Status(clusterName, levelName); err == nil && ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tp.shutdownLevel(clusterName, levelName)\n\t\t\tlog.Println(\"正在第\", i, \"次stop世界\", \"cluster: \", clusterName, \"level: \", levelName)\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t\ti++\n\t\t\tif i > 3 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tlog.Println(\"使用kill命令强制结束世界\", \"cluster: \", clusterName, \"level: \", levelName)\n\treturn p.killLevel(clusterName, levelName)\n}\n\nfunc (p *LinuxProcess) StartAll(clusterName string) error {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\terr := p.stopAll(clusterName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig, err := p.levelConfigUtils.GetLevelConfig(clusterName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar wg sync.WaitGroup\n\twg.Add(len(config.LevelList))\n\tfor i := range config.LevelList {\n\t\tgo func(i int) {\n\t\t\tdefer func() {\n\t\t\t\twg.Done()\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tlog.Println(r)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tlevelName := config.LevelList[i].File\n\t\t\terr := p.launchLevel(clusterName, levelName)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}(i)\n\t}\n\tClearScreen()\n\twg.Wait()\n\treturn nil\n}\n\nfunc (p *LinuxProcess) StopAll(clusterName string) error {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\treturn p.stopAll(clusterName)\n}\n\n// stopAll 内部实现，不加锁，供 StartAll 等方法内部调用\nfunc (p *LinuxProcess) stopAll(clusterName string) error {\n\tconfig, err := p.levelConfigUtils.GetLevelConfig(clusterName)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tvar wg sync.WaitGroup\n\twg.Add(len(config.LevelList))\n\tfor i := range config.LevelList {\n\t\tgo func(i int) {\n\t\t\tdefer func() {\n\t\t\t\twg.Done()\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tlog.Println(r)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tlevelName := config.LevelList[i].File\n\t\t\terr := p.stop(clusterName, levelName)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}(i)\n\t}\n\twg.Wait()\n\treturn nil\n}\n\nfunc (p *LinuxProcess) Status(clusterName, levelName string) (bool, error) {\n\tcmd := \" ps -ef | grep -v grep | grep -v tail |grep '\" + clusterName + \"'|grep \" + levelName + \" |sed -n '1P'|awk '{print $2}' \"\n\tresult, err := shellUtils.Shell(cmd)\n\tif err != nil {\n\t\treturn false, nil\n\t}\n\tres := strings.Split(result, \"\\n\")[0]\n\treturn res != \"\", nil\n}\n\nfunc (p *LinuxProcess) Command(clusterName, levelName, command string) error {\n\tcmd := \"screen -S \\\"\" + p.SessionName(clusterName, levelName) + \"\\\" -p 0 -X stuff \\\"\" + command + \"\\\\n\\\"\"\n\t_, err := shellUtils.Shell(cmd)\n\treturn err\n}\n\nfunc (p *LinuxProcess) PsAuxSpecified(clusterName, levelName string) DstPsAux {\n\tdstPsAux := DstPsAux{}\n\tcmd := \"ps -aux | grep -v grep | grep -v tail | grep \" + clusterName + \"  | grep \" + levelName + \" | sed -n '2P' |awk '{print $3, $4, $5, $6}'\"\n\n\tinfo, err := shellUtils.Shell(cmd)\n\tif err != nil {\n\t\tlog.Println(cmd + \" error: \" + err.Error())\n\t\treturn dstPsAux\n\t}\n\tif info == \"\" {\n\t\treturn dstPsAux\n\t}\n\n\tarr := strings.Split(info, \" \")\n\tdstPsAux.CpuUage = strings.Replace(arr[0], \"\\n\", \"\", -1)\n\tdstPsAux.MemUage = strings.Replace(arr[1], \"\\n\", \"\", -1)\n\tdstPsAux.VSZ = strings.Replace(arr[2], \"\\n\", \"\", -1)\n\tdstPsAux.RSS = strings.Replace(arr[3], \"\\n\", \"\", -1)\n\n\treturn dstPsAux\n}\n\nconst (\n\t// ClearScreenCmd 检查目前所有的screen作业，并删除已经无法使用的screen作业\n\tClearScreenCmd = \"screen -wipe \"\n)\n\nfunc ClearScreen() bool {\n\tresult, err := shellUtils.Shell(ClearScreenCmd)\n\tif err != nil {\n\t\treturn false\n\t}\n\tres := strings.Split(result, \"\\n\")[0]\n\treturn res != \"\"\n}\n"
  },
  {
    "path": "internal/service/game/process.go",
    "content": "package game\n\ntype DstPsAux struct {\n\tCpuUage string `json:\"cpuUage\"`\n\tMemUage string `json:\"memUage\"`\n\tVSZ     string `json:\"VSZ\"`\n\tRSS     string `json:\"RSS\"`\n}\n\ntype Process interface {\n\tSessionName(clusterName, levelName string) string\n\n\tStart(clusterName, levelName string) error\n\tStop(clusterName, levelName string) error\n\tStartAll(clusterName string) error\n\tStopAll(clusterName string) error\n\n\tStatus(clusterName, levelName string) (bool, error)\n\n\tCommand(clusterName, levelName, command string) error\n\n\tPsAuxSpecified(clusterName, levelName string) DstPsAux\n}\n"
  },
  {
    "path": "internal/service/game/windowGameCli.go",
    "content": "//package game\n//\n//import (\n//\t\"bufio\"\n//\t\"fmt\"\n//\t\"io\"\n//\t\"log\"\n//\t\"os\"\n//\t\"os/exec\"\n//\t\"strings\"\n//\t\"sync\"\n//\t\"sync/atomic\"\n//\t\"time\"\n//\n//\t\"github.com/shirou/gopsutil/process\"\n//)\n//\n//type ClusterContainer struct {\n//\tcontainer map[string]*LevelInstance\n//\tlock      sync.RWMutex\n//}\n//\n//func NewClusterContainer() *ClusterContainer {\n//\treturn &ClusterContainer{\n//\t\tcontainer: map[string]*LevelInstance{},\n//\t}\n//}\n//\n//func (receiver *ClusterContainer) StartLevel(cluster, levelName string, bin int, steamcmd, dstServerInstall, ugcDirectory, persistent_storage_root, conf_dir string) {\n//\treceiver.lock.Lock()\n//\n//\tkey := cluster + \"_\" + levelName\n//\tlog.Println(\"正在启动 \", key)\n//\tvalue, ok := receiver.container[key]\n//\tif !ok {\n//\t\tvalue = NewLevelInstance(cluster, levelName, bin, steamcmd, dstServerInstall, ugcDirectory, persistent_storage_root, conf_dir)\n//\t\treceiver.container[key] = value\n//\t} else {\n//\t\tif value.dstSeverInstall != dstServerInstall {\n//\t\t\t// 直接删除，避免死锁（不调用 Remove）\n//\t\t\tdelete(receiver.container, key)\n//\t\t\tvalue = NewLevelInstance(cluster, levelName, bin, steamcmd, dstServerInstall, ugcDirectory, persistent_storage_root, conf_dir)\n//\t\t\treceiver.container[key] = value\n//\t\t}\n//\t}\n//\t// 在锁外启动，避免长时间持有锁\n//\treceiver.lock.Unlock()\n//\tvalue.Start()\n//}\n//\n//func (receiver *ClusterContainer) StopLevel(cluster, levelName string) {\n//\treceiver.lock.RLock()\n//\tdefer receiver.lock.RUnlock()\n//\n//\tkey := cluster + \"_\" + levelName\n//\tvalue, ok := receiver.container[key]\n//\tlog.Println(\"正在停止世界\", cluster, levelName)\n//\tif ok {\n//\t\tvalue.Stop()\n//\t}\n//}\n//\n//func (receiver *ClusterContainer) Send(cluster, levelName, message string) {\n//\treceiver.lock.RLock()\n//\tdefer receiver.lock.RUnlock()\n//\n//\tkey := cluster + \"_\" + levelName\n//\tvalue, ok := receiver.container[key]\n//\tif ok {\n//\t\tvalue.Send(message)\n//\t}\n//}\n//\n//func (receiver *ClusterContainer) Status(cluster, levelName string) bool {\n//\treceiver.lock.RLock()\n//\tdefer receiver.lock.RUnlock()\n//\n//\tkey := cluster + \"_\" + levelName\n//\tvalue, ok := receiver.container[key]\n//\tif ok {\n//\t\treturn value.Status()\n//\t}\n//\treturn false\n//}\n//\n//func (receiver *ClusterContainer) MemUsage(cluster, levelName string) float64 {\n//\treceiver.lock.RLock()\n//\tdefer receiver.lock.RUnlock()\n//\n//\tkey := cluster + \"_\" + levelName\n//\tvalue, ok := receiver.container[key]\n//\tif ok {\n//\t\treturn value.GetProcessMemInfo()\n//\t}\n//\treturn 0\n//}\n//\n//func (receiver *ClusterContainer) CpuUsage(cluster, levelName string) float64 {\n//\treceiver.lock.RLock()\n//\tdefer receiver.lock.RUnlock()\n//\n//\tkey := cluster + \"_\" + levelName\n//\tvalue, ok := receiver.container[key]\n//\tif ok {\n//\t\treturn value.GetProcessCpuInfo()\n//\t}\n//\treturn 0\n//}\n//\n//func (receiver *ClusterContainer) Remove(cluster, levelName string) {\n//\treceiver.lock.Lock()\n//\tdefer receiver.lock.Unlock()\n//\tkey := cluster + \"_\" + levelName\n//\tdelete(receiver.container, key)\n//}\n//\n//type LevelInstance struct {\n//\trunning atomic.Bool\n//\tlock    sync.Mutex\n//\tstdin   io.WriteCloser\n//\tstdout  io.ReadCloser\n//\tpid     int\n//\n//\tcluster                 string\n//\tlevelName               string\n//\tbin                     int\n//\tsteamcmd                string\n//\tdstSeverInstall         string\n//\tugc_directory           string\n//\tpersistent_storage_root string\n//\tconf_dir                string\n//}\n//\n//func NewLevelInstance(cluster, levelName string, bin int, steamcmd, dstServerInstall, ugc_directory, persistent_storage_root, conf_dir string) *LevelInstance {\n//\treturn &LevelInstance{\n//\t\tcluster:                 cluster,\n//\t\tlevelName:               levelName,\n//\t\tbin:                     bin,\n//\t\tsteamcmd:                steamcmd,\n//\t\tdstSeverInstall:         dstServerInstall,\n//\t\tugc_directory:           ugc_directory,\n//\t\tpersistent_storage_root: persistent_storage_root,\n//\t\tconf_dir:                conf_dir,\n//\t}\n//}\n//\n//func (receiver *LevelInstance) Status() bool {\n//\treturn receiver.running.Load()\n//}\n//\n//func (receiver *LevelInstance) Start() {\n//\treceiver.lock.Lock()\n//\n//\t// 锁内检查，避免竞态条件\n//\tif receiver.running.Load() == true {\n//\t\treceiver.lock.Unlock()\n//\t\treturn\n//\t}\n//\n//\t// 创建输出文件\n//\ttLogsTxt := receiver.cluster + \"_\" + receiver.levelName + \"_log\"\n//\tlogFile, err := os.Create(tLogsTxt)\n//\tif err != nil {\n//\t\tlog.Println(\"Error creating log file:\", err)\n//\t\treceiver.lock.Unlock()\n//\t\treturn\n//\t}\n//\tdefer func(logFile *os.File) {\n//\t\terr := logFile.Close()\n//\t\tif err != nil {\n//\t\t\tlog.Println(\"Error closing log file:\", err)\n//\t\t}\n//\t}(logFile)\n//\n//\tvar args []string\n//\tif receiver.bin == 32 {\n//\t\targs = append(args, \"./dontstarve_dedicated_server_nullrenderer.exe\")\n//\t} else {\n//\t\targs = append(args, \"./dontstarve_dedicated_server_nullrenderer_x64.exe\")\n//\t}\n//\targs = append(args, \"-console\")\n//\targs = append(args, \"-cluster\")\n//\targs = append(args, receiver.cluster)\n//\targs = append(args, \"-shard\")\n//\targs = append(args, receiver.levelName)\n//\tif receiver.persistent_storage_root != \"\" {\n//\t\targs = append(args, \"-persistent_storage_root\")\n//\t\targs = append(args, receiver.persistent_storage_root)\n//\t}\n//\tif receiver.conf_dir != \"\" {\n//\t\targs = append(args, \"-conf_dir\")\n//\t\targs = append(args, receiver.conf_dir)\n//\t}\n//\tif receiver.ugc_directory != \"\" {\n//\t\targs = append(args, \"-ugc_directory\")\n//\t\targs = append(args, receiver.ugc_directory)\n//\t}\n//\t// 创建一个 cmd 对象\n//\tcmd := exec.Command(args[0], args[1:]...)\n//\tif receiver.bin == 32 {\n//\t\tcmd.Dir = receiver.dstSeverInstall + \"\\\\bin\"\n//\t} else {\n//\t\tcmd.Dir = receiver.dstSeverInstall + \"\\\\bin64\"\n//\t}\n//\n//\treceiver.running.Store(true)\n//\treceiver.lock.Unlock()\n//\n//\t// 获取子进程的 stdin、stdout 和 stderr\n//\treceiver.stdin, err = cmd.StdinPipe()\n//\tif err != nil {\n//\t\tlog.Printf(\"Error getting stdin pipe: %v\\n\", err)\n//\t\treceiver.running.Store(false)\n//\t\treturn\n//\t}\n//\treceiver.stdout, err = cmd.StdoutPipe()\n//\tif err != nil {\n//\t\tlog.Printf(\"Error getting stdout pipe: %v\\n\", err)\n//\t\treceiver.running.Store(false)\n//\t\treturn\n//\t}\n//\tstderr, err := cmd.StderrPipe()\n//\tif err != nil {\n//\t\tlog.Printf(\"Error getting stderr pipe: %v\\n\", err)\n//\t\treceiver.running.Store(false)\n//\t\treturn\n//\t}\n//\n//\t// 启动子进程\n//\tif err := cmd.Start(); err != nil {\n//\t\tfmt.Printf(\"Error starting command: %v\\n\", err)\n//\t\treceiver.running.Store(false)\n//\t\treturn\n//\t}\n//\n//\treceiver.pid = cmd.Process.Pid\n//\t// 开启 goroutine 实时读取子进程的输出并写入文件和控制台\n//\tgo func() {\n//\t\t_, _ = io.Copy(io.MultiWriter(os.Stdout, logFile), receiver.stdout)\n//\t}()\n//\tgo func() {\n//\t\t_, _ = io.Copy(io.MultiWriter(os.Stderr, logFile), stderr)\n//\t}()\n//\n//\t// 等待子进程退出\n//\tif err := cmd.Wait(); err != nil {\n//\t\tlog.Printf(\"Error waiting for command: %v\\n\", err)\n//\t\tif receiver.stdin != nil {\n//\t\t\t_ = receiver.stdin.Close()\n//\t\t}\n//\t\tif receiver.stdout != nil {\n//\t\t\t_ = receiver.stdout.Close()\n//\t\t}\n//\t\treceiver.running.Store(false)\n//\t}\n//\tlog.Println(\"process exit !!!\")\n//\treceiver.running.Store(false)\n//}\n//\n//func (receiver *LevelInstance) Stop() {\n//\treceiver.lock.Lock()\n//\tdefer receiver.lock.Unlock()\n//\n//\tif receiver.running.Load() == true {\n//\t\terr := receiver.Send(\"c_shutdown(true)\")\n//\t\tif err != nil {\n//\t\t\tlog.Println(\"stop game error\", err)\n//\t\t} else {\n//\t\t\treceiver.running.Store(false)\n//\t\t}\n//\t}\n//}\n//\n//func (receiver *LevelInstance) Send(cmd string) error {\n//\t// 向子进程写入命令\n//\twriter := bufio.NewWriter(receiver.stdin)\n//\tlog.Println(\"cmd: \", cmd)\n//\tcmd = strings.Replace(cmd, \"\\\\\", \"\", -1)\n//\tinput := cmd + \"\\n\"\n//\t_, err := writer.WriteString(input)\n//\tif err != nil {\n//\t\tlog.Printf(\"Error writing to stdin: %v\\n\", err)\n//\t\treturn err\n//\t}\n//\terr = writer.Flush()\n//\tif err != nil {\n//\t\treturn err\n//\t}\n//\treturn nil\n//}\n//\n//func (receiver *LevelInstance) GetProcessMemInfo() float64 {\n//\tp, err := process.NewProcess(int32(receiver.pid))\n//\tif err != nil {\n//\t\tfmt.Println(\"Error getting process info:\", err)\n//\t\treturn 0\n//\t}\n//\t// 获取内存使用情况\n//\tmemInfo, err := p.MemoryInfo()\n//\tif err != nil {\n//\t\tfmt.Println(\"Error getting memory info:\", err)\n//\t\treturn 0\n//\t}\n//\tmemUsage := float64(memInfo.RSS) / (1024 * 1024) // 以 MB 为单位\n//\treturn memUsage\n//}\n//\n//func (receiver *LevelInstance) GetProcessCpuInfo() float64 {\n//\tp, err := process.NewProcess(int32(receiver.pid))\n//\tif err != nil {\n//\t\tfmt.Println(\"Error getting process info:\", err)\n//\t\treturn 0\n//\t}\n//\t// 获取 CPU 使用情况\n//\tcpuPercent, err := p.Percent(time.Second)\n//\tif err != nil {\n//\t\tfmt.Println(\"Error getting CPU percent:\", err)\n//\t\treturn 0\n//\t}\n//\treturn cpuPercent\n//}\n\npackage game\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"github.com/shirou/gopsutil/process\"\n)\n\ntype ClusterContainer struct {\n\tcontainer map[string]*LevelInstance\n\tlock      sync.RWMutex\n}\n\nfunc NewClusterContainer() *ClusterContainer {\n\treturn &ClusterContainer{\n\t\tcontainer: map[string]*LevelInstance{},\n\t\tlock:      sync.RWMutex{},\n\t}\n}\n\nfunc (receiver *ClusterContainer) StartLevel(cluster, levelName string, bin int, steamcmd, dstServerInstall, ugcDirectory, persistent_storage_root, conf_dir string) {\n\t//receiver.lock.Lock()\n\t//defer receiver.lock.Unlock()\n\n\tkey := cluster + \"_\" + levelName\n\tlog.Println(\"正在启动 \", key)\n\tvalue, ok := receiver.container[key]\n\tif !ok {\n\t\tvalue = NewLevelInstance(cluster, levelName, bin, steamcmd, dstServerInstall, ugcDirectory, persistent_storage_root, conf_dir)\n\t\treceiver.container[key] = value\n\t} else {\n\t\tif value.dstSeverInstall != dstServerInstall {\n\t\t\treceiver.Remove(cluster, levelName)\n\t\t\tvalue = NewLevelInstance(cluster, levelName, bin, steamcmd, dstServerInstall, ugcDirectory, persistent_storage_root, conf_dir)\n\t\t\treceiver.container[key] = value\n\t\t}\n\t}\n\tvalue.Start()\n}\n\nfunc (receiver *ClusterContainer) StopLevel(cluster, levelName string) {\n\tkey := cluster + \"_\" + levelName\n\tvalue, ok := receiver.container[key]\n\tlog.Println(\"正在停止世界\", cluster, levelName)\n\tif ok {\n\t\tvalue.Stop()\n\t}\n}\n\nfunc (receiver *ClusterContainer) Send(cluster, levelName, message string) {\n\tkey := cluster + \"_\" + levelName\n\tvalue, ok := receiver.container[key]\n\tif ok {\n\t\tvalue.Send(message)\n\t}\n}\n\nfunc (receiver *ClusterContainer) Status(cluster, levelName string) bool {\n\tkey := cluster + \"_\" + levelName\n\tvalue, ok := receiver.container[key]\n\tif ok {\n\t\treturn value.Status()\n\t}\n\treturn false\n}\n\nfunc (receiver *ClusterContainer) MemUsage(cluster, levelName string) float64 {\n\tkey := cluster + \"_\" + levelName\n\tvalue, ok := receiver.container[key]\n\tif ok {\n\t\treturn value.GetProcessMemInfo()\n\t}\n\treturn 0\n}\n\nfunc (receiver *ClusterContainer) CpuUsage(cluster, levelName string) float64 {\n\tkey := cluster + \"_\" + levelName\n\tvalue, ok := receiver.container[key]\n\tif ok {\n\t\treturn value.GetProcessCpuInfo()\n\t}\n\treturn 0\n}\n\nfunc (receiver *ClusterContainer) Remove(cluster, levelName string) {\n\treceiver.lock.RLock()\n\tdefer receiver.lock.RUnlock()\n\tkey := cluster + \"_\" + levelName\n\tdelete(receiver.container, key)\n}\n\ntype LevelInstance struct {\n\trunning atomic.Bool\n\tlock    sync.Mutex\n\tstdin   io.WriteCloser\n\tstdout  io.ReadCloser\n\tpid     int\n\n\tcluster                 string\n\tlevelName               string\n\tbin                     int\n\tsteamcmd                string\n\tdstSeverInstall         string\n\tugc_directory           string\n\tpersistent_storage_root string\n\tconf_dir                string\n}\n\nfunc NewLevelInstance(cluster, levelName string, bin int, steamcmd, dstServerInstall, ugc_directory, persistent_storage_root, conf_dir string) *LevelInstance {\n\trunning := atomic.Bool{}\n\trunning.Store(false)\n\tgame := &LevelInstance{\n\t\tlock:                    sync.Mutex{},\n\t\trunning:                 running,\n\t\tcluster:                 cluster,\n\t\tlevelName:               levelName,\n\t\tbin:                     bin,\n\t\tsteamcmd:                steamcmd,\n\t\tdstSeverInstall:         dstServerInstall,\n\t\tugc_directory:           ugc_directory,\n\t\tpersistent_storage_root: persistent_storage_root,\n\t\tconf_dir:                conf_dir,\n\t}\n\treturn game\n}\n\nfunc (receiver *LevelInstance) Status() bool {\n\treturn receiver.running.Load()\n}\n\nfunc (receiver *LevelInstance) Start() {\n\tif receiver.running.Load() == true {\n\t\treturn\n\t}\n\treceiver.lock.Lock()\n\t// 创建输出文件\n\ttLogsTxt := receiver.cluster + \"_\" + receiver.levelName + \"_log\"\n\tlogFile, err := os.Create(tLogsTxt)\n\tif err != nil {\n\t\tlog.Println(\"Error creating log file:\", err)\n\t\treturn\n\t}\n\tdefer func(logFile *os.File) {\n\t\terr := logFile.Close()\n\t\tif err != nil {\n\t\t\treceiver.lock.Unlock()\n\t\t}\n\t}(logFile)\n\n\tvar args []string\n\tif receiver.bin == 32 {\n\t\targs = append(args, \"./dontstarve_dedicated_server_nullrenderer.exe\")\n\t} else {\n\t\targs = append(args, \"./dontstarve_dedicated_server_nullrenderer_x64.exe\")\n\t}\n\targs = append(args, \"-console\")\n\targs = append(args, \"-cluster\")\n\targs = append(args, receiver.cluster)\n\targs = append(args, \"-shard\")\n\targs = append(args, receiver.levelName)\n\tif receiver.persistent_storage_root != \"\" {\n\t\targs = append(args, \"-persistent_storage_root\")\n\t\targs = append(args, receiver.persistent_storage_root)\n\t}\n\tif receiver.conf_dir != \"\" {\n\t\targs = append(args, \"-conf_dir\")\n\t\targs = append(args, receiver.conf_dir)\n\t}\n\tif receiver.ugc_directory != \"\" {\n\t\targs = append(args, \"-ugc_directory\")\n\t\targs = append(args, receiver.ugc_directory)\n\t}\n\t// 创建一个 cmd 对象\n\tcmd := exec.Command(args[0], args[1:]...)\n\tif receiver.bin == 32 {\n\t\tcmd.Dir = receiver.dstSeverInstall + \"\\\\bin\"\n\t} else {\n\t\tcmd.Dir = receiver.dstSeverInstall + \"\\\\bin64\"\n\t}\n\n\treceiver.running.Store(true)\n\treceiver.lock.Unlock()\n\t// 获取子进程的 stdin、stdout 和 stderr\n\treceiver.stdin, err = cmd.StdinPipe()\n\tif err != nil {\n\t\tlog.Printf(\"Error getting stdin pipe: %v\\n\", err)\n\t\treturn\n\t}\n\treceiver.stdout, err = cmd.StdoutPipe()\n\tif err != nil {\n\t\tlog.Printf(\"Error getting stdout pipe: %v\\n\", err)\n\t\treturn\n\t}\n\tstderr, err := cmd.StderrPipe()\n\tif err != nil {\n\t\tlog.Printf(\"Error getting stderr pipe: %v\\n\", err)\n\t\treturn\n\t}\n\n\t// 启动子进程\n\tif err := cmd.Start(); err != nil {\n\t\tfmt.Printf(\"Error starting command: %v\\n\", err)\n\t\treturn\n\t}\n\n\treceiver.pid = cmd.Process.Pid\n\t// 开启 goroutine 实时读取子进程的输出并写入文件和控制台\n\tgo func() {\n\t\tio.Copy(io.MultiWriter(os.Stdout, logFile), receiver.stdout)\n\t}()\n\tgo func() {\n\t\tio.Copy(io.MultiWriter(os.Stderr, logFile), stderr)\n\t}()\n\n\t// 等待子进程退出\n\tif err := cmd.Wait(); err != nil {\n\t\tlog.Printf(\"Error waiting for command: %v\\n\", err)\n\t\tif receiver.stdin != nil {\n\t\t\treceiver.stdin.Close()\n\t\t}\n\t\tif receiver.stdout != nil {\n\t\t\treceiver.stdout.Close()\n\t\t}\n\t\treceiver.running.Store(false)\n\t}\n\tlog.Println(\"process exit !!!\")\n\treceiver.running.Store(false)\n}\n\nfunc (receiver *LevelInstance) Stop() {\n\treceiver.lock.Lock()\n\tdefer receiver.lock.Unlock()\n\n\tif receiver.running.Load() == true {\n\t\terr := receiver.Send(\"c_shutdown(true)\")\n\t\tif err != nil {\n\t\t\tlog.Println(\"stop game error\", err)\n\t\t} else {\n\t\t\treceiver.running.Store(false)\n\t\t}\n\t}\n}\n\nfunc (receiver *LevelInstance) Send(cmd string) error {\n\t// 向子进程写入命令\n\twriter := bufio.NewWriter(receiver.stdin)\n\tlog.Println(\"cmd: \", cmd)\n\tcmd = strings.Replace(cmd, \"\\\\\", \"\", -1)\n\tinput := cmd + \"\\n\"\n\t_, err := writer.WriteString(input)\n\tif err != nil {\n\t\tlog.Printf(\"Error writing to stdin: %v\\n\", err)\n\t\treturn err\n\t}\n\terr = writer.Flush()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (receiver *LevelInstance) GetProcessMemInfo() float64 {\n\tp, err := process.NewProcess(int32(receiver.pid))\n\tif err != nil {\n\t\tfmt.Println(\"Error getting process info:\", err)\n\t\treturn 0\n\t}\n\t// 获取内存使用情况\n\tmemInfo, err := p.MemoryInfo()\n\tif err != nil {\n\t\tfmt.Println(\"Error getting memory info:\", err)\n\t\treturn 0\n\t}\n\tmemUsage := float64(memInfo.RSS) / (1024 * 1024) // 以 MB 为单位\n\treturn memUsage\n}\n\nfunc (receiver *LevelInstance) GetProcessCpuInfo() float64 {\n\tp, err := process.NewProcess(int32(receiver.pid))\n\tif err != nil {\n\t\tfmt.Println(\"Error getting process info:\", err)\n\t\treturn 0\n\t}\n\t// 获取 CPU 使用情况\n\tcpuPercent, err := p.Percent(time.Second)\n\tif err != nil {\n\t\tfmt.Println(\"Error getting CPU percent:\", err)\n\t\treturn 0\n\t}\n\treturn cpuPercent\n}\n"
  },
  {
    "path": "internal/service/game/window_process.go",
    "content": "package game\n\nimport (\n\t\"dst-admin-go/internal/service/dstConfig\"\n\t\"dst-admin-go/internal/service/levelConfig\"\n\t\"fmt\"\n\t\"log\"\n\t\"sync\"\n)\n\ntype WindowProcess struct {\n\tdstConfig        dstConfig.Config\n\tcli              *ClusterContainer\n\tlevelConfigUtils *levelConfig.LevelConfigUtils\n}\n\nfunc NewWindowProcess(dstConfig *dstConfig.Config, levelConfigUtils *levelConfig.LevelConfigUtils) *WindowProcess {\n\treturn &WindowProcess{\n\t\tdstConfig:        *dstConfig,\n\t\tcli:              NewClusterContainer(),\n\t\tlevelConfigUtils: levelConfigUtils,\n\t}\n}\n\nfunc (p *WindowProcess) SessionName(clusterName, levelName string) string {\n\treturn clusterName + \"_\" + levelName\n}\n\nfunc (p *WindowProcess) Start(clusterName, levelName string) error {\n\tconfig, err := p.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo func() {\n\t\tp.cli.StartLevel(clusterName, levelName, config.Bin, config.Steamcmd, config.Force_install_dir, config.Ugc_directory, config.Persistent_storage_root, config.Conf_dir)\n\t}()\n\n\treturn err\n}\n\nfunc (p *WindowProcess) Stop(clusterName, levelName string) error {\n\tp.cli.StopLevel(clusterName, levelName)\n\treturn nil\n}\n\nfunc (p *WindowProcess) StartAll(clusterName string) error {\n\n\terr := p.StopAll(clusterName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig, err := p.levelConfigUtils.GetLevelConfig(clusterName)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tvar wg sync.WaitGroup\n\twg.Add(len(config.LevelList))\n\tfor i := range config.LevelList {\n\t\tgo func(i int) {\n\t\t\tdefer func() {\n\t\t\t\twg.Done()\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tlog.Println(r)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tlevelName := config.LevelList[i].File\n\t\t\terr := p.Start(clusterName, levelName)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}(i)\n\t}\n\twg.Wait()\n\treturn nil\n}\n\nfunc (p *WindowProcess) StopAll(clusterName string) error {\n\n\tconfig, err := p.levelConfigUtils.GetLevelConfig(clusterName)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tvar wg sync.WaitGroup\n\twg.Add(len(config.LevelList))\n\tfor i := range config.LevelList {\n\t\tgo func(i int) {\n\t\t\tdefer func() {\n\t\t\t\twg.Done()\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tlog.Println(r)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tlevelName := config.LevelList[i].File\n\t\t\terr := p.Stop(clusterName, levelName)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}(i)\n\t}\n\twg.Wait()\n\treturn nil\n}\n\nfunc (p *WindowProcess) Status(clusterName, levelName string) (bool, error) {\n\treturn p.cli.Status(clusterName, levelName), nil\n}\n\nfunc (p *WindowProcess) Command(clusterName, levelName, command string) error {\n\tp.cli.Send(clusterName, levelName, command)\n\treturn nil\n}\n\nfunc (p *WindowProcess) PsAuxSpecified(clusterName, levelName string) DstPsAux {\n\tcpuUsage := p.cli.CpuUsage(clusterName, levelName)\n\tmemUsage := p.cli.MemUsage(clusterName, levelName)\n\tdstPsAux := DstPsAux{}\n\tdstPsAux.RSS = fmt.Sprintf(\"%f\", memUsage*1024)\n\tdstPsAux.CpuUage = fmt.Sprintf(\"%f\", cpuUsage)\n\treturn dstPsAux\n}\n"
  },
  {
    "path": "internal/service/gameArchive/game_archive.go",
    "content": "package gameArchive\n\nimport (\n\t\"dst-admin-go/internal/config\"\n\t\"dst-admin-go/internal/pkg/utils/dstUtils\"\n\t\"dst-admin-go/internal/pkg/utils/fileUtils\"\n\t\"dst-admin-go/internal/pkg/utils/luaUtils\"\n\t\"dst-admin-go/internal/service/archive\"\n\t\"dst-admin-go/internal/service/gameConfig\"\n\t\"dst-admin-go/internal/service/level\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"path\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype GameArchive struct {\n\tgameConfig *gameConfig.GameConfig\n\tlevel      *level.LevelService\n\tarchive    *archive.PathResolver\n}\n\nfunc NewGameArchive(gameConfig *gameConfig.GameConfig, level *level.LevelService, archive *archive.PathResolver) *GameArchive {\n\treturn &GameArchive{\n\t\tgameConfig: gameConfig,\n\t\tlevel:      level,\n\t\tarchive:    archive,\n\t}\n}\n\ntype GameArchiveInfo struct {\n\tClusterName        string `json:\"clusterName\"`\n\tClusterDescription string `json:\"clusterDescription\"`\n\tClusterPassword    string `json:\"clusterPassword\"`\n\tGameMod            string `json:\"gameMod\"`\n\tMaxPlayers         int    `json:\"maxPlayers\"`\n\tMods               int    `json:\"mods\"`\n\tIpConnect          string `json:\"ipConnect\"`\n\tPort               uint   `json:\"port\"`\n\tIp                 string `json:\"ip\"`\n\tMeta               Meta   `json:\"meta\"`\n\tVersion            int64  `json:\"version\"`\n\tLastVersion        int64  `json:\"lastVersion\"`\n}\n\ntype Clock struct {\n\tTotalTimeInPhase     int     `lua:\"totaltimeinphase\"`\n\tCycles               int     `lua:\"cycles\"`\n\tPhase                string  `lua:\"phase\"`\n\tRemainingTimeInPhase float64 `lua:\"remainingtimeinphase\"`\n\tMooomPhaseCycle      int     `lua:\"mooomphasecycle\"`\n\tSegs                 Segs    `lua:\"segs\"`\n}\n\ntype Segs struct {\n\tNight int `lua:\"night\"`\n\tDay   int `lua:\"day\"`\n\tDusk  int `lua:\"dusk\"`\n}\n\ntype IsRandom struct {\n\tSummer bool `lua:\"summer\"`\n\tAutumn bool `lua:\"autumn\"`\n\tSpring bool `lua:\"spring\"`\n\tWinter bool `lua:\"winter\"`\n}\n\ntype Lengths struct {\n\tSummer int `lua:\"summer\"`\n\tAutumn int `lua:\"autumn\"`\n\tSpring int `lua:\"spring\"`\n\tWinter int `lua:\"winter\"`\n}\n\ntype Seasons struct {\n\tPremode               bool                   `lua:\"premode\"`\n\tSeason                string                 `lua:\"season\"`\n\tElapsedDaysInSeason   int                    `lua:\"elapseddaysinseason\"`\n\tIsRandom              IsRandom               `lua:\"israndom\"`\n\tLengths               Lengths                `lua:\"lengths\"`\n\tRemainingDaysInSeason int                    `lua:\"remainingdaysinseason\"`\n\tMode                  string                 `lua:\"mode\"`\n\tTotalDaysInSeason     int                    `lua:\"totaldaysinseason\"`\n\tSegs                  map[string]interface{} `lua:\"segs\"`\n}\n\ntype Meta struct {\n\tClock   Clock   `lua:\"clock\"`\n\tSeasons Seasons `lua:\"seasons\"`\n}\n\nfunc (d *GameArchive) GetGameArchive(clusterName string) GameArchiveInfo {\n\n\tvar wg sync.WaitGroup\n\twg.Add(5)\n\n\tgameArchie := GameArchiveInfo{}\n\tbasePath := d.archive.ClusterPath(clusterName)\n\n\t// 获取基础信息\n\tgo func() {\n\t\tclusterIni, _ := d.gameConfig.GetClusterIni(clusterName)\n\t\tgameArchie.ClusterName = clusterIni.ClusterName\n\t\tgameArchie.ClusterDescription = clusterIni.ClusterDescription\n\t\tgameArchie.ClusterPassword = clusterIni.ClusterPassword\n\t\tgameArchie.GameMod = clusterIni.GameMode\n\t\tgameArchie.MaxPlayers = int(clusterIni.MaxPlayers)\n\t\twg.Done()\n\t}()\n\n\t// 获取mod数量\n\tgo func() {\n\t\tmasterModoverrides, err := fileUtils.ReadFile(path.Join(basePath, \"Master\", \"modoverrides.lua\"))\n\t\tif err != nil {\n\t\t\tgameArchie.Mods = 0\n\t\t} else {\n\t\t\tgameArchie.Mods = len(dstUtils.WorkshopIds(masterModoverrides))\n\t\t}\n\t\twg.Done()\n\t}()\n\n\t// 获取天数和季节\n\tgo func() {\n\t\tdefer func() {\n\t\t\twg.Done()\n\t\t\tif r := recover(); r != nil {\n\t\t\t}\n\t\t}()\n\t\tgameArchie.Meta = d.Snapshoot(clusterName)\n\t}()\n\n\t// 获取直连ip\n\tgo func() {\n\t\tdefer func() {\n\t\t\twg.Done()\n\t\t\tif r := recover(); r != nil {\n\n\t\t\t}\n\t\t}()\n\t\tclusterIni, _ := d.gameConfig.GetClusterIni(clusterName)\n\t\tpassword := clusterIni.ClusterPassword\n\t\tserverIni := d.level.GetServerIni(path.Join(basePath, \"Master\", \"server.ini\"), true)\n\t\twanip := config.Cfg.WanIP\n\t\tif wanip != \"\" {\n\n\t\t} else {\n\t\t\tipv4, err := d.GetPublicIP()\n\t\t\tif err != nil {\n\t\t\t\twanip, _ = d.GetPrivateIP()\n\t\t\t} else {\n\t\t\t\twanip = ipv4\n\t\t\t}\n\t\t}\n\t\tif wanip == \"\" {\n\t\t\tgameArchie.IpConnect = \"\"\n\t\t} else {\n\t\t\t// c_connect(\"IP address\", port, \"password\")\n\t\t\tif password != \"\" {\n\t\t\t\tgameArchie.IpConnect = \"c_connect(\\\"\" + wanip + \"\\\",\" + strconv.Itoa(int(serverIni.ServerPort)) + \",\\\"\" + password + \"\\\"\" + \")\"\n\t\t\t} else {\n\t\t\t\tgameArchie.IpConnect = \"c_connect(\\\"\" + wanip + \"\\\",\" + strconv.Itoa(int(serverIni.ServerPort)) + \")\"\n\t\t\t}\n\t\t}\n\t\tgameArchie.Port = serverIni.ServerPort\n\t\tgameArchie.Ip = wanip\n\n\t}()\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\twg.Done()\n\t\t\tif r := recover(); r != nil {\n\n\t\t\t}\n\t\t}()\n\t\tlocalVersion, _ := d.archive.GetLocalDstVersion(clusterName)\n\t\tversion, _ := d.archive.GetLastDstVersion()\n\n\t\tgameArchie.Version = localVersion\n\t\tgameArchie.LastVersion = version\n\t}()\n\n\twg.Wait()\n\n\treturn gameArchie\n}\n\n/*\n- 以下均是公开接口，返回纯文本数据\n- 如果服务端有透明代理或者分流，可能获取到的是代理ip，优先使用能获取真实ip的接口\n- 饥荒暂不支持IPv6\n*/\nfunc (d *GameArchive) GetPublicIP() (string, error) {\n\tapis := [...]string{\n\t\t// == 以下优先返回国内ip ==\n\t\t\"https://myip.ipip.net\",\n\t\t\"https://cdid.c-ctrip.com/model-poc2/h\", // 某携程api，IPv6优先\n\t\t// == 以下优先返回国外ip ==\n\t\t\"https://lobby-v2.klei.com/lobby/getIP\", // Klei官方api\n\t\t\"https://api.ipify.org\",\n\t\t\"https://ifconfig.me/ip\",\n\t\t\"https://checkip.amazonaws.com\",\n\t}\n\n\tclient := &http.Client{\n\t\tTimeout: 5 * time.Second,\n\t}\n\n\tfor _, api := range apis {\n\t\tresp, err := client.Get(api)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tresp.Body.Close()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tipv4Regex := regexp.MustCompile(`\\b\\d{1,3}(\\.\\d{1,3}){3}\\b`)\n\t\ttext := strings.TrimSpace(string(body))\n\t\tif match := ipv4Regex.FindString(text); match != \"\" {\n\t\t\tif ip := net.ParseIP(match); ip != nil && ip.To4() != nil {\n\t\t\t\treturn ip.String(), nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", nil\n}\n\nfunc (d *GameArchive) GetPrivateIP() (string, error) {\n\taddrs, err := net.InterfaceAddrs()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, addr := range addrs {\n\t\tvar ip net.IP\n\n\t\tswitch v := addr.(type) {\n\t\tcase *net.IPNet:\n\t\t\tip = v.IP\n\t\tcase *net.IPAddr:\n\t\t\tip = v.IP\n\t\t}\n\n\t\tif ip == nil || ip.IsLoopback() {\n\t\t\tcontinue\n\t\t}\n\t\tif ipv4 := ip.To4(); ipv4 != nil {\n\t\t\treturn ipv4.String(), nil\n\t\t}\n\t}\n\n\treturn \"\", nil\n}\n\nfunc (d *GameArchive) getSubPathLevel(rootP, curPath string) int {\n\trelPath, err := filepath.Rel(rootP, curPath)\n\tif err != nil {\n\t\t// 如果计算相对路径时出错，说明 curPath 不是 rootP 的子目录\n\t\treturn -1\n\t}\n\t// 计算相对路径中 \"..\" 的数量，即为层数\n\treturn strings.Count(relPath, \"..\")\n}\n\nfunc (d *GameArchive) FindLatestMetaFile(rootDir string) (string, error) {\n\tvar latestFile string\n\tvar latestModTime time.Time\n\terr := filepath.Walk(rootDir, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !info.IsDir() && filepath.Ext(info.Name()) == \".meta\" && d.getSubPathLevel(rootDir, path) == 2 {\n\t\t\tif info.ModTime().After(latestModTime) {\n\t\t\t\tlatestFile = path\n\t\t\t\tlatestModTime = info.ModTime()\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn latestFile, nil\n}\n\nfunc findLatestMetaFile(directory string) (string, error) {\n\t// 检查指定目录是否存在\n\t_, err := os.Stat(directory)\n\tif os.IsNotExist(err) {\n\t\treturn \"\", fmt.Errorf(\"目录不存在：%s\", directory)\n\t}\n\n\t// 获取指定目录下一级的所有子目录\n\tsubdirs, err := ioutil.ReadDir(directory)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"读取目录失败：%s\", err)\n\t}\n\n\t// 用于存储最新的.meta文件路径和其修改时间\n\tvar latestMetaFile string\n\tvar latestMetaFileTime time.Time\n\n\tfor _, subdir := range subdirs {\n\t\t// 检查子目录是否是目录\n\t\tif subdir.IsDir() {\n\t\t\tsubdirPath := filepath.Join(directory, subdir.Name())\n\n\t\t\t// 获取子目录下的所有文件\n\t\t\tfiles, err := ioutil.ReadDir(subdirPath)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"读取子目录失败：%s\", err)\n\t\t\t}\n\n\t\t\tfor _, file := range files {\n\t\t\t\t// 检查文件是否是.meta文件\n\t\t\t\tif !file.IsDir() && filepath.Ext(file.Name()) == \".meta\" {\n\t\t\t\t\t// 获取文件的修改时间\n\t\t\t\t\tmodifiedTime := file.ModTime()\n\n\t\t\t\t\t// 如果找到的文件的修改时间比当前最新的.meta文件的修改时间更晚，则更新最新的.meta文件路径和修改时间\n\t\t\t\t\tif modifiedTime.After(latestMetaFileTime) {\n\t\t\t\t\t\tlatestMetaFile = filepath.Join(subdirPath, file.Name())\n\t\t\t\t\t\tlatestMetaFileTime = modifiedTime\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif latestMetaFile == \"\" {\n\t\treturn \"\", fmt.Errorf(\"未找到.meta文件\")\n\t}\n\n\treturn latestMetaFile, nil\n}\n\nfunc (d *GameArchive) Snapshoot(clusterName string) Meta {\n\tsessionPath := filepath.Join(d.archive.KleiBasePath(clusterName), clusterName, \"Master\", \"save\", \"session\")\n\tp, err := findLatestMetaFile(sessionPath)\n\tif err != nil {\n\t\tfmt.Println(\"查找meta文件失败\", err)\n\t\treturn Meta{}\n\t}\n\tcontent, err := fileUtils.ReadFile(p)\n\tif err != nil {\n\t\tfmt.Println(\"读取meta文件失败\", err)\n\t\treturn Meta{}\n\t}\n\tvar data Meta\n\terr = luaUtils.LuaTable2Struct(content[:len(content)-1], reflect.ValueOf(&data).Elem())\n\tif err != nil {\n\t\tfmt.Println(\"解析meta文件失败\", err)\n\t\treturn Meta{}\n\t}\n\treturn data\n}\n"
  },
  {
    "path": "internal/service/gameConfig/game_config.go",
    "content": "package gameConfig\n\nimport (\n\t\"dst-admin-go/internal/pkg/utils/collectionUtils\"\n\t\"dst-admin-go/internal/pkg/utils/dstUtils\"\n\t\"dst-admin-go/internal/pkg/utils/fileUtils\"\n\t\"dst-admin-go/internal/service/archive\"\n\t\"dst-admin-go/internal/service/levelConfig\"\n\t\"log\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/go-ini/ini\"\n)\n\nconst (\n\tClusterIniTemplate      = \"./static/template/cluster2.ini\"\n\tMasterServerIniTemplate = \"./static/template/master_server.ini\"\n\tCavesServerIniTemplate  = \"./static/template/caves_server.ini\"\n\tServerIniTemplate       = \"./static/template/server.ini\"\n)\n\ntype ClusterIni struct {\n\t// [GAEMPLAY]\n\tGameMode        string `json:\"game_mode\"`\n\tMaxPlayers      uint   `json:\"max_players\"`\n\tPvp             bool   `json:\"pvp\"`\n\tPauseWhenNobody bool   `json:\"pause_when_nobody\"`\n\tVoteEnabled     bool   `json:\"vote_enabled\"`\n\tVoteKickEnabled bool   `json:\"vote_kick_enabled\"`\n\n\t// [NETWORK]\n\tLanOnlyCluster     bool   `json:\"lan_only_cluster\"`\n\tClusterIntention   string `json:\"cluster_intention\"`\n\tClusterDescription string `json:\"cluster_description\"`\n\tClusterPassword    string `json:\"cluster_password\"`\n\tClusterName        string `json:\"cluster_name\"`\n\tOfflineCluster     bool   `json:\"offline_cluster\"`\n\tClusterLanguage    string `json:\"cluster_language\"`\n\tWhitelistSlots     uint   `json:\"whitelist_slots\"`\n\tTickRate           uint   `json:\"tick_rate\"`\n\n\t// [MISC]\n\tConsoleEnabled bool `json:\"console_enabled\"`\n\tMaxSnapshots   uint `json:\"max_snapshots\"`\n\n\t// [SHARD]\n\tShardEnabled bool   `json:\"shard_enabled\"`\n\tBindIp       string `json:\"bind_ip\"`\n\tMasterIp     string `json:\"master_ip\"`\n\tMasterPort   uint   `json:\"master_port\"`\n\tClusterKey   string `json:\"cluster_key\"`\n\n\t// [STEAM]\n\tSteamGroupId     string `json:\"steam_group_id\"`\n\tSteamGroupOnly   bool   `json:\"steam_group_only\"`\n\tSteamGroupAdmins bool   `json:\"steam_group_admins\"`\n}\ntype ServerIni struct {\n\n\t// [NETWORK]\n\tServerPort uint `json:\"server_port\"`\n\t// [SHARD]\n\tIsMaster bool   `json:\"is_master\"`\n\tName     string `json:\"name\"`\n\tId       uint   `json:\"id\"`\n\n\t// [ACCOUNT]\n\tEncodeUserPath bool `json:\"encode_user_path\"`\n\n\t// [STEAM]\n\tAuthenticationPort uint `json:\"authentication_port\"`\n\tMasterServerPort   uint `json:\"master_server_port\"`\n}\n\ntype ClusterIniConfig struct {\n\tClusterIni *ClusterIni `json:\"cluster\"`\n\tToken      string      `json:\"token\"`\n}\ntype GameConfig struct {\n\tarchive          *archive.PathResolver\n\tlevelConfigUtils *levelConfig.LevelConfigUtils\n}\n\nfunc NewGameConfig(archive *archive.PathResolver, levelConfigUtils *levelConfig.LevelConfigUtils) *GameConfig {\n\treturn &GameConfig{\n\t\tarchive:          archive,\n\t\tlevelConfigUtils: levelConfigUtils,\n\t}\n}\n\nfunc (p *GameConfig) GetClusterIniConfig(clusterName string) (ClusterIniConfig, error) {\n\tclusterIni, err := p.GetClusterIni(clusterName)\n\tif err != nil {\n\t\treturn ClusterIniConfig{}, err\n\t}\n\tclusterToken, err := p.GetClusterToken(clusterName)\n\tif err != nil {\n\t\treturn ClusterIniConfig{}, err\n\t}\n\treturn ClusterIniConfig{\n\t\tClusterIni: &clusterIni,\n\t\tToken:      clusterToken,\n\t}, nil\n}\n\nfunc (p *GameConfig) SaveClusterIniConfig(clusterName string, config *ClusterIniConfig) error {\n\terr := p.SaveClusterIni(clusterName, config.ClusterIni)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = p.SaveClusterToken(clusterName, config.Token)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (p *GameConfig) GetClusterIni(clusterName string) (ClusterIni, error) {\n\t// return fileUtils.ReadLnFile(p.archive.ClusterPath(clusterName))\n\t// 加载 INI 文件\n\tclusterIniPath := p.archive.ClusterIniPath(clusterName)\n\tif !fileUtils.Exists(clusterIniPath) {\n\t\terr := fileUtils.CreateFileIfNotExists(clusterIniPath)\n\t\tif err != nil {\n\t\t\treturn ClusterIni{}, err\n\t\t}\n\t}\n\tcfg, err := ini.Load(clusterIniPath)\n\tif err != nil {\n\t\tlog.Panicln(\"Failed to load INI file:\", err)\n\t}\n\n\t// [GAMEPLAY]\n\tGAMEPLAY := cfg.Section(\"GAMEPLAY\")\n\n\tnewClusterIni := ClusterIni{}\n\n\tnewClusterIni.GameMode = GAMEPLAY.Key(\"game_mode\").String()\n\tnewClusterIni.MaxPlayers = GAMEPLAY.Key(\"max_players\").MustUint(8)\n\tnewClusterIni.Pvp = GAMEPLAY.Key(\"pvp\").MustBool(false)\n\tnewClusterIni.PauseWhenNobody = GAMEPLAY.Key(\"pause_when_empty\").MustBool(true)\n\tnewClusterIni.VoteEnabled = GAMEPLAY.Key(\"vote_enabled\").MustBool(true)\n\tnewClusterIni.VoteKickEnabled = GAMEPLAY.Key(\"vote_kick_enabled\").MustBool(true)\n\n\t// [NETWORK]\n\tNETWORK := cfg.Section(\"NETWORK\")\n\n\tnewClusterIni.LanOnlyCluster = NETWORK.Key(\"lan_only_cluster\").MustBool(false)\n\tnewClusterIni.ClusterIntention = NETWORK.Key(\"cluster_intention\").String()\n\tnewClusterIni.ClusterPassword = NETWORK.Key(\"cluster_password\").String()\n\tnewClusterIni.ClusterDescription = NETWORK.Key(\"cluster_description\").String()\n\tnewClusterIni.ClusterName = NETWORK.Key(\"cluster_name\").String()\n\tnewClusterIni.OfflineCluster = NETWORK.Key(\"offline_cluster\").MustBool(false)\n\tnewClusterIni.ClusterLanguage = NETWORK.Key(\"cluster_language\").MustString(\"zh\")\n\tnewClusterIni.WhitelistSlots = NETWORK.Key(\"whitelist_slots\").MustUint(0)\n\tnewClusterIni.TickRate = NETWORK.Key(\"tick_rate\").MustUint(15)\n\n\t// [MISC]\n\tMISC := cfg.Section(\"MISC\")\n\n\tnewClusterIni.ConsoleEnabled = MISC.Key(\"console_enabled\").MustBool(true)\n\tnewClusterIni.MaxSnapshots = MISC.Key(\"max_snapshots\").MustUint(6)\n\n\t// [SHARD]\n\tSHARD := cfg.Section(\"SHARD\")\n\n\tnewClusterIni.ShardEnabled = SHARD.Key(\"shard_enabled\").MustBool(true)\n\tnewClusterIni.BindIp = SHARD.Key(\"bind_ip\").MustString(\"127.0.0.1\")\n\tnewClusterIni.MasterIp = SHARD.Key(\"master_ip\").MustString(\"127.0.0.1\")\n\tnewClusterIni.MasterPort = SHARD.Key(\"master_port\").MustUint(10888)\n\tnewClusterIni.ClusterKey = SHARD.Key(\"cluster_key\").String()\n\n\t// [STEAM]\n\tSTEAM := cfg.Section(\"STEAM\")\n\n\tnewClusterIni.SteamGroupId = STEAM.Key(\"steam_group_id\").MustString(\"\")\n\tnewClusterIni.SteamGroupOnly = STEAM.Key(\"steam_group_only\").MustBool(false)\n\tnewClusterIni.SteamGroupAdmins = STEAM.Key(\"steam_group_admins\").MustBool(false)\n\n\tclusterIni, err := fileUtils.ReadLnFile(clusterIniPath)\n\tif err != nil {\n\t\tpanic(\"read cluster.ini file error: \" + err.Error())\n\t}\n\tfor _, value := range clusterIni {\n\t\tif value == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif strings.Contains(value, \"cluster_password\") {\n\t\t\tsplit := strings.Split(value, \"=\")\n\t\t\tif len(split) > 1 {\n\t\t\t\ts := strings.TrimSpace(split[1])\n\t\t\t\tnewClusterIni.ClusterPassword = s\n\t\t\t}\n\t\t}\n\t\tif strings.Contains(value, \"cluster_description\") {\n\t\t\tsplit := strings.Split(value, \"=\")\n\t\t\tif len(split) > 1 {\n\t\t\t\ts := strings.TrimSpace(split[1])\n\t\t\t\tnewClusterIni.ClusterDescription = s\n\t\t\t}\n\t\t}\n\t\tif strings.Contains(value, \"cluster_name\") {\n\t\t\tsplit := strings.Split(value, \"=\")\n\t\t\tif len(split) > 1 {\n\t\t\t\ts := strings.TrimSpace(split[1])\n\t\t\t\tnewClusterIni.ClusterName = s\n\t\t\t}\n\t\t}\n\t}\n\treturn newClusterIni, nil\n}\n\nfunc (p *GameConfig) SaveClusterIni(clusterName string, clusterIni *ClusterIni) error {\n\tclusterIniPath := p.archive.ClusterIniPath(clusterName)\n\terr := fileUtils.WriterTXT(clusterIniPath, dstUtils.ParseTemplate(ClusterIniTemplate, clusterIni))\n\treturn err\n}\n\nfunc (p *GameConfig) GetClusterToken(clusterName string) (string, error) {\n\treturn fileUtils.ReadFile(p.archive.ClusterTokenPath(clusterName))\n}\n\nfunc (p *GameConfig) SaveClusterToken(clusterName string, token string) error {\n\treturn fileUtils.WriterTXT(p.archive.ClusterTokenPath(clusterName), token)\n}\n\nfunc (p *GameConfig) GetAdminList(clusterName string) ([]string, error) {\n\treturn fileUtils.ReadLnFile(p.archive.AdminlistPath(clusterName))\n}\n\nfunc (p *GameConfig) GetBlackList(clusterName string) ([]string, error) {\n\treturn fileUtils.ReadLnFile(p.archive.BlacklistPath(clusterName))\n}\n\nfunc (p *GameConfig) GetWhithList(clusterName string) ([]string, error) {\n\treturn fileUtils.ReadLnFile(p.archive.WhitelistPath(clusterName))\n}\n\nfunc (p *GameConfig) SaveAdminList(clusterName string, list []string) error {\n\tpath := p.archive.AdminlistPath(clusterName)\n\terr := fileUtils.CreateFileIfNotExists(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlnFile, err := fileUtils.ReadLnFile(path)\n\tset := collectionUtils.ToSet(append(lnFile, list...))\n\terr = fileUtils.WriterLnFile(path, set)\n\treturn err\n}\n\nfunc (p *GameConfig) SaveBlackList(clusterName string, list []string) error {\n\tpath := p.archive.BlacklistPath(clusterName)\n\terr := fileUtils.CreateFileIfNotExists(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlnFile, err := fileUtils.ReadLnFile(path)\n\tset := collectionUtils.ToSet(append(lnFile, list...))\n\terr = fileUtils.WriterLnFile(path, set)\n\treturn err\n}\n\nfunc (p *GameConfig) SaveWhithList(clusterName string, list []string) error {\n\tpath := p.archive.WhitelistPath(clusterName)\n\terr := fileUtils.CreateFileIfNotExists(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlnFile, err := fileUtils.ReadLnFile(path)\n\tset := collectionUtils.ToSet(append(lnFile, list...))\n\terr = fileUtils.WriterLnFile(path, set)\n\treturn err\n}\n\ntype HomeConfigVO struct {\n\tClusterIntention   string `json:\"clusterIntention\"`\n\tClusterName        string `json:\"clusterName\"`\n\tClusterDescription string `json:\"clusterDescription\"`\n\tGameMode           string `json:\"gameMode\"`\n\tPvp                bool   `json:\"pvp\"`\n\tMaxPlayers         uint   `json:\"maxPlayers\"`\n\tMaxSnapshots       uint   `json:\"max_snapshots\"`\n\tClusterPassword    string `json:\"clusterPassword\"`\n\tToken              string `json:\"token\"`\n\tMasterMapData      string `json:\"masterMapData\"`\n\tCavesMapData       string `json:\"cavesMapData\"`\n\tModData            string `json:\"modData\"`\n\tOtype              int64  `json:\"type\"`\n\tPauseWhenNobody    bool   `json:\"pause_when_nobody\"`\n\tVoteEnabled        bool   `json:\"vote_enabled\"`\n}\n\nfunc (p *GameConfig) GetHomeConfig(clusterName string) (HomeConfigVO, error) {\n\tclusterToken, err := p.GetClusterToken(clusterName)\n\tif err != nil {\n\t\treturn HomeConfigVO{}, err\n\t}\n\tclusterIni, err := p.GetClusterIni(clusterName)\n\tif err != nil {\n\t\treturn HomeConfigVO{}, err\n\t}\n\tmasterData, err := fileUtils.ReadFile(p.archive.DataFilePath(clusterName, \"Master\", \"leveldataoverride.lua\"))\n\tif err != nil {\n\t\treturn HomeConfigVO{}, err\n\t}\n\tcavesData, err := fileUtils.ReadFile(p.archive.DataFilePath(clusterName, \"Caves\", \"leveldataoverride.lua\"))\n\tif err != nil {\n\t\treturn HomeConfigVO{}, err\n\t}\n\tmodData, err := fileUtils.ReadFile(p.archive.DataFilePath(clusterName, \"Master\", \"modoverrides.lua\"))\n\tif err != nil {\n\t\treturn HomeConfigVO{}, err\n\t}\n\n\thomeConfigVo := HomeConfigVO{\n\t\tClusterIntention:   clusterIni.ClusterIntention,\n\t\tClusterName:        clusterIni.ClusterName,\n\t\tClusterDescription: clusterIni.ClusterDescription,\n\t\tGameMode:           clusterIni.GameMode,\n\t\tPvp:                clusterIni.Pvp,\n\t\tMaxPlayers:         clusterIni.MaxPlayers,\n\t\tMaxSnapshots:       clusterIni.MaxSnapshots,\n\t\tClusterPassword:    clusterIni.ClusterPassword,\n\t\tToken:              clusterToken,\n\t\tPauseWhenNobody:    clusterIni.PauseWhenNobody,\n\t\tVoteEnabled:        clusterIni.VoteEnabled,\n\t\tMasterMapData:      masterData,\n\t\tCavesMapData:       cavesData,\n\t\tModData:            modData,\n\t}\n\treturn homeConfigVo, nil\n}\n\nfunc (p *GameConfig) SaveConfig(clusterName string, homeConfig HomeConfigVO) {\n\tmodConfig := homeConfig.ModData\n\tif modConfig != \"\" {\n\t\tconfig, _ := p.levelConfigUtils.GetLevelConfig(clusterName)\n\t\tfor i := range config.LevelList {\n\t\t\tclusterPath := p.archive.ClusterPath(clusterName)\n\t\t\tfileUtils.WriterTXT(filepath.Join(clusterPath, config.LevelList[i].File, \"modoverrides.lua\"), modConfig)\n\t\t}\n\t\tvar serverModSetup = \"\"\n\t\tworkshopIds := dstUtils.WorkshopIds(modConfig)\n\t\tfor _, workshopId := range workshopIds {\n\t\t\tserverModSetup += \"ServerModSetup(\\\"\" + workshopId + \"\\\")\\n\"\n\t\t}\n\t\tfileUtils.WriterTXT(p.archive.GetModSetup(clusterName), serverModSetup)\n\t}\n}\n"
  },
  {
    "path": "internal/service/level/level.go",
    "content": "package level\n\nimport (\n\t\"dst-admin-go/internal/pkg/utils/dstUtils\"\n\t\"dst-admin-go/internal/pkg/utils/fileUtils\"\n\t\"dst-admin-go/internal/service/archive\"\n\t\"dst-admin-go/internal/service/dstConfig\"\n\t\"dst-admin-go/internal/service/game\"\n\t\"dst-admin-go/internal/service/gameConfig\"\n\t\"dst-admin-go/internal/service/levelConfig\"\n\t\"log\"\n\t\"path/filepath\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/go-ini/ini\"\n)\n\n// LevelService 关卡服务结构体\ntype LevelService struct {\n\tgameProcess      game.Process\n\tdstConfig        dstConfig.Config\n\tresolver         *archive.PathResolver\n\tlevelConfigUtils *levelConfig.LevelConfigUtils\n}\n\n// NewLevelService 创建关卡服务实例\nfunc NewLevelService(gameProcess game.Process, dstConfig dstConfig.Config, resolver *archive.PathResolver, levelConfigUtils *levelConfig.LevelConfigUtils) *LevelService {\n\treturn &LevelService{\n\t\tgameProcess:      gameProcess,\n\t\tdstConfig:        dstConfig,\n\t\tresolver:         resolver,\n\t\tlevelConfigUtils: levelConfigUtils,\n\t}\n}\n\n// GetLevelList 获取关卡列表\nfunc (l *LevelService) GetLevelList(clusterName string) []levelConfig.LevelInfo {\n\tconfig, err := l.levelConfigUtils.GetLevelConfig(clusterName)\n\tif err != nil {\n\t\treturn []levelConfig.LevelInfo{}\n\t}\n\tvar levels []levelConfig.LevelInfo\n\tif len(config.LevelList) == 0 {\n\t\tmasterLevelPath := filepath.Join(l.resolver.ClusterPath(clusterName), \"Master\")\n\t\tif !fileUtils.Exists(masterLevelPath) {\n\t\t\tmaster := levelConfig.LevelInfo{\n\t\t\t\tIsMaster:          true,\n\t\t\t\tLevelName:         \"森林\",\n\t\t\t\tUuid:              \"Master\",\n\t\t\t\tLeveldataoverride: \"return {}\",\n\t\t\t\tModoverrides:      \"return {}\",\n\t\t\t\tServerIni:         levelConfig.NewMasterServerIni(),\n\t\t\t}\n\t\t\tl.initLevel(filepath.Join(l.resolver.ClusterPath(clusterName), \"Master\"), &master)\n\t\t\tlevels = append([]levelConfig.LevelInfo{}, master)\n\t\t\tconfig.LevelList = append(config.LevelList, levelConfig.Item{\n\t\t\t\tName: \"森林\",\n\t\t\t\tFile: \"Master\",\n\t\t\t})\n\t\t\terr = l.levelConfigUtils.SaveLevelConfig(clusterName, config)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t\treturn levels\n\t\t} else {\n\t\t\t// 读取现有的 Master 世界配置\n\t\t\tmaster := l.GetLevel(clusterName, \"Master\")\n\t\t\tlevels = append([]levelConfig.LevelInfo{}, master)\n\t\t\tconfig.LevelList = append(config.LevelList, levelConfig.Item{\n\t\t\t\tName: \"森林\",\n\t\t\t\tFile: \"Master\",\n\t\t\t})\n\t\t\tcavesLevelPath := filepath.Join(l.resolver.ClusterPath(clusterName), \"Caves\")\n\t\t\tif fileUtils.Exists(cavesLevelPath) {\n\t\t\t\tconfig.LevelList = append(config.LevelList, levelConfig.Item{\n\t\t\t\t\tName: \"洞穴\",\n\t\t\t\t\tFile: \"Caves\",\n\t\t\t\t})\n\t\t\t\tcaves := l.GetLevel(clusterName, \"Caves\")\n\t\t\t\tlevels = append(levels, caves)\n\t\t\t}\n\t\t\terr = l.levelConfigUtils.SaveLevelConfig(clusterName, config)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t\treturn levels\n\t\t}\n\t}\n\tfor i := range config.LevelList {\n\t\tlevel1 := levelConfig.LevelInfo{}\n\t\tlevel1.LevelName = config.LevelList[i].Name\n\t\tlevel1.Uuid = config.LevelList[i].File\n\t\tlevel1.RunVersion = config.LevelList[i].RunVersion\n\t\tworld := l.GetLevel(clusterName, config.LevelList[i].File)\n\t\tlevel1.Leveldataoverride = world.Leveldataoverride\n\t\tlevel1.Modoverrides = world.Modoverrides\n\t\tlevel1.ServerIni = world.ServerIni\n\t\tlevels = append(levels, level1)\n\t}\n\treturn levels\n}\n\n// GetLevel 获取单个关卡配置\nfunc (l *LevelService) GetLevel(clusterName string, levelName string) levelConfig.LevelInfo {\n\tlevelFolderPath := filepath.Join(l.resolver.ClusterPath(clusterName), levelName)\n\tconfig, _ := l.levelConfigUtils.GetLevelConfig(clusterName)\n\tname := \"\"\n\tfor _, item := range config.LevelList {\n\t\tif item.File == levelName {\n\t\t\tname = item.Name\n\t\t}\n\t}\n\n\t// 读取 leveldataoverride.lua\n\tlPath := filepath.Join(levelFolderPath, \"leveldataoverride.lua\")\n\tleveldataoverride, err := fileUtils.ReadFile(lPath)\n\tif err != nil {\n\t\tleveldataoverride = \"return {}\"\n\t}\n\n\t// 读取 modoverrides.lua\n\tmPath := filepath.Join(levelFolderPath, \"modoverrides.lua\")\n\tmodoverrides, err := fileUtils.ReadFile(mPath)\n\tif err != nil {\n\t\tmodoverrides = \"return {}\"\n\t}\n\n\t// 读取 server.ini\n\tsPath := filepath.Join(levelFolderPath, \"server.ini\")\n\tserverIni := l.GetServerIni(sPath, levelName == \"Master\")\n\n\treturn levelConfig.LevelInfo{\n\t\tIsMaster:          levelName == \"Master\",\n\t\tLevelName:         name,\n\t\tUuid:              levelName,\n\t\tLeveldataoverride: leveldataoverride,\n\t\tModoverrides:      modoverrides,\n\t\tServerIni:         serverIni,\n\t}\n}\n\nfunc (l *LevelService) GetServerIni(filepath string, isMaster bool) levelConfig.ServerIni {\n\tfileUtils.CreateFileIfNotExists(filepath)\n\tvar serverPortDefault uint = 10998\n\tidDefault := 10010\n\n\tif isMaster {\n\t\tserverPortDefault = 10999\n\t\tidDefault = 10000\n\t}\n\n\tserverIni := levelConfig.NewCavesServerIni()\n\t// 加载 INI 文件\n\tcfg, err := ini.Load(filepath)\n\tif err != nil {\n\t\treturn serverIni\n\t}\n\n\t// [NETWORK]\n\tNETWORK := cfg.Section(\"NETWORK\")\n\n\tserverIni.ServerPort = NETWORK.Key(\"server_port\").MustUint(serverPortDefault)\n\n\t// [SHARD]\n\tSHARD := cfg.Section(\"SHARD\")\n\n\tserverIni.IsMaster = SHARD.Key(\"is_master\").MustBool(isMaster)\n\tserverIni.Name = SHARD.Key(\"name\").String()\n\tserverIni.Id = SHARD.Key(\"id\").MustUint(uint(idDefault))\n\n\t// [ACCOUNT]\n\tACCOUNT := cfg.Section(\"ACCOUNT\")\n\tserverIni.EncodeUserPath = ACCOUNT.Key(\"encode_user_path\").MustBool(true)\n\n\t// [STEAM]\n\tSTEAM := cfg.Section(\"STEAM\")\n\n\tserverIni.AuthenticationPort = STEAM.Key(\"authentication_port\").MustUint(8766)\n\tserverIni.MasterServerPort = STEAM.Key(\"master_server_port\").MustUint(27016)\n\n\treturn serverIni\n}\n\n// UpdateLevels 更新多个关卡配置\nfunc (l *LevelService) UpdateLevels(clusterName string, levels []levelConfig.LevelInfo) error {\n\tfor i := range levels {\n\t\tconfig, _ := l.dstConfig.GetDstConfig(clusterName)\n\t\tdstUtils.DedicatedServerModsSetup(config, levels[i].Modoverrides)\n\t\terr := l.UpdateLevel(clusterName, &levels[i])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// UpdateLevel 更新单个关卡配置\nfunc (l *LevelService) UpdateLevel(clusterName string, level *levelConfig.LevelInfo) error {\n\tlevelFolderPath := filepath.Join(l.resolver.ClusterPath(clusterName), level.Uuid)\n\tfileUtils.CreateDirIfNotExists(levelFolderPath)\n\tl.initLevel(levelFolderPath, level)\n\n\t// 记录level.json 文件\n\tlevelConfig, err := l.levelConfigUtils.GetLevelConfig(clusterName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor i := range levelConfig.LevelList {\n\t\tif level.Uuid == levelConfig.LevelList[i].File {\n\t\t\tlevelConfig.LevelList[i].Name = level.LevelName\n\t\t\t// 更新世界配置\n\t\t\tl.initLevel(levelFolderPath, level)\n\t\t\tbreak\n\t\t}\n\t}\n\terr = l.levelConfigUtils.SaveLevelConfig(clusterName, levelConfig)\n\treturn err\n}\n\n// CreateLevel 创建新关卡\nfunc (l *LevelService) CreateLevel(clusterName string, level *levelConfig.LevelInfo) error {\n\tuuid := \"\"\n\tif level.Uuid == \"\" {\n\t\tuuid = l.generateUUID()\n\t} else {\n\t\tuuid = level.Uuid\n\t}\n\tlevelFolderPath := filepath.Join(l.resolver.ClusterPath(clusterName), uuid)\n\tfileUtils.CreateDirIfNotExists(levelFolderPath)\n\tl.initLevel(levelFolderPath, level)\n\n\t// 记录level.json 文件\n\tconfig, err := l.levelConfigUtils.GetLevelConfig(clusterName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig.LevelList = append(config.LevelList, levelConfig.Item{Name: level.LevelName, File: uuid})\n\terr = l.levelConfigUtils.SaveLevelConfig(clusterName, config)\n\tif err != nil {\n\t\terr := fileUtils.DeleteFile(filepath.Join(l.resolver.ClusterPath(clusterName), uuid))\n\t\treturn err\n\t}\n\tlevel.Uuid = uuid\n\treturn nil\n}\n\n// DeleteLevel 删除关卡\nfunc (l *LevelService) DeleteLevel(clusterName string, levelName string) error {\n\t// 停止关卡服务\n\tl.gameProcess.Stop(clusterName, levelName)\n\n\t// 删除关卡目录\n\terr := fileUtils.DeleteDir(filepath.Join(l.resolver.ClusterPath(clusterName), levelName))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// 删除 json 文件中的记录\n\tconfig, err := l.levelConfigUtils.GetLevelConfig(clusterName)\n\tif err != nil {\n\t\tlog.Panicln(\"删除文件失败\")\n\t}\n\tnewLevelsConfig := levelConfig.LevelConfig{}\n\tfor i := range config.LevelList {\n\t\tif config.LevelList[i].File != levelName {\n\t\t\tnewLevelsConfig.LevelList = append(newLevelsConfig.LevelList, config.LevelList[i])\n\t\t}\n\t}\n\terr = l.levelConfigUtils.SaveLevelConfig(clusterName, &newLevelsConfig)\n\n\t// TODO 同时删除定时任务和自动维护\n\n\treturn err\n}\n\n// initLevel 初始化关卡文件\nfunc (l *LevelService) initLevel(levelFolderPath string, level *levelConfig.LevelInfo) {\n\n\tlPath := filepath.Join(levelFolderPath, \"leveldataoverride.lua\")\n\tmPath := filepath.Join(levelFolderPath, \"modoverrides.lua\")\n\tsPath := filepath.Join(levelFolderPath, \"server.ini\")\n\n\tfileUtils.CreateFileIfNotExists(lPath)\n\tfileUtils.CreateFileIfNotExists(mPath)\n\tfileUtils.CreateFileIfNotExists(sPath)\n\n\tfileUtils.WriterTXT(lPath, level.Leveldataoverride)\n\tfileUtils.WriterTXT(mPath, level.Modoverrides)\n\tserverBuf := l.ParseTemplate(level.ServerIni)\n\tfileUtils.WriterTXT(sPath, serverBuf)\n}\n\n// ParseTemplate 解析服务器配置模板\nfunc (l *LevelService) ParseTemplate(serverIni levelConfig.ServerIni) string {\n\t// 使用 gameConfig 中的 ParseTemplate 方法\n\treturn dstUtils.ParseTemplate(gameConfig.ServerIniTemplate, serverIni)\n}\n\n// generateUUID 生成 UUID\nfunc (l *LevelService) generateUUID() string {\n\t// 简化实现，实际应该使用标准的 UUID 生成库\n\treturn \"level_\" + strconv.FormatInt(time.Now().UnixNano(), 10)\n}\n"
  },
  {
    "path": "internal/service/levelConfig/level_config.go",
    "content": "package levelConfig\n\nimport (\n\t\"dst-admin-go/internal/pkg/utils/dstUtils\"\n\t\"dst-admin-go/internal/pkg/utils/fileUtils\"\n\t\"dst-admin-go/internal/service/archive\"\n\t\"encoding/json\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\ntype Item struct {\n\tName       string `json:\"name\"`\n\tFile       string `json:\"file\"`\n\tRunVersion int64  `json:\"runVersion\"`\n\tVersion    int64  `json:\"Version\"`\n}\n\ntype LevelConfig struct {\n\tLevelList []Item `json:\"levelList\"`\n}\n\n// LevelInfo 世界配置结构体\ntype LevelInfo struct {\n\tIsMaster          bool      `json:\"isMaster\"`\n\tLevelName         string    `json:\"levelName\"`\n\tUuid              string    `json:\"uuid\"`\n\tRunVersion        int64     `json:\"runVersion\"`\n\tLeveldataoverride string    `json:\"leveldataoverride\"`\n\tModoverrides      string    `json:\"modoverrides\"`\n\tServerIni         ServerIni `json:\"server_ini\"`\n}\n\ntype ServerIni struct {\n\n\t// [NETWORK]\n\tServerPort uint `json:\"server_port\"`\n\n\t// [SHARD]\n\tIsMaster bool   `json:\"is_master\"`\n\tName     string `json:\"name\"`\n\tId       uint   `json:\"id\"`\n\n\t// [ACCOUNT]\n\tEncodeUserPath bool `json:\"encode_user_path\"`\n\n\t// [STEAM]\n\tAuthenticationPort uint `json:\"authentication_port\"`\n\tMasterServerPort   uint `json:\"master_server_port\"`\n}\n\nfunc NewMasterServerIni() ServerIni {\n\treturn ServerIni{\n\t\tServerPort:     10999,\n\t\tIsMaster:       true,\n\t\tName:           \"Master\",\n\t\tId:             10000,\n\t\tEncodeUserPath: true,\n\t}\n}\n\nfunc NewCavesServerIni() ServerIni {\n\treturn ServerIni{\n\t\tServerPort:         10998,\n\t\tIsMaster:           false,\n\t\tName:               \"Caves\",\n\t\tId:                 10010,\n\t\tEncodeUserPath:     true,\n\t\tAuthenticationPort: 8766,\n\t\tMasterServerPort:   27016,\n\t}\n}\n\ntype LevelConfigUtils struct {\n\tarchive *archive.PathResolver\n}\n\nfunc NewLevelConfigUtils(archive *archive.PathResolver) *LevelConfigUtils {\n\treturn &LevelConfigUtils{\n\t\tarchive: archive,\n\t}\n}\n\nfunc (p *LevelConfigUtils) initLevel(levelFolderPath string, level *LevelInfo) {\n\n\tlPath := filepath.Join(levelFolderPath, \"leveldataoverride.lua\")\n\tmPath := filepath.Join(levelFolderPath, \"modoverrides.lua\")\n\tsPath := filepath.Join(levelFolderPath, \"server.ini\")\n\n\tfileUtils.CreateFileIfNotExists(lPath)\n\tfileUtils.CreateFileIfNotExists(mPath)\n\tfileUtils.CreateFileIfNotExists(sPath)\n\n\tfileUtils.WriterTXT(lPath, level.Leveldataoverride)\n\tfileUtils.WriterTXT(mPath, level.Modoverrides)\n\tserverBuf := dstUtils.ParseTemplate(\"./static/template/server.ini\", level.ServerIni)\n\tfileUtils.WriterTXT(sPath, serverBuf)\n}\n\nfunc (p *LevelConfigUtils) GetLevelConfig(clusterName string) (*LevelConfig, error) {\n\tclusterBasePath := p.archive.ClusterPath(clusterName)\n\tjsonPath := filepath.Join(clusterBasePath, \"level.json\")\n\tfileUtils.CreateDirIfNotExists(clusterBasePath)\n\t// fileUtils.CreateFileIfNotExists(jsonPath)\n\tif !fileUtils.Exists(jsonPath) {\n\t\tfileUtils.CreateFile(jsonPath)\n\t\tfileUtils.WriterTXT(jsonPath, \"{}\")\n\t}\n\t// 打开JSON文件\n\tfile, err := os.Open(jsonPath)\n\tif err != nil {\n\t\tlog.Println(\"无法打开level.json文件:\", err)\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\n\t// 解码JSON数据\n\tvar config LevelConfig\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(&config)\n\tif err != nil {\n\t\tlog.Println(\"无法解析level.json文件:\", err)\n\t\treturn nil, err\n\t}\n\n\tif len(config.LevelList) == 0 {\n\t\tmasterLevelPath := filepath.Join(clusterBasePath, \"Master\")\n\t\tif !fileUtils.Exists(masterLevelPath) {\n\t\t\tmaster := LevelInfo{\n\t\t\t\tIsMaster:          true,\n\t\t\t\tLevelName:         \"森林\",\n\t\t\t\tUuid:              \"Master\",\n\t\t\t\tLeveldataoverride: \"return {}\",\n\t\t\t\tModoverrides:      \"return {}\",\n\t\t\t\tServerIni:         NewMasterServerIni(),\n\t\t\t}\n\t\t\tp.initLevel(filepath.Join(clusterBasePath, \"Master\"), &master)\n\t\t\tconfig.LevelList = append(config.LevelList, Item{\n\t\t\t\tName: \"森林\",\n\t\t\t\tFile: \"Master\",\n\t\t\t})\n\t\t\terr = p.SaveLevelConfig(clusterName, &config)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t} else {\n\t\t\tconfig.LevelList = append(config.LevelList, Item{\n\t\t\t\tName: \"森林\",\n\t\t\t\tFile: \"Master\",\n\t\t\t})\n\t\t\tcavesLevelPath := filepath.Join(clusterBasePath, \"Caves\")\n\t\t\tif fileUtils.Exists(cavesLevelPath) {\n\t\t\t\tconfig.LevelList = append(config.LevelList, Item{\n\t\t\t\t\tName: \"洞穴\",\n\t\t\t\t\tFile: \"Caves\",\n\t\t\t\t})\n\t\t\t}\n\t\t\terr = p.SaveLevelConfig(clusterName, &config)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &config, nil\n}\n\nfunc (p *LevelConfigUtils) SaveLevelConfig(clusterName string, levelConfig *LevelConfig) error {\n\tclusterBasePath := p.archive.ClusterPath(clusterName)\n\tjsonPath := filepath.Join(clusterBasePath, \"level.json\")\n\tfileUtils.CreateFileIfNotExists(jsonPath)\n\t// 打开JSON文件\n\tfile, err := os.Open(jsonPath)\n\tif err != nil {\n\t\tlog.Println(\"无法打开level.json文件:\", err)\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tbytes, err := json.Marshal(levelConfig)\n\tif err != nil {\n\t\tlog.Println(\"json 解析错误\")\n\t}\n\tfileUtils.WriterTXT(jsonPath, string(bytes))\n\treturn err\n}\n"
  },
  {
    "path": "internal/service/login/login_service.go",
    "content": "package login\n\nimport (\n\t\"dst-admin-go/internal/config\"\n\t\"dst-admin-go/internal/pkg/response\"\n\t\"dst-admin-go/internal/pkg/utils/fileUtils\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n\n\t\"github.com/gin-contrib/sessions\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nconst (\n\tPasswordPath = \"./password.txt\"\n)\n\ntype LoginService struct {\n\tconfig *config.Config\n}\n\ntype UserInfo struct {\n\tUsername    string `json:\"username\"`\n\tPassword    string `json:\"password\"`\n\tDisplayName string `json:\"displayName\"`\n\tPhotoURL    string `json:\"photoURL\"`\n}\n\nfunc NewLoginService(config *config.Config) *LoginService {\n\treturn &LoginService{\n\t\tconfig: config,\n\t}\n}\n\nfunc (l *LoginService) GetUserInfo() UserInfo {\n\tuser, err := fileUtils.ReadLnFile(PasswordPath)\n\n\tif err != nil {\n\t\tlog.Panicln(\"Not find password file error: \" + err.Error())\n\t}\n\n\tusername := strings.TrimSpace(strings.Split(user[0], \"=\")[1])\n\t// password := strings.TrimSpace(strings.Split(user[1], \"=\")[1])\n\tdisplayName := strings.TrimSpace(strings.Split(user[2], \"=\")[1])\n\tphotoURL := strings.TrimSpace(strings.Split(user[3], \"=\")[1])\n\n\treturn UserInfo{\n\t\tUsername:    username,\n\t\tDisplayName: displayName,\n\t\tPhotoURL:    photoURL,\n\t}\n}\n\nfunc (l *LoginService) Login(userInfo UserInfo, ctx *gin.Context) *response.Response {\n\n\tresponse := &response.Response{}\n\n\tuser, err := fileUtils.ReadLnFile(PasswordPath)\n\tif err != nil {\n\t\tlog.Panicln(\"Not find password file error: \" + err.Error())\n\t}\n\n\tusername := strings.TrimSpace(strings.Split(user[0], \"=\")[1])\n\tpassword := strings.TrimSpace(strings.Split(user[1], \"=\")[1])\n\tdisplayName := strings.TrimSpace(strings.Split(user[2], \"=\")[1])\n\tphotoURL := strings.TrimSpace(strings.Split(user[3], \"=\")[1])\n\twhite := l.IsWhiteIP(ctx)\n\tif !white {\n\t\tif username != userInfo.Username || password != userInfo.Password {\n\t\t\tlog.Panicln(\"User authentication failed\")\n\t\t\tresponse.Code = 401\n\t\t\tresponse.Msg = \"User authentication failed\"\n\t\t\treturn response\n\t\t}\n\t}\n\tsession := sessions.Default(ctx)\n\tsession.Set(\"username\", username)\n\terr = session.Save()\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\n\tresponse.Code = 200\n\tresponse.Msg = \"Login success\"\n\tresponse.Data = map[string]interface{}{\n\t\t\"username\":    username,\n\t\t\"displayName\": displayName,\n\t\t\"photoURL\":    photoURL,\n\t}\n\n\treturn response\n}\n\nfunc (l *LoginService) Logout(ctx *gin.Context) {\n\tsession := sessions.Default(ctx)\n\tsession.Clear()\n\terr := session.Save()\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n}\n\nfunc (l *LoginService) DirectLogin(ctx *gin.Context) {\n\tuser, err := fileUtils.ReadLnFile(PasswordPath)\n\tif err != nil {\n\t\tlog.Panicln(\"Not find password file error: \" + err.Error())\n\t}\n\tusername := strings.TrimSpace(strings.Split(user[0], \"=\")[1])\n\tsession := sessions.Default(ctx)\n\tsession.Set(\"username\", username)\n}\n\nfunc (l *LoginService) ChangeUser(username, password string) {\n\tuser, err := fileUtils.ReadLnFile(PasswordPath)\n\tif err != nil {\n\t\tlog.Panicln(\"Not find password file error: \" + err.Error())\n\t}\n\tdisplayName := strings.TrimSpace(strings.Split(user[2], \"=\")[1])\n\tphotoURL := strings.TrimSpace(strings.Split(user[3], \"=\")[1])\n\tfileUtils.WriterLnFile(PasswordPath, []string{\n\t\t\"username = \" + username,\n\t\t\"password = \" + password,\n\t\t\"displayName=\" + displayName,\n\t\t\"photoURL=\" + photoURL,\n\t})\n}\n\nfunc (l *LoginService) ChangePassword(newPassword string) *response.Response {\n\n\tresponse := &response.Response{}\n\tuser, err := fileUtils.ReadLnFile(PasswordPath)\n\n\tif err != nil {\n\t\tlog.Panicln(\"Not find password file error: \" + err.Error())\n\t}\n\tusername := strings.TrimSpace(strings.Split(user[0], \"=\")[1])\n\tdisplayName := strings.TrimSpace(strings.Split(user[2], \"=\")[1])\n\tphotoURL := strings.TrimSpace(strings.Split(user[3], \"=\")[1])\n\tfileUtils.WriterLnFile(PasswordPath, []string{\n\t\t\"username = \" + username,\n\t\t\"password = \" + newPassword,\n\t\t\"displayName=\" + displayName,\n\t\t\"photoURL=\" + photoURL,\n\t})\n\n\tresponse.Code = 200\n\tresponse.Msg = \"Update user new password success\"\n\n\treturn response\n}\n\nfunc (l *LoginService) InitUserInfo(userInfo UserInfo) {\n\tusername := \"username=\" + userInfo.Username\n\tpassword := \"password=\" + userInfo.Password\n\tdisplayName := \"displayName=\" + userInfo.DisplayName\n\tphotoURL := \"photoURL=\" + userInfo.PhotoURL\n\tfileUtils.WriterLnFile(PasswordPath, []string{username, password, displayName, photoURL})\n}\n\nfunc (l *LoginService) IsWhiteIP(ctx *gin.Context) bool {\n\tif l.config == nil {\n\t\treturn false\n\t}\n\tWhiteAdminIP := l.config.WhiteAdminIP\n\tif WhiteAdminIP != \"\" {\n\t\t//\n\t\tipaddr := ctx.Request.RemoteAddr\n\t\tip, _, _ := net.SplitHostPort(ipaddr)\n\t\tif ip != \"\" {\n\t\t\tipnet := net.ParseIP(ip)\n\t\t\tadminips := strings.Split(WhiteAdminIP, \",\")\n\t\t\t//fmt.Println(ipnet)\n\t\t\tfor _, s := range adminips {\n\t\t\t\tif strings.Count(s, \"/\") > 0 {\n\t\t\t\t\t_, netadmin, err := net.ParseCIDR(s)\n\t\t\t\t\t//fmt.Println(netadmin)\n\t\t\t\t\t//fmt.Println(len)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Printf(\"Error parsing CIDR: %v\\n\", err)\n\t\t\t\t\t}\n\t\t\t\t\tif netadmin.Contains(ipnet) {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tnetadmin := net.ParseIP(s)\n\t\t\t\t\tif netadmin != nil && netadmin.Equal(ipnet) {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\treturn false\n}\n"
  },
  {
    "path": "internal/service/mod/mod_service.go",
    "content": "package mod\n\nimport (\n\t\"archive/zip\"\n\t\"bytes\"\n\t\"crypto/tls\"\n\t\"dst-admin-go/internal/model\"\n\t\"dst-admin-go/internal/pkg/utils/fileUtils\"\n\t\"dst-admin-go/internal/pkg/utils/shellUtils\"\n\t\"dst-admin-go/internal/service/archive\"\n\t\"dst-admin-go/internal/service/dstConfig\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"math\"\n\t\"mime/multipart\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\tlua \"github.com/yuin/gopher-lua\"\n\t\"gorm.io/gorm\"\n)\n\nconst (\n\tsteamAPIKey = \"73DF9F781D195DFD3D19DED1CB72EEE6\"\n\tappID       = 322330\n\tlanguage    = 6\n)\n\ntype ModService struct {\n\tdb           *gorm.DB\n\tdstConfig    dstConfig.Config\n\tpathResolver *archive.PathResolver\n}\n\nfunc NewModService(db *gorm.DB, config dstConfig.Config, pathResolver *archive.PathResolver) *ModService {\n\treturn &ModService{\n\t\tdb:           db,\n\t\tdstConfig:    config,\n\t\tpathResolver: pathResolver,\n\t}\n}\n\n// SearchResult 搜索结果\ntype SearchResult struct {\n\tPage      int       `json:\"page\"`\n\tSize      int       `json:\"size\"`\n\tTotal     int       `json:\"total\"`\n\tTotalPage int       `json:\"totalPage\"`\n\tData      []ModInfo `json:\"data\"`\n}\n\n// ModInfo 搜索返回的mod信息\ntype ModInfo struct {\n\tID            string  `json:\"id\"`\n\tName          string  `json:\"name\"`\n\tAuthor        string  `json:\"author\"`\n\tDesc          string  `json:\"desc\"`\n\tTime          int     `json:\"time\"`\n\tSub           int     `json:\"sub\"`\n\tImg           string  `json:\"img\"`\n\tFileUrl       string  `json:\"file_url\"`\n\tV             string  `json:\"v\"`\n\tLastTime      float64 `json:\"last_time\"`\n\tConsumerAppid float64 `json:\"consumer_appid\"`\n\tCreatorAppid  float64 `json:\"creator_appid\"`\n\tVote          struct {\n\t\tStar int `json:\"star\"`\n\t\tNum  int `json:\"num\"`\n\t} `json:\"vote\"`\n\tChild []string `json:\"child,omitempty\"`\n}\n\n// Publishedfiledetail Steam API 返回的模组详情\ntype Publishedfiledetail struct {\n\tPublishedfileid       string  `json:\"publishedfileid\"`\n\tResult                int     `json:\"result\"`\n\tCreator               string  `json:\"creator\"`\n\tCreatorAppID          int     `json:\"creator_app_id\"`\n\tConsumerAppID         int     `json:\"consumer_app_id\"`\n\tFilename              string  `json:\"filename\"`\n\tFileURL               string  `json:\"file_url\"`\n\tHcontentFile          string  `json:\"hcontent_file\"`\n\tPreviewURL            string  `json:\"preview_url\"`\n\tHcontentPreview       string  `json:\"hcontent_preview\"`\n\tTitle                 string  `json:\"title\"`\n\tDescription           string  `json:\"description\"`\n\tTimeCreated           float64 `json:\"time_created\"`\n\tTimeUpdated           float64 `json:\"time_updated\"`\n\tVisibility            int     `json:\"visibility\"`\n\tBanReason             string  `json:\"ban_reason\"`\n\tSubscriptions         int     `json:\"subscriptions\"`\n\tFavorited             int     `json:\"favorited\"`\n\tLifetimeSubscriptions int     `json:\"lifetime_subscriptions\"`\n\tLifetimeFavorited     int     `json:\"lifetime_favorited\"`\n\tViews                 int     `json:\"views\"`\n\tTags                  []struct {\n\t\tTag string `json:\"tag\"`\n\t} `json:\"tags\"`\n}\n\n// WorkshopItemDetail UGC mod详情\ntype WorkshopItemDetail struct {\n\tWorkShopId  string  `json:\"workshopId\"`\n\tName        string  `json:\"name\"`\n\tTimeupdated int64   `json:\"timeupdated\"`\n\tTimelast    float64 `json:\"timelast\"`\n\tImg         string  `json:\"img\"`\n}\n\n// WorkshopItem ACF文件中的Workshop项\ntype WorkshopItem struct {\n\tTimeUpdated int64\n\tManifest    string\n\tUgchandle   string\n}\n\n// SearchModList 搜索模组列表\nfunc (s *ModService) SearchModList(text string, page, size int, lang string) (*SearchResult, error) {\n\t// 判断是否是modID搜索\n\tmodId, ok := isModId(text)\n\tif ok {\n\t\tmodInfo := s.searchModInfoByWorkshopId(modId)\n\t\tdata := []ModInfo{}\n\t\tif modInfo.ID != \"\" {\n\t\t\tdata = append(data, modInfo)\n\t\t}\n\t\treturn &SearchResult{\n\t\t\tPage:      1,\n\t\t\tSize:      1,\n\t\t\tTotal:     1,\n\t\t\tTotalPage: 1,\n\t\t\tData:      data,\n\t\t}, nil\n\t}\n\n\t// 调用 Steam API 搜索\n\turlStr := \"http://api.steampowered.com/IPublishedFileService/QueryFiles/v1/\"\n\tdata := url.Values{\n\t\t\"page\":             {fmt.Sprintf(\"%d\", page)},\n\t\t\"key\":              {steamAPIKey},\n\t\t\"appid\":            {\"322330\"},\n\t\t\"language\":         {\"6\"},\n\t\t\"return_tags\":      {\"true\"},\n\t\t\"numperpage\":       {fmt.Sprintf(\"%d\", size)},\n\t\t\"search_text\":      {text},\n\t\t\"return_vote_data\": {\"true\"},\n\t\t\"return_children\":  {\"true\"},\n\t}\n\tif lang == \"zh\" {\n\t\tdata.Set(\"language\", \"6\")\n\t} else {\n\t\tdata.Set(\"language\", \"\")\n\t}\n\turlStr = urlStr + \"?\" + data.Encode()\n\n\tvar modData map[string]interface{}\n\tfor i := 0; i < 2; i++ {\n\t\tresp, err := http.Get(urlStr)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"搜索mod失败: %w\", err)\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\terr = json.NewDecoder(resp.Body).Decode(&modData)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"解析mod数据失败: %w\", err)\n\t\t}\n\t\tif modData[\"response\"] != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif modData[\"response\"] == nil {\n\t\treturn nil, errors.New(\"no response found in mod data\")\n\t}\n\n\tmodResponse := modData[\"response\"].(map[string]interface{})\n\ttotal := int(modResponse[\"total\"].(float64))\n\tmodInfoRaw := modResponse[\"publishedfiledetails\"].([]interface{})\n\n\tmodList := make([]ModInfo, 0)\n\tif len(modInfoRaw) > 0 {\n\t\tfor _, modInfoRaw := range modInfoRaw {\n\t\t\tmodInfo := modInfoRaw.(map[string]interface{})\n\t\t\timg := modInfo[\"preview_url\"].(string)\n\t\t\tvoteData := modInfo[\"vote_data\"].(map[string]interface{})\n\t\t\tauth := modInfo[\"creator\"].(string)\n\t\t\tvar authorURL string\n\t\t\tif auth != \"\" {\n\t\t\t\tauthorURL = fmt.Sprintf(\"https://steamcommunity.com/profiles/%s/?xml=1\", auth)\n\t\t\t}\n\t\t\tmod := ModInfo{\n\t\t\t\tID:     fmt.Sprintf(\"%v\", modInfo[\"publishedfileid\"]),\n\t\t\t\tName:   fmt.Sprintf(\"%v\", modInfo[\"title\"]),\n\t\t\t\tAuthor: authorURL,\n\t\t\t\tDesc:   fmt.Sprintf(\"%v\", modInfo[\"file_description\"]),\n\t\t\t\tTime:   int(modInfo[\"time_updated\"].(float64)),\n\t\t\t\tSub:    int(modInfo[\"subscriptions\"].(float64)),\n\t\t\t\tImg:    img,\n\t\t\t\tVote: struct {\n\t\t\t\t\tStar int `json:\"star\"`\n\t\t\t\t\tNum  int `json:\"num\"`\n\t\t\t\t}{\n\t\t\t\t\tStar: int(voteData[\"score\"].(float64)*5) + 1,\n\t\t\t\t\tNum:  int(voteData[\"votes_up\"].(float64) + voteData[\"votes_down\"].(float64)),\n\t\t\t\t},\n\t\t\t}\n\t\t\tif modInfo[\"num_children\"].(float64) != 0 {\n\t\t\t\tchildren := modInfo[\"children\"].([]interface{})\n\t\t\t\tchild := make([]string, len(children))\n\t\t\t\tfor i, c := range children {\n\t\t\t\t\tchild[i] = fmt.Sprintf(\"%v\", c.(map[string]interface{})[\"publishedfileid\"])\n\t\t\t\t}\n\t\t\t\tmod.Child = child\n\t\t\t}\n\t\t\tmodList = append(modList, mod)\n\t\t}\n\t}\n\n\treturn &SearchResult{\n\t\tPage:      page,\n\t\tSize:      size,\n\t\tTotal:     total,\n\t\tTotalPage: int(math.Ceil(float64(total) / float64(size))),\n\t\tData:      modList,\n\t}, nil\n}\n\n// SubscribeModByModId 订阅并下载模组\nfunc (s *ModService) SubscribeModByModId(clusterName, modId, lang string) (*model.ModInfo, error) {\n\tif !isWorkshopId(modId) {\n\t\t// 非workshop mod，从本地读取\n\t\treturn s.getLocalModInfo(clusterName, lang, modId)\n\t}\n\n\t// 从Steam API获取mod信息\n\turlStr := \"http://api.steampowered.com/IPublishedFileService/GetDetails/v1/\"\n\tdata := url.Values{}\n\tdata.Set(\"key\", steamAPIKey)\n\tdata.Set(\"language\", \"6\")\n\tdata.Set(\"publishedfileids[0]\", modId)\n\turlStr = urlStr + \"?\" + data.Encode()\n\n\treq, err := http.NewRequest(\"GET\", urlStr, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"创建请求失败: %w\", err)\n\t}\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"请求Steam API失败: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tvar result map[string]interface{}\n\terr = json.NewDecoder(resp.Body).Decode(&result)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"解析响应失败: %w\", err)\n\t}\n\n\tdataList, ok := result[\"response\"].(map[string]interface{})[\"publishedfiledetails\"].([]interface{})\n\tif !ok || len(dataList) == 0 {\n\t\treturn nil, errors.New(\"获取mod信息失败\")\n\t}\n\n\tdata2 := dataList[0].(map[string]interface{})\n\timg := data2[\"preview_url\"].(string)\n\tauth := data2[\"creator\"].(string)\n\tvar authorURL string\n\tif auth != \"\" {\n\t\tauthorURL = fmt.Sprintf(\"https://steamcommunity.com/profiles/%s/?xml=1\", auth)\n\t}\n\n\tname := data2[\"title\"].(string)\n\tlastTime := data2[\"time_updated\"].(float64)\n\tdescription := data2[\"file_description\"].(string)\n\tauth = authorURL\n\tfileUrl := data2[\"file_url\"]\n\timg = fmt.Sprintf(\"%s?imw=64&imh=64&ima=fit&impolicy=Letterbox&imcolor=%%23000000&letterbox=true\", img)\n\tv := s.getVersion(data2[\"tags\"])\n\tcreatorAppid := data2[\"creator_appid\"].(float64)\n\tconsumerAppid := data2[\"consumer_appid\"].(float64)\n\n\t// 检查数据库中是否已存在\n\texistingMod, err := s.GetModByModId(modId)\n\tif err == nil && existingMod.Modid != \"\" {\n\t\tif lastTime == existingMod.LastTime {\n\t\t\treturn existingMod, nil\n\t\t}\n\t\t// 需要更新\n\t\tvar modConfig string\n\t\tvar fileUrlStr = \"\"\n\t\tif fileUrl != nil {\n\t\t\tfileUrlStr = fileUrl.(string)\n\t\t}\n\t\tif fileUrlStr != \"\" {\n\t\t\tmodConfigJson, _ := json.Marshal(s.getV1ModInfoConfig(clusterName, lang, modId, fileUrlStr))\n\t\t\tmodConfig = string(modConfigJson)\n\t\t} else {\n\t\t\tmodConfigJson, _ := json.Marshal(s.getModInfoConfig(clusterName, lang, modId))\n\t\t\tmodConfig = string(modConfigJson)\n\t\t}\n\n\t\texistingMod.LastTime = lastTime\n\t\texistingMod.Name = name\n\t\texistingMod.Auth = auth\n\t\texistingMod.Description = description\n\t\texistingMod.Img = img\n\t\texistingMod.V = v\n\t\texistingMod.ModConfig = modConfig\n\t\texistingMod.Update = false\n\t\ts.db.Save(existingMod)\n\t\treturn existingMod, nil\n\t}\n\n\t// 新增mod\n\tvar fileUrlStr = \"\"\n\tif fileUrl != nil {\n\t\tfileUrlStr = fileUrl.(string)\n\t}\n\n\tvar modConfig string\n\tif fileUrlStr != \"\" {\n\t\tmodConfigJson, _ := json.Marshal(s.getV1ModInfoConfig(clusterName, lang, modId, fileUrlStr))\n\t\tmodConfig = string(modConfigJson)\n\t} else {\n\t\tmodConfigJson, _ := json.Marshal(s.getModInfoConfig(clusterName, lang, modId))\n\t\tmodConfig = string(modConfigJson)\n\t}\n\n\tnewModInfo := &model.ModInfo{\n\t\tAuth:          auth,\n\t\tConsumerAppid: consumerAppid,\n\t\tCreatorAppid:  creatorAppid,\n\t\tDescription:   description,\n\t\tFileUrl:       fileUrlStr,\n\t\tModid:         modId,\n\t\tImg:           img,\n\t\tLastTime:      lastTime,\n\t\tName:          name,\n\t\tV:             v,\n\t\tModConfig:     modConfig,\n\t}\n\n\terr = s.db.Create(newModInfo).Error\n\treturn newModInfo, err\n}\n\n// GetMyModList 获取已订阅的模组列表\nfunc (s *ModService) GetMyModList() ([]model.ModInfo, error) {\n\tvar modInfos []model.ModInfo\n\terr := s.db.Find(&modInfos).Error\n\treturn modInfos, err\n}\n\n// GetModByModId 根据modId获取模组\nfunc (s *ModService) GetModByModId(modId string) (*model.ModInfo, error) {\n\tvar modInfo model.ModInfo\n\terr := s.db.Where(\"modid = ?\", modId).First(&modInfo).Error\n\treturn &modInfo, err\n}\n\n// DeleteMod 删除模组\nfunc (s *ModService) DeleteMod(clusterName, modId string) error {\n\t// 从数据库删除\n\terr := s.db.Where(\"modid = ?\", modId).Delete(&model.ModInfo{}).Error\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// 删除本地文件\n\tconfig, _ := s.dstConfig.GetDstConfig(clusterName)\n\tmodDownloadPath := config.Mod_download_path\n\tmodPath := filepath.Join(modDownloadPath, \"steamapps\", \"workshop\", \"content\", \"322330\", modId)\n\treturn fileUtils.DeleteDir(modPath)\n}\n\n// UpdateAllModInfos 批量更新所有模组信息\nfunc (s *ModService) UpdateAllModInfos(clusterName, lang string) error {\n\tvar modInfos []model.ModInfo\n\tvar needUpdateList []model.ModInfo\n\tvar workshopIds []string\n\n\ts.db.Find(&modInfos)\n\n\tfor i := range modInfos {\n\t\tworkshopIds = append(workshopIds, modInfos[i].Modid)\n\t}\n\n\tpublishedFileDetails, err := s.getPublishedFileDetailsBatched(workshopIds, 20)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i := range publishedFileDetails {\n\t\tpublishedfiledetail := publishedFileDetails[i]\n\t\tfor j := range modInfos {\n\t\t\tif modInfos[j].Modid == publishedfiledetail.Publishedfileid && modInfos[j].LastTime < publishedfiledetail.TimeUpdated {\n\t\t\t\tneedUpdateList = append(needUpdateList, modInfos[i])\n\t\t\t}\n\t\t}\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(len(needUpdateList))\n\n\tfor i := range needUpdateList {\n\t\tgo func(i int) {\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tlog.Println(r)\n\t\t\t\t}\n\t\t\t\twg.Done()\n\t\t\t}()\n\t\t\tmodId := needUpdateList[i].Modid\n\t\t\t// 删除之前的数据\n\t\t\tconfig, _ := s.dstConfig.GetDstConfig(clusterName)\n\t\t\tmodDownloadPath := config.Mod_download_path\n\t\t\tmodPath := filepath.Join(modDownloadPath, \"/steamapps/workshop/content/322330/\", modId)\n\t\t\t_ = fileUtils.DeleteDir(modPath)\n\t\t\t_, _ = s.SubscribeModByModId(clusterName, modId, lang)\n\t\t}(i)\n\t}\n\twg.Wait()\n\n\treturn nil\n}\n\n// DeleteSetupWorkshop 删除所有workshop模组\nfunc (s *ModService) DeleteSetupWorkshop(clusterName string) error {\n\tconfig, err := s.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdstPath := config.Force_install_dir\n\tmodsPath := filepath.Join(dstPath, \"mods\")\n\n\tdirectories, err := fileUtils.ListDirectories(modsPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"列出目录失败: %w\", err)\n\t}\n\n\tvar workshopList []string\n\tfor _, directory := range directories {\n\t\tif strings.Contains(directory, \"workshop\") {\n\t\t\tworkshopList = append(workshopList, directory)\n\t\t}\n\t}\n\n\tfor _, workshop := range workshopList {\n\t\terr := fileUtils.DeleteDir(workshop)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// SaveModInfo 保存模组信息\nfunc (s *ModService) SaveModInfo(modInfo *model.ModInfo) error {\n\treturn s.db.Save(modInfo).Error\n}\n\n// AddModInfo 手动添加模组\nfunc (s *ModService) AddModInfo(clusterName, lang, modid, modinfo, modDownloadPath string) error {\n\t// 创建workshop文件\n\tworkshopDirPath := filepath.Join(modDownloadPath, \"/steamapps/workshop/content/322330\", modid)\n\tfileUtils.CreateDirIfNotExists(workshopDirPath)\n\n\tmodinfoPath := filepath.Join(workshopDirPath, \"modinfo.lua\")\n\terr := fileUtils.CreateFileIfNotExists(modinfoPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"创建modinfo.lua失败: %w\", err)\n\t}\n\n\terr = fileUtils.WriterTXT(modinfoPath, modinfo)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"写入modinfo.lua失败: %w\", err)\n\t}\n\n\t// 添加到数据库\n\treturn s.addModInfoToDb(clusterName, lang, modid)\n}\n\n// GetUgcModInfo 获取UGC模组信息\nfunc (s *ModService) GetUgcModInfo(clusterName, levelName string) ([]WorkshopItemDetail, error) {\n\tacfPath := s.pathResolver.GetUgcAcfPath(clusterName, levelName)\n\tacfWorkshops := s.parseACFFile(acfPath)\n\n\tvar workshopItemDetails []WorkshopItemDetail\n\tvar modIds []string\n\tfor key := range acfWorkshops {\n\t\tmodIds = append(modIds, key)\n\t}\n\n\turlStr := \"http://api.steampowered.com/IPublishedFileService/GetDetails/v1/\"\n\tdata := url.Values{}\n\tdata.Set(\"key\", steamAPIKey)\n\tdata.Set(\"language\", \"6\")\n\tfor i := range modIds {\n\t\tdata.Set(\"publishedfileids[\"+strconv.Itoa(i)+\"]\", modIds[i])\n\t}\n\turlStr = urlStr + \"?\" + data.Encode()\n\n\treq, err := http.NewRequest(\"GET\", urlStr, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar result map[string]interface{}\n\terr = json.NewDecoder(resp.Body).Decode(&result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdataList, ok := result[\"response\"].(map[string]interface{})[\"publishedfiledetails\"].([]interface{})\n\tif !ok {\n\t\treturn nil, errors.New(\"解析响应失败\")\n\t}\n\n\tfor i := range dataList {\n\t\tworkshop := dataList[i].(map[string]interface{})\n\t\t_, find := workshop[\"time_updated\"]\n\t\tif find {\n\t\t\ttimeUpdated := workshop[\"time_updated\"].(float64)\n\t\t\tmodId := workshop[\"publishedfileid\"].(string)\n\t\t\tvalue, ok := acfWorkshops[modId]\n\t\t\tif ok {\n\t\t\t\timg := workshop[\"preview_url\"].(string)\n\t\t\t\timg = fmt.Sprintf(\"%s?imw=64&imh=64&ima=fit&impolicy=Letterbox&imcolor=%%23000000&letterbox=true\", img)\n\t\t\t\tworkshopItemDetails = append(workshopItemDetails, WorkshopItemDetail{\n\t\t\t\t\tWorkShopId:  modId,\n\t\t\t\t\tTimeupdated: value.TimeUpdated,\n\t\t\t\t\tTimelast:    timeUpdated,\n\t\t\t\t\tImg:         img,\n\t\t\t\t\tName:        workshop[\"title\"].(string),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn workshopItemDetails, nil\n}\n\n// DeleteUgcModFile 删除UGC模组文件\nfunc (s *ModService) DeleteUgcModFile(clusterName, levelName, workshopId string) error {\n\tmodFilePath := s.pathResolver.GetUgcWorkshopModPath(clusterName, levelName, workshopId)\n\tif fileUtils.Exists(modFilePath) {\n\t\treturn fileUtils.DeleteDir(modFilePath)\n\t}\n\treturn nil\n}\n\n// ===== 私有方法 =====\n\n// parseACFFile 解析ACF文件\nfunc (s *ModService) parseACFFile(filePath string) map[string]WorkshopItem {\n\tlines, err := fileUtils.ReadLnFile(filePath)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil\n\t}\n\tparsingWorkshopItemsInstalled := false\n\tworkshopItems := make(map[string]WorkshopItem)\n\tvar currentItemID string\n\tvar currentItem WorkshopItem\n\n\tfor _, line := range lines {\n\t\tif strings.Contains(line, \"WorkshopItemsInstalled\") {\n\t\t\tparsingWorkshopItemsInstalled = true\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.Contains(line, \"{\") && parsingWorkshopItemsInstalled {\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.Contains(line, \"}\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tif parsingWorkshopItemsInstalled {\n\t\t\treplace := strings.Replace(line, \"\\t\\t\", \"\", -1)\n\t\t\treplace = strings.Replace(replace, \"\\\"\", \"\", -1)\n\t\t\tif _, err := strconv.Atoi(replace); err == nil {\n\t\t\t\t// This line contains the Workshop Item ID\n\t\t\t\tfields := strings.Fields(line)\n\t\t\t\tvalue := strings.Replace(fields[0], \"\\\"\", \"\", -1)\n\t\t\t\tcurrentItemID = value\n\t\t\t} else {\n\t\t\t\t// This line contains the Workshop Item details\n\t\t\t\tfields := strings.Fields(line)\n\t\t\t\tif len(fields) == 2 {\n\t\t\t\t\tkey := strings.Replace(fields[0], \"\\\"\", \"\", -1)\n\t\t\t\t\tvalue := strings.Replace(fields[1], \"\\\"\", \"\", -1)\n\t\t\t\t\t// Remove double quotes from keys\n\t\t\t\t\tkey = strings.ReplaceAll(key, \"\\\"\", \"\")\n\t\t\t\t\tswitch key {\n\t\t\t\t\tcase \"timeupdated\":\n\t\t\t\t\t\tcurrentItem.TimeUpdated, _ = strconv.ParseInt(value, 10, 64)\n\t\t\t\t\tcase \"manifest\":\n\t\t\t\t\t\tcurrentItem.Manifest = strings.ReplaceAll(value, \"\\\"\", \"\")\n\t\t\t\t\tcase \"ugchandle\":\n\t\t\t\t\t\tcurrentItem.Ugchandle = strings.ReplaceAll(value, \"\\\"\", \"\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif currentItemID != \"\" && currentItem.TimeUpdated != 0 {\n\t\t\t\tworkshopItems[currentItemID] = currentItem\n\t\t\t\tcurrentItemID = \"\"\n\t\t\t\tcurrentItem = WorkshopItem{}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn workshopItems\n}\n\n// getModInfoConfig 获取mod配置信息\nfunc (s *ModService) getModInfoConfig(clusterName, lang, modId string) map[string]interface{} {\n\t// 从服务器本地读取mod信息\n\tif dstModInstalledPath, ok := s.getDstUcgsModsInstalledPath(clusterName, modId); ok {\n\t\tmodinfoPath := filepath.Join(dstModInstalledPath, \"modinfo.lua\")\n\t\tif _, err := os.Stat(modinfoPath); err == nil {\n\t\t\treturn s.readModInfo(lang, modId, modinfoPath)\n\t\t}\n\t}\n\n\t// 检查mod文件是否已经存在\n\tconfig, _ := s.dstConfig.GetDstConfig(clusterName)\n\tmodDownloadPath := config.Mod_download_path\n\tfileUtils.CreateDirIfNotExists(modDownloadPath)\n\n\t// 下载的模组位置\n\tmodPath := filepath.Join(modDownloadPath, \"steamapps\", \"workshop\", \"content\", \"322330\", modId)\n\tif _, err := os.Stat(modPath); err == nil {\n\t\tlog.Println(\"Mod already downloaded to:\", modPath)\n\t} else {\n\t\t// 调用 SteamCMD 命令下载 mod\n\t\tsteamcmd := config.Steamcmd\n\t\tif runtime.GOOS == \"windows\" {\n\t\t\tcmd := \"cd /d \" + steamcmd + \" && Start steamcmd.exe +login anonymous +force_install_dir \" + modDownloadPath + \" +workshop_download_item 322330 \" + modId + \" +quit\"\n\t\t\tlog.Println(\"正在下载模组 command:\", cmd)\n\t\t\t_, err := shellUtils.ExecuteCommandInWin(cmd)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"下载mod失败，请检查steamcmd路径是否配置正确\", err)\n\t\t\t\treturn make(map[string]interface{})\n\t\t\t}\n\t\t} else {\n\t\t\tvar cmd *exec.Cmd\n\t\t\tif fileUtils.Exists(filepath.Join(steamcmd, \"steamcmd\")) {\n\t\t\t\tcmd = exec.Command(filepath.Join(steamcmd, \"steamcmd\"), \"+login anonymous\", \"+force_install_dir\", modDownloadPath, \"+workshop_download_item 322330 \"+modId, \"+quit\")\n\t\t\t} else {\n\t\t\t\tcmd = exec.Command(filepath.Join(steamcmd, \"steamcmd.sh\"), \"+login anonymous\", \"+force_install_dir\", modDownloadPath, \"+workshop_download_item 322330 \"+modId, \"+quit\")\n\t\t\t}\n\n\t\t\tlog.Println(\"正在下载模组 command:\", cmd)\n\t\t\toutput, err := cmd.CombinedOutput()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"下载mod失败，请检查steamcmd路径是否配置正确\", err)\n\t\t\t\treturn make(map[string]interface{})\n\t\t\t}\n\n\t\t\t// 解析 SteamCMD 输出\n\t\t\tre := regexp.MustCompile(`Downloaded item \\d+ to \"([^\"]+)\"`)\n\t\t\tmatch := re.FindStringSubmatch(string(output))\n\t\t\tif len(match) < 2 {\n\t\t\t\tlog.Println(\"Error parsing output:\", string(output))\n\t\t\t\treturn make(map[string]interface{})\n\t\t\t}\n\t\t\tlog.Println(\"Mod downloaded to:\", match[1])\n\t\t}\n\t}\n\n\t// 查找 modinfo.lua 文件\n\tmodinfoPath := filepath.Join(modPath, \"modinfo.lua\")\n\tif _, err := os.Stat(modinfoPath); err != nil {\n\t\tlog.Println(\"Error finding modinfo.lua:\", err)\n\t\treturn make(map[string]interface{})\n\t}\n\treturn s.readModInfo(lang, modId, modinfoPath)\n}\n\n// getV1ModInfoConfig 从v1 mod中获取配置\nfunc (s *ModService) getV1ModInfoConfig(clusterName, lang, modid, fileUrl string) map[string]interface{} {\n\tlog.Println(\"开始下载 v1 mod，并提取 modinfo.lua 文件\")\n\tmodinfo := map[string][]byte{\"modinfo\": nil, \"modinfo_chs\": nil}\n\tvar tmp bytes.Buffer\n\n\tfor i := 0; i < 3; i++ {\n\t\treq, err := http.NewRequest(\"GET\", fileUrl, nil)\n\t\tif err != nil {\n\t\t\tlog.Println(fileUrl, \"下载失败\", err)\n\t\t\tcontinue\n\t\t}\n\t\tclient := http.Client{\n\t\t\tTimeout: time.Duration(10 * time.Second),\n\t\t}\n\t\tres, err := client.Do(req)\n\t\tif err != nil {\n\t\t\tlog.Println(fileUrl, \"下载失败\", err)\n\t\t\tcontinue\n\t\t}\n\t\tdefer res.Body.Close()\n\t\t_, err = tmp.ReadFrom(res.Body)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\n\tif tmp.Len() == 0 {\n\t\tlog.Println(fileUrl, \"下载失败 3 次，不再尝试\")\n\t\treturn make(map[string]interface{})\n\t}\n\n\tlog.Println(fileUrl, \"下载成功，开始解压\")\n\tzipReader, err := zip.NewReader(bytes.NewReader(tmp.Bytes()), int64(tmp.Len()))\n\tif err != nil {\n\t\tlog.Println(\"模组zip解压失败\", err)\n\t\treturn make(map[string]interface{})\n\t}\n\n\t_ = s.unzipToDir(zipReader, filepath.Join(s.pathResolver.GetUgcModPath(clusterName), \"content\", \"322330\", modid))\n\n\tfor _, file := range zipReader.File {\n\t\tswitch file.Name {\n\t\tcase \"modinfo.lua\":\n\t\t\tf, _ := file.Open()\n\t\t\tmodinfoBytes, err := ioutil.ReadAll(f)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(fileUrl, \"解压 modinfo.lua 失败\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmodinfo[\"modinfo\"] = modinfoBytes\n\t\tcase \"modinfo_chs.lua\":\n\t\t\tf, _ := file.Open()\n\t\t\tmodinfoBytes, err := ioutil.ReadAll(f)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(fileUrl, \"解压 modinfo_chs.lua 失败\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmodinfo[\"modinfo_chs\"] = modinfoBytes\n\t\t}\n\t}\n\n\tif modinfo[\"modinfo\"] != nil {\n\t\treturn s.parseModInfoLua(lang, modid, string(modinfo[\"modinfo\"]))\n\t}\n\treturn make(map[string]interface{})\n}\n\n// getDstUcgsModsInstalledPath 获取饥荒本身modid的位置\nfunc (s *ModService) getDstUcgsModsInstalledPath(clusterName, modid string) (string, bool) {\n\tconfig, _ := s.dstConfig.GetDstConfig(clusterName)\n\tvar masterModFilePath, caveModFilePath string\n\n\tif config.Ugc_directory != \"\" {\n\t\tmasterModFilePath = filepath.Join(s.pathResolver.GetUgcModPath(clusterName), \"content\", \"322330\", modid)\n\t\tcaveModFilePath = filepath.Join(s.pathResolver.GetUgcModPath(clusterName), \"content\", \"322330\", modid)\n\t} else {\n\t\tmasterModFilePath = filepath.Join(config.Force_install_dir, \"ugc_mods\", clusterName, \"Master\", \"content\", \"322330\", modid)\n\t\tcaveModFilePath = filepath.Join(config.Force_install_dir, \"ugc_mods\", clusterName, \"Caves\", \"content\", \"322330\", modid)\n\t}\n\n\tif fileUtils.Exists(masterModFilePath) {\n\t\treturn masterModFilePath, true\n\t}\n\tif fileUtils.Exists(caveModFilePath) {\n\t\treturn caveModFilePath, true\n\t}\n\treturn \"\", false\n}\n\n// readModInfo 读取modinfo.lua文件\nfunc (s *ModService) readModInfo(lang, modId, modinfoPath string) map[string]interface{} {\n\tscript, err := ioutil.ReadFile(modinfoPath)\n\tif err != nil {\n\t\tlog.Println(\"Error reading modinfo.lua:\", err)\n\t\treturn make(map[string]interface{})\n\t}\n\treturn s.parseModInfoLua(lang, modId, string(script))\n}\n\n// parseModInfoLua 解析modinfo.lua文件\nfunc (s *ModService) parseModInfoLua(lang, modId, script string) map[string]interface{} {\n\tL := lua.NewState()\n\tdefer L.Close()\n\n\tL.SetGlobal(\"locale\", lua.LString(lang))\n\tL.SetGlobal(\"folder_name\", lua.LString(fmt.Sprintf(\"workshop-%s\", modId)))\n\tL.SetGlobal(\"ChooseTranslationTable\", L.NewFunction(func(L *lua.LState) int {\n\t\ttbl := L.ToTable(1)\n\t\tlangTbl := tbl.RawGetString(lang)\n\t\tif langTbl != lua.LNil {\n\t\t\tL.Push(langTbl)\n\t\t} else {\n\t\t\tL.Push(tbl.RawGetInt(1))\n\t\t}\n\t\treturn 1\n\t}))\n\n\tL.DoString(script)\n\n\tglobal := L.Get(lua.GlobalsIndex).(*lua.LTable)\n\tm := make(map[string]interface{})\n\tglobal.ForEach(func(k lua.LValue, v lua.LValue) {\n\t\tif !excludeList[k.String()] && v.Type() != lua.LTFunction {\n\t\t\tm[k.String()] = toInterface(v)\n\t\t}\n\t})\n\n\treturn m\n}\n\n// getVersion 从tags中获取版本号\nfunc (s *ModService) getVersion(tags interface{}) string {\n\ttagList, ok := tags.([]interface{})\n\tif !ok {\n\t\treturn \"\"\n\t}\n\tfor _, tag := range tagList {\n\t\ttagMap, ok := tag.(map[string]interface{})\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\ttagStr, ok := tagMap[\"tag\"].(string)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif len(tagStr) > 8 && tagStr[:8] == \"version:\" {\n\t\t\treturn tagStr[8:]\n\t\t}\n\t}\n\treturn \"\"\n}\n\n// searchModInfoByWorkshopId 通过workshopId搜索mod信息\nfunc (s *ModService) searchModInfoByWorkshopId(modID int) ModInfo {\n\turlStr := \"http://api.steampowered.com/IPublishedFileService/GetDetails/v1/\"\n\tdata := url.Values{}\n\tdata.Set(\"key\", steamAPIKey)\n\tdata.Set(\"language\", \"6\")\n\tdata.Set(\"publishedfileids[0]\", strconv.Itoa(modID))\n\turlStr = urlStr + \"?\" + data.Encode()\n\n\treq, err := http.NewRequest(\"GET\", urlStr, nil)\n\tif err != nil {\n\t\treturn ModInfo{}\n\t}\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn ModInfo{}\n\t}\n\tdefer resp.Body.Close()\n\n\tvar result map[string]interface{}\n\terr = json.NewDecoder(resp.Body).Decode(&result)\n\tif err != nil {\n\t\treturn ModInfo{}\n\t}\n\n\tdataList, ok := result[\"response\"].(map[string]interface{})[\"publishedfiledetails\"].([]interface{})\n\tif !ok || len(dataList) == 0 {\n\t\treturn ModInfo{}\n\t}\n\n\tdata2 := dataList[0].(map[string]interface{})\n\tif data2[\"consumer_appid\"] == nil || data2[\"consumer_appid\"].(float64) != 322330 {\n\t\treturn ModInfo{}\n\t}\n\n\timg := data2[\"preview_url\"].(string)\n\tauth := data2[\"creator\"].(string)\n\tvar authorURL string\n\tif auth != \"\" {\n\t\tauthorURL = fmt.Sprintf(\"https://steamcommunity.com/profiles/%s/?xml=1\", auth)\n\t}\n\n\tmodId := data2[\"publishedfileid\"].(string)\n\tname := data2[\"title\"].(string)\n\tdescription := data2[\"file_description\"].(string)\n\timg = fmt.Sprintf(\"%s?imw=64&imh=64&ima=fit&impolicy=Letterbox&imcolor=%%23000000&letterbox=true\", img)\n\n\treturn ModInfo{\n\t\tID:     modId,\n\t\tName:   name,\n\t\tAuthor: authorURL,\n\t\tDesc:   description,\n\t\tTime:   int(data2[\"time_updated\"].(float64)),\n\t\tSub:    int(data2[\"subscriptions\"].(float64)),\n\t\tImg:    img,\n\t}\n}\n\n// getLocalModInfo 获取本地mod信息\nfunc (s *ModService) getLocalModInfo(clusterName, lang, modId string) (*model.ModInfo, error) {\n\tmodConfigJson, _ := json.Marshal(s.getModInfoConfig(clusterName, lang, modId))\n\tmodConfig := string(modConfigJson)\n\n\tnewModInfo := &model.ModInfo{\n\t\tAuth:          \"\",\n\t\tConsumerAppid: 0,\n\t\tCreatorAppid:  0,\n\t\tDescription:   \"\",\n\t\tModid:         modId,\n\t\tImg:           \"xxx\",\n\t\tLastTime:      0,\n\t\tName:          modId,\n\t\tV:             \"\",\n\t\tModConfig:     modConfig,\n\t}\n\n\terr := s.db.Create(newModInfo).Error\n\treturn newModInfo, err\n}\n\n// addModInfoToDb 添加mod信息到数据库\nfunc (s *ModService) addModInfoToDb(clusterName, lang, modid string) error {\n\tvar modInfo *model.ModInfo\n\tvar err error\n\n\tif !isWorkshopId(modid) {\n\t\tmodInfo, err = s.getLocalModInfo(clusterName, lang, modid)\n\t} else {\n\t\t// 从Steam获取mod基本信息\n\t\tmodInfo, err = s.getModInfo2(modid)\n\t}\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"获取modinfo失败: %w\", err)\n\t}\n\n\t// 从数据库查找是否已存在\n\toldModinfo, err := s.GetModByModId(modid)\n\tvar modConfig string\n\tmodConfigJson, _ := json.Marshal(s.getModInfoConfig(clusterName, lang, modid))\n\tmodConfig = string(modConfigJson)\n\n\tif err == nil && oldModinfo.Modid != \"\" {\n\t\t// 更新\n\t\toldModinfo.LastTime = modInfo.LastTime\n\t\toldModinfo.Name = modInfo.Name\n\t\toldModinfo.Auth = modInfo.Auth\n\t\toldModinfo.Description = modInfo.Description\n\t\toldModinfo.Img = modInfo.Img\n\t\toldModinfo.V = modInfo.V\n\t\toldModinfo.ModConfig = modConfig\n\t\treturn s.db.Save(oldModinfo).Error\n\t}\n\n\t// 新增\n\tmodInfo.ModConfig = modConfig\n\treturn s.db.Create(modInfo).Error\n}\n\n// getModInfo2 从Steam API获取mod基本信息\nfunc (s *ModService) getModInfo2(modID string) (*model.ModInfo, error) {\n\turlStr := \"http://api.steampowered.com/IPublishedFileService/GetDetails/v1/\"\n\tdata := url.Values{}\n\tdata.Set(\"key\", steamAPIKey)\n\tdata.Set(\"language\", \"6\")\n\tdata.Set(\"publishedfileids[0]\", modID)\n\turlStr = urlStr + \"?\" + data.Encode()\n\n\treq, err := http.NewRequest(\"GET\", urlStr, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar result map[string]interface{}\n\terr = json.NewDecoder(resp.Body).Decode(&result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdataList, ok := result[\"response\"].(map[string]interface{})[\"publishedfiledetails\"].([]interface{})\n\tif !ok || len(dataList) == 0 {\n\t\treturn nil, errors.New(\"获取mod信息失败\")\n\t}\n\n\tdata2 := dataList[0].(map[string]interface{})\n\timg := data2[\"preview_url\"].(string)\n\tauth := data2[\"creator\"].(string)\n\tvar authorURL string\n\tif auth != \"\" {\n\t\tauthorURL = fmt.Sprintf(\"https://steamcommunity.com/profiles/%s/?xml=1\", auth)\n\t}\n\n\tmodId := data2[\"publishedfileid\"].(string)\n\tname := data2[\"title\"].(string)\n\tlastTime := data2[\"time_updated\"].(float64)\n\tdescription := data2[\"file_description\"].(string)\n\tfileUrl := data2[\"file_url\"]\n\timg = fmt.Sprintf(\"%s?imw=64&imh=64&ima=fit&impolicy=Letterbox&imcolor=%%23000000&letterbox=true\", img)\n\tv := s.getVersion(data2[\"tags\"])\n\tcreatorAppid := data2[\"creator_appid\"].(float64)\n\tconsumerAppid := data2[\"consumer_appid\"].(float64)\n\n\tvar fileUrlStr = \"\"\n\tif fileUrl != nil {\n\t\tfileUrlStr = fileUrl.(string)\n\t}\n\n\treturn &model.ModInfo{\n\t\tAuth:          authorURL,\n\t\tConsumerAppid: consumerAppid,\n\t\tCreatorAppid:  creatorAppid,\n\t\tDescription:   description,\n\t\tFileUrl:       fileUrlStr,\n\t\tModid:         modId,\n\t\tImg:           img,\n\t\tLastTime:      lastTime,\n\t\tName:          name,\n\t\tV:             v,\n\t}, nil\n}\n\n// getPublishedFileDetailsBatched 批量获取mod详情\nfunc (s *ModService) getPublishedFileDetailsBatched(workshopIds []string, batchSize int) ([]Publishedfiledetail, error) {\n\tvar allPublishedFileDetails []Publishedfiledetail\n\n\tfor i := 0; i < len(workshopIds); i += batchSize {\n\t\tend := i + batchSize\n\t\tif end > len(workshopIds) {\n\t\t\tend = len(workshopIds)\n\t\t}\n\n\t\tbatch := workshopIds[i:end]\n\t\tpublishedFileDetails, err := s.getPublishedFileDetailsWithGet(batch)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tallPublishedFileDetails = append(allPublishedFileDetails, publishedFileDetails...)\n\t}\n\n\treturn allPublishedFileDetails, nil\n}\n\n// getPublishedFileDetailsWithGet 通过GET方式获取mod详情\nfunc (s *ModService) getPublishedFileDetailsWithGet(workshopIds []string) ([]Publishedfiledetail, error) {\n\turlStr := \"http://api.steampowered.com/IPublishedFileService/GetDetails/v1/\"\n\tdata := url.Values{}\n\tdata.Set(\"key\", steamAPIKey)\n\tdata.Set(\"language\", \"6\")\n\tfor i := range workshopIds {\n\t\tdata.Set(\"publishedfileids[\"+strconv.Itoa(i)+\"]\", workshopIds[i])\n\t}\n\turlStr = urlStr + \"?\" + data.Encode()\n\n\treq, err := http.NewRequest(\"GET\", urlStr, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := &http.Client{}\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\n\tvar publishedFileDetailsData struct {\n\t\tResponse struct {\n\t\t\tPublishedfiledetails []Publishedfiledetail `json:\"publishedfiledetails\"`\n\t\t} `json:\"response\"`\n\t}\n\n\terr = json.NewDecoder(res.Body).Decode(&publishedFileDetailsData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn publishedFileDetailsData.Response.Publishedfiledetails, nil\n}\n\n// getPublishedFileDetails 通过POST方式获取mod详情\nfunc (s *ModService) getPublishedFileDetails(workshopIds []string) ([]Publishedfiledetail, error) {\n\turl := \"https://api.steampowered.com/ISteamRemoteStorage/GetPublishedFileDetails/v1/\"\n\tpayload := &bytes.Buffer{}\n\twriter := multipart.NewWriter(payload)\n\n\t_ = writer.WriteField(\"itemcount\", strconv.Itoa(len(workshopIds)))\n\tfor i := range workshopIds {\n\t\t_ = writer.WriteField(\"publishedfileids[\"+strconv.Itoa(i)+\"]\", workshopIds[i])\n\t}\n\n\terr := writer.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr}\n\treq, err := http.NewRequest(\"POST\", url, payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"Content-Type\", writer.FormDataContentType())\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\n\tvar publishedFileDetailsData struct {\n\t\tResponse struct {\n\t\t\tResult               int                   `json:\"result\"`\n\t\t\tResultcount          int                   `json:\"resultcount\"`\n\t\t\tPublishedfiledetails []Publishedfiledetail `json:\"publishedfiledetails\"`\n\t\t} `json:\"response\"`\n\t}\n\n\terr = json.NewDecoder(res.Body).Decode(&publishedFileDetailsData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif publishedFileDetailsData.Response.Result == 1 {\n\t\treturn publishedFileDetailsData.Response.Publishedfiledetails, nil\n\t}\n\n\treturn nil, errors.New(\"请求失败\")\n}\n\n// unzipToDir 解压zip文件到指定目录\nfunc (s *ModService) unzipToDir(zipReader *zip.Reader, destDir string) error {\n\tfor _, file := range zipReader.File {\n\t\tdestPath := filepath.Join(destDir, file.Name)\n\n\t\tif !filepath.HasPrefix(destPath, filepath.Clean(destDir)+string(os.PathSeparator)) {\n\t\t\treturn fmt.Errorf(\"非法文件路径: %s\", destPath)\n\t\t}\n\n\t\tif file.FileInfo().IsDir() {\n\t\t\terr := os.MkdirAll(destPath, os.ModePerm)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := os.MkdirAll(filepath.Dir(destPath), os.ModePerm); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\toutFile, err := os.OpenFile(destPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer outFile.Close()\n\n\t\trc, err := file.Open()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer rc.Close()\n\n\t\t_, err = io.Copy(outFile, rc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// ===== 辅助函数 =====\n\n// excludeList Lua自带对象名称\nvar excludeList = map[string]bool{\n\t\"_G\": true, \"assert\": true, \"collectgarbage\": true, \"dofile\": true, \"error\": true,\n\t\"getmetatable\": true, \"ipairs\": true, \"load\": true, \"loadfile\": true, \"module\": true,\n\t\"next\": true, \"pairs\": true, \"pcall\": true, \"print\": true, \"rawequal\": true, \"rawget\": true,\n\t\"rawset\": true, \"require\": true, \"select\": true, \"setmetatable\": true, \"tonumber\": true,\n\t\"tostring\": true, \"type\": true, \"unpack\": true, \"xpcall\": true, \"debug\": true, \"_VERSION\": true,\n\t\"os\": true, \"_GOPHER_LUA_VERSION\": true, \"string\": true, \"math\": true, \"io\": true, \"channel\": true,\n\t\"package\": true, \"coroutine\": true, \"table\": true,\n}\n\n// toInterface 将Lua值转换为interface{}\nfunc toInterface(lv lua.LValue) interface{} {\n\tswitch lv.Type() {\n\tcase lua.LTNil:\n\t\treturn nil\n\tcase lua.LTBool:\n\t\treturn bool(lv.(lua.LBool))\n\tcase lua.LTNumber:\n\t\treturn float64(lv.(lua.LNumber))\n\tcase lua.LTString:\n\t\treturn lv.String()\n\tcase lua.LTTable:\n\t\tt := lv.(*lua.LTable)\n\t\tif isTableArray(t) {\n\t\t\tarr := make([]interface{}, t.Len())\n\t\t\tt.ForEach(func(i lua.LValue, v lua.LValue) {\n\t\t\t\tindex := int(float64(i.(lua.LNumber)) - 1)\n\t\t\t\tif index != -1 && index < len(arr) {\n\t\t\t\t\tarr[index] = toInterface(v)\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn arr\n\t\t}\n\t\treturn toMap(t)\n\tdefault:\n\t\treturn lv.String()\n\t}\n}\n\n// toMap 将Lua table转换为map\nfunc toMap(t *lua.LTable) map[string]interface{} {\n\tm := make(map[string]interface{})\n\tt.ForEach(func(k lua.LValue, v lua.LValue) {\n\t\tkey := \"\"\n\t\tswitch k.Type() {\n\t\tcase lua.LTString:\n\t\t\tkey = k.String()\n\t\tcase lua.LTNumber:\n\t\t\tkey = fmt.Sprintf(\"%g\", float64(k.(lua.LNumber)))\n\t\tdefault:\n\t\t\tkey = fmt.Sprintf(\"%v\", k)\n\t\t}\n\t\tm[key] = toInterface(v)\n\t})\n\treturn m\n}\n\n// isTableArray 判断Lua table是否为数组\nfunc isTableArray(t *lua.LTable) bool {\n\tmaxIndex := 0\n\tisSequential := true\n\tt.ForEach(func(k lua.LValue, v lua.LValue) {\n\t\tif i, ok := k.(lua.LNumber); ok {\n\t\t\tif i != lua.LNumber(int(i)) {\n\t\t\t\tisSequential = false\n\t\t\t} else if int(i) > maxIndex {\n\t\t\t\tmaxIndex = int(i)\n\t\t\t}\n\t\t} else {\n\t\t\tisSequential = false\n\t\t}\n\t})\n\treturn isSequential && maxIndex == t.Len()\n}\n\n// isWorkshopId 判断是否为workshop ID\nfunc isWorkshopId(id string) bool {\n\t_, err := strconv.Atoi(id)\n\treturn err == nil\n}\n\n// isModId 判断字符串是否为modID\nfunc isModId(str string) (int, bool) {\n\tid, err := strconv.Atoi(str)\n\treturn id, err == nil\n}\n"
  },
  {
    "path": "internal/service/player/player_service.go",
    "content": "package player\n\nimport (\n\t\"dst-admin-go/internal/pkg/utils/fileUtils\"\n\t\"dst-admin-go/internal/service/archive\"\n\t\"dst-admin-go/internal/service/game\"\n\t\"log\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// PlayerInfo 玩家信息结构体\ntype PlayerInfo struct {\n\tKey  string `json:\"key\"`\n\tDay  string `json:\"day\"`\n\tKuId string `json:\"kuId\"`\n\tName string `json:\"name\"`\n\tRole string `json:\"role\"`\n}\n\ntype PlayerService struct {\n\tarchive *archive.PathResolver\n}\n\nfunc NewPlayerService(archive *archive.PathResolver) *PlayerService {\n\treturn &PlayerService{\n\t\tarchive: archive,\n\t}\n}\n\nfunc (p *PlayerService) GetPlayerList(clusterName string, levelName string, gameProcess game.Process) []PlayerInfo {\n\t// 处理 #ALL_LEVEL 情况\n\tqueryName := \"\"\n\tif levelName == \"#ALL_LEVEL\" {\n\t\tqueryName = \"Master\"\n\t} else {\n\t\tqueryName = levelName\n\t}\n\tstatus, _ := gameProcess.Status(clusterName, queryName)\n\tif !status {\n\t\treturn make([]PlayerInfo, 0)\n\t}\n\n\tid := strconv.FormatInt(time.Now().Unix(), 10)\n\n\tcommand := \"\"\n\tif levelName == \"#ALL_LEVEL\" {\n\t\tlevelName = \"Master\"\n\t\tcommand = \"for i, v in ipairs(TheNet:GetClientTable()) do  print(string.format(\\\\\\\"player: {[%s] [%d] [%s] [%s] [%s] [%s]} \\\\\\\", \" + \"'\" + id + \"'\" + \",i-1, string.format('%03d', v.playerage), v.userid, v.name, v.prefab)) end\"\n\t} else {\n\t\tcommand = \"for i, v in ipairs(AllPlayers) do print(string.format(\\\\\\\"player: {[%d] [%d] [%d] [%s] [%s] [%s]} \\\\\\\", \" + id + \",i,v.components.age:GetAgeInDays(), v.userid, v.name, v.prefab)) end\"\n\t}\n\n\terr := gameProcess.Command(clusterName, levelName, command)\n\tlog.Println(\"clusterName:\", clusterName, \"levelName:\", levelName, \"command:\", command)\n\tif err != nil {\n\t\tlog.Println(\"Error sending command:\", err)\n\t\treturn make([]PlayerInfo, 0)\n\t}\n\n\ttime.Sleep(time.Duration(1) * time.Second)\n\n\t// 读取日志\n\tserverLogPath := p.archive.ServerLogPath(clusterName, levelName)\n\tdstLogs, err := fileUtils.ReverseRead(serverLogPath, 1000)\n\tplayerInfoList := make([]PlayerInfo, 0)\n\n\tfor _, line := range dstLogs {\n\t\tif strings.Contains(line, id) && strings.Contains(line, \"KU\") && !strings.Contains(line, \"Host\") {\n\n\t\t\tlog.Println(line)\n\n\t\t\t// 提取 {} 中的内容\n\t\t\treCurlyBraces := regexp.MustCompile(`\\{([^}]*)\\}`)\n\t\t\tcurlyBracesMatches := reCurlyBraces.FindStringSubmatch(line)\n\n\t\t\tif len(curlyBracesMatches) > 1 {\n\t\t\t\t// curlyBracesMatches[1] 包含 {} 中的内容\n\t\t\t\tcontentInsideCurlyBraces := curlyBracesMatches[1]\n\n\t\t\t\t// 提取 [] 中的内容\n\t\t\t\treSquareBrackets := regexp.MustCompile(`\\[([^\\]]*)\\]`)\n\t\t\t\tsquareBracketsMatches := reSquareBrackets.FindAllStringSubmatch(contentInsideCurlyBraces, -1)\n\t\t\t\tvar result []string\n\t\t\t\tfor _, match := range squareBracketsMatches {\n\t\t\t\t\t// match[1] 包含 [] 中的内容\n\t\t\t\t\tcontentInsideSquareBrackets := match[1]\n\t\t\t\t\tresult = append(result, contentInsideSquareBrackets)\n\t\t\t\t}\n\t\t\t\tif len(result) >= 6 {\n\t\t\t\t\tplayerInfo := PlayerInfo{Key: result[1], Day: result[2], KuId: result[3], Name: result[4], Role: result[5]}\n\t\t\t\t\tplayerInfoList = append(playerInfoList, playerInfo)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// 创建一个map，用于存储不重复的KuId和对应的PlayerInfo对象\n\tuniquePlayers := make(map[string]PlayerInfo)\n\n\t// 遍历players切片\n\tfor _, player := range playerInfoList {\n\t\t// 将PlayerInfo对象添加到map中，以KuId作为键\n\t\tuniquePlayers[player.KuId] = player\n\t}\n\n\t// 将不重复的PlayerInfo对象从map中提取到新的切片中\n\tfilteredPlayers := make([]PlayerInfo, 0, len(uniquePlayers))\n\tfor _, player := range uniquePlayers {\n\t\tfilteredPlayers = append(filteredPlayers, player)\n\t}\n\n\treturn filteredPlayers\n}\n\nfunc (p *PlayerService) GetPlayerAllList(clusterName string, gameProcess game.Process) []PlayerInfo {\n\t// 使用 #ALL_LEVEL 调用 GetPlayerList，获取所有玩家\n\treturn p.GetPlayerList(clusterName, \"#ALL_LEVEL\", gameProcess)\n}\n"
  },
  {
    "path": "internal/service/update/factory.go",
    "content": "package update\n\nimport (\n\t\"dst-admin-go/internal/pkg/utils\"\n\t\"dst-admin-go/internal/service/dstConfig\"\n)\n\nfunc NewUpdateService(dstConfig dstConfig.Config) Update {\n\tisWindow := utils.IsWindow()\n\tif isWindow {\n\t\treturn NewWindowUpdate(dstConfig)\n\t}\n\treturn NewLinuxUpdate(dstConfig)\n}\n"
  },
  {
    "path": "internal/service/update/linux_update.go",
    "content": "package update\n\nimport (\n\t\"dst-admin-go/internal/pkg/utils/shellUtils\"\n\t\"dst-admin-go/internal/service/dstConfig\"\n\t\"log\"\n)\n\ntype LinuxUpdate struct {\n\tdstConfig dstConfig.Config\n}\n\nfunc NewLinuxUpdate(dstConfig dstConfig.Config) *LinuxUpdate {\n\treturn &LinuxUpdate{\n\t\tdstConfig: dstConfig,\n\t}\n}\n\nfunc (u LinuxUpdate) Update(clusterName string) error {\n\tconfig, err := u.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tupdateCommand, err := LinuxUpdateCommand(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"正在更新游戏\", \"cluster: \", clusterName, \"command: \", updateCommand)\n\t_, err = shellUtils.Shell(updateCommand)\n\treturn err\n}\n"
  },
  {
    "path": "internal/service/update/update.go",
    "content": "package update\n\nimport (\n\t\"dst-admin-go/internal/pkg/utils/fileUtils\"\n\t\"dst-admin-go/internal/service/dstConfig\"\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n)\n\ntype Update interface {\n\tUpdate(clusterName string) error\n}\n\nfunc EscapePath(path string) string {\n\tif runtime.GOOS == \"windows\" {\n\t\treturn path\n\t}\n\t// 在这里添加需要转义的特殊字符\n\tescapedChars := []string{\" \", \"'\", \"(\", \")\"}\n\tfor _, char := range escapedChars {\n\t\tpath = strings.ReplaceAll(path, char, \"\\\\\"+char)\n\t}\n\treturn path\n}\n\nfunc GetBaseUpdateCmd(cluster dstConfig.DstConfig) string {\n\tsteamCmdPath := cluster.Steamcmd\n\tdstInstallDir := cluster.Force_install_dir\n\tif cluster.Beta == 1 {\n\t\tdstInstallDir = dstInstallDir + \"-beta\"\n\t}\n\t// 确保路径是跨平台兼容的\n\tdstInstallDir = filepath.Clean(EscapePath(dstInstallDir))\n\tsteamCmdPath = filepath.Clean(steamCmdPath)\n\n\t// 构建基本命令\n\tbaseCmd := \"+login anonymous +force_install_dir %s +app_update 343050\"\n\tif cluster.Beta == 1 {\n\t\tbaseCmd += \" -beta updatebeta\"\n\t}\n\tbaseCmd += \" validate +quit\"\n\tbaseCmd = fmt.Sprintf(baseCmd, dstInstallDir)\n\treturn baseCmd\n}\n\nfunc WindowUpdateCommand(cluster dstConfig.DstConfig) (string, error) {\n\tsteamCmdPath := cluster.Steamcmd\n\tbaseCmd := GetBaseUpdateCmd(cluster)\n\n\tvar cmd string\n\tcmd = fmt.Sprintf(\"cd /d %s && Start steamcmd.exe %s\", steamCmdPath, baseCmd)\n\treturn cmd, nil\n}\n\nfunc LinuxUpdateCommand(cluster dstConfig.DstConfig) (string, error) {\n\tsteamCmdPath := cluster.Steamcmd\n\tbaseCmd := GetBaseUpdateCmd(cluster)\n\tvar cmd string\n\tsteamCmdScript := filepath.Join(steamCmdPath, \"steamcmd.sh\")\n\tif cluster.Bin == 86 {\n\t\tcmd = fmt.Sprintf(\"cd %s ; box86 ./linux32/steamcmd %s\", steamCmdPath, baseCmd)\n\t} else {\n\t\tif fileUtils.Exists(steamCmdScript) {\n\t\t\tcmd = fmt.Sprintf(\"cd %s ; ./steamcmd.sh %s\", steamCmdPath, baseCmd)\n\t\t} else {\n\t\t\tcmd = fmt.Sprintf(\"cd %s ; ./steamcmd %s\", steamCmdPath, baseCmd)\n\t\t}\n\t}\n\treturn cmd, nil\n}\n"
  },
  {
    "path": "internal/service/update/window_update.go",
    "content": "package update\n\nimport (\n\t\"dst-admin-go/internal/pkg/utils/shellUtils\"\n\t\"dst-admin-go/internal/service/dstConfig\"\n\t\"log\"\n)\n\ntype WindowUpdate struct {\n\tdstConfig dstConfig.Config\n}\n\nfunc NewWindowUpdate(dstConfig dstConfig.Config) *WindowUpdate {\n\treturn &WindowUpdate{\n\t\tdstConfig: dstConfig,\n\t}\n}\n\nfunc (u WindowUpdate) Update(clusterName string) error {\n\tconfig, err := u.dstConfig.GetDstConfig(clusterName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tupdateCommand, err := WindowUpdateCommand(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"正在更新游戏\", \"cluster: \", clusterName, \"command: \", updateCommand)\n\tresult, err := shellUtils.ExecuteCommandInWin(updateCommand)\n\tlog.Println(result)\n\treturn err\n}\n"
  },
  {
    "path": "scripts/build_linux.sh",
    "content": "rm -rf dst-admin-go\nGOOS=linux GOARCH=amd64 go build -o dst-admin-go cmd/server/main.go"
  },
  {
    "path": "scripts/build_swagger.sh",
    "content": "swag init -g cmd/server/main.go -o docs"
  },
  {
    "path": "scripts/build_window.sh",
    "content": "GOOS=windows GOARCH=amd64 go build -o dst-admin-go.exe cmd/server/main.go"
  },
  {
    "path": "scripts/docker/Dockerfile",
    "content": "# 使用官方的Ubuntu基础镜像\nFROM ubuntu:20.04\n\nLABEL maintainer=\"hujinbo23 jinbohu23@outlook.com\"\nLABEL description=\"DoNotStarveTogehter server panel written in golang.  github: https://github.com/hujinbo23/dst-admin-go\"\n\n# 更新并安装必要的软件包\nRUN dpkg --add-architecture i386 && \\\n    apt-get update && \\\n    apt-get install -y \\\n    curl \\\n    libcurl4-gnutls-dev:i386 \\\n    lib32gcc1 \\\n    lib32stdc++6 \\\n    libcurl4-gnutls-dev \\\n    libgcc1 \\\n    libstdc++6 \\\n    wget \\\n    ca-certificates \\\n    screen \\\n    procps \\\n    sudo \\\n    unzip \\\n    && rm -rf /var/lib/apt/lists/*\n\n# 设置工作目录\nWORKDIR /app\n\n# 拷贝程序二进制文件\nCOPY dst-admin-go /app/dst-admin-go\nRUN chmod 755 /app/dst-admin-go\n\nCOPY docker-entrypoint.sh /app/docker-entrypoint.sh\nRUN chmod 755 /app/docker-entrypoint.sh\n\nCOPY config.yml /app/config.yml\nCOPY docker_dst_config /app/dst_config\nCOPY dist /app/dist\nCOPY static /app/static\n\n# 内嵌源配置信息\n# 控制面板访问的端口\nEXPOSE 8082/tcp\n# 饥荒世界通信的端口\nEXPOSE 10888/udp\n# 饥荒洞穴世界的端口\nEXPOSE 10998/udp\n# 饥荒森林世界的端口\nEXPOSE 10999/udp\n\n# 运行命令\nENTRYPOINT [\"./docker-entrypoint.sh\"]"
  },
  {
    "path": "scripts/docker/README.md",
    "content": "# Docker 部署脚本\n\n用于构建 DST Admin Go 的标准 Docker 镜像（Linux x86_64 架构）。\n\n## 目录内容\n\n- `Dockerfile` - Docker 镜像构建文件（基于 Ubuntu 20.04）\n- `docker-entrypoint.sh` - 容器启动入口脚本\n- `docker_build.sh` - 构建并推送镜像到 Docker Hub 的自动化脚本\n- `docker_dst_config` - Docker 环境默认配置文件\n\n## 快速开始\n\n### 1. 构建镜像\n\n```bash\n# 首先在项目根目录构建 Linux 二进制文件\nbash scripts/build_linux.sh\n\n# 进入 docker 目录\ncd scripts/docker\n\n# 构建并推送镜像（需要先登录 Docker Hub）\nbash docker_build.sh <version_tag>\n\n# 示例\nbash docker_build.sh 1.6.1\n```\n\n### 2. 运行容器\n\n```bash\n# 创建数据目录\nmkdir -p ~/dstsave/{back,steamcmd,dst-dedicated-server}\n\n# 运行容器\ndocker run -d \\\n  --name dst-admin \\\n  -p 8082:8082 \\\n  -p 10888:10888/udp \\\n  -p 10998:10998/udp \\\n  -p 10999:10999/udp \\\n  -v ~/dstsave:/root/.klei/DoNotStarveTogether \\\n  -v ~/dstsave/back:/app/backup \\\n  -v ~/dstsave/steamcmd:/app/steamcmd \\\n  -v ~/dstsave/dst-dedicated-server:/app/dst-dedicated-server \\\n  hujinbo23/dst-admin-go:latest\n```\n\n### 3. 访问管理面板\n\n打开浏览器访问: http://localhost:8082\n\n## 端口说明\n\n| 端口 | 协议 | 用途 |\n|-----|------|------|\n| 8082 | TCP | 管理面板 Web 访问端口 |\n| 10888 | UDP | 饥荒主世界（Master）通信端口 |\n| 10998 | UDP | 饥荒洞穴世界（Caves）端口 |\n| 10999 | UDP | 饥荒森林世界（Forest）端口 |\n\n## 数据卷\n\n容器内重要路径说明：\n\n| 容器内路径 | 用途 | 是否推荐挂载 |\n|-----------|------|-------------|\n| `/root/.klei/DoNotStarveTogether` | 游戏存档目录 | ✅ 推荐 |\n| `/app/backup` | 存档备份目录 | ✅ 推荐 |\n| `/app/mod` | MOD 缓存目录 | 可选 |\n| `/app/steamcmd` | SteamCMD 安装目录 | ✅ 推荐 |\n| `/app/dst-dedicated-server` | 饥荒服务器文件 | ✅ 推荐 |\n| `/app/dst-db` | SQLite 数据库文件 | ✅ 推荐 |\n| `/app/password.txt` | 初始密码文件 | ✅ 推荐 |\n| `/app/first` | 首次登录标记文件 | ✅ 推荐 |\n| `/app/dst-admin-go.log` | 应用日志文件 | 可选 |\n| `/app/config.yml` | 配置文件 | 可选 |\n\n**特别说明**：\n- `first` 文件：如果存在，启动时会跳过初始化界面，使用 `password.txt` 中的账号登录\n- `dst-db` 文件：SQLite 数据库，包含所有配置和运行数据\n- `password.txt` 文件：初始管理员账号信息，格式见 Docker Compose 示例\n\n## 镜像特性\n\n- **基础镜像**: Ubuntu 20.04\n- **目标架构**: Linux x86_64 (amd64)\n- **已安装组件**:\n  - curl, wget - 网络工具\n  - screen - 游戏进程管理\n  - lib32gcc1, lib32stdc++6 - 32位运行库（饥荒服务器依赖）\n  - libcurl4-gnutls-dev - cURL 开发库\n  - procps, sudo, unzip - 系统工具\n\n## 配置自定义\n\n### 方法一：环境变量\n\n```bash\ndocker run -d \\\n  -e BIND_ADDRESS=\"\" \\\n  -e PORT=8082 \\\n  -e DATABASE=dst-db \\\n  hujinbo23/dst-admin-go:latest\n```\n\n### 方法二：挂载配置文件\n\n```bash\ndocker run -d \\\n  -p 8082:8082 \\\n  -p 10888:10888/udp \\\n  -p 10998:10998/udp \\\n  -p 10999:10999/udp \\\n  -v ~/dstsave:/root/.klei/DoNotStarveTogether \\\n  -v ~/dstsave/back:/app/backup \\\n  -v ~/dstsave/steamcmd:/app/steamcmd \\\n  -v ~/dstsave/dst-dedicated-server:/app/dst-dedicated-server \\\n  -v ~/dstsave/config.yml:/app/config.yml \\\n  hujinbo23/dst-admin-go:latest\n```\n\n## Docker Compose 示例\n\n### 1. 创建前置文件和目录\n\n在使用 Docker Compose 之前，需要先创建必要的文件和目录：\n\n```bash\n# 创建所有必要的目录\nmkdir -p ~/dstsave/back\nmkdir -p ~/dstsave/steamcmd\nmkdir -p ~/dstsave/dst-dedicated-server\n\n# 创建 first 文件（标记非首次登录，避免进入初始化界面）\ntouch ~/dstsave/first\n\n# 创建数据库文件\ntouch ~/dstsave/dst-db\n\n# 创建初始密码文件\ncat > ~/dstsave/password.txt << EOF\nusername = admin\npassword = 123456\ndisplayName = admin\nphotoURL =\nemail = xxx\nEOF\n```\n\n**目录结构**：\n```\n~/dstsave/\n├── back/                        # 备份目录\n├── steamcmd/                    # SteamCMD 安装目录\n├── dst-dedicated-server/        # 饥荒服务器文件\n├── dst-db                       # SQLite 数据库文件\n├── password.txt                 # 初始密码文件\n└── first                        # 首次登录标记文件\n```\n\n**说明**：\n- `first` 文件：如果存在则跳过初始化界面，直接使用 `password.txt` 中的账号登录\n- `dst-db` 文件：SQLite 数据库文件\n- `password.txt` 文件：初始管理员账号信息\n\n### 2. 创建 docker-compose.yml\n\n```yaml\nversion: '3.8'\n\nservices:\n  dst-admin:\n    image: hujinbo23/dst-admin-go:latest\n    container_name: dst-admin\n    restart: unless-stopped\n    ports:\n      - \"8082:8082\"\n      - \"10888:10888/udp\"\n      - \"10998:10998/udp\"\n      - \"10999:10999/udp\"\n    volumes:\n      # 时区同步\n      - /etc/localtime:/etc/localtime:ro\n      - /etc/timezone:/etc/timezone:ro\n      # 游戏存档目录\n      - ${PWD}/dstsave:/root/.klei/DoNotStarveTogether\n      # 备份目录\n      - ${PWD}/dstsave/back:/app/backup\n      # SteamCMD 目录\n      - ${PWD}/dstsave/steamcmd:/app/steamcmd\n      # 饥荒服务器目录\n      - ${PWD}/dstsave/dst-dedicated-server:/app/dst-dedicated-server\n      # 数据库文件\n      - ${PWD}/dstsave/dst-db:/app/dst-db\n      # 初始密码文件\n      - ${PWD}/dstsave/password.txt:/app/password.txt\n      # 首次登录标记文件\n      - ${PWD}/dstsave/first:/app/first\n    environment:\n      - TZ=Asia/Shanghai\n```\n\n### 3. 启动容器\n\n```bash\ndocker-compose up -d\n```\n\n### 4. 查看日志\n\n```bash\n# 查看容器日志\ndocker-compose logs -f\n\n# 查看应用日志\ndocker exec -it dst-admin cat /app/dst-admin-go.log\n```\n\n## 常见问题\n\n### 容器无法启动\n\n查看日志排查问题：\n```bash\ndocker logs dst-admin\n```\n\n### 游戏端口无法访问\n\n1. 确保端口映射正确且使用 UDP 协议\n2. 检查宿主机防火墙设置：\n```bash\n# CentOS/RHEL\nfirewall-cmd --add-port=10888/udp --permanent\nfirewall-cmd --reload\n\n# Ubuntu/Debian\nufw allow 10888/udp\n```\n\n### 数据持久化失败\n\n确保挂载目录有正确的权限：\n```bash\nchmod -R 755 ~/dstsave\n```\n\n### 游戏下载缓慢\n\n首次启动需要下载 SteamCMD 和饥荒服务器文件（约 1-2GB），国内网络可能较慢。可以考虑：\n1. 预先下载 SteamCMD 到 `~/dstsave/steamcmd` 目录\n2. 预先使用 SteamCMD 下载游戏文件到 `~/dstsave/dst-dedicated-server` 目录\n3. 使用代理加速 Steam 下载\n\n## 性能建议\n\n- **最低配置**: 2 核 CPU, 2GB 内存, 10GB 磁盘\n- **推荐配置**: 4 核 CPU, 4GB 内存, 20GB 磁盘\n- **生产环境**: 根据玩家数量和世界复杂度适当增加资源\n\n## 注意事项\n\n1. 生产环境建议使用固定版本标签，避免使用 `latest`\n2. 定期备份 `~/dstsave` 目录，里面包含所有重要数据\n3. 游戏端口必须使用 UDP 协议，TCP 无法正常工作\n4. 容器重启后游戏进程需要手动启动（通过管理面板）\n5. 首次启动会自动下载 SteamCMD 和饥荒服务器文件，需要一定时间\n6. 所有数据统一存放在 `~/dstsave` 目录，便于管理和备份\n\n## 相关链接\n\n- [Docker Hub 镜像](https://hub.docker.com/r/hujinbo23/dst-admin-go)\n- [GitHub 项目主页](https://github.com/hujinbo23/dst-admin-go)\n- [饥荒联机版官方 Wiki](https://dontstarve.fandom.com/wiki/Don%27t_Starve_Together)\n"
  },
  {
    "path": "scripts/docker/docker-entrypoint.sh",
    "content": "#!/bin/bash\n\n# 修正最大文件描述符数，部分docker版本给的默认值过高，会导致screen运行卡顿\nulimit -Sn 10000\n\n# 获取传入的参数\nsteam_cmd_path='/app/steamcmd'\nsteam_dst_server='/app/dst-dedicated-server'\n\n# 判断 steam_cmd_path 是否存在，不存在则创建\nif [ ! -d \"$steam_cmd_path\" ]; then\n  mkdir -p \"$steam_cmd_path\"\nfi\n\n# 进入 steam_cmd_path 目录\ncd \"$steam_cmd_path\"\n\n# 如果 $steam_dst_server 目录不存在，则下载并解压 SteamCMD 并安装游戏服务器\nretry=1\nwhile [ ! -d \"${steam_cmd_path}\" ] || [ ! -e \"${steam_cmd_path}/steamcmd.sh\" ]; do\n  if [ $retry -gt 3 ]; then\n    echo \"Download steamcmd failed after three times\"\n    exit -2\n  fi\n  echo \"Not found steamcmd, start to installing steamcmd, try: ${retry}\"\n  wget http://media.steampowered.com/installer/steamcmd_linux.tar.gz -P $steam_cmd_path\n  tar -zxvf $steam_cmd_path/steamcmd_linux.tar.gz -C $steam_cmd_path\n  sleep 3\n  ((retry++))\ndone\n\n# 如果 $steam_dst_server 目录不存在，则下载并解压 SteamCMD 并安装游戏服务器\nretry=1\nwhile [ ! -e \"${steam_dst_server}/bin/dontstarve_dedicated_server_nullrenderer\" ]; do\n  if [ $retry -gt 3 ]; then\n    echo \"Download Dont Starve Together Sever failed after three times\"\n    exit -2\n  fi\n  echo \"Not found Dont Starve Together Sever, start to installing, try: ${retry}\"\n  bash $steam_cmd_path/steamcmd.sh +force_install_dir $steam_dst_server +login anonymous +app_update 343050 validate +quit\n  mkdir -p $USER_DIR/.klei/DoNotStarveTogether/MyDediServer\n  mkdir -p /app/backup\n  mkdir -p /app/mod\n  echo \"username=admin\" >> /app/password.txt\n  echo \"password=123456\" >> /app/password.txt\n  echo \"displayName=admin\" >> /app/password.txt\n  echo \"photoURL=xxx\" >> /app/password.txt\n  sleep 3\n  ((retry++))\ndone\n\n\n# 运行其他命令，这里只是做示例\necho \"SteamCMD installed at $steam_cmd_path\"\necho \"SteamDST server installed at $steam_dst_server\"\n\n\ncd /app\nexec ./dst-admin-go"
  },
  {
    "path": "scripts/docker/docker_build.sh",
    "content": "#!/bin/bash\n\n# 获取命令行参数\nTAG=$1\n\n# 构建镜像\ndocker build -t hujinbo23/dst-admin-go:$TAG .\n\n# 推送镜像到Docker Hub\ndocker push hujinbo23/dst-admin-go:$TAG"
  },
  {
    "path": "scripts/docker/docker_dst_config",
    "content": "steamcmd=/app/steamcmd\nforce_install_dir=/app/dst-dedicated-server\ncluster=MyDediServer\nbackup=/app/backup\nmod_download_path=/app/mod\nbin=32\nbeta=0\n"
  },
  {
    "path": "scripts/docker-build-mac/Dockerfile",
    "content": "FROM ubuntu:22.04\n\nENV DEBIAN_FRONTEND=noninteractive\nENV DST_DIR=/dst-server\n\n\n# ===== 安装必要依赖 =====\nRUN apt update && apt install -y --no-install-recommends \\\n    wget screen git unzip curl tar build-essential cmake ca-certificates \\\n    python3 python3-pip tzdata \\\n    && ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \\\n    && echo \"Asia/Shanghai\" > /etc/timezone \\\n    && rm -rf /var/lib/apt/lists/*\n\n\n# ===== 安装 .NET 8 runtime（DepotDownloader 依赖） =====\nRUN wget https://packages.microsoft.com/config/ubuntu/22.04/packages-microsoft-prod.deb -O /tmp/packages-microsoft-prod.deb \\\n    && dpkg -i /tmp/packages-microsoft-prod.deb \\\n    && apt update \\\n    && apt install -y dotnet-runtime-8.0 \\\n    && rm -rf /var/lib/apt/lists/* /tmp/packages-microsoft-prod.deb\n\n# ===== 安装 box64 =====\nRUN git clone https://github.com/ptitSeb/box64.git /opt/box64 \\\n    && mkdir /opt/box64/build && cd /opt/box64/build \\\n    && cmake .. -DARM_DYNAREC=ON -DCMAKE_BUILD_TYPE=RelWithDebInfo \\\n    && make -j$(nproc) \\\n    && make install \\\n    && rm -rf /opt/box64\n\n# ===== 安装 DepotDownloader 最新 Release =====\nRUN wget https://github.com/SteamRE/DepotDownloader/releases/download/DepotDownloader_3.4.0/DepotDownloader-linux-arm64.zip -O /opt/DepotDownloader.zip \\\n    && unzip /opt/DepotDownloader.zip -d /opt/DepotDownloader \\\n    && rm /opt/DepotDownloader.zip\n\n# ===== 创建饥荒服务器目录 =====\nRUN mkdir -p $DST_DIR\n\nWORKDIR /app\n\nENV PATH=/usr/local/bin:$PATH\n\nCOPY dst-admin-go /app/dst-admin-go\nRUN chmod 755 /app/dst-admin-go\n\nCOPY docker-entrypoint.sh /app/docker-entrypoint.sh\nRUN chmod 755 /app/docker-entrypoint.sh\n\nCOPY config.yml /app/config.yml\nCOPY docker_dst_config /app/dst_config\nCOPY dist /app/dist\nCOPY static /app/static\n\n\nENTRYPOINT [\"./docker-entrypoint.sh\"]\n\n"
  },
  {
    "path": "scripts/docker-build-mac/README.md",
    "content": "# Docker 部署脚本（Mac ARM64）\n\n用于在 Mac ARM64（Apple Silicon: M1/M2/M3）平台上构建和运行 DST Admin Go 的特殊 Docker 镜像。\n\n## 背景说明\n\n饥荒联机版（Don't Starve Together）服务器原生只支持 x86_64 架构，无法直接在 ARM64 设备上运行。本镜像通过 **Box64** 动态翻译技术实现 x86_64 程序在 ARM64 平台上执行，使得 Apple Silicon Mac 也能运行饥荒服务器。\n\n## 技术架构\n\n```\nARM64 主机（Apple Silicon Mac）\n  └─> Docker 容器（ARM64）\n       ├─> dst-admin-go（原生 ARM64 Go 程序）\n       ├─> Box64（x86_64 → ARM64 动态翻译层）\n       │    └─> DST Server（x86_64 游戏服务器）\n       └─> DepotDownloader（ARM64 版本，用于下载游戏文件）\n```\n\n## 目录内容\n\n- `Dockerfile` - ARM64 优化的镜像构建文件（Ubuntu 22.04）\n- `docker-entrypoint.sh` - 容器启动脚本\n- `docker_dst_config` - 默认配置文件\n- `dst-mac-arm64-env-install.md` - 手动安装环境的详细步骤文档（非 Docker 部署）\n\n## 核心组件\n\n| 组件 | 版本 | 用途 |\n|-----|------|------|\n| Box64 | 最新版 | x86_64 到 ARM64 的动态二进制翻译器（启用 ARM_DYNAREC 优化） |\n| .NET Runtime | 8.0 | DepotDownloader 运行依赖 |\n| DepotDownloader | 3.4.0 | Steam 内容下载工具（ARM64 版本） |\n\n## 快速开始\n\n### 1. 构建镜像\n\n```bash\n# 在 Mac ARM64 机器上执行\ncd scripts/docker-build-mac\n\n# 构建镜像\ndocker build --platform linux/arm64 -t dst-admin-go-arm64:latest .\n```\n\n### 2. 运行容器\n\n```bash\n# 创建数据目录\nmkdir -p ~/dstsave/{back,dst-dedicated-server}\n\n# 运行容器\ndocker run -d \\\n  --name dst-admin-arm64 \\\n  --platform linux/arm64 \\\n  -p 8082:8082 \\\n  -p 10888:10888/udp \\\n  -p 10998:10998/udp \\\n  -p 10999:10999/udp \\\n  -v ~/dstsave:/root/.klei/DoNotStarveTogether \\\n  -v ~/dstsave/back:/app/backup \\\n  -v ~/dstsave/dst-dedicated-server:/app/dst-dedicated-server \\\n  dst-admin-go-arm64:latest\n```\n\n### 3. 访问管理面板\n\n打开浏览器访问: http://localhost:8082\n\n## 性能对比\n\n### 性能表现\n\n| 指标 | x86_64 原生 | ARM64 + Box64 |\n|-----|------------|---------------|\n| CPU 性能 | 100% | 60-80% |\n| 内存占用 | 基准 | +30-40% |\n| 启动速度 | 快 | 中等 |\n| 稳定性 | 完美 | 良好（偶尔崩溃） |\n\n### 适用场景\n\n✅ **推荐用于**:\n- 开发和测试环境\n- 小型私服（<10 人）\n- 个人学习和实验\n\n❌ **不推荐用于**:\n- 大型公开服务器\n- 高并发生产环境\n- 对性能要求严格的场景\n\n## 镜像特性\n\n- **基础镜像**: Ubuntu 22.04\n- **目标架构**: ARM64 (aarch64)\n- **时区设置**: Asia/Shanghai\n- **已安装组件**:\n  - Box64（从源码编译，启用 ARM_DYNAREC 优化）\n  - .NET 8.0 Runtime\n  - DepotDownloader（ARM64 版本）\n  - screen, wget, curl, git\n  - Python 3, pip\n  - build-essential, cmake（用于编译 Box64）\n\n## 环境变量\n\n| 变量名 | 默认值 | 说明 |\n|-------|--------|------|\n| `DST_DIR` | `/dst-server` | 饥荒服务器安装目录 |\n| `DEBIAN_FRONTEND` | `noninteractive` | 非交互式安装模式 |\n\n## Docker Compose 示例\n\n### 1. 创建前置文件和目录\n\n在使用 Docker Compose 之前，需要先创建必要的文件和目录：\n\n```bash\n# 创建所有必要的目录\nmkdir -p ~/dstsave/back\nmkdir -p ~/dstsave/dst-dedicated-server\n\n# 创建 first 文件（标记非首次登录，避免进入初始化界面）\ntouch ~/dstsave/first\n\n# 创建数据库文件\ntouch ~/dstsave/dst-db\n\n# 创建初始密码文件\ncat > ~/dstsave/password.txt << EOF\nusername = admin\npassword = 123456\ndisplayName = admin\nphotoURL =\nemail = xxx\nEOF\n```\n\n**目录结构**：\n```\n~/dstsave/\n├── back/                        # 备份目录\n├── dst-dedicated-server/        # 饥荒服务器文件\n├── dst-db                       # SQLite 数据库文件\n├── password.txt                 # 初始密码文件\n└── first                        # 首次登录标记文件\n```\n\n**说明**：\n- `first` 文件：如果存在则跳过初始化界面，直接使用 `password.txt` 中的账号登录\n- `dst-db` 文件：SQLite 数据库文件\n- `password.txt` 文件：初始管理员账号信息\n- ARM64 版本不使用 SteamCMD，而是通过 DepotDownloader 下载游戏文件\n\n### 2. 创建 docker-compose.yml\n\n```yaml\nversion: '3.8'\n\nservices:\n  dst-admin-arm64:\n    image: dst-admin-go-arm64:latest\n    container_name: dst-admin-arm64\n    platform: linux/arm64\n    restart: unless-stopped\n    ports:\n      - \"8082:8082\"\n      - \"10888:10888/udp\"\n      - \"10998:10998/udp\"\n      - \"10999:10999/udp\"\n    volumes:\n      # 时区同步\n      - /etc/localtime:/etc/localtime:ro\n      - /etc/timezone:/etc/timezone:ro\n      # 游戏存档目录\n      - ${PWD}/dstsave:/root/.klei/DoNotStarveTogether\n      # 备份目录\n      - ${PWD}/dstsave/back:/app/backup\n      # 饥荒服务器目录（ARM64 版本使用 DepotDownloader 下载）\n      - ${PWD}/dstsave/dst-dedicated-server:/app/dst-dedicated-server\n      # 数据库文件\n      - ${PWD}/dstsave/dst-db:/app/dst-db\n      # 初始密码文件\n      - ${PWD}/dstsave/password.txt:/app/password.txt\n      # 首次登录标记文件\n      - ${PWD}/dstsave/first:/app/first\n    environment:\n      - TZ=Asia/Shanghai\n    # 为 ARM64 翻译层提供更多资源\n    deploy:\n      resources:\n        limits:\n          memory: 4G\n        reservations:\n          memory: 2G\n```\n\n### 3. 启动容器\n\n```bash\ndocker-compose up -d\n```\n\n### 4. 查看日志\n\n```bash\n# 查看容器日志\ndocker-compose logs -f\n\n# 查看应用日志\ndocker exec -it dst-admin-arm64 cat /app/dst-admin-go.log\n```\n\n## 手动安装（非 Docker）\n\n如果需要在 ARM64 Linux 系统上手动部署，请参考 `dst-mac-arm64-env-install.md` 文档。\n\n关键步骤概述：\n1. 安装 .NET 8 Runtime\n2. 从源码编译安装 Box64（启用 ARM_DYNAREC）\n3. 下载 DepotDownloader（ARM64 版本）\n4. 使用 DepotDownloader 下载饥荒服务器\n5. 配置 Box64 环境变量\n\n## 故障排查\n\n### Box64 启动失败\n\n检查 Box64 是否正确安装：\n```bash\ndocker exec -it dst-admin-arm64 box64 --version\n```\n\n查看 Box64 日志（如果有）：\n```bash\ndocker exec -it dst-admin-arm64 cat /var/log/box64.log\n```\n\n### 游戏服务器崩溃\n\nARM64 翻译层可能遇到兼容性问题，查看容器日志：\n```bash\n# 查看容器日志\ndocker logs dst-admin-arm64\n\n# 进入容器查看 screen 会话\ndocker exec -it dst-admin-arm64 screen -ls\ndocker exec -it dst-admin-arm64 screen -r <session_name>\n```\n\n### 性能不足\n\n优化建议：\n1. 增加容器内存限制: `--memory=4g`\n2. 减少游戏世界大小和复杂度\n3. 减少加载的 MOD 数量\n4. 降低玩家数量上限\n\n### 游戏下载失败\n\n首次启动需要通过 DepotDownloader 下载游戏文件：\n```bash\n# 手动下载游戏文件\ndocker exec -it dst-admin-arm64 /opt/DepotDownloader/DepotDownloader \\\n  -app 343050 -os linux -osarch 64 -dir /dst-server -validate\n```\n\n## 性能优化建议\n\n### 1. 资源配置\n\n```bash\ndocker run -d \\\n  --cpus=\"4\" \\\n  --memory=\"4g\" \\\n  --memory-swap=\"6g\" \\\n  ... # 其他参数\n```\n\n### 2. Box64 优化\n\nBox64 在构建时已启用以下优化：\n- `ARM_DYNAREC=ON` - 启用 ARM 动态重编译（显著提升性能）\n- `CMAKE_BUILD_TYPE=RelWithDebInfo` - 优化构建模式\n\n### 3. 游戏配置优化\n\n- 选择较小的世界大小（Small/Medium）\n- 减少世界生成的生物数量\n- 避免使用性能密集型 MOD\n- 限制玩家数量（建议 ≤ 8 人）\n\n## 与标准版对比\n\n| 特性 | 标准版（x86_64） | ARM64 版 |\n|-----|----------------|----------|\n| 架构 | x86_64 | ARM64 + Box64 翻译 |\n| 部署难度 | 简单 | 中等 |\n| 性能 | 100% | 60-80% |\n| 内存占用 | 标准 | +30-40% |\n| 兼容性 | 完美 | 良好（偶尔问题） |\n| 适用场景 | 生产环境 | 开发/测试/小型服务器 |\n| 镜像大小 | ~800MB | ~1.2GB |\n\n## 注意事项\n\n1. **仅适用于 Mac ARM64**: M1/M2/M3/M4 系列芯片\n2. **首次启动耗时长**: 需要下载约 1-2GB 的游戏文件\n3. **不建议生产环境**: 性能和稳定性不如原生 x86_64\n4. **内存需求高**: 建议至少 4GB 可用内存\n5. **可能的兼容性问题**: 某些 MOD 可能在 Box64 下无法正常工作\n6. **崩溃处理**: 游戏崩溃后需要手动重启（通过管理面板）\n\n## 已知限制\n\n- 某些 CPU 密集型 MOD 可能导致性能下降\n- 大型世界（Huge）可能出现卡顿\n- 多世界（Master + Caves）同时运行时内存压力大\n- Box64 翻译层偶尔可能遇到兼容性问题导致崩溃\n\n## 参考资源\n\n- [Box64 项目](https://github.com/ptitSeb/box64) - x86_64 到 ARM64 翻译器\n- [DepotDownloader](https://github.com/SteamRE/DepotDownloader) - Steam 内容下载工具\n- [.NET Runtime 下载](https://dotnet.microsoft.com/download/dotnet/8.0) - .NET 8 运行时\n- [DST 专用服务器 Wiki](https://dontstarve.fandom.com/wiki/Guides/Don%E2%80%99t_Starve_Together_Dedicated_Servers)\n\n## 支持与反馈\n\n如果在 ARM64 环境下遇到问题，请在 GitHub Issues 中注明：\n- 设备型号（M1/M2/M3 等）\n- macOS 版本\n- Docker 版本\n- 具体的错误日志\n\n由于 ARM64 是实验性支持，某些问题可能无法完全解决。生产环境建议使用标准的 x86_64 版本。\n"
  },
  {
    "path": "scripts/docker-build-mac/docker-entrypoint.sh",
    "content": "#!/bin/bash\n\n# 修正最大文件描述符数，部分docker版本给的默认值过高，会导致screen运行卡顿\nulimit -Sn 10000\n\n# 启用 amd64 架构\ndpkg --add-architecture amd64\n\n# 添加 amd64 源\necho \"deb [arch=amd64] http://archive.ubuntu.com/ubuntu jammy main universe multiverse restricted\ndeb [arch=amd64] http://archive.ubuntu.com/ubuntu jammy-updates main universe multiverse restricted\ndeb [arch=amd64] http://archive.ubuntu.com/ubuntu jammy-security main universe multiverse restricted\" > /etc/apt/sources.list.d/amd64.list\n\n# 更新源\napt update\n\n# 安装 x86_64 运行库\napt install -y libc6:amd64 libstdc++6:amd64\n\ncd /opt/DepotDownloader\n./DepotDownloader -app 343050 -os linux -osarch 64 -dir /app/dst-dedicated-server -validate\n\nchmod +x /app/dst-dedicated-server/bin64/dontstarve_dedicated_server_nullrenderer_x64\n\ncd /app\nexec ./dst-admin-go\n"
  },
  {
    "path": "scripts/docker-build-mac/docker_dst_config",
    "content": "steamcmd=/app/steamcmd\nforce_install_dir=/app/dst-dedicated-server\ncluster=MyDediServer\nbackup=/app/backup\nmod_download_path=/app/mod\nbin=2664\nbeta=0\n"
  },
  {
    "path": "scripts/docker-build-mac/dst-mac-arm64-env-install.md",
    "content": "# dst-mac-arm64-env-install\n\n安装基础依赖\n\n```shell\napt update\napt install -y wget unzip tar\n```\n\n\n\n下载 DepotDownloader\n\n```shell\ncd /opt\nwget https://github.com/SteamRE/DepotDownloader/releases/latest/download/DepotDownloader-linux-arm64.zip -O DepotDownloader.zip || \\\nwget https://github.com/SteamRE/DepotDownloader/releases/latest/download/DepotDownloader.zip -O DepotDownloader.zip\n```\n\n安装 .NET 运行时\n\n```shell\nwget https://packages.microsoft.com/config/ubuntu/22.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb\ndpkg -i packages-microsoft-prod.deb\napt update\napt install -y dotnet-runtime-8.0\n```\n\n下载 饥荒服务器\n\n```shell\nunzip DepotDownloader.zip -d DepotDownloader\ncd DepotDownloader\n./DepotDownloader -app 343050 -os linux -osarch 64 -dir /app/dst-dedicated-server -validate\n```\n\n\n\n```\napt update\napt install -y git cmake build-essential\n\n# 克隆源码\ngit clone https://github.com/ptitSeb/box64.git /opt/box64\ncd /opt/box64\n\n# 创建构建目录\nmkdir build && cd build\n\n# 配置并启用 ARM 动态编译器（性能更好）\ncmake .. -DARM_DYNAREC=ON -DCMAKE_BUILD_TYPE=RelWithDebInfo\n\n# 编译\nmake -j$(nproc)\n\n# 安装\nmake install\n\ncp box64 /usr/local/bin/\n```\n\n\n\n```\n# 启用 amd64 架构\ndpkg --add-architecture amd64\n\n# 添加 amd64 源\necho \"deb [arch=amd64] http://archive.ubuntu.com/ubuntu jammy main universe multiverse restricted\ndeb [arch=amd64] http://archive.ubuntu.com/ubuntu jammy-updates main universe multiverse restricted\ndeb [arch=amd64] http://archive.ubuntu.com/ubuntu jammy-security main universe multiverse restricted\" > /etc/apt/sources.list.d/amd64.list\n\n# 更新源\napt update\n\n# 安装 x86_64 运行库\napt install -y libc6:amd64 libstdc++6:amd64\n\n```\n\n"
  },
  {
    "path": "scripts/py-dst-cli/README.md",
    "content": "# py-dst-cli\n\nPython 工具集，用于解析和处理饥荒联机版（Don't Starve Together）的各类配置文件、MOD 信息和游戏资源。\n\n## 功能概述\n\n本工具提供以下核心功能：\n\n1. **世界配置解析** - 解析和生成 `leveldataoverride.lua` 配置文件\n2. **MOD 信息提取** - 从 Steam Workshop 获取 MOD 详细信息\n3. **游戏版本查询** - 获取当前最新的饥荒服务器版本号\n4. **物品数据解析** - 解析 TooManyItemPlus 等 MOD 的物品数据\n5. **资源提取** - 从游戏文件中提取图片资源（worldgen_customization.tex）\n\n## 目录结构\n\n```\npy-dst-cli/\n├── main.py                              # 主入口程序\n├── dst_version.py                       # 版本查询工具\n├── parse_world_setting.py               # 世界配置解析器\n├── parse_mod.py                         # MOD 信息解析器\n├── parse_TooManyItemPlus_items.py       # 物品数据解析器\n├── parse_world_webp.py                  # 世界图片资源处理\n├── dst_world_setting.json               # 世界配置 JSON 数据\n├── requirements.txt                     # Python 依赖列表\n└── steamapikey.txt                      # Steam API Key 配置\n```\n\n## 安装依赖\n\n### 方法一：使用虚拟环境（推荐）\n\n```bash\n# 创建虚拟环境\npython3 -m venv env\n\n# 激活虚拟环境\nsource env/bin/activate  # Linux/Mac\n# 或\nenv\\Scripts\\activate  # Windows\n\n# 安装依赖库\npip install -r requirements.txt\n\n# 使用完毕后退出虚拟环境\ndeactivate\n```\n\n### 方法二：直接安装\n\n```bash\npip install -r requirements.txt\n```\n\n### 更新依赖列表\n\n如果添加了新的依赖，使用以下命令更新 `requirements.txt`：\n```bash\npip freeze > requirements.txt\n```\n\n## 使用方法\n\n### 1. 配置 Steam API Key\n\n在 `steamapikey.txt` 文件中配置你的 Steam Web API Key：\n\n```\nYOUR_STEAM_API_KEY_HERE\n```\n\n获取 API Key: https://steamcommunity.com/dev/apikey\n\n### 2. 运行主程序\n\n```bash\npython main.py\n```\n\n### 3. 单独使用各个工具\n\n#### 查询游戏版本\n\n```bash\npython dst_version.py\n```\n\n输出示例：\n```json\n{\n  \"version\": \"573123\",\n  \"update_time\": \"2024-01-15 10:30:00\"\n}\n```\n\n#### 解析世界配置\n\n```bash\npython parse_world_setting.py\n```\n\n生成标准的 `dst_world_setting.json` 配置文件供管理面板使用。\n\n#### 解析 MOD 信息\n\n```bash\npython parse_mod.py <mod_id>\n```\n\n示例：\n```bash\npython parse_mod.py 375859599  # 解析 Global Positions MOD\n```\n\n#### 解析物品数据\n\n```bash\npython parse_TooManyItemPlus_items.py\n```\n\n从 TooManyItemPlus MOD 中提取物品列表和属性。\n\n#### 处理世界图片资源\n\n```bash\npython parse_world_webp.py\n```\n\n将 worldgen_customization.tex 文件转换为可用的图片格式。\n\n## 获取游戏资源文件\n\n### 方法一：从游戏安装目录获取\n\n如果已安装饥荒联机版，可直接从安装目录获取：\n\n**Windows:**\n```\nC:\\Program Files (x86)\\Steam\\steamapps\\common\\Don't Starve Together\\data\\images\n```\n\n**Linux:**\n```\n~/.steam/steam/steamapps/common/Don't Starve Together/data/images\n```\n\n**Mac:**\n```\n~/Library/Application Support/Steam/steamapps/common/Don't Starve Together/data/images\n```\n\n关键文件：\n- `worldgen_customization.tex` - 世界生成配置界面资源\n\n### 方法二：通过 SteamCMD 下载\n\n```bash\n# 安装 SteamCMD\n# Ubuntu/Debian:\nsudo apt install steamcmd\n\n# 下载游戏文件\nsteamcmd +login anonymous +app_update 343050 validate +quit\n\n# 游戏文件位置:\n# Linux: ~/.steam/steam/steamapps/common/Don't Starve Together/\n```\n\n### 方法三：使用 DepotDownloader\n\n```bash\n# 下载 DepotDownloader\nwget https://github.com/SteamRE/DepotDownloader/releases/latest/download/DepotDownloader.zip\n\n# 解压并运行\nunzip DepotDownloader.zip -d DepotDownloader\ncd DepotDownloader\n\n# 下载饥荒服务器文件\n./DepotDownloader -app 343050 -os linux -osarch 64 -dir ./dst-server -validate\n```\n\n## 常见配置项说明\n\n### 世界配置（leveldataoverride.lua）\n\n主要配置项：\n- `world_size` - 世界大小: small/medium/large/huge\n- `season_start` - 起始季节: autumn/winter/spring/summer\n- `day` - 昼夜长度设置\n- `weather` - 天气频率\n- `resources` - 资源丰富度\n- `creatures` - 生物数量\n- `branching` - 地图分支复杂度\n\n### MOD 配置（modoverrides.lua）\n\n从 Steam Workshop 获取 MOD 配置选项，支持：\n- MOD 名称、描述、作者\n- 配置项列表和默认值\n- 订阅数、更新时间\n- 兼容性标签\n\n## 依赖库\n\n主要 Python 库：\n- `requests` - HTTP 请求，用于 Steam API 调用\n- `beautifulsoup4` - HTML 解析\n- `Pillow` - 图片处理\n- 其他工具库\n\n## 与 DST Admin Go 集成\n\n本工具集的输出数据会被 DST Admin Go 的以下模块使用：\n- `internal/service/levelConfig/` - 世界配置管理\n- `internal/service/mod/` - MOD 管理\n- `internal/service/update/` - 游戏更新检测\n- `internal/api/handler/dst_map_handler.go` - 地图生成\n\n## 输出格式\n\n所有工具默认输出 JSON 格式数据，可直接被 DST Admin Go 管理面板使用：\n\n```json\n{\n  \"success\": true,\n  \"data\": { ... },\n  \"message\": \"操作成功\"\n}\n```\n\n## 故障排查\n\n### 无法获取 MOD 信息\n\n- 检查 `steamapikey.txt` 是否正确配置\n- 确认网络可以访问 Steam API\n- 检查 MOD ID 是否有效\n- Steam API 可能有速率限制，稍后重试\n\n### 版本查询失败\n\n- Steam 服务器可能暂时不可用，稍后重试\n- 检查防火墙是否拦截了 Steam 相关域名\n- 尝试使用代理访问\n\n### 依赖安装失败\n\n```bash\n# 升级 pip 到最新版本\npip install --upgrade pip\n\n# 使用国内镜像源（清华大学）\npip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple\n\n# 或使用阿里云镜像\npip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/\n```\n\n### 图片资源转换失败\n\n- 确保安装了 Pillow 库：`pip install Pillow`\n- 检查源文件格式是否正确\n- 某些 .tex 文件可能需要特定的转换工具\n\n## 常见用例\n\n### 1. 批量查询 MOD 信息\n\n```bash\n# 创建 MOD ID 列表\necho \"375859599\" > mod_list.txt\necho \"462372013\" >> mod_list.txt\n\n# 循环查询\nwhile read mod_id; do\n  python parse_mod.py $mod_id\ndone < mod_list.txt\n```\n\n### 2. 定时检查游戏版本更新\n\n```bash\n# 添加到 crontab（每小时检查一次）\n0 * * * * cd /path/to/py-dst-cli && python dst_version.py >> version_log.txt\n```\n\n### 3. 导出世界配置模板\n\n```bash\npython parse_world_setting.py > world_template.json\n```\n\n## 注意事项\n\n1. **Steam API 限制**: Steam Web API 有频率限制（每天 100,000 次调用），请勿频繁调用\n2. **网络要求**: 部分功能需要访问 Steam 服务器，确保网络畅通\n3. **编码问题**: 处理中文 MOD 时注意字符编码（统一使用 UTF-8）\n4. **虚拟环境**: 建议使用虚拟环境隔离依赖，避免污染系统 Python 环境\n5. **API Key 安全**: 不要将 `steamapikey.txt` 提交到公开仓库\n\n## 开发者信息\n\n本工具集用于辅助 DST Admin Go 项目，提供游戏数据的离线解析和在线查询能力。\n\n相关项目：\n- [DST Admin Go](https://github.com/hujinbo23/dst-admin-go) - 主项目\n- [Steam Web API](https://steamcommunity.com/dev) - Steam API 文档\n- [Don't Starve Together Wiki](https://dontstarve.fandom.com/wiki/Don%27t_Starve_Together) - 游戏官方 Wiki\n\n## 贡献指南\n\n如果需要添加新功能：\n1. 在对应的 Python 文件中添加函数\n2. 更新 `main.py` 以集成新功能\n3. 更新 `requirements.txt`（如果有新依赖）\n4. 更新本 README 文档\n\n"
  },
  {
    "path": "scripts/py-dst-cli/dst_version.py",
    "content": "import steam.client\nimport steam.client.cdn\nimport steam.core.cm\nimport steam.webapi\nfrom steam.exceptions import SteamError\n\n\ndef get_dst_version(steamcdn=None):\n\n    anonymous = steam.client.SteamClient()\n    anonymous.anonymous_login()\n    steamcdn = steam.client.cdn.CDNClient(anonymous)\n\n    print(\"开始获取dst版本文件\")\n\n    # 0 下载失败， 1 下载成功， 2 内容为空\n    for _ in range(3):\n        try:\n            # b = next(steamcdn.get_manifests(343050, filter_func=lambda x, y: x == 343052))\n            # version = next(b.iter_files('version.txt')).read().decode('utf-8').strip()\n            version = [*steamcdn.iter_files(343050, 'version.txt', filter_func=lambda x, y: x == 343052)]\n            if not version:\n                return 0\n            version = version[0].read().decode('utf-8').strip()\n            # print(version)\n            return int(version)\n        except SteamError as e:\n            print(\"get dst version error\", SteamError)\n            return 0\n    return 0\n\nif __name__ == \"__main__\":\n    print(get_dst_version())"
  },
  {
    "path": "scripts/py-dst-cli/dst_world_setting.json",
    "content": "{\"zh\": {\"forest\": {\"WORLDGEN_GROUP\": {\"monsters\": {\"order\": 5, \"text\": \"敌对生物以及刷新点\", \"atlas\": {\"name\": \"worldgen_customization\", \"width\": 2048, \"height\": 1024, \"item_size\": 128}, \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"uncommon\": \"较少\", \"default\": \"默认\", \"often\": \"较多\", \"mostly\": \"很多\", \"always\": \"大量\", \"insane\": \"疯狂\"}, \"items\": {\"spiders\": {\"image\": {\"x\": 0.9375, \"y\": 0.375}, \"text\": \"蜘蛛巢\", \"value\": \"default\"}, \"angrybees\": {\"image\": {\"x\": 0.5, \"y\": 0.5}, \"text\": \"杀人蜂蜂窝\", \"value\": \"default\"}, \"chess\": {\"image\": {\"x\": 0.875, \"y\": 0.0}, \"text\": \"发条装置\", \"value\": \"default\"}, \"tentacles\": {\"image\": {\"x\": 0.1875, \"y\": 0.5}, \"text\": \"触手\", \"value\": \"default\"}, \"walrus\": {\"image\": {\"x\": 0.625, \"y\": 0.125}, \"text\": \"海象营地\", \"value\": \"default\"}, \"ocean_waterplant\": {\"image\": {\"x\": 0.0, \"y\": 0.375}, \"text\": \"海草\", \"desc\": {\"ocean_never\": \"无\", \"ocean_rare\": \"很少\", \"ocean_uncommon\": \"较少\", \"ocean_default\": \"默认\", \"ocean_often\": \"较多\", \"ocean_mostly\": \"很多\", \"ocean_always\": \"大量\", \"ocean_insane\": \"疯狂\"}, \"value\": \"ocean_default\"}, \"tallbirds\": {\"image\": {\"x\": 0.125, \"y\": 0.5}, \"text\": \"高脚鸟\", \"value\": \"default\"}, \"moon_spiders\": {\"image\": {\"x\": 0.4375, \"y\": 0.25}, \"text\": \"破碎蜘蛛洞\", \"value\": \"default\"}, \"houndmound\": {\"image\": {\"x\": 0.3125, \"y\": 0.125}, \"text\": \"猎犬丘\", \"value\": \"default\"}, \"merm\": {\"image\": {\"x\": 0.75, \"y\": 0.125}, \"text\": \"漏雨的小屋\", \"value\": \"default\"}}}, \"resources\": {\"order\": 3, \"text\": \"资源\", \"atlas\": {\"name\": \"worldgen_customization\", \"width\": 2048, \"height\": 1024, \"item_size\": 128}, \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"uncommon\": \"较少\", \"default\": \"默认\", \"often\": \"较多\", \"mostly\": \"很多\", \"always\": \"大量\", \"insane\": \"疯狂\"}, \"items\": {\"moon_starfish\": {\"image\": {\"x\": 0.5, \"y\": 0.25}, \"text\": \"海星\", \"value\": \"default\"}, \"rock_ice\": {\"image\": {\"x\": 0.375, \"y\": 0.125}, \"text\": \"迷你冰川\", \"value\": \"default\"}, \"moon_sapling\": {\"image\": {\"x\": 0.375, \"y\": 0.25}, \"text\": \"月亮树苗\", \"value\": \"default\"}, \"rock\": {\"image\": {\"x\": 0.5, \"y\": 0.375}, \"text\": \"巨石\", \"value\": \"default\"}, \"moon_tree\": {\"image\": {\"x\": 0.5625, \"y\": 0.25}, \"text\": \"月树\", \"value\": \"default\"}, \"reeds\": {\"image\": {\"x\": 0.375, \"y\": 0.375}, \"text\": \"芦苇\", \"value\": \"default\"}, \"cactus\": {\"image\": {\"x\": 0.5625, \"y\": 0.0}, \"text\": \"仙人掌\", \"value\": \"default\"}, \"grass\": {\"image\": {\"x\": 0.25, \"y\": 0.125}, \"text\": \"草\", \"value\": \"default\"}, \"palmconetree\": {\"image\": {\"x\": 0.125, \"y\": 0.375}, \"text\": \"棕榈松果树\", \"value\": \"default\"}, \"ponds\": {\"image\": {\"x\": 0.25, \"y\": 0.375}, \"text\": \"池塘\", \"value\": \"default\"}, \"flowers\": {\"image\": {\"x\": 0.125, \"y\": 0.125}, \"text\": \"花，邪恶花\", \"value\": \"default\"}, \"ocean_bullkelp\": {\"image\": {\"x\": 0.75, \"y\": 0.25}, \"text\": \"公牛海带\", \"value\": \"default\"}, \"trees\": {\"image\": {\"x\": 0.375, \"y\": 0.5}, \"text\": \"树（所有）\", \"value\": \"default\"}, \"moon_hotspring\": {\"image\": {\"x\": 0.25, \"y\": 0.25}, \"text\": \"温泉\", \"value\": \"default\"}, \"marshbush\": {\"image\": {\"x\": 0.6875, \"y\": 0.125}, \"text\": \"尖刺灌木\", \"value\": \"default\"}, \"ocean_seastack\": {\"image\": {\"x\": 0.875, \"y\": 0.25}, \"text\": \"海蚀柱\", \"desc\": {\"ocean_never\": \"无\", \"ocean_rare\": \"很少\", \"ocean_uncommon\": \"较少\", \"ocean_default\": \"默认\", \"ocean_often\": \"较多\", \"ocean_mostly\": \"很多\", \"ocean_always\": \"大量\", \"ocean_insane\": \"疯狂\"}, \"value\": \"ocean_default\"}, \"tumbleweed\": {\"image\": {\"x\": 0.4375, \"y\": 0.5}, \"text\": \"风滚草\", \"value\": \"default\"}, \"moon_berrybush\": {\"image\": {\"x\": 0.9375, \"y\": 0.125}, \"text\": \"石果灌木丛\", \"value\": \"default\"}, \"moon_bullkelp\": {\"image\": {\"x\": 0.0, \"y\": 0.25}, \"text\": \"海岸公牛海带\", \"value\": \"default\"}, \"mushroom\": {\"image\": {\"x\": 0.625, \"y\": 0.25}, \"text\": \"蘑菇\", \"value\": \"default\"}, \"moon_rock\": {\"image\": {\"x\": 0.3125, \"y\": 0.25}, \"text\": \"月亮石\", \"value\": \"default\"}, \"carrot\": {\"image\": {\"x\": 0.625, \"y\": 0.0}, \"text\": \"胡萝卜\", \"value\": \"default\"}, \"flint\": {\"image\": {\"x\": 0.0625, \"y\": 0.125}, \"text\": \"燧石\", \"value\": \"default\"}, \"berrybush\": {\"image\": {\"x\": 0.3125, \"y\": 0.0}, \"text\": \"浆果丛\", \"value\": \"default\"}, \"meteorspawner\": {\"image\": {\"x\": 0.4375, \"y\": 0.0}, \"text\": \"流星区域\", \"value\": \"default\"}, \"sapling\": {\"image\": {\"x\": 0.625, \"y\": 0.375}, \"text\": \"树苗\", \"value\": \"default\"}}}, \"animals\": {\"order\": 4, \"text\": \"生物以及刷新点\", \"atlas\": {\"name\": \"worldgen_customization\", \"width\": 2048, \"height\": 1024, \"item_size\": 128}, \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"uncommon\": \"较少\", \"default\": \"默认\", \"often\": \"较多\", \"mostly\": \"很多\", \"always\": \"大量\", \"insane\": \"疯狂\"}, \"items\": {\"ocean_shoal\": {\"image\": {\"x\": 0.9375, \"y\": 0.25}, \"text\": \"鱼群\", \"value\": \"default\"}, \"moon_fruitdragon\": {\"image\": {\"x\": 0.1875, \"y\": 0.25}, \"text\": \"沙拉蝾螈\", \"value\": \"default\"}, \"rabbits\": {\"image\": {\"x\": 0.3125, \"y\": 0.375}, \"text\": \"兔洞\", \"value\": \"default\"}, \"catcoon\": {\"image\": {\"x\": 0.6875, \"y\": 0.0}, \"text\": \"空心树桩\", \"value\": \"default\"}, \"ocean_otterdens\": {\"image\": {\"x\": 0.8125, \"y\": 0.25}, \"text\": \"水獭掠夺者窝点\", \"value\": \"default\"}, \"ocean_wobsterden\": {\"image\": {\"x\": 0.0625, \"y\": 0.375}, \"text\": \"龙虾窝\", \"value\": \"default\"}, \"moles\": {\"image\": {\"x\": 0.8125, \"y\": 0.125}, \"text\": \"鼹鼠丘\", \"value\": \"default\"}, \"buzzard\": {\"image\": {\"x\": 0.5, \"y\": 0.0}, \"text\": \"秃鹫\", \"value\": \"default\"}, \"moon_carrot\": {\"image\": {\"x\": 0.0625, \"y\": 0.25}, \"text\": \"胡萝卜鼠\", \"value\": \"default\"}, \"pigs\": {\"image\": {\"x\": 0.1875, \"y\": 0.375}, \"text\": \"猪屋\", \"value\": \"default\"}, \"lightninggoat\": {\"image\": {\"x\": 0.5625, \"y\": 0.125}, \"text\": \"伏特羊\", \"value\": \"default\"}, \"beefalo\": {\"image\": {\"x\": 0.1875, \"y\": 0.0}, \"text\": \"皮弗娄牛\", \"value\": \"default\"}, \"bees\": {\"image\": {\"x\": 0.25, \"y\": 0.0}, \"text\": \"蜜蜂蜂窝\", \"value\": \"default\"}}}, \"misc\": {\"order\": 2, \"text\": \"世界\", \"atlas\": {\"name\": \"worldgen_customization\", \"width\": 2048, \"height\": 1024, \"item_size\": 128}, \"desc\": null, \"items\": {\"terrariumchest\": {\"image\": {\"x\": 0.25, \"y\": 0.5}, \"text\": \"盒中泰拉\", \"desc\": {\"never\": \"无\", \"default\": \"默认\"}, \"value\": \"default\"}, \"prefabswaps_start\": {\"image\": {\"x\": 0.0625, \"y\": 0.5}, \"text\": \"开始资源多样化\", \"desc\": {\"classic\": \"经典\", \"default\": \"默认\", \"highly random\": \"非常随机\"}, \"order\": 20, \"value\": \"default\"}, \"stageplays\": {\"image\": {\"x\": 0.0, \"y\": 0.5}, \"text\": \"舞台剧\", \"desc\": {\"never\": \"无\", \"default\": \"默认\"}, \"value\": \"default\"}, \"task_set\": {\"image\": {\"x\": 0.6875, \"y\": 0.5}, \"text\": \"生物群系\", \"desc\": {\"default\": \"联机版\", \"classic\": \"经典\"}, \"order\": 1, \"value\": \"default\"}, \"touchstone\": {\"image\": {\"x\": 0.3125, \"y\": 0.5}, \"text\": \"试金石\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"uncommon\": \"较少\", \"default\": \"默认\", \"often\": \"较多\", \"mostly\": \"很多\", \"always\": \"大量\", \"insane\": \"疯狂\"}, \"order\": 17, \"value\": \"default\"}, \"world_size\": {\"image\": {\"x\": 0.75, \"y\": 0.5}, \"text\": \"世界大小\", \"desc\": {\"small\": \"小\", \"medium\": \"中\", \"default\": \"大\", \"huge\": \"巨大\"}, \"order\": 3, \"value\": \"default\"}, \"balatro\": {\"image\": {\"x\": 0.0, \"y\": 0.0}, \"text\": \"小丑\", \"desc\": {\"never\": \"无\", \"default\": \"默认\"}, \"value\": \"default\"}, \"junkyard\": {\"image\": {\"x\": 0.4375, \"y\": 0.125}, \"text\": \"垃圾场\", \"desc\": {\"never\": \"无\", \"default\": \"默认\"}, \"value\": \"default\"}, \"branching\": {\"image\": {\"x\": 0.5625, \"y\": 0.5}, \"text\": \"分支\", \"desc\": {\"never\": \"从不\", \"least\": \"最少\", \"default\": \"默认\", \"most\": \"最多\", \"random\": \"随机\"}, \"order\": 4, \"value\": \"default\"}, \"loop\": {\"image\": {\"x\": 0.625, \"y\": 0.5}, \"text\": \"环形\", \"desc\": {\"never\": \"从不\", \"default\": \"默认\", \"always\": \"总是\"}, \"order\": 5, \"value\": \"default\"}, \"start_location\": {\"image\": {\"x\": 0.8125, \"y\": 0.5}, \"text\": \"出生点\", \"desc\": {\"darkness\": \"黑暗\", \"default\": \"默认\", \"plus\": \"额外资源\"}, \"order\": 2, \"value\": \"default\"}, \"moon_fissure\": {\"image\": {\"x\": 0.125, \"y\": 0.25}, \"text\": \"天体裂隙\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"uncommon\": \"较少\", \"default\": \"默认\", \"often\": \"较多\", \"mostly\": \"很多\", \"always\": \"大量\", \"insane\": \"疯狂\"}, \"value\": \"default\"}, \"roads\": {\"image\": {\"x\": 0.4375, \"y\": 0.375}, \"text\": \"道路\", \"desc\": {\"never\": \"无\", \"default\": \"默认\"}, \"order\": 6, \"value\": \"default\"}, \"boons\": {\"image\": {\"x\": 0.75, \"y\": 0.375}, \"text\": \"失败的冒险家\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"uncommon\": \"较少\", \"default\": \"默认\", \"often\": \"较多\", \"mostly\": \"很多\", \"always\": \"大量\", \"insane\": \"疯狂\"}, \"order\": 18, \"value\": \"default\"}}}, \"global\": {\"order\": 1, \"text\": \"全局\", \"atlas\": {\"name\": \"worldgen_customization\", \"width\": 2048, \"height\": 1024, \"item_size\": 128}, \"desc\": null, \"items\": {\"season_start\": {\"image\": {\"x\": 0.6875, \"y\": 0.375}, \"text\": \"起始季节\", \"desc\": {\"default\": \"秋\", \"winter\": \"冬\", \"spring\": \"春\", \"summer\": \"夏\", \"autumn|spring\": \"春或秋\", \"winter|summer\": \"冬季或夏季\", \"autumn|winter|spring|summer\": \"随机\"}, \"order\": 1, \"value\": \"default\"}}}}, \"WORLDSETTINGS_GROUP\": {\"survivors\": {\"order\": 2, \"text\": \"冒险家\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": null, \"items\": {\"healthpenalty\": {\"image\": {\"x\": 0.375, \"y\": 0.1875}, \"text\": \"生命值上限惩罚\", \"desc\": {\"none\": \"禁用\", \"always\": \"启用\"}, \"order\": 5, \"value\": \"always\"}, \"extrastartingitems\": {\"image\": {\"x\": 0.375, \"y\": 0.125}, \"text\": \"额外起始资源\", \"desc\": {\"0\": \"总是\", \"5\": \"第5天后\", \"default\": \"第10天后\", \"15\": \"第15天后\", \"20\": \"第20天后\", \"none\": \"从不\"}, \"order\": 1, \"value\": \"default\"}, \"spawnprotection\": {\"image\": {\"x\": 0.875, \"y\": 0.4375}, \"text\": \"防骚扰出生保护\", \"desc\": {\"never\": \"无\", \"default\": \"自动检测\", \"always\": \"总是\"}, \"order\": 3, \"value\": \"default\"}, \"temperaturedamage\": {\"image\": {\"x\": 0.5625, \"y\": 0.5}, \"text\": \"温度伤害\", \"desc\": {\"nonlethal\": \"非致命\", \"default\": \"默认\"}, \"order\": 7, \"value\": \"default\"}, \"shadowcreatures\": {\"image\": {\"x\": 0.375, \"y\": 0.4375}, \"text\": \"理智怪兽\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"order\": 10, \"value\": \"default\"}, \"darkness\": {\"image\": {\"x\": 0.5625, \"y\": 0.0625}, \"text\": \"黑暗伤害\", \"desc\": {\"nonlethal\": \"非致命\", \"default\": \"默认\"}, \"order\": 9, \"value\": \"default\"}, \"seasonalstartingitems\": {\"image\": {\"x\": 0.3125, \"y\": 0.4375}, \"text\": \"季节起始物品\", \"desc\": {\"never\": \"无\", \"default\": \"默认\"}, \"order\": 2, \"value\": \"default\"}, \"dropeverythingondespawn\": {\"image\": {\"x\": 0.0625, \"y\": 0.125}, \"text\": \"离开游戏后物品掉落\", \"desc\": {\"default\": \"默认\", \"always\": \"所有\"}, \"order\": 4, \"value\": \"default\"}, \"brightmarecreatures\": {\"image\": {\"x\": 0.9375, \"y\": 0.0}, \"text\": \"启蒙怪兽\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"order\": 11, \"value\": \"default\"}, \"hunger\": {\"image\": {\"x\": 0.5625, \"y\": 0.1875}, \"text\": \"饥饿伤害\", \"desc\": {\"nonlethal\": \"非致命\", \"default\": \"默认\"}, \"order\": 8, \"value\": \"default\"}, \"lessdamagetaken\": {\"image\": {\"x\": 0.875, \"y\": 0.1875}, \"text\": \"受到的伤害\", \"desc\": {\"always\": \"较少\", \"none\": \"默认\", \"more\": \"较多\"}, \"order\": 6, \"value\": \"none\"}}}, \"global\": {\"order\": 0, \"text\": \"全局\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": null, \"items\": {\"specialevent\": {\"image\": {\"x\": 0.25, \"y\": 0.125}, \"text\": \"活动\", \"desc\": {\"none\": \"无\", \"default\": \"自动\"}, \"order\": 1, \"value\": \"default\"}, \"ghostenabled\": {\"image\": {\"x\": 0.9375, \"y\": 0.125}, \"text\": \"冒险家死亡\", \"desc\": {\"none\": \"更改冒险家\", \"always\": \"变鬼魂\"}, \"order\": 8, \"value\": \"always\"}, \"spawnmode\": {\"image\": {\"x\": 0.8125, \"y\": 0.4375}, \"text\": \"出生模式\", \"desc\": {\"fixed\": \"绚丽之门\", \"scatter\": \"随机\"}, \"order\": 7, \"value\": \"fixed\"}, \"portalresurection\": {\"image\": {\"x\": 0.6875, \"y\": 0.375}, \"text\": \"在绚丽之门复活\", \"desc\": {\"none\": \"禁用\", \"always\": \"启用\"}, \"order\": 9, \"value\": \"none\"}, \"autumn\": {\"image\": {\"x\": 0.25, \"y\": 0.0}, \"text\": \"秋\", \"desc\": {\"noseason\": \"无\", \"veryshortseason\": \"极短\", \"shortseason\": \"短\", \"default\": \"默认\", \"longseason\": \"长\", \"verylongseason\": \"极长\", \"random\": \"随机\"}, \"order\": 2, \"value\": \"default\"}, \"winter\": {\"image\": {\"x\": 0.0, \"y\": 0.5625}, \"text\": \"冬\", \"desc\": {\"noseason\": \"无\", \"veryshortseason\": \"极短\", \"shortseason\": \"短\", \"default\": \"默认\", \"longseason\": \"长\", \"verylongseason\": \"极长\", \"random\": \"随机\"}, \"order\": 3, \"value\": \"default\"}, \"krampus\": {\"image\": {\"x\": 0.8125, \"y\": 0.1875}, \"text\": \"坎普斯\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"order\": 13, \"value\": \"default\"}, \"beefaloheat\": {\"image\": {\"x\": 0.5625, \"y\": 0.0}, \"text\": \"皮弗娄牛交配频率\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"order\": 12, \"value\": \"default\"}, \"spring\": {\"image\": {\"x\": 0.3125, \"y\": 0.5}, \"text\": \"春\", \"desc\": {\"noseason\": \"无\", \"veryshortseason\": \"极短\", \"shortseason\": \"短\", \"default\": \"默认\", \"longseason\": \"长\", \"verylongseason\": \"极长\", \"random\": \"随机\"}, \"order\": 4, \"value\": \"default\"}, \"ghostsanitydrain\": {\"image\": {\"x\": 0.0, \"y\": 0.1875}, \"text\": \"鬼魂理智值惩罚\", \"desc\": {\"none\": \"禁用\", \"always\": \"启用\"}, \"order\": 10, \"value\": \"always\"}, \"summer\": {\"image\": {\"x\": 0.4375, \"y\": 0.5}, \"text\": \"夏\", \"desc\": {\"noseason\": \"无\", \"veryshortseason\": \"极短\", \"shortseason\": \"短\", \"default\": \"默认\", \"longseason\": \"长\", \"verylongseason\": \"极长\", \"random\": \"随机\"}, \"order\": 5, \"value\": \"default\"}, \"resettime\": {\"image\": {\"x\": 0.0625, \"y\": 0.4375}, \"text\": \"死亡重置倒计时\", \"desc\": {\"none\": \"禁用\", \"slow\": \"慢\", \"default\": \"默认\", \"fast\": \"快\", \"always\": \"立刻\"}, \"order\": 11, \"value\": \"default\"}, \"day\": {\"image\": {\"x\": 0.625, \"y\": 0.0625}, \"text\": \"昼夜选项\", \"desc\": {\"default\": \"默认\", \"longday\": \"长 白天\", \"longdusk\": \"长 黄昏\", \"longnight\": \"长 夜晚\", \"noday\": \"无 白天\", \"nodusk\": \"无 黄昏\", \"nonight\": \"无 夜晚\", \"onlyday\": \"仅 白天\", \"onlydusk\": \"仅 黄昏\", \"onlynight\": \"仅 夜晚\"}, \"order\": 6, \"value\": \"default\"}}}, \"resources\": {\"order\": 4, \"text\": \"资源再生\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"无\", \"veryslow\": \"极慢\", \"slow\": \"慢\", \"default\": \"默认\", \"fast\": \"快\", \"veryfast\": \"极快\"}, \"items\": {\"carrots_regrowth\": {\"image\": {\"x\": 0.1875, \"y\": 0.0625}, \"text\": \"胡萝卜\", \"value\": \"default\"}, \"basicresource_regrowth\": {\"image\": {\"x\": 0.375, \"y\": 0.0}, \"text\": \"基础资源\", \"desc\": {\"none\": \"禁用\", \"always\": \"启用\"}, \"value\": \"none\"}, \"cactus_regrowth\": {\"image\": {\"x\": 0.125, \"y\": 0.0625}, \"text\": \"仙人掌\", \"value\": \"default\"}, \"deciduoustree_regrowth\": {\"image\": {\"x\": 0.875, \"y\": 0.0625}, \"text\": \"桦栗树\", \"value\": \"default\"}, \"palmconetree_regrowth\": {\"image\": {\"x\": 0.125, \"y\": 0.375}, \"text\": \"棕榈松果树\", \"value\": \"default\"}, \"flowers_regrowth\": {\"image\": {\"x\": 0.625, \"y\": 0.125}, \"text\": \"花\", \"value\": \"default\"}, \"twiggytrees_regrowth\": {\"image\": {\"x\": 0.75, \"y\": 0.5}, \"text\": \"多枝树\", \"value\": \"default\"}, \"regrowth\": {\"image\": {\"x\": 0.0, \"y\": 0.4375}, \"text\": \"再生速度\", \"order\": 1, \"value\": \"default\"}, \"moon_tree_regrowth\": {\"image\": {\"x\": 0.125, \"y\": 0.3125}, \"text\": \"月树\", \"value\": \"default\"}, \"reeds_regrowth\": {\"image\": {\"x\": 0.9375, \"y\": 0.375}, \"text\": \"芦苇\", \"value\": \"default\"}, \"saltstack_regrowth\": {\"image\": {\"x\": 0.1875, \"y\": 0.4375}, \"text\": \"盐堆\", \"value\": \"default\"}, \"evergreen_regrowth\": {\"image\": {\"x\": 0.3125, \"y\": 0.125}, \"text\": \"常青树\", \"value\": \"default\"}}}, \"events\": {\"order\": 1, \"text\": \"活动\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"default\": \"默认\", \"enabled\": \"总是\"}, \"items\": {\"hallowed_nights\": {\"image\": {\"x\": 0.3125, \"y\": 0.1875}, \"text\": \"万圣夜\", \"order\": 2, \"value\": \"default\"}, \"year_of_the_catcoon\": {\"image\": {\"x\": 0.6875, \"y\": 0.5625}, \"text\": \"浣猫之年\", \"order\": 9, \"value\": \"default\"}, \"year_of_the_gobbler\": {\"image\": {\"x\": 0.375, \"y\": 0.375}, \"text\": \"火鸡之年\", \"order\": 4, \"value\": \"default\"}, \"year_of_the_carrat\": {\"image\": {\"x\": 0.4375, \"y\": 0.5625}, \"text\": \"胡萝卜鼠之年\", \"order\": 7, \"value\": \"default\"}, \"year_of_the_snake\": {\"image\": {\"x\": 0.625, \"y\": 0.5625}, \"text\": \"洞穴蠕虫之年\", \"order\": 12, \"value\": \"default\"}, \"crow_carnival\": {\"image\": {\"x\": 0.5, \"y\": 0.0625}, \"text\": \"盛夏鸦年华\", \"order\": 1, \"value\": \"default\"}, \"year_of_the_bunnyman\": {\"image\": {\"x\": 0.5625, \"y\": 0.5625}, \"text\": \"兔人之年\", \"order\": 10, \"value\": \"default\"}, \"year_of_the_pig\": {\"image\": {\"x\": 0.5625, \"y\": 0.375}, \"text\": \"猪王之年\", \"order\": 6, \"value\": \"default\"}, \"year_of_the_varg\": {\"image\": {\"x\": 0.875, \"y\": 0.5}, \"text\": \"座狼之年\", \"order\": 5, \"value\": \"default\"}, \"year_of_the_beefalo\": {\"image\": {\"x\": 0.375, \"y\": 0.5625}, \"text\": \"皮弗娄牛之年\", \"order\": 8, \"value\": \"default\"}, \"year_of_the_dragonfly\": {\"image\": {\"x\": 0.5, \"y\": 0.5625}, \"text\": \"龙蝇之年\", \"order\": 11, \"value\": \"default\"}, \"winters_feast\": {\"image\": {\"x\": 0.125, \"y\": 0.5625}, \"text\": \"冬季盛宴\", \"order\": 3, \"value\": \"default\"}}}, \"giants\": {\"order\": 8, \"text\": \"巨兽\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"items\": {\"goosemoose\": {\"image\": {\"x\": 0.125, \"y\": 0.1875}, \"text\": \"麋鹿鹅\", \"value\": \"default\"}, \"eyeofterror\": {\"image\": {\"x\": 0.4375, \"y\": 0.125}, \"text\": \"恐怖之眼\", \"value\": \"default\"}, \"bearger\": {\"image\": {\"x\": 0.5, \"y\": 0.0}, \"text\": \"熊獾\", \"value\": \"default\"}, \"deciduousmonster\": {\"image\": {\"x\": 0.8125, \"y\": 0.0625}, \"text\": \"毒桦栗树\", \"value\": \"default\"}, \"antliontribute\": {\"image\": {\"x\": 0.125, \"y\": 0.0}, \"text\": \"蚁狮贡品\", \"value\": \"default\"}, \"malbatross\": {\"image\": {\"x\": 0.5, \"y\": 0.25}, \"text\": \"邪天翁\", \"value\": \"default\"}, \"deerclops\": {\"image\": {\"x\": 0.9375, \"y\": 0.0625}, \"text\": \"独眼巨鹿\", \"value\": \"default\"}, \"dragonfly\": {\"image\": {\"x\": 0.0, \"y\": 0.125}, \"text\": \"龙蝇\", \"value\": \"default\"}, \"crabking\": {\"image\": {\"x\": 0.4375, \"y\": 0.0625}, \"text\": \"帝王蟹\", \"value\": \"default\"}, \"sharkboi\": {\"image\": {\"x\": 0.5, \"y\": 0.4375}, \"text\": \"大霜鲨\", \"value\": \"default\"}, \"beequeen\": {\"image\": {\"x\": 0.625, \"y\": 0.0}, \"text\": \"蜂王\", \"value\": \"default\"}, \"daywalker2\": {\"image\": {\"x\": 0.75, \"y\": 0.0625}, \"text\": \"拾荒疯猪\", \"value\": \"default\"}, \"spiderqueen\": {\"image\": {\"x\": 0.9375, \"y\": 0.4375}, \"text\": \"蜘蛛女王\", \"value\": \"default\"}, \"liefs\": {\"image\": {\"x\": 0.9375, \"y\": 0.1875}, \"text\": \"树精守卫\", \"value\": \"default\"}, \"fruitfly\": {\"image\": {\"x\": 0.875, \"y\": 0.125}, \"text\": \"果蝇王\", \"value\": \"default\"}, \"klaus\": {\"image\": {\"x\": 0.75, \"y\": 0.1875}, \"text\": \"克劳斯\", \"value\": \"default\"}}}, \"lunar_mutations\": {\"order\": 9, \"text\": \"月亮变异\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"无\", \"default\": \"默认\"}, \"items\": {\"mutated_buzzard_gestalt\": {\"image\": {\"x\": 0.625, \"y\": 0.3125}, \"text\": \"水晶冠秃鹫\", \"value\": \"default\"}, \"mutated_birds\": {\"image\": {\"x\": 0.5, \"y\": 0.3125}, \"text\": \"变异的鸟\", \"value\": \"default\"}, \"penguins_moon\": {\"image\": {\"x\": 0.0, \"y\": 0.3125}, \"text\": \"永冻企鸥\", \"value\": \"default\"}, \"mutated_merm\": {\"image\": {\"x\": 0.8125, \"y\": 0.3125}, \"text\": \"变异鱼人\", \"value\": \"default\"}, \"mutated_spiderqueen\": {\"image\": {\"x\": 0.875, \"y\": 0.3125}, \"text\": \"破碎蜘蛛洞\", \"value\": \"default\"}, \"mutated_hounds\": {\"image\": {\"x\": 0.75, \"y\": 0.3125}, \"text\": \"恐怖猎犬\", \"value\": \"default\"}, \"mutated_warg\": {\"image\": {\"x\": 0.9375, \"y\": 0.3125}, \"text\": \"附身座狼\", \"value\": \"default\"}, \"mutated_bearger\": {\"image\": {\"x\": 0.4375, \"y\": 0.3125}, \"text\": \"装甲熊獾\", \"value\": \"default\"}, \"mutated_bird_gestalt\": {\"image\": {\"x\": 0.5625, \"y\": 0.3125}, \"text\": \"亮喙鸟\", \"value\": \"default\"}, \"mutated_deerclops\": {\"image\": {\"x\": 0.6875, \"y\": 0.3125}, \"text\": \"晶体独眼巨鹿\", \"value\": \"default\"}, \"moon_spider\": {\"image\": {\"x\": 0.0625, \"y\": 0.3125}, \"text\": \"破碎蜘蛛\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"value\": \"default\"}}}, \"animals\": {\"order\": 6, \"text\": \"生物\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"items\": {\"grassgekkos\": {\"image\": {\"x\": 0.25, \"y\": 0.1875}, \"text\": \"草壁虎转化\", \"value\": \"default\"}, \"wobsters\": {\"image\": {\"x\": 0.1875, \"y\": 0.5625}, \"text\": \"龙虾\", \"value\": \"default\"}, \"butterfly\": {\"image\": {\"x\": 0.0625, \"y\": 0.0625}, \"text\": \"蝴蝶\", \"value\": \"default\"}, \"rabbits_setting\": {\"image\": {\"x\": 0.8125, \"y\": 0.375}, \"text\": \"兔子\", \"value\": \"default\"}, \"bees_setting\": {\"image\": {\"x\": 0.6875, \"y\": 0.0}, \"text\": \"蜜蜂\", \"value\": \"default\"}, \"pigs_setting\": {\"image\": {\"x\": 0.5, \"y\": 0.375}, \"text\": \"猪\", \"value\": \"default\"}, \"gnarwail\": {\"image\": {\"x\": 0.0625, \"y\": 0.1875}, \"text\": \"一角鲸\", \"value\": \"default\"}, \"birds\": {\"image\": {\"x\": 0.875, \"y\": 0.0}, \"text\": \"鸟\", \"value\": \"default\"}, \"penguins\": {\"image\": {\"x\": 0.25, \"y\": 0.375}, \"text\": \"企鸥\", \"value\": \"default\"}, \"catcoons\": {\"image\": {\"x\": 0.25, \"y\": 0.0625}, \"text\": \"浣猫\", \"value\": \"default\"}, \"otters_setting\": {\"image\": {\"x\": 0.0625, \"y\": 0.375}, \"text\": \"水獭掠夺者\", \"value\": \"default\"}, \"fishschools\": {\"image\": {\"x\": 0.5, \"y\": 0.125}, \"text\": \"鱼群\", \"value\": \"default\"}, \"bunnymen_setting\": {\"image\": {\"x\": 0.0, \"y\": 0.0625}, \"text\": \"兔人\", \"value\": \"default\"}, \"perd\": {\"image\": {\"x\": 0.3125, \"y\": 0.375}, \"text\": \"火鸡\", \"value\": \"default\"}, \"moles_setting\": {\"image\": {\"x\": 0.75, \"y\": 0.25}, \"text\": \"鼹鼠\", \"value\": \"default\"}}}, \"portal_resources\": {\"order\": 5, \"text\": \"非自然传送门资源\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"items\": {\"lightcrab_portalrate\": {\"image\": {\"x\": 0.0, \"y\": 0.25}, \"text\": \"发光蟹\", \"value\": \"default\"}, \"monkeytail_portalrate\": {\"image\": {\"x\": 0.9375, \"y\": 0.25}, \"text\": \"猴尾草\", \"value\": \"default\"}, \"powder_monkey_portalrate\": {\"image\": {\"x\": 0.75, \"y\": 0.375}, \"text\": \"火药猴\", \"value\": \"default\"}, \"bananabush_portalrate\": {\"image\": {\"x\": 0.3125, \"y\": 0.0}, \"text\": \"香蕉丛\", \"value\": \"default\"}, \"portal_spawnrate\": {\"image\": {\"x\": 0.8125, \"y\": 0.25}, \"text\": \"传送频率\", \"value\": \"default\"}, \"palmcone_seed_portalrate\": {\"image\": {\"x\": 0.1875, \"y\": 0.375}, \"text\": \"棕榈松果树芽\", \"value\": \"default\"}}}, \"misc\": {\"order\": 3, \"text\": \"世界\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": null, \"items\": {\"lightning\": {\"image\": {\"x\": 0.1875, \"y\": 0.25}, \"text\": \"闪电\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"value\": \"default\"}, \"wanderingtrader_enabled\": {\"image\": {\"x\": 0.8125, \"y\": 0.5}, \"text\": \"流浪商人\", \"desc\": {\"none\": \"禁用\", \"always\": \"启用\"}, \"value\": \"always\"}, \"petrification\": {\"image\": {\"x\": 0.4375, \"y\": 0.375}, \"text\": \"森林石化\", \"desc\": {\"none\": \"无\", \"few\": \"慢\", \"default\": \"默认\", \"many\": \"快\", \"max\": \"极快\"}, \"value\": \"default\"}, \"hunt\": {\"image\": {\"x\": 0.6875, \"y\": 0.5}, \"text\": \"狩猎\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"value\": \"default\"}, \"frograin\": {\"image\": {\"x\": 0.8125, \"y\": 0.125}, \"text\": \"青蛙雨\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"value\": \"default\"}, \"hounds\": {\"image\": {\"x\": 0.4375, \"y\": 0.1875}, \"text\": \"猎犬袭击\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"order\": 1, \"value\": \"default\"}, \"alternatehunt\": {\"image\": {\"x\": 0.0625, \"y\": 0.0}, \"text\": \"狩猎惊喜\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"value\": \"default\"}, \"wildfires\": {\"image\": {\"x\": 0.6875, \"y\": 0.4375}, \"text\": \"野火\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"value\": \"default\"}, \"rifts_frequency\": {\"image\": {\"x\": 0.25, \"y\": 0.25}, \"text\": \"荒野裂隙频率\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"value\": \"default\"}, \"weather\": {\"image\": {\"x\": 0.875, \"y\": 0.375}, \"text\": \"雨\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"value\": \"default\"}, \"winterhounds\": {\"image\": {\"x\": 0.0625, \"y\": 0.5625}, \"text\": \"冰猎犬群\", \"desc\": {\"never\": \"无\", \"default\": \"默认\"}, \"order\": 2, \"value\": \"default\"}, \"lunarhail_frequency\": {\"image\": {\"x\": 0.3125, \"y\": 0.25}, \"text\": \"月雹\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"value\": \"default\"}, \"summerhounds\": {\"image\": {\"x\": 0.5, \"y\": 0.5}, \"text\": \"火猎犬群\", \"desc\": {\"never\": \"无\", \"default\": \"默认\"}, \"order\": 3, \"value\": \"default\"}, \"rifts_enabled\": {\"image\": {\"x\": 0.25, \"y\": 0.25}, \"text\": \"荒野裂隙\", \"desc\": {\"never\": \"无\", \"default\": \"自动检测\", \"always\": \"总是\"}, \"value\": \"default\"}, \"meteorshowers\": {\"image\": {\"x\": 0.625, \"y\": 0.25}, \"text\": \"流星频率\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"value\": \"default\"}}}, \"monsters\": {\"order\": 7, \"text\": \"敌对生物\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"items\": {\"mosquitos\": {\"image\": {\"x\": 0.1875, \"y\": 0.3125}, \"text\": \"蚊子\", \"value\": \"default\"}, \"cookiecutters\": {\"image\": {\"x\": 0.375, \"y\": 0.0625}, \"text\": \"饼干切割机\", \"value\": \"default\"}, \"spiders_setting\": {\"image\": {\"x\": 0.0, \"y\": 0.5}, \"text\": \"蜘蛛\", \"value\": \"default\"}, \"hound_mounds\": {\"image\": {\"x\": 0.5, \"y\": 0.1875}, \"text\": \"猎犬\", \"value\": \"default\"}, \"merms\": {\"image\": {\"x\": 0.5625, \"y\": 0.25}, \"text\": \"鱼人\", \"value\": \"default\"}, \"squid\": {\"image\": {\"x\": 0.375, \"y\": 0.5}, \"text\": \"鱿鱼\", \"value\": \"default\"}, \"lureplants\": {\"image\": {\"x\": 0.375, \"y\": 0.25}, \"text\": \"食人花\", \"value\": \"default\"}, \"pirateraids\": {\"image\": {\"x\": 0.625, \"y\": 0.375}, \"text\": \"月亮码头海盗\", \"value\": \"default\"}, \"bats_setting\": {\"image\": {\"x\": 0.4375, \"y\": 0.0}, \"text\": \"蝙蝠\", \"value\": \"default\"}, \"spider_warriors\": {\"image\": {\"x\": 0.25, \"y\": 0.5}, \"text\": \"蜘蛛战士\", \"desc\": {\"never\": \"无\", \"default\": \"默认\"}, \"value\": \"default\"}, \"walrus_setting\": {\"image\": {\"x\": 0.4375, \"y\": 0.25}, \"text\": \"海象\", \"value\": \"default\"}, \"sharks\": {\"image\": {\"x\": 0.5625, \"y\": 0.4375}, \"text\": \"鲨鱼\", \"value\": \"default\"}, \"wasps\": {\"image\": {\"x\": 0.9375, \"y\": 0.5}, \"text\": \"杀人蜂\", \"value\": \"default\"}, \"frogs\": {\"image\": {\"x\": 0.75, \"y\": 0.125}, \"text\": \"青蛙\", \"value\": \"default\"}}}}}, \"cave\": {\"WORLDGEN_GROUP\": {\"monsters\": {\"order\": 5, \"text\": \"敌对生物以及刷新点\", \"atlas\": {\"name\": \"worldgen_customization\", \"width\": 2048, \"height\": 1024, \"item_size\": 128}, \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"uncommon\": \"较少\", \"default\": \"默认\", \"often\": \"较多\", \"mostly\": \"很多\", \"always\": \"大量\", \"insane\": \"疯狂\"}, \"items\": {\"spiders\": {\"image\": {\"x\": 0.9375, \"y\": 0.375}, \"text\": \"蜘蛛巢\", \"value\": \"default\"}, \"chess\": {\"image\": {\"x\": 0.875, \"y\": 0.0}, \"text\": \"发条装置\", \"value\": \"default\"}, \"tentacles\": {\"image\": {\"x\": 0.1875, \"y\": 0.5}, \"text\": \"触手\", \"value\": \"default\"}, \"fissure\": {\"image\": {\"x\": 0.0, \"y\": 0.125}, \"text\": \"梦魇裂隙\", \"value\": \"default\"}, \"cave_spiders\": {\"image\": {\"x\": 0.8125, \"y\": 0.0}, \"text\": \"蛛网岩\", \"value\": \"default\"}, \"worms\": {\"image\": {\"x\": 0.9375, \"y\": 0.5}, \"text\": \"洞穴蠕虫\", \"value\": \"default\"}, \"bats\": {\"image\": {\"x\": 0.125, \"y\": 0.0}, \"text\": \"蝙蝠\", \"value\": \"default\"}}}, \"resources\": {\"order\": 3, \"text\": \"资源\", \"atlas\": {\"name\": \"worldgen_customization\", \"width\": 2048, \"height\": 1024, \"item_size\": 128}, \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"uncommon\": \"较少\", \"default\": \"默认\", \"often\": \"较多\", \"mostly\": \"很多\", \"always\": \"大量\", \"insane\": \"疯狂\"}, \"items\": {\"wormlights\": {\"image\": {\"x\": 0.875, \"y\": 0.5}, \"text\": \"发光浆果\", \"value\": \"default\"}, \"rock\": {\"image\": {\"x\": 0.5, \"y\": 0.375}, \"text\": \"巨石\", \"value\": \"default\"}, \"mushtree\": {\"image\": {\"x\": 0.6875, \"y\": 0.25}, \"text\": \"蘑菇树\", \"value\": \"default\"}, \"reeds\": {\"image\": {\"x\": 0.375, \"y\": 0.375}, \"text\": \"芦苇\", \"value\": \"default\"}, \"grass\": {\"image\": {\"x\": 0.25, \"y\": 0.125}, \"text\": \"草\", \"value\": \"default\"}, \"banana\": {\"image\": {\"x\": 0.0625, \"y\": 0.0}, \"text\": \"香蕉\", \"value\": \"default\"}, \"trees\": {\"image\": {\"x\": 0.375, \"y\": 0.5}, \"text\": \"树（所有）\", \"value\": \"default\"}, \"lichen\": {\"image\": {\"x\": 0.5, \"y\": 0.125}, \"text\": \"苔藓\", \"value\": \"default\"}, \"cave_ponds\": {\"image\": {\"x\": 0.25, \"y\": 0.375}, \"text\": \"池塘\", \"value\": \"default\"}, \"marshbush\": {\"image\": {\"x\": 0.6875, \"y\": 0.125}, \"text\": \"尖刺灌木\", \"value\": \"default\"}, \"fern\": {\"image\": {\"x\": 0.9375, \"y\": 0.0}, \"text\": \"洞穴蕨类\", \"value\": \"default\"}, \"mushroom\": {\"image\": {\"x\": 0.625, \"y\": 0.25}, \"text\": \"蘑菇\", \"value\": \"default\"}, \"flint\": {\"image\": {\"x\": 0.0625, \"y\": 0.125}, \"text\": \"燧石\", \"value\": \"default\"}, \"berrybush\": {\"image\": {\"x\": 0.3125, \"y\": 0.0}, \"text\": \"浆果丛\", \"value\": \"default\"}, \"flower_cave\": {\"image\": {\"x\": 0.1875, \"y\": 0.125}, \"text\": \"荧光花\", \"value\": \"default\"}, \"sapling\": {\"image\": {\"x\": 0.625, \"y\": 0.375}, \"text\": \"树苗\", \"value\": \"default\"}}}, \"animals\": {\"order\": 4, \"text\": \"生物以及刷新点\", \"atlas\": {\"name\": \"worldgen_customization\", \"width\": 2048, \"height\": 1024, \"item_size\": 128}, \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"uncommon\": \"较少\", \"default\": \"默认\", \"often\": \"较多\", \"mostly\": \"很多\", \"always\": \"大量\", \"insane\": \"疯狂\"}, \"items\": {\"monkey\": {\"image\": {\"x\": 0.875, \"y\": 0.125}, \"text\": \"穴居猴桶\", \"value\": \"default\"}, \"slurtles\": {\"image\": {\"x\": 0.875, \"y\": 0.375}, \"text\": \"蛞蝓龟窝\", \"value\": \"default\"}, \"slurper\": {\"image\": {\"x\": 0.8125, \"y\": 0.375}, \"text\": \"啜食者\", \"value\": \"default\"}, \"bunnymen\": {\"image\": {\"x\": 0.375, \"y\": 0.0}, \"text\": \"兔屋\", \"value\": \"default\"}, \"rocky\": {\"image\": {\"x\": 0.5625, \"y\": 0.375}, \"text\": \"石虾\", \"value\": \"default\"}}}, \"misc\": {\"order\": 2, \"text\": \"世界\", \"atlas\": {\"name\": \"worldgen_customization\", \"width\": 2048, \"height\": 1024, \"item_size\": 128}, \"desc\": null, \"items\": {\"prefabswaps_start\": {\"image\": {\"x\": 0.0625, \"y\": 0.5}, \"text\": \"开始资源多样化\", \"desc\": {\"classic\": \"经典\", \"default\": \"默认\", \"highly random\": \"非常随机\"}, \"order\": 20, \"value\": \"default\"}, \"task_set\": {\"image\": {\"x\": 0.6875, \"y\": 0.5}, \"text\": \"生物群系\", \"desc\": {\"cave_default\": \"地下\"}, \"order\": 1, \"value\": \"cave_default\"}, \"touchstone\": {\"image\": {\"x\": 0.3125, \"y\": 0.5}, \"text\": \"试金石\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"uncommon\": \"较少\", \"default\": \"默认\", \"often\": \"较多\", \"mostly\": \"很多\", \"always\": \"大量\", \"insane\": \"疯狂\"}, \"order\": 17, \"value\": \"default\"}, \"world_size\": {\"image\": {\"x\": 0.75, \"y\": 0.5}, \"text\": \"世界大小\", \"desc\": {\"small\": \"小\", \"medium\": \"中\", \"default\": \"大\", \"huge\": \"巨大\"}, \"order\": 3, \"value\": \"default\"}, \"branching\": {\"image\": {\"x\": 0.5625, \"y\": 0.5}, \"text\": \"分支\", \"desc\": {\"never\": \"从不\", \"least\": \"最少\", \"default\": \"默认\", \"most\": \"最多\", \"random\": \"随机\"}, \"order\": 4, \"value\": \"default\"}, \"loop\": {\"image\": {\"x\": 0.625, \"y\": 0.5}, \"text\": \"环形\", \"desc\": {\"never\": \"从不\", \"default\": \"默认\", \"always\": \"总是\"}, \"order\": 5, \"value\": \"default\"}, \"start_location\": {\"image\": {\"x\": 0.8125, \"y\": 0.5}, \"text\": \"出生点\", \"desc\": {\"caves\": \"洞穴\"}, \"order\": 2, \"value\": \"caves\"}, \"cavelight\": {\"image\": {\"x\": 0.75, \"y\": 0.0}, \"text\": \"洞穴光照\", \"desc\": {\"never\": \"无\", \"veryslow\": \"极慢\", \"slow\": \"慢\", \"default\": \"默认\", \"fast\": \"快\", \"veryfast\": \"极快\"}, \"order\": 18, \"value\": \"default\"}, \"boons\": {\"image\": {\"x\": 0.75, \"y\": 0.375}, \"text\": \"失败的冒险家\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"uncommon\": \"较少\", \"default\": \"默认\", \"often\": \"较多\", \"mostly\": \"很多\", \"always\": \"大量\", \"insane\": \"疯狂\"}, \"order\": 18, \"value\": \"default\"}}}}, \"WORLDSETTINGS_GROUP\": {\"resources\": {\"order\": 4, \"text\": \"资源再生\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"无\", \"veryslow\": \"极慢\", \"slow\": \"慢\", \"default\": \"默认\", \"fast\": \"快\", \"veryfast\": \"极快\"}, \"items\": {\"mushtree_regrowth\": {\"image\": {\"x\": 0.3125, \"y\": 0.3125}, \"text\": \"蘑菇树\", \"value\": \"default\"}, \"mushtree_moon_regrowth\": {\"image\": {\"x\": 0.375, \"y\": 0.3125}, \"text\": \"月亮蘑菇树\", \"value\": \"default\"}, \"flower_cave_regrowth\": {\"image\": {\"x\": 0.6875, \"y\": 0.125}, \"text\": \"荧光花\", \"value\": \"default\"}, \"lightflier_flower_regrowth\": {\"image\": {\"x\": 0.125, \"y\": 0.25}, \"text\": \"光虫花\", \"value\": \"default\"}, \"regrowth\": {\"image\": {\"x\": 0.0, \"y\": 0.4375}, \"text\": \"再生速度\", \"order\": 1, \"value\": \"default\"}}}, \"giants\": {\"order\": 8, \"text\": \"巨兽\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"items\": {\"toadstool\": {\"image\": {\"x\": 0.625, \"y\": 0.5}, \"text\": \"毒菌蟾蜍\", \"value\": \"default\"}, \"daywalker\": {\"image\": {\"x\": 0.6875, \"y\": 0.0625}, \"text\": \"梦魇疯猪\", \"value\": \"default\"}, \"spiderqueen\": {\"image\": {\"x\": 0.9375, \"y\": 0.4375}, \"text\": \"蜘蛛女王\", \"value\": \"default\"}, \"liefs\": {\"image\": {\"x\": 0.9375, \"y\": 0.1875}, \"text\": \"树精守卫\", \"value\": \"default\"}, \"fruitfly\": {\"image\": {\"x\": 0.875, \"y\": 0.125}, \"text\": \"果蝇王\", \"value\": \"default\"}}}, \"lunar_mutations\": {\"order\": 9, \"text\": \"月亮变异\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"无\", \"default\": \"默认\"}, \"items\": {\"mutated_birds\": {\"image\": {\"x\": 0.5, \"y\": 0.3125}, \"text\": \"变异的鸟\", \"value\": \"default\"}, \"mutated_merm\": {\"image\": {\"x\": 0.8125, \"y\": 0.3125}, \"text\": \"变异鱼人\", \"value\": \"default\"}, \"mutated_spiderqueen\": {\"image\": {\"x\": 0.875, \"y\": 0.3125}, \"text\": \"破碎蜘蛛洞\", \"value\": \"default\"}, \"moon_spider\": {\"image\": {\"x\": 0.0625, \"y\": 0.3125}, \"text\": \"破碎蜘蛛\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"value\": \"default\"}}}, \"animals\": {\"order\": 6, \"text\": \"生物\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"items\": {\"grassgekkos\": {\"image\": {\"x\": 0.25, \"y\": 0.1875}, \"text\": \"草壁虎转化\", \"value\": \"default\"}, \"dustmoths\": {\"image\": {\"x\": 0.125, \"y\": 0.125}, \"text\": \"尘蛾\", \"value\": \"default\"}, \"pigs_setting\": {\"image\": {\"x\": 0.5, \"y\": 0.375}, \"text\": \"猪\", \"value\": \"default\"}, \"slurtles_setting\": {\"image\": {\"x\": 0.625, \"y\": 0.4375}, \"text\": \"蛞蝓龟\", \"value\": \"default\"}, \"mushgnome\": {\"image\": {\"x\": 0.25, \"y\": 0.3125}, \"text\": \"蘑菇地精\", \"value\": \"default\"}, \"monkey_setting\": {\"image\": {\"x\": 0.875, \"y\": 0.25}, \"text\": \"穴居猴\", \"value\": \"default\"}, \"lightfliers\": {\"image\": {\"x\": 0.0625, \"y\": 0.25}, \"text\": \"球状光虫\", \"value\": \"default\"}, \"rocky_setting\": {\"image\": {\"x\": 0.125, \"y\": 0.4375}, \"text\": \"石虾\", \"value\": \"default\"}, \"snurtles\": {\"image\": {\"x\": 0.75, \"y\": 0.4375}, \"text\": \"蜗牛龟\", \"value\": \"default\"}, \"bunnymen_setting\": {\"image\": {\"x\": 0.0, \"y\": 0.0625}, \"text\": \"兔人\", \"value\": \"default\"}, \"moles_setting\": {\"image\": {\"x\": 0.75, \"y\": 0.25}, \"text\": \"鼹鼠\", \"value\": \"default\"}}}, \"misc\": {\"order\": 3, \"text\": \"世界\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": null, \"items\": {\"rifts_frequency_cave\": {\"image\": {\"x\": 0.4375, \"y\": 0.4375}, \"text\": \"荒野裂隙频率\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"value\": \"default\"}, \"acidrain_enabled\": {\"image\": {\"x\": 0.0, \"y\": 0.0}, \"text\": \"酸雨\", \"desc\": {\"none\": \"禁用\", \"always\": \"启用\"}, \"value\": \"always\"}, \"rifts_enabled_cave\": {\"image\": {\"x\": 0.4375, \"y\": 0.4375}, \"text\": \"荒野裂隙\", \"desc\": {\"never\": \"无\", \"default\": \"自动检测\", \"always\": \"总是\"}, \"value\": \"default\"}, \"atriumgate\": {\"image\": {\"x\": 0.1875, \"y\": 0.0}, \"text\": \"远古大门\", \"desc\": {\"veryslow\": \"极慢\", \"slow\": \"慢\", \"default\": \"默认\", \"fast\": \"快\", \"veryfast\": \"极快\"}, \"value\": \"default\"}, \"wormattacks_boss\": {\"image\": {\"x\": 0.3125, \"y\": 0.5625}, \"text\": \"大蠕虫\", \"desc\": {\"never\": \"从不\", \"rare\": \"稀有\", \"default\": \"默认\", \"often\": \"常见\", \"always\": \"总是\"}, \"value\": \"default\"}, \"wormattacks\": {\"image\": {\"x\": 0.25, \"y\": 0.5625}, \"text\": \"洞穴蠕虫袭击\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"value\": \"default\"}, \"earthquakes\": {\"image\": {\"x\": 0.1875, \"y\": 0.125}, \"text\": \"地震\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"value\": \"default\"}, \"weather\": {\"image\": {\"x\": 0.875, \"y\": 0.375}, \"text\": \"雨\", \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"value\": \"default\"}}}, \"monsters\": {\"order\": 7, \"text\": \"敌对生物\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"无\", \"rare\": \"很少\", \"default\": \"默认\", \"often\": \"较多\", \"always\": \"大量\"}, \"items\": {\"chest_mimics\": {\"image\": {\"x\": 0.3125, \"y\": 0.0625}, \"text\": \"暴躁箱子\", \"value\": \"default\"}, \"spiders_setting\": {\"image\": {\"x\": 0.0, \"y\": 0.5}, \"text\": \"蜘蛛\", \"value\": \"default\"}, \"spider_spitter\": {\"image\": {\"x\": 0.1875, \"y\": 0.5}, \"text\": \"喷射蜘蛛\", \"value\": \"default\"}, \"merms\": {\"image\": {\"x\": 0.5625, \"y\": 0.25}, \"text\": \"鱼人\", \"value\": \"default\"}, \"bats_setting\": {\"image\": {\"x\": 0.4375, \"y\": 0.0}, \"text\": \"蝙蝠\", \"value\": \"default\"}, \"spider_warriors\": {\"image\": {\"x\": 0.25, \"y\": 0.5}, \"text\": \"蜘蛛战士\", \"desc\": {\"never\": \"无\", \"default\": \"默认\"}, \"value\": \"default\"}, \"spider_dropper\": {\"image\": {\"x\": 0.0625, \"y\": 0.5}, \"text\": \"穴居悬蛛\", \"value\": \"default\"}, \"spider_hider\": {\"image\": {\"x\": 0.125, \"y\": 0.5}, \"text\": \"洞穴蜘蛛\", \"value\": \"default\"}, \"nightmarecreatures\": {\"image\": {\"x\": 0.0, \"y\": 0.375}, \"text\": \"遗迹梦魇\", \"value\": \"default\"}, \"molebats\": {\"image\": {\"x\": 0.6875, \"y\": 0.25}, \"text\": \"裸鼹蝠\", \"value\": \"default\"}, \"itemmimics\": {\"image\": {\"x\": 0.6875, \"y\": 0.1875}, \"text\": \"拟态蠕虫\", \"value\": \"default\"}}}}}}, \"en\": {\"forest\": {\"WORLDGEN_GROUP\": {\"monsters\": {\"order\": 5, \"text\": \"Hostile Creatures and Spawners\", \"atlas\": {\"name\": \"worldgen_customization\", \"width\": 2048, \"height\": 1024, \"item_size\": 128}, \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"uncommon\": \"Less\", \"default\": \"Default\", \"often\": \"More\", \"mostly\": \"Lots\", \"always\": \"Tons\", \"insane\": \"Insane\"}, \"items\": {\"spiders\": {\"image\": {\"x\": 0.9375, \"y\": 0.375}, \"text\": \"Spider Dens\", \"value\": \"default\"}, \"angrybees\": {\"image\": {\"x\": 0.5, \"y\": 0.5}, \"text\": \"Killer Bee Hives\", \"value\": \"default\"}, \"chess\": {\"image\": {\"x\": 0.875, \"y\": 0.0}, \"text\": \"Clockworks\", \"value\": \"default\"}, \"tentacles\": {\"image\": {\"x\": 0.1875, \"y\": 0.5}, \"text\": \"Tentacles\", \"value\": \"default\"}, \"walrus\": {\"image\": {\"x\": 0.625, \"y\": 0.125}, \"text\": \"MacTusk Camps\", \"value\": \"default\"}, \"ocean_waterplant\": {\"image\": {\"x\": 0.0, \"y\": 0.375}, \"text\": \"Sea Weeds\", \"desc\": {\"ocean_never\": \"None\", \"ocean_rare\": \"Little\", \"ocean_uncommon\": \"Less\", \"ocean_default\": \"Default\", \"ocean_often\": \"More\", \"ocean_mostly\": \"Lots\", \"ocean_always\": \"Tons\", \"ocean_insane\": \"Insane\"}, \"value\": \"ocean_default\"}, \"tallbirds\": {\"image\": {\"x\": 0.125, \"y\": 0.5}, \"text\": \"Tallbirds\", \"value\": \"default\"}, \"moon_spiders\": {\"image\": {\"x\": 0.4375, \"y\": 0.25}, \"text\": \"Shattered Spider Holes\", \"value\": \"default\"}, \"houndmound\": {\"image\": {\"x\": 0.3125, \"y\": 0.125}, \"text\": \"Hound Mounds\", \"value\": \"default\"}, \"merm\": {\"image\": {\"x\": 0.75, \"y\": 0.125}, \"text\": \"Leaky Shack\", \"value\": \"default\"}}}, \"resources\": {\"order\": 3, \"text\": \"Resources\", \"atlas\": {\"name\": \"worldgen_customization\", \"width\": 2048, \"height\": 1024, \"item_size\": 128}, \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"uncommon\": \"Less\", \"default\": \"Default\", \"often\": \"More\", \"mostly\": \"Lots\", \"always\": \"Tons\", \"insane\": \"Insane\"}, \"items\": {\"moon_starfish\": {\"image\": {\"x\": 0.5, \"y\": 0.25}, \"text\": \"Anenemies\", \"value\": \"default\"}, \"rock_ice\": {\"image\": {\"x\": 0.375, \"y\": 0.125}, \"text\": \"Mini Glaciers\", \"value\": \"default\"}, \"moon_sapling\": {\"image\": {\"x\": 0.375, \"y\": 0.25}, \"text\": \"Lunar Saplings\", \"value\": \"default\"}, \"rock\": {\"image\": {\"x\": 0.5, \"y\": 0.375}, \"text\": \"Boulders\", \"value\": \"default\"}, \"moon_tree\": {\"image\": {\"x\": 0.5625, \"y\": 0.25}, \"text\": \"Lune Trees\", \"value\": \"default\"}, \"reeds\": {\"image\": {\"x\": 0.375, \"y\": 0.375}, \"text\": \"Reeds\", \"value\": \"default\"}, \"cactus\": {\"image\": {\"x\": 0.5625, \"y\": 0.0}, \"text\": \"Cacti\", \"value\": \"default\"}, \"grass\": {\"image\": {\"x\": 0.25, \"y\": 0.125}, \"text\": \"Grass\", \"value\": \"default\"}, \"palmconetree\": {\"image\": {\"x\": 0.125, \"y\": 0.375}, \"text\": \"Palmcone Tree\", \"value\": \"default\"}, \"ponds\": {\"image\": {\"x\": 0.25, \"y\": 0.375}, \"text\": \"Ponds\", \"value\": \"default\"}, \"flowers\": {\"image\": {\"x\": 0.125, \"y\": 0.125}, \"text\": \"Flowers, Evil Flowers\", \"value\": \"default\"}, \"ocean_bullkelp\": {\"image\": {\"x\": 0.75, \"y\": 0.25}, \"text\": \"Bull Kelp\", \"value\": \"default\"}, \"trees\": {\"image\": {\"x\": 0.375, \"y\": 0.5}, \"text\": \"Trees (All)\", \"value\": \"default\"}, \"moon_hotspring\": {\"image\": {\"x\": 0.25, \"y\": 0.25}, \"text\": \"Hot Springs\", \"value\": \"default\"}, \"marshbush\": {\"image\": {\"x\": 0.6875, \"y\": 0.125}, \"text\": \"Spiky Bushes\", \"value\": \"default\"}, \"ocean_seastack\": {\"image\": {\"x\": 0.875, \"y\": 0.25}, \"text\": \"Sea Stacks\", \"desc\": {\"ocean_never\": \"None\", \"ocean_rare\": \"Little\", \"ocean_uncommon\": \"Less\", \"ocean_default\": \"Default\", \"ocean_often\": \"More\", \"ocean_mostly\": \"Lots\", \"ocean_always\": \"Tons\", \"ocean_insane\": \"Insane\"}, \"value\": \"ocean_default\"}, \"tumbleweed\": {\"image\": {\"x\": 0.4375, \"y\": 0.5}, \"text\": \"Tumbleweeds\", \"value\": \"default\"}, \"moon_berrybush\": {\"image\": {\"x\": 0.9375, \"y\": 0.125}, \"text\": \"Stone Fruit Bushes\", \"value\": \"default\"}, \"moon_bullkelp\": {\"image\": {\"x\": 0.0, \"y\": 0.25}, \"text\": \"Beached Bull Kelp\", \"value\": \"default\"}, \"mushroom\": {\"image\": {\"x\": 0.625, \"y\": 0.25}, \"text\": \"Mushrooms\", \"value\": \"default\"}, \"moon_rock\": {\"image\": {\"x\": 0.3125, \"y\": 0.25}, \"text\": \"Lunar Rocks\", \"value\": \"default\"}, \"carrot\": {\"image\": {\"x\": 0.625, \"y\": 0.0}, \"text\": \"Carrots\", \"value\": \"default\"}, \"flint\": {\"image\": {\"x\": 0.0625, \"y\": 0.125}, \"text\": \"Flint\", \"value\": \"default\"}, \"berrybush\": {\"image\": {\"x\": 0.3125, \"y\": 0.0}, \"text\": \"Berry Bushes\", \"value\": \"default\"}, \"meteorspawner\": {\"image\": {\"x\": 0.4375, \"y\": 0.0}, \"text\": \"Meteor Fields\", \"value\": \"default\"}, \"sapling\": {\"image\": {\"x\": 0.625, \"y\": 0.375}, \"text\": \"Saplings\", \"value\": \"default\"}}}, \"animals\": {\"order\": 4, \"text\": \"Creatures and Spawners\", \"atlas\": {\"name\": \"worldgen_customization\", \"width\": 2048, \"height\": 1024, \"item_size\": 128}, \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"uncommon\": \"Less\", \"default\": \"Default\", \"often\": \"More\", \"mostly\": \"Lots\", \"always\": \"Tons\", \"insane\": \"Insane\"}, \"items\": {\"ocean_shoal\": {\"image\": {\"x\": 0.9375, \"y\": 0.25}, \"text\": \"Shoals\", \"value\": \"default\"}, \"moon_fruitdragon\": {\"image\": {\"x\": 0.1875, \"y\": 0.25}, \"text\": \"Saladmander\", \"value\": \"default\"}, \"rabbits\": {\"image\": {\"x\": 0.3125, \"y\": 0.375}, \"text\": \"Rabbit Holes\", \"value\": \"default\"}, \"catcoon\": {\"image\": {\"x\": 0.6875, \"y\": 0.0}, \"text\": \"Hollow Stump\", \"value\": \"default\"}, \"ocean_otterdens\": {\"image\": {\"x\": 0.8125, \"y\": 0.25}, \"text\": \"Marotter Dens\", \"value\": \"default\"}, \"ocean_wobsterden\": {\"image\": {\"x\": 0.0625, \"y\": 0.375}, \"text\": \"Wobster Mounds\", \"value\": \"default\"}, \"moles\": {\"image\": {\"x\": 0.8125, \"y\": 0.125}, \"text\": \"Mole Burrows\", \"value\": \"default\"}, \"buzzard\": {\"image\": {\"x\": 0.5, \"y\": 0.0}, \"text\": \"Buzzards\", \"value\": \"default\"}, \"moon_carrot\": {\"image\": {\"x\": 0.0625, \"y\": 0.25}, \"text\": \"Carrats\", \"value\": \"default\"}, \"pigs\": {\"image\": {\"x\": 0.1875, \"y\": 0.375}, \"text\": \"Pig Houses\", \"value\": \"default\"}, \"lightninggoat\": {\"image\": {\"x\": 0.5625, \"y\": 0.125}, \"text\": \"Volt Goats\", \"value\": \"default\"}, \"beefalo\": {\"image\": {\"x\": 0.1875, \"y\": 0.0}, \"text\": \"Beefalos\", \"value\": \"default\"}, \"bees\": {\"image\": {\"x\": 0.25, \"y\": 0.0}, \"text\": \"Bee Hives\", \"value\": \"default\"}}}, \"misc\": {\"order\": 2, \"text\": \"World\", \"atlas\": {\"name\": \"worldgen_customization\", \"width\": 2048, \"height\": 1024, \"item_size\": 128}, \"desc\": null, \"items\": {\"terrariumchest\": {\"image\": {\"x\": 0.25, \"y\": 0.5}, \"text\": \"Terrarium\", \"desc\": {\"never\": \"None\", \"default\": \"Default\"}, \"value\": \"default\"}, \"prefabswaps_start\": {\"image\": {\"x\": 0.0625, \"y\": 0.5}, \"text\": \"Starting Resource Variety\", \"desc\": {\"classic\": \"Classic\", \"default\": \"Default\", \"highly random\": \"Highly Random\"}, \"order\": 20, \"value\": \"default\"}, \"stageplays\": {\"image\": {\"x\": 0.0, \"y\": 0.5}, \"text\": \"Stage Plays\", \"desc\": {\"never\": \"None\", \"default\": \"Default\"}, \"value\": \"default\"}, \"task_set\": {\"image\": {\"x\": 0.6875, \"y\": 0.5}, \"text\": \"Biomes\", \"desc\": {\"default\": \"Together\", \"classic\": \"Classic\"}, \"order\": 1, \"value\": \"default\"}, \"touchstone\": {\"image\": {\"x\": 0.3125, \"y\": 0.5}, \"text\": \"Touch Stones\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"uncommon\": \"Less\", \"default\": \"Default\", \"often\": \"More\", \"mostly\": \"Lots\", \"always\": \"Tons\", \"insane\": \"Insane\"}, \"order\": 17, \"value\": \"default\"}, \"world_size\": {\"image\": {\"x\": 0.75, \"y\": 0.5}, \"text\": \"World Size\", \"desc\": {\"small\": \"Small\", \"medium\": \"Medium\", \"default\": \"Large\", \"huge\": \"Huge\"}, \"order\": 3, \"value\": \"default\"}, \"balatro\": {\"image\": {\"x\": 0.0, \"y\": 0.0}, \"text\": \"JIMBO\", \"desc\": {\"never\": \"None\", \"default\": \"Default\"}, \"value\": \"default\"}, \"junkyard\": {\"image\": {\"x\": 0.4375, \"y\": 0.125}, \"text\": \"Junk Yard\", \"desc\": {\"never\": \"None\", \"default\": \"Default\"}, \"value\": \"default\"}, \"branching\": {\"image\": {\"x\": 0.5625, \"y\": 0.5}, \"text\": \"Branches\", \"desc\": {\"never\": \"Never\", \"least\": \"Least\", \"default\": \"Default\", \"most\": \"Most\", \"random\": \"Random\"}, \"order\": 4, \"value\": \"default\"}, \"loop\": {\"image\": {\"x\": 0.625, \"y\": 0.5}, \"text\": \"Loops\", \"desc\": {\"never\": \"Never\", \"default\": \"Default\", \"always\": \"Always\"}, \"order\": 5, \"value\": \"default\"}, \"start_location\": {\"image\": {\"x\": 0.8125, \"y\": 0.5}, \"text\": \"Spawn Area\", \"desc\": {\"darkness\": \"Dark\", \"default\": \"Default\", \"plus\": \"Plus\"}, \"order\": 2, \"value\": \"default\"}, \"moon_fissure\": {\"image\": {\"x\": 0.125, \"y\": 0.25}, \"text\": \"Celestial Fissures\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"uncommon\": \"Less\", \"default\": \"Default\", \"often\": \"More\", \"mostly\": \"Lots\", \"always\": \"Tons\", \"insane\": \"Insane\"}, \"value\": \"default\"}, \"roads\": {\"image\": {\"x\": 0.4375, \"y\": 0.375}, \"text\": \"Roads\", \"desc\": {\"never\": \"None\", \"default\": \"Default\"}, \"order\": 6, \"value\": \"default\"}, \"boons\": {\"image\": {\"x\": 0.75, \"y\": 0.375}, \"text\": \"Failed Survivors\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"uncommon\": \"Less\", \"default\": \"Default\", \"often\": \"More\", \"mostly\": \"Lots\", \"always\": \"Tons\", \"insane\": \"Insane\"}, \"order\": 18, \"value\": \"default\"}}}, \"global\": {\"order\": 1, \"text\": \"Global\", \"atlas\": {\"name\": \"worldgen_customization\", \"width\": 2048, \"height\": 1024, \"item_size\": 128}, \"desc\": null, \"items\": {\"season_start\": {\"image\": {\"x\": 0.6875, \"y\": 0.375}, \"text\": \"Starting Season\", \"desc\": {\"default\": \"Autumn\", \"winter\": \"Winter\", \"spring\": \"Spring\", \"summer\": \"Summer\", \"autumn|spring\": \"Autumn or Spring\", \"winter|summer\": \"Winter or Summer\", \"autumn|winter|spring|summer\": \"Random\"}, \"order\": 1, \"value\": \"default\"}}}}, \"WORLDSETTINGS_GROUP\": {\"survivors\": {\"order\": 2, \"text\": \"Survivors\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": null, \"items\": {\"healthpenalty\": {\"image\": {\"x\": 0.375, \"y\": 0.1875}, \"text\": \"Max Health Penalty\", \"desc\": {\"none\": \"Disabled\", \"always\": \"Enabled\"}, \"order\": 5, \"value\": \"always\"}, \"extrastartingitems\": {\"image\": {\"x\": 0.375, \"y\": 0.125}, \"text\": \"Extra Starting Resources\", \"desc\": {\"0\": \"Always\", \"5\": \"After Day 5\", \"default\": \"After Day 10\", \"15\": \"After Day 15\", \"20\": \"After Day 20\", \"none\": \"Never\"}, \"order\": 1, \"value\": \"default\"}, \"spawnprotection\": {\"image\": {\"x\": 0.875, \"y\": 0.4375}, \"text\": \"Griefer Spawn Protection\", \"desc\": {\"never\": \"None\", \"default\": \"Auto Detect\", \"always\": \"Always\"}, \"order\": 3, \"value\": \"default\"}, \"temperaturedamage\": {\"image\": {\"x\": 0.5625, \"y\": 0.5}, \"text\": \"Temperature Damage\", \"desc\": {\"nonlethal\": \"Nonlethal\", \"default\": \"Default\"}, \"order\": 7, \"value\": \"default\"}, \"shadowcreatures\": {\"image\": {\"x\": 0.375, \"y\": 0.4375}, \"text\": \"Sanity Monsters\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"order\": 10, \"value\": \"default\"}, \"darkness\": {\"image\": {\"x\": 0.5625, \"y\": 0.0625}, \"text\": \"Darkness Damage\", \"desc\": {\"nonlethal\": \"Nonlethal\", \"default\": \"Default\"}, \"order\": 9, \"value\": \"default\"}, \"seasonalstartingitems\": {\"image\": {\"x\": 0.3125, \"y\": 0.4375}, \"text\": \"Seasonal Starting Items\", \"desc\": {\"never\": \"None\", \"default\": \"Default\"}, \"order\": 2, \"value\": \"default\"}, \"dropeverythingondespawn\": {\"image\": {\"x\": 0.0625, \"y\": 0.125}, \"text\": \"Drop Items on Disconnect\", \"desc\": {\"default\": \"Default\", \"always\": \"Everything\"}, \"order\": 4, \"value\": \"default\"}, \"brightmarecreatures\": {\"image\": {\"x\": 0.9375, \"y\": 0.0}, \"text\": \"Enlightenment Monsters\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"order\": 11, \"value\": \"default\"}, \"hunger\": {\"image\": {\"x\": 0.5625, \"y\": 0.1875}, \"text\": \"Hunger Damage\", \"desc\": {\"nonlethal\": \"Nonlethal\", \"default\": \"Default\"}, \"order\": 8, \"value\": \"default\"}, \"lessdamagetaken\": {\"image\": {\"x\": 0.875, \"y\": 0.1875}, \"text\": \"Damage Taken\", \"desc\": {\"always\": \"Less\", \"none\": \"Default\", \"more\": \"More\"}, \"order\": 6, \"value\": \"none\"}}}, \"global\": {\"order\": 0, \"text\": \"Global\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": null, \"items\": {\"specialevent\": {\"image\": {\"x\": 0.25, \"y\": 0.125}, \"text\": \"Events\", \"desc\": {\"none\": \"None\", \"default\": \"Auto\"}, \"order\": 1, \"value\": \"default\"}, \"ghostenabled\": {\"image\": {\"x\": 0.9375, \"y\": 0.125}, \"text\": \"Survivor Death\", \"desc\": {\"none\": \"Change Survivor\", \"always\": \"Become a Ghost\"}, \"order\": 8, \"value\": \"always\"}, \"spawnmode\": {\"image\": {\"x\": 0.8125, \"y\": 0.4375}, \"text\": \"Spawn Mode\", \"desc\": {\"fixed\": \"Florid Postern\", \"scatter\": \"Random\"}, \"order\": 7, \"value\": \"fixed\"}, \"portalresurection\": {\"image\": {\"x\": 0.6875, \"y\": 0.375}, \"text\": \"Revive At Florid Postern\", \"desc\": {\"none\": \"Disabled\", \"always\": \"Enabled\"}, \"order\": 9, \"value\": \"none\"}, \"autumn\": {\"image\": {\"x\": 0.25, \"y\": 0.0}, \"text\": \"Autumn\", \"desc\": {\"noseason\": \"None\", \"veryshortseason\": \"Very Short\", \"shortseason\": \"Short\", \"default\": \"Default\", \"longseason\": \"Long\", \"verylongseason\": \"Very Long\", \"random\": \"Random\"}, \"order\": 2, \"value\": \"default\"}, \"winter\": {\"image\": {\"x\": 0.0, \"y\": 0.5625}, \"text\": \"Winter\", \"desc\": {\"noseason\": \"None\", \"veryshortseason\": \"Very Short\", \"shortseason\": \"Short\", \"default\": \"Default\", \"longseason\": \"Long\", \"verylongseason\": \"Very Long\", \"random\": \"Random\"}, \"order\": 3, \"value\": \"default\"}, \"krampus\": {\"image\": {\"x\": 0.8125, \"y\": 0.1875}, \"text\": \"Krampii\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"order\": 13, \"value\": \"default\"}, \"beefaloheat\": {\"image\": {\"x\": 0.5625, \"y\": 0.0}, \"text\": \"Beefalo Mating Frequency\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"order\": 12, \"value\": \"default\"}, \"spring\": {\"image\": {\"x\": 0.3125, \"y\": 0.5}, \"text\": \"Spring\", \"desc\": {\"noseason\": \"None\", \"veryshortseason\": \"Very Short\", \"shortseason\": \"Short\", \"default\": \"Default\", \"longseason\": \"Long\", \"verylongseason\": \"Very Long\", \"random\": \"Random\"}, \"order\": 4, \"value\": \"default\"}, \"ghostsanitydrain\": {\"image\": {\"x\": 0.0, \"y\": 0.1875}, \"text\": \"Ghost Sanity Drain\", \"desc\": {\"none\": \"Disabled\", \"always\": \"Enabled\"}, \"order\": 10, \"value\": \"always\"}, \"summer\": {\"image\": {\"x\": 0.4375, \"y\": 0.5}, \"text\": \"Summer\", \"desc\": {\"noseason\": \"None\", \"veryshortseason\": \"Very Short\", \"shortseason\": \"Short\", \"default\": \"Default\", \"longseason\": \"Long\", \"verylongseason\": \"Very Long\", \"random\": \"Random\"}, \"order\": 5, \"value\": \"default\"}, \"resettime\": {\"image\": {\"x\": 0.0625, \"y\": 0.4375}, \"text\": \"Death Reset Timer\", \"desc\": {\"none\": \"Disabled\", \"slow\": \"Slow\", \"default\": \"Default\", \"fast\": \"Fast\", \"always\": \"Instant\"}, \"order\": 11, \"value\": \"default\"}, \"day\": {\"image\": {\"x\": 0.625, \"y\": 0.0625}, \"text\": \"Day Type\", \"desc\": {\"default\": \"Default\", \"longday\": \"Long Day\", \"longdusk\": \"Long Dusk\", \"longnight\": \"Long Night\", \"noday\": \"No Day\", \"nodusk\": \"No Dusk\", \"nonight\": \"No Night\", \"onlyday\": \"Only Day\", \"onlydusk\": \"Only Dusk\", \"onlynight\": \"Only Night\"}, \"order\": 6, \"value\": \"default\"}}}, \"resources\": {\"order\": 4, \"text\": \"Resource Regrowth\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"None\", \"veryslow\": \"Very Slow\", \"slow\": \"Slow\", \"default\": \"Default\", \"fast\": \"Fast\", \"veryfast\": \"Very Fast\"}, \"items\": {\"carrots_regrowth\": {\"image\": {\"x\": 0.1875, \"y\": 0.0625}, \"text\": \"Carrots\", \"value\": \"default\"}, \"basicresource_regrowth\": {\"image\": {\"x\": 0.375, \"y\": 0.0}, \"text\": \"Basic Resources\", \"desc\": {\"none\": \"Disabled\", \"always\": \"Enabled\"}, \"value\": \"none\"}, \"cactus_regrowth\": {\"image\": {\"x\": 0.125, \"y\": 0.0625}, \"text\": \"Cacti\", \"value\": \"default\"}, \"deciduoustree_regrowth\": {\"image\": {\"x\": 0.875, \"y\": 0.0625}, \"text\": \"Birchnut Trees\", \"value\": \"default\"}, \"palmconetree_regrowth\": {\"image\": {\"x\": 0.125, \"y\": 0.375}, \"text\": \"Palmcone Tree\", \"value\": \"default\"}, \"flowers_regrowth\": {\"image\": {\"x\": 0.625, \"y\": 0.125}, \"text\": \"Flowers\", \"value\": \"default\"}, \"twiggytrees_regrowth\": {\"image\": {\"x\": 0.75, \"y\": 0.5}, \"text\": \"Twiggy Trees\", \"value\": \"default\"}, \"regrowth\": {\"image\": {\"x\": 0.0, \"y\": 0.4375}, \"text\": \"Regrowth Multiplier\", \"order\": 1, \"value\": \"default\"}, \"moon_tree_regrowth\": {\"image\": {\"x\": 0.125, \"y\": 0.3125}, \"text\": \"Lune Trees\", \"value\": \"default\"}, \"reeds_regrowth\": {\"image\": {\"x\": 0.9375, \"y\": 0.375}, \"text\": \"Reeds\", \"value\": \"default\"}, \"saltstack_regrowth\": {\"image\": {\"x\": 0.1875, \"y\": 0.4375}, \"text\": \"Salt Formations\", \"value\": \"default\"}, \"evergreen_regrowth\": {\"image\": {\"x\": 0.3125, \"y\": 0.125}, \"text\": \"Evergreens\", \"value\": \"default\"}}}, \"events\": {\"order\": 1, \"text\": \"Events\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"default\": \"Default\", \"enabled\": \"Always\"}, \"items\": {\"hallowed_nights\": {\"image\": {\"x\": 0.3125, \"y\": 0.1875}, \"text\": \"Hallowed Nights\", \"order\": 2, \"value\": \"default\"}, \"year_of_the_catcoon\": {\"image\": {\"x\": 0.6875, \"y\": 0.5625}, \"text\": \"Year of the Catcoon\", \"order\": 9, \"value\": \"default\"}, \"year_of_the_gobbler\": {\"image\": {\"x\": 0.375, \"y\": 0.375}, \"text\": \"Year of the Gobbler\", \"order\": 4, \"value\": \"default\"}, \"year_of_the_carrat\": {\"image\": {\"x\": 0.4375, \"y\": 0.5625}, \"text\": \"Year of the Carrat\", \"order\": 7, \"value\": \"default\"}, \"year_of_the_snake\": {\"image\": {\"x\": 0.625, \"y\": 0.5625}, \"text\": \"Year of the Depths Worm\", \"order\": 12, \"value\": \"default\"}, \"crow_carnival\": {\"image\": {\"x\": 0.5, \"y\": 0.0625}, \"text\": \"Midsummer Cawnival\", \"order\": 1, \"value\": \"default\"}, \"year_of_the_bunnyman\": {\"image\": {\"x\": 0.5625, \"y\": 0.5625}, \"text\": \"Year of the Bunnyman\", \"order\": 10, \"value\": \"default\"}, \"year_of_the_pig\": {\"image\": {\"x\": 0.5625, \"y\": 0.375}, \"text\": \"Year of the Pig King\", \"order\": 6, \"value\": \"default\"}, \"year_of_the_varg\": {\"image\": {\"x\": 0.875, \"y\": 0.5}, \"text\": \"Year of the Varg\", \"order\": 5, \"value\": \"default\"}, \"year_of_the_beefalo\": {\"image\": {\"x\": 0.375, \"y\": 0.5625}, \"text\": \"Year of the Beefalo\", \"order\": 8, \"value\": \"default\"}, \"year_of_the_dragonfly\": {\"image\": {\"x\": 0.5, \"y\": 0.5625}, \"text\": \"Year of the Dragonfly\", \"order\": 11, \"value\": \"default\"}, \"winters_feast\": {\"image\": {\"x\": 0.125, \"y\": 0.5625}, \"text\": \"Winter's Feast\", \"order\": 3, \"value\": \"default\"}}}, \"giants\": {\"order\": 8, \"text\": \"Giants\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"items\": {\"goosemoose\": {\"image\": {\"x\": 0.125, \"y\": 0.1875}, \"text\": \"Meese/Geese\", \"value\": \"default\"}, \"eyeofterror\": {\"image\": {\"x\": 0.4375, \"y\": 0.125}, \"text\": \"Eye of Terror\", \"value\": \"default\"}, \"bearger\": {\"image\": {\"x\": 0.5, \"y\": 0.0}, \"text\": \"Bearger\", \"value\": \"default\"}, \"deciduousmonster\": {\"image\": {\"x\": 0.8125, \"y\": 0.0625}, \"text\": \"Poison Birchnut Trees\", \"value\": \"default\"}, \"antliontribute\": {\"image\": {\"x\": 0.125, \"y\": 0.0}, \"text\": \"Antlion Tribute\", \"value\": \"default\"}, \"malbatross\": {\"image\": {\"x\": 0.5, \"y\": 0.25}, \"text\": \"Malbatross\", \"value\": \"default\"}, \"deerclops\": {\"image\": {\"x\": 0.9375, \"y\": 0.0625}, \"text\": \"Deerclops\", \"value\": \"default\"}, \"dragonfly\": {\"image\": {\"x\": 0.0, \"y\": 0.125}, \"text\": \"Dragonfly\", \"value\": \"default\"}, \"crabking\": {\"image\": {\"x\": 0.4375, \"y\": 0.0625}, \"text\": \"Crabking\", \"value\": \"default\"}, \"sharkboi\": {\"image\": {\"x\": 0.5, \"y\": 0.4375}, \"text\": \"Frostjaw\", \"value\": \"default\"}, \"beequeen\": {\"image\": {\"x\": 0.625, \"y\": 0.0}, \"text\": \"Bee Queen\", \"value\": \"default\"}, \"daywalker2\": {\"image\": {\"x\": 0.75, \"y\": 0.0625}, \"text\": \"Scrappy Werepig\", \"value\": \"default\"}, \"spiderqueen\": {\"image\": {\"x\": 0.9375, \"y\": 0.4375}, \"text\": \"Spider Queen\", \"value\": \"default\"}, \"liefs\": {\"image\": {\"x\": 0.9375, \"y\": 0.1875}, \"text\": \"Treeguards\", \"value\": \"default\"}, \"fruitfly\": {\"image\": {\"x\": 0.875, \"y\": 0.125}, \"text\": \"Lord of the Fruit Flies\", \"value\": \"default\"}, \"klaus\": {\"image\": {\"x\": 0.75, \"y\": 0.1875}, \"text\": \"Klaus\", \"value\": \"default\"}}}, \"lunar_mutations\": {\"order\": 9, \"text\": \"Lunar Mutations\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"None\", \"default\": \"Default\"}, \"items\": {\"mutated_buzzard_gestalt\": {\"image\": {\"x\": 0.625, \"y\": 0.3125}, \"text\": \"Crystal-Crested Buzzards\", \"value\": \"default\"}, \"mutated_birds\": {\"image\": {\"x\": 0.5, \"y\": 0.3125}, \"text\": \"Mutated Birds\", \"value\": \"default\"}, \"penguins_moon\": {\"image\": {\"x\": 0.0, \"y\": 0.3125}, \"text\": \"Permafrost Pengulls\", \"value\": \"default\"}, \"mutated_merm\": {\"image\": {\"x\": 0.8125, \"y\": 0.3125}, \"text\": \"Mutated Merms\", \"value\": \"default\"}, \"mutated_spiderqueen\": {\"image\": {\"x\": 0.875, \"y\": 0.3125}, \"text\": \"Shattered Spider Holes\", \"value\": \"default\"}, \"mutated_hounds\": {\"image\": {\"x\": 0.75, \"y\": 0.3125}, \"text\": \"Horror Hounds\", \"value\": \"default\"}, \"mutated_warg\": {\"image\": {\"x\": 0.9375, \"y\": 0.3125}, \"text\": \"Possessed Vargs\", \"value\": \"default\"}, \"mutated_bearger\": {\"image\": {\"x\": 0.4375, \"y\": 0.3125}, \"text\": \"Armored Bearger\", \"value\": \"default\"}, \"mutated_bird_gestalt\": {\"image\": {\"x\": 0.5625, \"y\": 0.3125}, \"text\": \"Bright-Beaked Birds\", \"value\": \"default\"}, \"mutated_deerclops\": {\"image\": {\"x\": 0.6875, \"y\": 0.3125}, \"text\": \"Crystal Deerclops\", \"value\": \"default\"}, \"moon_spider\": {\"image\": {\"x\": 0.0625, \"y\": 0.3125}, \"text\": \"Shattered Spiders\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"value\": \"default\"}}}, \"animals\": {\"order\": 6, \"text\": \"Creatures\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"items\": {\"grassgekkos\": {\"image\": {\"x\": 0.25, \"y\": 0.1875}, \"text\": \"Grass Gekko Morphing\", \"value\": \"default\"}, \"wobsters\": {\"image\": {\"x\": 0.1875, \"y\": 0.5625}, \"text\": \"Wobsters\", \"value\": \"default\"}, \"butterfly\": {\"image\": {\"x\": 0.0625, \"y\": 0.0625}, \"text\": \"Butterflies\", \"value\": \"default\"}, \"rabbits_setting\": {\"image\": {\"x\": 0.8125, \"y\": 0.375}, \"text\": \"Rabbits\", \"value\": \"default\"}, \"bees_setting\": {\"image\": {\"x\": 0.6875, \"y\": 0.0}, \"text\": \"Bees\", \"value\": \"default\"}, \"pigs_setting\": {\"image\": {\"x\": 0.5, \"y\": 0.375}, \"text\": \"Pigs\", \"value\": \"default\"}, \"gnarwail\": {\"image\": {\"x\": 0.0625, \"y\": 0.1875}, \"text\": \"Gnarwails\", \"value\": \"default\"}, \"birds\": {\"image\": {\"x\": 0.875, \"y\": 0.0}, \"text\": \"Birds\", \"value\": \"default\"}, \"penguins\": {\"image\": {\"x\": 0.25, \"y\": 0.375}, \"text\": \"Pengulls\", \"value\": \"default\"}, \"catcoons\": {\"image\": {\"x\": 0.25, \"y\": 0.0625}, \"text\": \"Catcoons\", \"value\": \"default\"}, \"otters_setting\": {\"image\": {\"x\": 0.0625, \"y\": 0.375}, \"text\": \"Marotters\", \"value\": \"default\"}, \"fishschools\": {\"image\": {\"x\": 0.5, \"y\": 0.125}, \"text\": \"Schools of Fish\", \"value\": \"default\"}, \"bunnymen_setting\": {\"image\": {\"x\": 0.0, \"y\": 0.0625}, \"text\": \"Bunnymen\", \"value\": \"default\"}, \"perd\": {\"image\": {\"x\": 0.3125, \"y\": 0.375}, \"text\": \"Gobblers\", \"value\": \"default\"}, \"moles_setting\": {\"image\": {\"x\": 0.75, \"y\": 0.25}, \"text\": \"Moles\", \"value\": \"default\"}}}, \"portal_resources\": {\"order\": 5, \"text\": \"Unnatural Portal Resources\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"items\": {\"lightcrab_portalrate\": {\"image\": {\"x\": 0.0, \"y\": 0.25}, \"text\": \"Crustashines\", \"value\": \"default\"}, \"monkeytail_portalrate\": {\"image\": {\"x\": 0.9375, \"y\": 0.25}, \"text\": \"Monkeytails\", \"value\": \"default\"}, \"powder_monkey_portalrate\": {\"image\": {\"x\": 0.75, \"y\": 0.375}, \"text\": \"Powder Monkeys\", \"value\": \"default\"}, \"bananabush_portalrate\": {\"image\": {\"x\": 0.3125, \"y\": 0.0}, \"text\": \"Banana Bushes\", \"value\": \"default\"}, \"portal_spawnrate\": {\"image\": {\"x\": 0.8125, \"y\": 0.25}, \"text\": \"Portal Activity\", \"value\": \"default\"}, \"palmcone_seed_portalrate\": {\"image\": {\"x\": 0.1875, \"y\": 0.375}, \"text\": \"Palmcone Sprouts\", \"value\": \"default\"}}}, \"misc\": {\"order\": 3, \"text\": \"World\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": null, \"items\": {\"lightning\": {\"image\": {\"x\": 0.1875, \"y\": 0.25}, \"text\": \"Lightning\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"value\": \"default\"}, \"wanderingtrader_enabled\": {\"image\": {\"x\": 0.8125, \"y\": 0.5}, \"text\": \"Wandering Trader\", \"desc\": {\"none\": \"Disabled\", \"always\": \"Enabled\"}, \"value\": \"always\"}, \"petrification\": {\"image\": {\"x\": 0.4375, \"y\": 0.375}, \"text\": \"Forest Petrification\", \"desc\": {\"none\": \"None\", \"few\": \"Slow\", \"default\": \"Default\", \"many\": \"Fast\", \"max\": \"Very Fast\"}, \"value\": \"default\"}, \"hunt\": {\"image\": {\"x\": 0.6875, \"y\": 0.5}, \"text\": \"Hunts\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"value\": \"default\"}, \"frograin\": {\"image\": {\"x\": 0.8125, \"y\": 0.125}, \"text\": \"Frog Rain\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"value\": \"default\"}, \"hounds\": {\"image\": {\"x\": 0.4375, \"y\": 0.1875}, \"text\": \"Hound Attacks\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"order\": 1, \"value\": \"default\"}, \"alternatehunt\": {\"image\": {\"x\": 0.0625, \"y\": 0.0}, \"text\": \"Hunt Surprises\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"value\": \"default\"}, \"wildfires\": {\"image\": {\"x\": 0.6875, \"y\": 0.4375}, \"text\": \"Wildfires\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"value\": \"default\"}, \"rifts_frequency\": {\"image\": {\"x\": 0.25, \"y\": 0.25}, \"text\": \"Wild Rift Frequency\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"value\": \"default\"}, \"weather\": {\"image\": {\"x\": 0.875, \"y\": 0.375}, \"text\": \"Rain\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"value\": \"default\"}, \"winterhounds\": {\"image\": {\"x\": 0.0625, \"y\": 0.5625}, \"text\": \"Ice Hound Waves\", \"desc\": {\"never\": \"None\", \"default\": \"Default\"}, \"order\": 2, \"value\": \"default\"}, \"lunarhail_frequency\": {\"image\": {\"x\": 0.3125, \"y\": 0.25}, \"text\": \"Lunar Hail\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"value\": \"default\"}, \"summerhounds\": {\"image\": {\"x\": 0.5, \"y\": 0.5}, \"text\": \"Fire Hound Waves\", \"desc\": {\"never\": \"None\", \"default\": \"Default\"}, \"order\": 3, \"value\": \"default\"}, \"rifts_enabled\": {\"image\": {\"x\": 0.25, \"y\": 0.25}, \"text\": \"Wild Rifts\", \"desc\": {\"never\": \"None\", \"default\": \"Auto Detect\", \"always\": \"Always\"}, \"value\": \"default\"}, \"meteorshowers\": {\"image\": {\"x\": 0.625, \"y\": 0.25}, \"text\": \"Meteor Frequency\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"value\": \"default\"}}}, \"monsters\": {\"order\": 7, \"text\": \"Hostile Creatures\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"items\": {\"mosquitos\": {\"image\": {\"x\": 0.1875, \"y\": 0.3125}, \"text\": \"Mosquitos\", \"value\": \"default\"}, \"cookiecutters\": {\"image\": {\"x\": 0.375, \"y\": 0.0625}, \"text\": \"Cookie Cutters\", \"value\": \"default\"}, \"spiders_setting\": {\"image\": {\"x\": 0.0, \"y\": 0.5}, \"text\": \"Spiders\", \"value\": \"default\"}, \"hound_mounds\": {\"image\": {\"x\": 0.5, \"y\": 0.1875}, \"text\": \"Hounds\", \"value\": \"default\"}, \"merms\": {\"image\": {\"x\": 0.5625, \"y\": 0.25}, \"text\": \"Merms\", \"value\": \"default\"}, \"squid\": {\"image\": {\"x\": 0.375, \"y\": 0.5}, \"text\": \"Skittersquids\", \"value\": \"default\"}, \"lureplants\": {\"image\": {\"x\": 0.375, \"y\": 0.25}, \"text\": \"Lureplants\", \"value\": \"default\"}, \"pirateraids\": {\"image\": {\"x\": 0.625, \"y\": 0.375}, \"text\": \"Moon Quay Pirates\", \"value\": \"default\"}, \"bats_setting\": {\"image\": {\"x\": 0.4375, \"y\": 0.0}, \"text\": \"Bats\", \"value\": \"default\"}, \"spider_warriors\": {\"image\": {\"x\": 0.25, \"y\": 0.5}, \"text\": \"Spider Warriors\", \"desc\": {\"never\": \"None\", \"default\": \"Default\"}, \"value\": \"default\"}, \"walrus_setting\": {\"image\": {\"x\": 0.4375, \"y\": 0.25}, \"text\": \"MacTusk\", \"value\": \"default\"}, \"sharks\": {\"image\": {\"x\": 0.5625, \"y\": 0.4375}, \"text\": \"Sharks\", \"value\": \"default\"}, \"wasps\": {\"image\": {\"x\": 0.9375, \"y\": 0.5}, \"text\": \"Killer Bees\", \"value\": \"default\"}, \"frogs\": {\"image\": {\"x\": 0.75, \"y\": 0.125}, \"text\": \"Frogs\", \"value\": \"default\"}}}}}, \"cave\": {\"WORLDGEN_GROUP\": {\"monsters\": {\"order\": 5, \"text\": \"Hostile Creatures and Spawners\", \"atlas\": {\"name\": \"worldgen_customization\", \"width\": 2048, \"height\": 1024, \"item_size\": 128}, \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"uncommon\": \"Less\", \"default\": \"Default\", \"often\": \"More\", \"mostly\": \"Lots\", \"always\": \"Tons\", \"insane\": \"Insane\"}, \"items\": {\"spiders\": {\"image\": {\"x\": 0.9375, \"y\": 0.375}, \"text\": \"Spider Dens\", \"value\": \"default\"}, \"chess\": {\"image\": {\"x\": 0.875, \"y\": 0.0}, \"text\": \"Clockworks\", \"value\": \"default\"}, \"tentacles\": {\"image\": {\"x\": 0.1875, \"y\": 0.5}, \"text\": \"Tentacles\", \"value\": \"default\"}, \"fissure\": {\"image\": {\"x\": 0.0, \"y\": 0.125}, \"text\": \"Nightmare Fissures\", \"value\": \"default\"}, \"cave_spiders\": {\"image\": {\"x\": 0.8125, \"y\": 0.0}, \"text\": \"Spilagmites\", \"value\": \"default\"}, \"worms\": {\"image\": {\"x\": 0.9375, \"y\": 0.5}, \"text\": \"Cave Worms\", \"value\": \"default\"}, \"bats\": {\"image\": {\"x\": 0.125, \"y\": 0.0}, \"text\": \"Bats\", \"value\": \"default\"}}}, \"resources\": {\"order\": 3, \"text\": \"Resources\", \"atlas\": {\"name\": \"worldgen_customization\", \"width\": 2048, \"height\": 1024, \"item_size\": 128}, \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"uncommon\": \"Less\", \"default\": \"Default\", \"often\": \"More\", \"mostly\": \"Lots\", \"always\": \"Tons\", \"insane\": \"Insane\"}, \"items\": {\"wormlights\": {\"image\": {\"x\": 0.875, \"y\": 0.5}, \"text\": \"Glow Berries\", \"value\": \"default\"}, \"rock\": {\"image\": {\"x\": 0.5, \"y\": 0.375}, \"text\": \"Boulders\", \"value\": \"default\"}, \"mushtree\": {\"image\": {\"x\": 0.6875, \"y\": 0.25}, \"text\": \"Mushroom Trees\", \"value\": \"default\"}, \"reeds\": {\"image\": {\"x\": 0.375, \"y\": 0.375}, \"text\": \"Reeds\", \"value\": \"default\"}, \"grass\": {\"image\": {\"x\": 0.25, \"y\": 0.125}, \"text\": \"Grass\", \"value\": \"default\"}, \"banana\": {\"image\": {\"x\": 0.0625, \"y\": 0.0}, \"text\": \"Bananas\", \"value\": \"default\"}, \"trees\": {\"image\": {\"x\": 0.375, \"y\": 0.5}, \"text\": \"Trees (All)\", \"value\": \"default\"}, \"lichen\": {\"image\": {\"x\": 0.5, \"y\": 0.125}, \"text\": \"Lichen\", \"value\": \"default\"}, \"cave_ponds\": {\"image\": {\"x\": 0.25, \"y\": 0.375}, \"text\": \"Ponds\", \"value\": \"default\"}, \"marshbush\": {\"image\": {\"x\": 0.6875, \"y\": 0.125}, \"text\": \"Spiky Bushes\", \"value\": \"default\"}, \"fern\": {\"image\": {\"x\": 0.9375, \"y\": 0.0}, \"text\": \"Cave Ferns\", \"value\": \"default\"}, \"mushroom\": {\"image\": {\"x\": 0.625, \"y\": 0.25}, \"text\": \"Mushrooms\", \"value\": \"default\"}, \"flint\": {\"image\": {\"x\": 0.0625, \"y\": 0.125}, \"text\": \"Flint\", \"value\": \"default\"}, \"berrybush\": {\"image\": {\"x\": 0.3125, \"y\": 0.0}, \"text\": \"Berry Bushes\", \"value\": \"default\"}, \"flower_cave\": {\"image\": {\"x\": 0.1875, \"y\": 0.125}, \"text\": \"Light Flowers\", \"value\": \"default\"}, \"sapling\": {\"image\": {\"x\": 0.625, \"y\": 0.375}, \"text\": \"Saplings\", \"value\": \"default\"}}}, \"animals\": {\"order\": 4, \"text\": \"Creatures and Spawners\", \"atlas\": {\"name\": \"worldgen_customization\", \"width\": 2048, \"height\": 1024, \"item_size\": 128}, \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"uncommon\": \"Less\", \"default\": \"Default\", \"often\": \"More\", \"mostly\": \"Lots\", \"always\": \"Tons\", \"insane\": \"Insane\"}, \"items\": {\"monkey\": {\"image\": {\"x\": 0.875, \"y\": 0.125}, \"text\": \"Splumonkey Pods\", \"value\": \"default\"}, \"slurtles\": {\"image\": {\"x\": 0.875, \"y\": 0.375}, \"text\": \"Slurtle Mounds\", \"value\": \"default\"}, \"slurper\": {\"image\": {\"x\": 0.8125, \"y\": 0.375}, \"text\": \"Slurpers\", \"value\": \"default\"}, \"bunnymen\": {\"image\": {\"x\": 0.375, \"y\": 0.0}, \"text\": \"Rabbit Hutches\", \"value\": \"default\"}, \"rocky\": {\"image\": {\"x\": 0.5625, \"y\": 0.375}, \"text\": \"Rock Lobsters\", \"value\": \"default\"}}}, \"misc\": {\"order\": 2, \"text\": \"World\", \"atlas\": {\"name\": \"worldgen_customization\", \"width\": 2048, \"height\": 1024, \"item_size\": 128}, \"desc\": null, \"items\": {\"prefabswaps_start\": {\"image\": {\"x\": 0.0625, \"y\": 0.5}, \"text\": \"Starting Resource Variety\", \"desc\": {\"classic\": \"Classic\", \"default\": \"Default\", \"highly random\": \"Highly Random\"}, \"order\": 20, \"value\": \"default\"}, \"task_set\": {\"image\": {\"x\": 0.6875, \"y\": 0.5}, \"text\": \"Biomes\", \"desc\": {\"cave_default\": \"Underground\"}, \"order\": 1, \"value\": \"cave_default\"}, \"touchstone\": {\"image\": {\"x\": 0.3125, \"y\": 0.5}, \"text\": \"Touch Stones\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"uncommon\": \"Less\", \"default\": \"Default\", \"often\": \"More\", \"mostly\": \"Lots\", \"always\": \"Tons\", \"insane\": \"Insane\"}, \"order\": 17, \"value\": \"default\"}, \"world_size\": {\"image\": {\"x\": 0.75, \"y\": 0.5}, \"text\": \"World Size\", \"desc\": {\"small\": \"Small\", \"medium\": \"Medium\", \"default\": \"Large\", \"huge\": \"Huge\"}, \"order\": 3, \"value\": \"default\"}, \"branching\": {\"image\": {\"x\": 0.5625, \"y\": 0.5}, \"text\": \"Branches\", \"desc\": {\"never\": \"Never\", \"least\": \"Least\", \"default\": \"Default\", \"most\": \"Most\", \"random\": \"Random\"}, \"order\": 4, \"value\": \"default\"}, \"loop\": {\"image\": {\"x\": 0.625, \"y\": 0.5}, \"text\": \"Loops\", \"desc\": {\"never\": \"Never\", \"default\": \"Default\", \"always\": \"Always\"}, \"order\": 5, \"value\": \"default\"}, \"start_location\": {\"image\": {\"x\": 0.8125, \"y\": 0.5}, \"text\": \"Spawn Area\", \"desc\": {\"caves\": \"Caves\"}, \"order\": 2, \"value\": \"caves\"}, \"cavelight\": {\"image\": {\"x\": 0.75, \"y\": 0.0}, \"text\": \"Sinkhole Lights\", \"desc\": {\"never\": \"None\", \"veryslow\": \"Very Slow\", \"slow\": \"Slow\", \"default\": \"Default\", \"fast\": \"Fast\", \"veryfast\": \"Very Fast\"}, \"order\": 18, \"value\": \"default\"}, \"boons\": {\"image\": {\"x\": 0.75, \"y\": 0.375}, \"text\": \"Failed Survivors\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"uncommon\": \"Less\", \"default\": \"Default\", \"often\": \"More\", \"mostly\": \"Lots\", \"always\": \"Tons\", \"insane\": \"Insane\"}, \"order\": 18, \"value\": \"default\"}}}}, \"WORLDSETTINGS_GROUP\": {\"resources\": {\"order\": 4, \"text\": \"Resource Regrowth\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"None\", \"veryslow\": \"Very Slow\", \"slow\": \"Slow\", \"default\": \"Default\", \"fast\": \"Fast\", \"veryfast\": \"Very Fast\"}, \"items\": {\"mushtree_regrowth\": {\"image\": {\"x\": 0.3125, \"y\": 0.3125}, \"text\": \"Mushroom Trees\", \"value\": \"default\"}, \"mushtree_moon_regrowth\": {\"image\": {\"x\": 0.375, \"y\": 0.3125}, \"text\": \"Lunar Mushtrees\", \"value\": \"default\"}, \"flower_cave_regrowth\": {\"image\": {\"x\": 0.6875, \"y\": 0.125}, \"text\": \"Light Flower\", \"value\": \"default\"}, \"lightflier_flower_regrowth\": {\"image\": {\"x\": 0.125, \"y\": 0.25}, \"text\": \"Lightbug Flower\", \"value\": \"default\"}, \"regrowth\": {\"image\": {\"x\": 0.0, \"y\": 0.4375}, \"text\": \"Regrowth Multiplier\", \"order\": 1, \"value\": \"default\"}}}, \"giants\": {\"order\": 8, \"text\": \"Giants\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"items\": {\"toadstool\": {\"image\": {\"x\": 0.625, \"y\": 0.5}, \"text\": \"Toadstool\", \"value\": \"default\"}, \"daywalker\": {\"image\": {\"x\": 0.6875, \"y\": 0.0625}, \"text\": \"Nightmare Werepig\", \"value\": \"default\"}, \"spiderqueen\": {\"image\": {\"x\": 0.9375, \"y\": 0.4375}, \"text\": \"Spider Queen\", \"value\": \"default\"}, \"liefs\": {\"image\": {\"x\": 0.9375, \"y\": 0.1875}, \"text\": \"Treeguards\", \"value\": \"default\"}, \"fruitfly\": {\"image\": {\"x\": 0.875, \"y\": 0.125}, \"text\": \"Lord of the Fruit Flies\", \"value\": \"default\"}}}, \"lunar_mutations\": {\"order\": 9, \"text\": \"Lunar Mutations\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"None\", \"default\": \"Default\"}, \"items\": {\"mutated_birds\": {\"image\": {\"x\": 0.5, \"y\": 0.3125}, \"text\": \"Mutated Birds\", \"value\": \"default\"}, \"mutated_merm\": {\"image\": {\"x\": 0.8125, \"y\": 0.3125}, \"text\": \"Mutated Merms\", \"value\": \"default\"}, \"mutated_spiderqueen\": {\"image\": {\"x\": 0.875, \"y\": 0.3125}, \"text\": \"Shattered Spider Holes\", \"value\": \"default\"}, \"moon_spider\": {\"image\": {\"x\": 0.0625, \"y\": 0.3125}, \"text\": \"Shattered Spiders\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"value\": \"default\"}}}, \"animals\": {\"order\": 6, \"text\": \"Creatures\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"items\": {\"grassgekkos\": {\"image\": {\"x\": 0.25, \"y\": 0.1875}, \"text\": \"Grass Gekko Morphing\", \"value\": \"default\"}, \"dustmoths\": {\"image\": {\"x\": 0.125, \"y\": 0.125}, \"text\": \"Dust Moths\", \"value\": \"default\"}, \"pigs_setting\": {\"image\": {\"x\": 0.5, \"y\": 0.375}, \"text\": \"Pigs\", \"value\": \"default\"}, \"slurtles_setting\": {\"image\": {\"x\": 0.625, \"y\": 0.4375}, \"text\": \"Slurtles\", \"value\": \"default\"}, \"mushgnome\": {\"image\": {\"x\": 0.25, \"y\": 0.3125}, \"text\": \"Mush Gnomes\", \"value\": \"default\"}, \"monkey_setting\": {\"image\": {\"x\": 0.875, \"y\": 0.25}, \"text\": \"Splumonkeys\", \"value\": \"default\"}, \"lightfliers\": {\"image\": {\"x\": 0.0625, \"y\": 0.25}, \"text\": \"Bulbous Lightbugs\", \"value\": \"default\"}, \"rocky_setting\": {\"image\": {\"x\": 0.125, \"y\": 0.4375}, \"text\": \"Rock Lobsters\", \"value\": \"default\"}, \"snurtles\": {\"image\": {\"x\": 0.75, \"y\": 0.4375}, \"text\": \"Snurtles\", \"value\": \"default\"}, \"bunnymen_setting\": {\"image\": {\"x\": 0.0, \"y\": 0.0625}, \"text\": \"Bunnymen\", \"value\": \"default\"}, \"moles_setting\": {\"image\": {\"x\": 0.75, \"y\": 0.25}, \"text\": \"Moles\", \"value\": \"default\"}}}, \"misc\": {\"order\": 3, \"text\": \"World\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": null, \"items\": {\"rifts_frequency_cave\": {\"image\": {\"x\": 0.4375, \"y\": 0.4375}, \"text\": \"Wild Rift Frequency\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"value\": \"default\"}, \"acidrain_enabled\": {\"image\": {\"x\": 0.0, \"y\": 0.0}, \"text\": \"Acid Rain\", \"desc\": {\"none\": \"Disabled\", \"always\": \"Enabled\"}, \"value\": \"always\"}, \"rifts_enabled_cave\": {\"image\": {\"x\": 0.4375, \"y\": 0.4375}, \"text\": \"Wild Rifts\", \"desc\": {\"never\": \"None\", \"default\": \"Auto Detect\", \"always\": \"Always\"}, \"value\": \"default\"}, \"atriumgate\": {\"image\": {\"x\": 0.1875, \"y\": 0.0}, \"text\": \"Ancient Gateway\", \"desc\": {\"veryslow\": \"Very Slow\", \"slow\": \"Slow\", \"default\": \"Default\", \"fast\": \"Fast\", \"veryfast\": \"Very Fast\"}, \"value\": \"default\"}, \"wormattacks_boss\": {\"image\": {\"x\": 0.3125, \"y\": 0.5625}, \"text\": \"Great Worm\", \"desc\": {\"never\": \"Never\", \"rare\": \"Rare\", \"default\": \"Default\", \"often\": \"Often\", \"always\": \"Always\"}, \"value\": \"default\"}, \"wormattacks\": {\"image\": {\"x\": 0.25, \"y\": 0.5625}, \"text\": \"Cave Worm Attacks\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"value\": \"default\"}, \"earthquakes\": {\"image\": {\"x\": 0.1875, \"y\": 0.125}, \"text\": \"Earthquakes\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"value\": \"default\"}, \"weather\": {\"image\": {\"x\": 0.875, \"y\": 0.375}, \"text\": \"Rain\", \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"value\": \"default\"}}}, \"monsters\": {\"order\": 7, \"text\": \"Hostile Creatures\", \"atlas\": {\"name\": \"worldsettings_customization\", \"width\": 2048, \"height\": 2048, \"item_size\": 128}, \"desc\": {\"never\": \"None\", \"rare\": \"Little\", \"default\": \"Default\", \"often\": \"More\", \"always\": \"Tons\"}, \"items\": {\"chest_mimics\": {\"image\": {\"x\": 0.3125, \"y\": 0.0625}, \"text\": \"Ornery Chests\", \"value\": \"default\"}, \"spiders_setting\": {\"image\": {\"x\": 0.0, \"y\": 0.5}, \"text\": \"Spiders\", \"value\": \"default\"}, \"spider_spitter\": {\"image\": {\"x\": 0.1875, \"y\": 0.5}, \"text\": \"Spitter Spiders\", \"value\": \"default\"}, \"merms\": {\"image\": {\"x\": 0.5625, \"y\": 0.25}, \"text\": \"Merms\", \"value\": \"default\"}, \"bats_setting\": {\"image\": {\"x\": 0.4375, \"y\": 0.0}, \"text\": \"Bats\", \"value\": \"default\"}, \"spider_warriors\": {\"image\": {\"x\": 0.25, \"y\": 0.5}, \"text\": \"Spider Warriors\", \"desc\": {\"never\": \"None\", \"default\": \"Default\"}, \"value\": \"default\"}, \"spider_dropper\": {\"image\": {\"x\": 0.0625, \"y\": 0.5}, \"text\": \"Dangling Depth Dwellers\", \"value\": \"default\"}, \"spider_hider\": {\"image\": {\"x\": 0.125, \"y\": 0.5}, \"text\": \"Cave Spiders\", \"value\": \"default\"}, \"nightmarecreatures\": {\"image\": {\"x\": 0.0, \"y\": 0.375}, \"text\": \"Ruins Nightmares\", \"value\": \"default\"}, \"molebats\": {\"image\": {\"x\": 0.6875, \"y\": 0.25}, \"text\": \"Naked Mole Bats\", \"value\": \"default\"}, \"itemmimics\": {\"image\": {\"x\": 0.6875, \"y\": 0.1875}, \"text\": \"Mimicreeps\", \"value\": \"default\"}}}}}}}"
  },
  {
    "path": "scripts/py-dst-cli/main.py",
    "content": "import json\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\n\nimport dst_version\nimport parse_world_setting\nimport parse_world_webp\n\nimport sys\nimport os\nimport sched\nimport time\n\nworld_gen_path = sys.argv[1]\n\n# 初始化调度器\nscheduler = sched.scheduler(time.time, time.sleep)\n\ndef gen_world_iamge_job(path):\n    print(\"定时任务--生成世界misc文件正在执行, 参数为:\", path)\n    parse_world_webp.download_dst_scripts()\n\ndef gen_world_setting_job(path):\n    print(\"定时任务--生成世界json文件正在执行, 参数为:\", path)\n    datadata = parse_world_setting.parse_world_setting()\n    import json\n    if not os.path.exists('data'):\n        os.mkdir('data')\n    with open('data/dst_world_setting.json', 'w', encoding='utf-8') as f:\n        f.write(json.dumps(datadata, ensure_ascii=False))\n\ndef run():\n\n    scheduler.enter(10, 1, gen_world_iamge_job, (world_gen_path,))\n\n    scheduler.enter(20, 1, gen_world_setting_job, (world_gen_path,))\n\n    scheduler.run()\n\n# 循环执行任务\nwhile True:\n    run()\n\n\n\n'''\nclass DstWorldHandler(BaseHTTPRequestHandler):\n    \n    def do_GET(self):\n        if self.path.startswith('/py/dst/version/'):\n            self.getDstVersion()\n        elif self.path.startswith('/py/dst/world/setting/webp'):\n            self.getDstWorldSettingWebp()\n        elif self.path.startswith('/py/dst/world/setting/json'):\n            self.getDstWorldSettingJson()\n        else:\n            self.send_error(404)\n\n    def getDstVersion(self):\n        version = dst_version.get_dst_version()\n        self.send_response(200)\n        self.send_header('Content-type', 'application/json')\n        self.end_headers()\n        self.wfile.write(json.dumps(version).encode())\n\n    def getDstWorldSettingWebp(self):\n        parse_world_webp.download_dst_scripts()\n        self.send_response(200)\n        self.send_header('Content-type', 'application/json')\n        self.end_headers()\n        self.wfile.write(json.dumps(\"ok\").encode())\n    \n    def getDstWorldSettingJson(self):\n        response = parse_world_setting.parse_world_setting()\n        self.send_response(200)\n        self.send_header('Content-type', 'application/json')\n        self.end_headers()\n        self.wfile.write(json.dumps(response).encode())\n\nPORT = 8000\nhttpd = HTTPServer(('127.0.0.1', PORT), DstWorldHandler)\nprint(f'Serving on port {PORT}')\nhttpd.serve_forever()\n'''\n"
  },
  {
    "path": "scripts/py-dst-cli/parse_TooManyItemPlus_items.py",
    "content": "import os\nimport re\nimport json\n\n# 定义修饰词规则\nSPICE_TRANSLATIONS = {\n    \"_SPICE_GARLIC\": \"蒜\",\n    \"_SPICE_CHILI\": \"辣\",\n    \"_SPICE_SUGAR\": \"甜\",\n    \"_SPICE_SALT\": \"盐\",\n}\n\ndef parse_po_file(po_file):\n    \"\"\"解析 .po 文件，从第 9 行开始，返回仅包含 STRINGS.NAMES 的 msgctxt 与 msgstr 的映射\"\"\"\n    translations = {}\n    with open(po_file, \"r\", encoding=\"utf-8\") as f:\n        lines = f.readlines()\n\n    # 从第 9 行开始解析\n    lines = lines[8:]\n\n    msgctxt, msgid, msgstr = None, None, None\n    for line in lines:\n        line = line.strip()\n        if line.startswith(\"msgctxt\") and \"STRINGS.NAMES.\" in line:\n            msgctxt = re.search(r'\"STRINGS\\.NAMES\\.(.+)\"', line).group(1)  # 提取物品名\n        elif line.startswith(\"msgid\"):\n            msgid = re.search(r'\"(.*)\"', line).group(1)  # 捕获空字符串\n        elif line.startswith(\"msgstr\"):\n            msgstr = re.search(r'\"(.*)\"', line).group(1)  # 捕获空字符串\n\n            # 只有在 msgctxt、msgid 和 msgstr 都非空时才保存\n            if msgctxt and msgid and msgstr:\n                translations[msgctxt] = msgstr\n\n            # 重置状态\n            msgctxt, msgid, msgstr = None, None, None\n    return translations\n\ndef apply_spice_rule(item, base_translation):\n    print(item)\n    \"\"\"根据规则生成修饰后的翻译\"\"\"\n    for suffix, spice_translation in SPICE_TRANSLATIONS.items():\n        if item.endswith(suffix):\n            base_item = item.replace(suffix, \"\")\n            if base_item in base_translation:\n                return f\"{base_translation[base_item]}-{spice_translation}\"\n    return \"未翻译\"\n\ndef generate_translations(input_folder, po_file, output_file):\n    \"\"\"生成带翻译的 JSON 数据\"\"\"\n    # 解析 .po 文件\n    translations = parse_po_file(po_file)\n\n    # 初始化结果字典\n    result = {}\n\n    # 遍历输入文件夹，处理分类数据\n    for filename in os.listdir(input_folder):\n        if filename.endswith(\".lua\"):\n            category_name = os.path.splitext(filename)[0]\n            file_path = os.path.join(input_folder, filename)\n            with open(file_path, \"r\", encoding=\"utf-8\") as f:\n                content = f.read()\n            if \"return\" in content:\n                content = content.split(\"return\", 1)[1].strip().strip(\"{}\")\n                items = [item.strip().strip('\"') for item in content.split(\",\")]\n                result[category_name] = {\n                    item: translations.get(item.upper(), apply_spice_rule(item.upper(), translations))\n                    for item in items\n                }\n\n    # 保存结果为 JSON 文件\n    with open(output_file, \"w\", encoding=\"utf-8\") as f:\n        json.dump(result, f, ensure_ascii=False, indent=4)\n    print(f\"翻译结果已保存到 {output_file}\")\n\n\n# 设置文件路径\ninput_folder = \"./scripts/TMIP/list\"  # 替换为文件夹路径\npo_file = \"./chinese_s.po\"           # 替换为 .po 文件路径\noutput_file = \"tooManyItemPlus.json\"     # 输出文件路径\n\n# 运行生成函数\ngenerate_translations(input_folder, po_file, output_file)\n"
  },
  {
    "path": "scripts/py-dst-cli/parse_mod.py",
    "content": "import lupa\nfrom functools import reduce\n\nimport steam.client\nimport steam.client.cdn\nimport steam.core.cm\nimport steam.webapi\nfrom steam.exceptions import SteamError\n\nimport requests\nimport json\nfrom io import BytesIO\nfrom urllib.parse import urlencode\nfrom urllib.request import Request, urlopen\nimport zipfile\nimport math\n\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nfrom urllib.parse import urlparse, parse_qs\n\n\nanonymous = steam.client.SteamClient()\nanonymous.anonymous_login()\nsteamcdn = steam.client.cdn.CDNClient(anonymous)\n\nencoding = 'utf-8'\nmodinfo_lua = 'modinfo.lua'\nmodinfo_chs_lua = 'modinfo_chs.lua'\n\nwith open('steamapikey.txt', 'r', encoding='utf-8') as key_value:\n    steamapikey = key_value.read()\n    print('从文件读取 steamapikey 成功')\n\n\ndef search_mod_list(text='', page=1, num=25): \n\n    url = 'http://api.steampowered.com/IPublishedFileService/QueryFiles/v1/'\n    data = {\n        'page': page,\n        'key': steamapikey,  # steam apikey  https://steamcommunity.com/dev/apikey\n        'appid': 322330,  # 游戏id\n        'language': 6,  # 0英文，6简中，7繁中\n        'return_tags': True,  # 返回mod详情中的标签\n        'numperpage': num,  # 每页结果\n        'search_text': text,  # 标题或描述中匹配的文字\n        'return_vote_data': True,\n        'return_children': True\n    }\n    url = url + '?' + urlencode(data)\n    for _ in range(2):\n        try:\n            req = Request(url=url)\n            response = urlopen(req, timeout=10)\n            mod_data = response.read().decode('utf-8')\n            # print(mod_data)\n            response.close()\n            break\n        except Exception as e:\n            print('搜索mod失败\\n', e )\n    else:\n        return   \n    mod_data = json.loads(mod_data).get('response')\n\n    total = mod_data.get('total')\n    mod_info_full = mod_data.get('publishedfiledetails')\n\n    mod_list = []\n    if mod_info_full:\n        for mod_info_raw in mod_info_full:\n            img = mod_info_raw.get('preview_url', '')\n            vote_data = mod_info_raw.get('vote_data', {})\n            auth = mod_info_raw.get(\"creator\", 0),\n            mod_info = {\n                'id': mod_info_raw.get('publishedfileid', ''),\n                'name': mod_info_raw.get('title', ''),\n                'author': f'https://steamcommunity.com/profiles/{auth}/?xml=1' if auth else '',\n                'desc': mod_info_raw.get('file_description'),\n                'time': int(mod_info_raw.get('time_updated', 0)),\n                'sub': int(mod_info_raw.get('subscriptions', '0')),\n                'img': img if 'steamuserimages' in img else '',\n                # 'v': [*[i.get('tag')[8:] for i in mod_info_raw.get('tags', '') if i.get('tag', '').startswith('version:')], ''][0],\n                'vote': {'star': int(vote_data.get('score') * 5) + 1 if vote_data.get('votes_up') + vote_data.get('votes_down') >= 25 else 0,\n                         'num': vote_data.get('votes_up') + vote_data.get('votes_down')}\n            }\n            if mod_info_raw.get(\"num_children\"):\n                mod_info['child'] = list(map(lambda x: x.get('publishedfileid'), mod_info_raw.get(\"children\")))\n\n            mod_list.append(mod_info)\n    return {'page': page, 'size': num,'total': total, 'totalPage': 1 if total/num < 1  else math.ceil(total/num),'data': mod_list}\n\n\ndef get_mod_base_info(modId: int):\n\n    url = 'http://api.steampowered.com/IPublishedFileService/GetDetails/v1/'\n    data = {\n        'key': steamapikey,  # steam apikey  https://steamcommunity.com/dev/apikey\n        'language': 6,  # 0英文，6简中，7繁中\n        'publishedfileids[0]': str(modId),  # 要查询的发布文件的ID\n    }\n    url = url + '?' + urlencode(data)\n    payload={}\n    headers = {}\n    response = requests.request(\"GET\", url, headers=headers, data=payload, verify=False)\n\n    data = json.loads(response.text)['response']['publishedfiledetails'][0]\n    if data['result'] != 1:\n        print(\"get mod error\")\n        return {}\n    img = data.get('preview_url', '')\n    author = data.get('creator')\n    return {\n        'id': data.get('publishedfileid'),\n        'name': data.get('title'),\n        'last_time': data.get('time_updated'),\n        \"description\": data.get(\"file_description\"),\n        'auth': f'https://steamcommunity.com/profiles/{author}/?xml=1' if author else '',\n        'file_url': data.get('file_url'),\n        'img': f'{img}?imw=64&imh=64&ima=fit&impolicy=Letterbox&imcolor=%23000000&letterbox=true'\n        if 'steamuserimages' in img else '',\n        'v': [*[i.get('tag')[8:] for i in data.get('tags', '') if i.get('tag', '').startswith('version:')], ''][0],\n        'creator_appid': data.get('creator_appid'),\n        'consumer_appid': data.get('consumer_appid'),\n    }\n\ndef check_is_dst_mod(mod_info):\n    creator_appid, consumer_appid = mod_info.get('creator_appid'), mod_info.get('consumer_appid')\n    if not (creator_appid == 245850 and consumer_appid == 322330):\n        print('%s 不是饥荒联机版 mod', mod_info.get(\"id\"))\n        return False\n    return True\n\ndef get_mod_info(modId: int):\n\n    # 获取基础信息\n    mod_info = get_mod_base_info(modId)\n\n    if not check_is_dst_mod(mod_info):\n        return {}\n    \n    file_url = mod_info['file_url']\n    if file_url:\n        mod_type = 'v1'\n        mod_config = get_mod_config_file_by_url(file_url=file_url)\n    else:\n        mod_config = get_mod_config_file_by_steamcmd(modId=modId)\n        mod_type = 'v2'\n    # 获取 mod 文件\n\n    mod_info['mod_type'] = mod_type\n    mod_info['mod_config'] = mod_config\n\n    return mod_info\n\ndef get_mod_config_file_by_url(file_url: str):\n    status, modinfo = 0, {'modinfo': b'', 'modinfo_chs': b''}\n    resp_input_io = BytesIO()\n    isSuccess = False\n    for i in range(3):\n        try:\n            req = Request(url=file_url)\n            res = urlopen(req, timeout=10)\n            resp_input_io.write(res.read())\n            res.close()\n            isSuccess = True\n            break\n        except Exception as e:\n            print(\"下载失败 \\n\", e, file_url)\n    if not isSuccess:\n        return {}\n    with zipfile.ZipFile(resp_input_io) as file_zip:\n        namelist = file_zip.namelist()\n        if modinfo_lua in namelist:\n            modinfo['modinfo'] = file_zip.read(modinfo_lua)\n        if modinfo_chs_lua in namelist:\n            modinfo['modinfo_chs'] = file_zip.read(modinfo_chs_lua)\n    \n    resp_input_io.close()\n    data = modinfo['modinfo'].decode(encoding)\n    return lua_runtime(data)\n\ndef get_mod_config_file_by_steamcmd(modId: int):\n    return get_mod_info_dict(modId=modId)\n\n#TODO 解决并发问题\n'''\nlock\n使用一个cache{modId: xxx, semaphore: xxx, mod: xxx}\ninit cache\n初始化信号量\nunlock\n\n执行IO\n\n其他等待 mod 数据返回\n\n'''\ndef get_mod_info_dict(modId:int):\n\n    status, modinfo = 0, {'modinfo':b'', 'modinfo_chs': b''}\n    mod_item = steamcdn.get_manifest_for_workshop_item(modId)\n    modinfo_names = ['modinfo.lua', 'modinfo_chs.lua']\n    modinfo_list = list(filter(lambda x: x.filename in modinfo_names, mod_item.iter_files() ))\n    if not modinfo:\n        print(\"未找到modinfo\", modId)\n\n    for info in modinfo_list:\n        modinfo[info.filename[:-4]] = info.read()\n        status = 1\n        \n    data = modinfo['modinfo'].decode(encoding)\n    \n    return lua_runtime(data)\n    \n\ndef lua_runtime(data: bytes):\n    lua = lupa.LuaRuntime()\n    lang='zh'\n    # lupa 全局变量\n    lupag = ['locale', 'folder_name', 'ChooseTranslationTable'] + ['print', 'rawlen', 'loadfile', 'rawequal', 'pairs', '_VERSION', 'select', 'pcall', 'debug', 'io', 'getmetatable', 'assert', 'package', 'os', 'warn', 'next', 'load', 'tostring', 'setmetatable', 'rawget', 'coroutine', 'tonumber', 'error', 'collectgarbage', 'python', 'utf8', 'math', 'ipairs', 'rawset', 'type', 'xpcall', '_G', 'table', 'dofile', 'require', 'string']\n\n    # 模拟运行环境\n    lua.execute(f'locale = \"{lang}\"')\n    lua.execute(f'folder_name = \"workshop-{modId}\"')\n    lua.execute(f'ChooseTranslationTable = function(tbl) return tbl[\"{lang}\"] or tbl[1] end')\n\n    # 开始处理数据\n    lua.execute(data)\n\n    # 选取需要的值并转为 python 对象\n    g = lua.globals()\n    # 选择白名单或黑名单模式\n    info_dict = {key: table_dict(g[key]) for key in filter(lambda x: x not in lupag, g)}\n    # info_dict = {key: table_dict(g[key]) for key in filter(lambda x: x in info_list_full, g)}\n\n    # 去除空值\n    info_dict = {i: j for i, j in info_dict.items() if j or j is False or j == 0}\n    \n    return info_dict\n\ndef table_dict(lua_table):\n    if lupa.lua_type(lua_table) == 'table':\n        keys = list(lua_table)\n        # 假如lupa.table为空，或keys都是整数，且从数字 1 开始以 1 为单位递增，则认为是列表，否则为字典\n        if reduce(lambda x, y: x and isinstance(y, int), keys, len(keys) == 0 or keys[0] == 1):  # 为空或首项为 1，全为整数\n            if all(map(lambda x, y: x + 1 == y, keys[:-1], keys[1:])):  # 以 1 为单位递增\n                return list(map(lambda x: table_dict(x), lua_table.values()))\n        return dict(map(lambda x, y: (x, table_dict(y)), keys, lua_table.values()))\n    # 由于需要用于解析 modinfo 为 json 格式，所以不支持函数，这里直接删掉\n    if lupa.lua_type(lua_table) == 'function':\n        return '这里原本是个函数，不过已经被我干掉了'\n    return lua_table\n        \nmodId = 2505341606\n# mod_info_dict = get_mod_info_dict(modId)\n# print(mod_info_dict)\n\n#print(get_mod_base_info(modId=modId))\n# 1216718131\n\n# print(get_mod_info(modId=modId))\n\ndef get_dst_version():\n    # 0 下载失败， 1 下载成功， 2 内容为空\n    for _ in range(3):\n        try:\n            # b = next(steamcdn.get_manifests(343050, filter_func=lambda x, y: x == 343052))\n            # version = next(b.iter_files('version.txt')).read().decode('utf-8').strip()\n            version = [*steamcdn.iter_files(343050, 'version.txt', filter_func=lambda x, y: x == 343052)]\n            if not version:\n                return 0\n            print(version)\n            version = version[0].read().decode('utf-8').strip()\n            # print(version)\n            return version\n        except SteamError as e:\n            print('获取版本失败', e)\n    return 0\n\n\nclass ModHandler(BaseHTTPRequestHandler):\n    \n    def do_GET(self):\n        if self.path.startswith('/py/mod/'):\n            self.mod_api()\n        elif self.path.startswith('/py/search/mod'):\n            self.search_api()\n        elif self.path.startswith('/py/version'):\n            self.dst_version_api()\n        else:\n            self.send_error(404)\n\n    def mod_api(self):\n        mod_id = self.path.split('/')[3]\n        mod_info = get_mod_info(int(mod_id))\n        response = {'modInfo': mod_info}\n        self.send_response(200)\n        self.send_header('Content-type', 'application/json')\n        self.end_headers()\n        self.wfile.write(json.dumps(response).encode())\n\n    def search_api(self):\n        \n        query = parse_qs(urlparse(self.path).query)\n        search_text = query['text'][0]\n        page = query['page'][0]\n        size = query['size'][0]\n\n        print(search_text, page, size)\n\n        response = search_mod_list(search_text, int(page), int(size))\n\n        self.send_response(200)\n        self.send_header('Content-type', 'application/json')\n        self.end_headers()\n        self.wfile.write(json.dumps(response).encode())\n    \n    def dst_version_api(self):\n        response = get_dst_version()\n        self.send_response(200)\n        self.send_header('Content-type', 'application/json')\n        self.end_headers()\n        self.wfile.write(json.dumps(response).encode())\n\nPORT = 8000\nhttpd = HTTPServer(('localhost', PORT), ModHandler)\nprint(f'Serving on port {PORT}')\nhttpd.serve_forever()\n"
  },
  {
    "path": "scripts/py-dst-cli/parse_world_setting.py",
    "content": "##!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport os\nfrom functools import reduce\nfrom os.path import join as pjoin\nfrom re import compile, findall, search, sub\n\nimport lupa\n\n\ndef table_dict(lua_table):\n    if lupa.lua_type(lua_table) == 'table':\n        keys = list(lua_table)\n        # 假如lupa.table为空，或keys都是整数，且从数字 1 开始以 1 为单位递增，则认为是列表，否则为字典\n        if reduce(lambda x, y: x and isinstance(y, int), keys, len(keys) == 0 or keys[0] == 1):  # 为空或首项为 1，全为整数\n            if all(map(lambda x, y: x + 1 == y, keys[:-1], keys[1:])):  # 以 1 为单位递增\n                return list(map(lambda x: table_dict(x), lua_table.values()))\n        new_dict = dict(map(lambda x, y: (x, table_dict(y)), keys, lua_table.values()))\n        if 'desc' in new_dict:  # task_set 和 start_location 的 desc 是个函数，需要调用一下返回实际值\n            for i, j in new_dict.items():\n                if lupa.lua_type(j) == 'function':\n                    new_dict[i] = {world: table_dict(j(world)) for world in new_dict.get('world', [])}\n        return new_dict\n    return lua_table\n\n\ndef dict_table(py_dict, lua_temp):  # dict 转 table。列表之类类型的转过去会有索引，table_from 的问题\n    if isinstance(py_dict, dict):\n        return lua_temp.table_from(\n            {i: (dict_table(j, lua_temp) if isinstance(j, (dict, list, tuple, set)) else j) for i, j in py_dict.items()})\n    if isinstance(py_dict, (list, tuple, set)):\n        return lua_temp.table_from([(dict_table(i, lua_temp) if isinstance(i, (dict, list, tuple, set)) else i) for i in py_dict])\n    return py_dict\n\n\ndef scan(dict_scan, num, key_set):  # 返回指定深度的 keys 集合, key_set初始传入空set\n    if num != 0:\n        for value in dict_scan.values():\n            if isinstance(value, dict):\n                key_set = key_set | scan(value, num - 1, key_set)\n        return key_set\n    return key_set | set(dict_scan)\n\n\ndef parse_po(path_po):  # 把 .po 文件按照 msgctxt: msgstr 的格式转为字典，再以 . 的深度分割 keys。这里为了效率主要转了 UI 部分的\n    print('开始通过 .po 文件 获取翻译')\n    with open(path_po, 'rb') as f:\n        f.seek(-50000, 2)\n        data = f.read()\n        while b'\"STRINGS.T' not in data:\n            f.seek(-100000, 1)\n            data = f.read(50000) + data\n    data = data.decode('utf-8').replace('\\r\\n', '\\n')\n    pattern = compile(r'\\nmsgctxt\\s*\"(.*)\"\\nmsgid\\s*\"(.*)\"\\nmsgstr\\s*\"(.*)\"')\n\n    dict_zh_split, dict_en_split = {}, {}\n\n    print('获取中文翻译')\n    dict_zh = {i[0]: i[2] for i in pattern.findall(data)}  # 因为 costomize 中有连接字符串的，所以这里不能构建成一个字典，会出错\n    for i, j in dict_zh.items():\n        split_key(dict_zh_split, i.split(\".\"), j)\n\n    # print('获取英文对照')\n    dict_en = {i[0]: i[1] for i in pattern.findall(data)}  # 因为 costomize 中有连接字符串的，所以这里不能构建成一个字典，会出错\n    for i, j in dict_en.items():\n        split_key(dict_en_split, i.split(\".\"), j)\n\n    dict_split = {'zh': dict_zh_split}\n    if dict_en_split:\n        dict_split['en'] = dict_en_split\n    return dict_split\n\n\ndef split_key(dict_split, list_split, value):  # 以列表值为 keys 补全字典深度。用于分割 dict 的 keys，所以叫 split\n    if not list_split:\n        return\n    if list_split[0] not in dict_split:\n        dict_split[list_split[0]] = value if len(list_split) == 1 else {}\n    split_key(dict_split.get(list_split.pop(0)), list_split, value)\n\n\ndef creat_newdata(path_cus, new_cus):  # 删去local、不必要的require 和不需要的内容\n    with open(path_cus + '.lua', 'r') as f:\n        data = f.read()\n    if 'local MOD_WORLDSETTINGS_GROUP' in data:\n        data = data[:data.find('local MOD_WORLDSETTINGS_GROUP')]\n    data = sub(r'local [^=]+?\\n', '', data).replace('local ', '')\n    data = sub(r'require(?![^\\n]+?(?=tasksets\"|startlocations\"))', '', data)\n    with open(new_cus + '.lua', 'w+') as f:\n        f.write(data)\n\n\ndef parse_cus(lua_cus, po):\n    print('准备解析 customize.lua 文件')\n    new_cus = lua_cus + '_tmp'\n    creat_newdata(lua_cus, new_cus)  # 删去多余的不需要的数据并另存\n\n    print('准备运行环境')\n    lua = lupa.LuaRuntime()\n    lua.execute('function IsNotConsole() return true end')  # IsNotConsole() 不是 PS4 或 XBONE 就返回 True  # for customize\n    lua.execute('function IsConsole() return false end')  # IsConsole() 是 PS4 或 XBONE 就返回 True\n    lua.execute('function IsPS4() return false end')  # IsPS4() 不是 PS4 就返回False  # for customize\n    lua.execute('ModManager = {}')  # for startlocations\n    lua.require('class')  # for util\n    lua.require('util')  # for startlocations\n    lua.require('constants')  # 新年活动相关\n    lua.require(\"strict\")\n\n    dict_po = parse_po(po)\n    options_list = ['WORLDGEN_GROUP', 'WORLDSETTINGS_GROUP']  # 所需数据列表\n    misc_list = ['WORLDGEN_MISC', 'WORLDSETTINGS_MISC']  # 所需数据列表\n    options = {}\n\n    print('解析 customize.lua 文件，语言：%s', ', '.join(dict_po.keys()))\n    # 获取英文版的应该可以通过导入strings来做？应该不需要通过 .po 文件匹配\n    for lang, tran in dict_po.items():\n        strings = dict_table(tran.get('STRINGS'), lua)\n        if strings:\n            pass\n        lua.execute('STRINGS=python.eval(\"strings\")')  # 为了翻译，也免去要先给 STRINGS 加引号之类的麻烦事\n        # lua.execute('POT_GENERATION = true')\n        # lua.require('strings')\n        lua.require(new_cus)  # 终于开始干正事了。导入的 tasksets 会自动打印一些东西出来\n        options[lang] = {'setting': {i: table_dict(lua.globals()[i]) for i in options_list if i in lua.globals()},\n                         'translate': tran}\n        for package in list(lua.globals().package.loaded):  # 清除加载的 customize 模块，避免下次 require 时不加载\n            if 'map/' in package:\n                lua.execute(f'package.loaded[\"{package}\"]=nil')  # table.remove 不能用，显示 package.loaded 长度为0\n    miscs = {i: table_dict(lua.globals()[i]) for i in misc_list if i in lua.globals()}\n\n    print('解析 customize.lua 文件完毕')\n    return options, miscs\n\n\ndef parse_option(group_dict, path_base):\n    print('重新组织设置格式')\n    print('这里写的太什么了，不好插日志')\n\n    result = {}\n    img_info = {}\n    img_name = ''\n    for lang, opt in group_dict.items():\n        setting, translate = opt.values()\n        result[lang] = {'forest': {}, 'cave': {}}\n        for group, group_value in setting.items():\n            for world_type in result[lang].values():\n                world_type[group] = {}\n            for com, com_value in group_value.items():\n                desc_val = com_value.get('desc')\n                if desc_val:\n                    desc_val = {i['data']: i['text'] for i in desc_val}\n                for world, world_value in result.get(lang).items():\n                    img_name = com_value.get('atlas', '').replace('images/', '').replace('.xml', '')\n                    if img_name not in img_info:\n                        with open(pjoin(path_base, com_value.get('atlas')), 'r', encoding='utf-8') as f:\n                            data = f.read()\n                        image_filename = search('filename=\"([^\"]+)\"', data).group(1)\n                        with open(pjoin(path_base, 'images', image_filename), 'rb') as f:\n                            img_data = f.read(96)\n                        image_width, image_height = int(img_data[88:90].hex(), 16), int(img_data[90:92].hex(), 16)\n                        img_width_start, img_width_end = search(r'u1=\"([^\"]+?)\"\\s*?u2=\"([^\"]+?)\"', data).groups()\n                        img_item_width = int(image_width / round(1 / (float(img_width_end) - float(img_width_start))))\n                        item_num_w, item_num_h = image_width / img_item_width, image_height / img_item_width\n                        img_pos = {i[0]: {'x': round(float(i[1]) * item_num_w) / item_num_w,\n                                          'y': 1 - round(float(i[2]) * item_num_h) / item_num_h} for i in\n                                   findall(r'<Element\\s+name=\"([^\"]+?)\"\\s*u1=\"([^\"]+?)\"[\\d\\D]*?v2=\"([^\"]+?)\"', data)}\n                        img_info[img_name] = {'img_items': img_pos, 'width': image_width, 'height': image_height,\n                                              'item_size': img_item_width}\n                    world_value.get(group)[com] = {\n                        'order': int(com_value.get('order', 0)),\n                        'text': com_value.get('text', ''),\n                        'atlas': {'name': img_name, 'width': img_info[img_name]['width'],\n                                  'height': img_info[img_name]['height'], 'item_size': img_info[img_name]['item_size']},\n                        'desc': desc_val,\n                        'items': {}}\n                for item, item_value in com_value['items'].items():\n                    tmp = []\n                    if 'forest' in item_value.get('world', '') or not item_value.get('world'):\n                        tmp.append(('forest', result[lang]['forest']))\n                    if 'cave' in item_value.get('world', ''):\n                        tmp.append(('cave', result[lang]['cave']))\n                    print('这个有问题{}\\n'.format(item_value) if not tmp else '', end='')\n                    for world, world_value in tmp:\n                        items = world_value[group][com]['items']\n                        items[item] = {\n                            'image': img_info[img_name]['img_items'][item_value['image']],\n                            'text': translate['STRINGS']['UI']['CUSTOMIZATIONSCREEN'].get(item.upper())}\n                        if item_value.get('desc'):\n                            item_desc = item_value['desc']\n                            item_desc = item_desc.get(world) if isinstance(item_desc, dict) else item_desc\n                            item_desc = {i['data']: i['text'] for i in item_desc}\n                            items[item]['desc'] = item_desc\n\n                        # 为带有排序优先属性 order 的项目添加 order\n                        if item_value.get('order'):\n                            items[item]['order'] = item_value['order']\n                        # 修正地上地下使用不同 desc 时，共用的 value 不在某个的 desc 内的情况\n                        tmp_desc = items[item].get('desc') or world_value[group][com]['desc']\n                        tmp_value = item_value.get('value')\n                        items[item]['value'] = item_value.get('value') if tmp_value in tmp_desc else list(tmp_desc)[0]\n\n    print('格式重组完成')\n\n    # 清理空的 items 项。并打印不同世界的项目数。\n    tip_times = 0\n    for lang_value in result.values():\n        for world_name, world_value in lang_value.items():\n            setting_num = 0\n            for groups_value in world_value.values():\n                for group_name, group_value in list(groups_value.items())[:]:\n                    setting_num += len(group_value['items'])\n                    if not group_value['items']:\n                        del groups_value[group_name]\n            if tip_times < len(lang_value):\n                print(f'{world_name} 拥有 {setting_num} 个可设置项')\n                tip_times += 1\n\n    return result\n\n\ndef parse_world_setting(path_base=\"data\"):\n\n    print('开始解析世界设置')\n\n    # path_base 指向饥荒程序文件夹中的 data 文件夹路径\n    # path_base = \"data\"\n    path_script = pjoin(path_base, 'databundles', 'scripts')\n    po_chs = 'languages/chinese_s.po'\n    lua_customize = 'map/customize'  # 务必用正斜杠避免问题。lua 内部 require 会用正斜杠，两个不一样的话操作对应模块时会有坑\n\n    # if not os.path.exists(path_cus := pjoin(path_script, lua_customize + '.lua')):\n    #     print('未找到 %s 文件，准备退出', path_cus)\n    #     return\n    # if not os.path.exists(path_po := pjoin(path_script, po_chs)):\n    #     print('未找到 %s 文件，准备退出', path_po)\n    #     return\n    path_cus = pjoin(path_script, lua_customize + '.lua')\n    if not os.path.exists(path_cus):\n        print('未找到 %s 文件，准备退出' % path_cus)\n        return\n\n    path_po = pjoin(path_script, po_chs)\n    if not os.path.exists(path_po):\n        print('未找到 %s 文件，准备退出' % path_po)\n        return\n\n    cwd_now = os.getcwd()\n    os.chdir(path_script)\n    settings = None\n\n    try:\n        options_raw, misc = parse_cus(lua_customize, po_chs)\n        # print(options_raw)\n        os.chdir(cwd_now)\n        settings = parse_option(options_raw, path_base)\n        print('解析世界设置完成')\n    except Exception as e:\n        os.chdir(cwd_now)\n        print('解析世界设置失败')\n        print(e, exc_info=True)\n\n    return settings\n\n\nif __name__ == \"__main__\":\n    datadata = parse_world_setting(\"C:\\\\Program Files (x86)\\\\Steam\\steamapps\\\\common\\\\Don't Starve Together\\\\data\")\n    print(datadata)\n    import json\n    with open('C:\\\\Users\\\\paratera\\\\Desktop\\\\我的\\\\饥荒面板\\\\dst-admin-go\\\\py-dst-cli\\\\dst_world_setting.json', 'w', encoding='utf-8') as f:\n        f.write(json.dumps(datadata, ensure_ascii=False))"
  },
  {
    "path": "scripts/py-dst-cli/parse_world_webp.py",
    "content": "# -*- coding: utf-8 -*-\nimport os\nimport zipfile\nfrom shutil import rmtree\n\nimport gevent\nimport steam.client\nimport steam.client.cdn\nimport steam.core.cm\nimport steam.webapi\nfrom steam.exceptions import SteamError\n\ndef download_dst_scripts(steamcdn=None):\n\n    anonymous = steam.client.SteamClient()\n    anonymous.anonymous_login()\n    steamcdn = steam.client.cdn.CDNClient(anonymous)\n\n    print('开始下载世界设置所需饥荒文件')\n    # 0:失败, 1:下载成功, 2:没有全部下载成功\n    if not os.path.exists('data'):\n        os.mkdir('data')\n    if not os.path.exists('data/databundles'):\n        os.mkdir('data/databundles')\n    if not os.path.exists('data/images'):\n        os.mkdir('data/images')\n    code = 0\n    status = {'scripts': False, 'set_tex': False, 'set_xml': False, 'gen_tex': False, 'gen_xml': False, 'ver': False}\n    for i in range(5):\n        try:\n            # b = next(steamcdn.get_manifests(343050, filter_func=lambda x, y: x == 343052))\n            # version = next(b.iter_files('version.txt')).read().decode('utf-8').strip()\n            for file in steamcdn.iter_files(343050, filter_func=lambda x, y: x == 343052):\n                if 'scripts.zip' in file.filename and not status['scripts']:\n                    scripts_con = file.read()\n                    with open('data/databundles/scripts.zip', 'wb') as f:\n                        f.write(scripts_con)\n                    with zipfile.ZipFile('data/databundles/scripts.zip') as file_zip:\n                        if os.path.exists('data/databundles/scripts'):\n                            rmtree('data/databundles/scripts')\n                        file_zip.extractall('data/databundles')\n                    print('获取 scripts.zip 成功')\n                    status['scripts'] = True\n                elif 'worldsettings_customization.tex' in file.filename and not status['set_tex']:\n                    with open('data/images/worldsettings_customization.tex', 'wb') as f:\n                        f.write(file.read())\n                    print('获取 worldsettings_customization.tex 成功')\n                    status['set_tex'] = True\n                elif 'worldsettings_customization.xml' in file.filename and not status['set_xml']:\n                    with open('data/images/worldsettings_customization.xml', 'wb') as f:\n                        f.write(file.read())\n                    print('获取 worldsettings_customization.xml 成功')\n                    status['set_xml'] = True\n                elif 'worldgen_customization.tex' in file.filename and not status['gen_tex']:\n                    with open('data/images/worldgen_customization.tex', 'wb') as f:\n                        f.write(file.read())\n                    print('获取 worldgen_customization.tex 成功')\n                    status['gen_tex'] = True\n                elif 'worldgen_customization.xml' in file.filename and not status['gen_xml']:\n                    with open('data/images/worldgen_customization.xml', 'wb') as f:\n                        f.write(file.read())\n                    print('获取 worldgen_customization.xml 成功')\n                    status['gen_xml'] = True\n                elif 'version.txt' in file.filename and not status['ver']:\n                    with open('data/version.txt', 'wb') as f:\n                        f.write(file.read())\n                    print('获取 version.txt 成功')\n                    status['ver'] = True\n\n                code = 1 if all(status.values()) else 2\n            if code == 1:\n                break\n        except SteamError as e:\n            print(e, exc_info=True)\n        except gevent.timeout.Timeout:\n            print('超时了')\n    return code, status\n\nif __name__ == \"__main__\":\n    print(download_dst_scripts())"
  },
  {
    "path": "scripts/py-dst-cli/steamapikey.txt",
    "content": "73DF9F781D195DFD3D19DED1CB72EEE6"
  },
  {
    "path": "static/Caves/leveldataoverride.lua",
    "content": "return {\n\tbackground_node_range = {\n\t\t0,\n\t\t1,\n\t},\n\tdesc = \"探查洞穴…… 一起！\",\n\thideminimap = false,\n\tid = \"DST_CAVE\",\n\tlocation = \"cave\",\n\tmax_playlist_position = 999,\n\tmin_playlist_position = 0,\n\tname = \"洞穴\",\n\tnumrandom_set_pieces = 0,\n\toverride_level_string = false,\n\toverrides = {\n    loop = \"default\",\n    start_location = \"caves\",\n    touchstone = \"default\",\n    cavelight = \"default\",\n    prefabswaps_start = \"default\",\n    world_size = \"default\",\n    task_set = \"cave_default\",\n    boons = \"default\",\n    branching = \"default\",\n    rock = \"default\",\n    mushroom = \"default\",\n    trees = \"default\",\n    flint = \"default\",\n    mushtree = \"default\",\n    cave_ponds = \"default\",\n    marshbush = \"default\",\n    reeds = \"default\",\n    lichen = \"default\",\n    berrybush = \"default\",\n    flower_cave = \"default\",\n    sapling = \"default\",\n    wormlights = \"default\",\n    grass = \"default\",\n    banana = \"default\",\n    fern = \"default\",\n    rocky = \"default\",\n    slurtles = \"default\",\n    monkey = \"default\",\n    slurper = \"default\",\n    bunnymen = \"default\",\n    tentacles = \"default\",\n    cave_spiders = \"default\",\n    chess = \"default\",\n    worms = \"default\",\n    fissure = \"default\",\n    spiders = \"default\",\n    bats = \"default\",\n    earthquakes = \"default\",\n    weather = \"default\",\n    rifts_enabled_cave = \"default\",\n    rifts_frequency_cave = \"default\",\n    wormattacks = \"default\",\n    atriumgate = \"default\",\n    regrowth = \"default\",\n    mushtree_moon_regrowth = \"default\",\n    mushtree_regrowth = \"default\",\n    lightflier_flower_regrowth = \"default\",\n    flower_cave_regrowth = \"default\",\n    slurtles_setting = \"default\",\n    grassgekkos = \"default\",\n    monkey_setting = \"default\",\n    snurtles = \"default\",\n    moles_setting = \"default\",\n    mushgnome = \"default\",\n    pigs_setting = \"default\",\n    dustmoths = \"default\",\n    lightfliers = \"default\",\n    bunnymen_setting = \"default\",\n    rocky_setting = \"default\",\n    spider_dropper = \"default\",\n    bats_setting = \"default\",\n    molebats = \"default\",\n    nightmarecreatures = \"default\",\n    spider_spitter = \"default\",\n    spider_hider = \"default\",\n    spider_warriors = \"default\",\n    merms = \"default\",\n    spiders_setting = \"default\",\n    liefs = \"default\",\n    spiderqueen = \"default\",\n    toadstool = \"default\",\n    daywalker = \"default\",\n    fruitfly = \"default\",\n    basicresource_regrowth = \"always\",\n    beefaloheat = \"default\",\n    brightmarecreatures = \"default\",\n    crow_carnival = \"default\",\n    darkness = \"default\",\n    day = \"default\",\n    dropeverythingondespawn = \"default\",\n    extrastartingitems = \"default\",\n    ghostenabled = \"always\",\n    ghostsanitydrain = \"none\",\n    hallowed_nights = \"default\",\n    healthpenalty = \"always\",\n    hunger = \"default\",\n    krampus = \"default\",\n    layout_mode = \"RestrictNodesByKey\",\n    lessdamagetaken = \"none\",\n    portalresurection = \"always\",\n    resettime = \"none\",\n    roads = \"never\",\n    season_start = \"default\",\n    seasonalstartingitems = \"default\",\n    shadowcreatures = \"default\",\n    spawnmode = \"fixed\",\n    spawnprotection = \"default\",\n    specialevent = \"default\",\n    temperaturedamage = \"default\",\n    winters_feast = \"default\",\n    wormhole_prefab = \"tentacle_pillar\",\n    year_of_the_beefalo = \"default\",\n    year_of_the_bunnyman = \"default\",\n    year_of_the_carrat = \"default\",\n    year_of_the_catcoon = \"default\",\n    year_of_the_gobbler = \"default\",\n    year_of_the_pig = \"default\",\n    year_of_the_varg = \"default\",},\n\trequired_prefabs = {\n\t\t\"multiplayer_portal\",\n\t},\n\tsettings_desc = \"探查洞穴…… 一起！\",\n\tsettings_id = \"DST_CAVE\",\n\tsettings_name = \"洞穴\",\n\tsubstitutes = {},\n\tversion = 4,\n\tworldgen_desc = \"探查洞穴…… 一起！\",\n\tworldgen_id = \"DST_CAVE\",\n\tworldgen_name = \"洞穴\",\n}"
  },
  {
    "path": "static/Caves/modoverrides.lua",
    "content": "return {  }"
  },
  {
    "path": "static/Caves/server.ini",
    "content": "[NETWORK]\nserver_port = 10998\n\n\n[SHARD]\nis_master = false\nname = Caves\nid = 2\n\n\n[ACCOUNT]\nencode_user_path = false\n\n\n[STEAM]\nmaster_server_port = 27017\nauthentication_port = 8767\n"
  },
  {
    "path": "static/Master/leveldataoverride.lua",
    "content": "return {\n\tdesc = \"永不结束的饥荒沙盒模式。永远可以在绚丽之门复活。\",\n\thideminimap = false,\n\tid = \"ENDLESS\",\n\tlocation = \"forest\",\n\tmax_playlist_position = 999,\n\tmin_playlist_position = 0,\n\tname = \"无尽\",\n\tnumrandom_set_pieces = 4,\n\toverride_level_string = false,\n\toverrides = {\n    season_start = \"default\",\n    loop = \"default\",\n    start_location = \"default\",\n    touchstone = \"default\",\n    roads = \"default\",\n    stageplays = \"default\",\n    terrariumchest = \"default\",\n    moon_fissure = \"default\",\n    prefabswaps_start = \"default\",\n    world_size = \"default\",\n    task_set = \"default\",\n    boons = \"default\",\n    branching = \"default\",\n    moon_sapling = \"default\",\n    meteorspawner = \"default\",\n    rock_ice = \"default\",\n    rock = \"default\",\n    mushroom = \"default\",\n    ocean_bullkelp = \"default\",\n    trees = \"default\",\n    flint = \"default\",\n    flowers = \"default\",\n    moon_starfish = \"default\",\n    marshbush = \"default\",\n    tumbleweed = \"default\",\n    reeds = \"default\",\n    moon_hotspring = \"default\",\n    moon_berrybush = \"default\",\n    berrybush = \"default\",\n    palmconetree = \"default\",\n    carrot = \"default\",\n    cactus = \"default\",\n    sapling = \"default\",\n    ponds = \"default\",\n    moon_bullkelp = \"default\",\n    moon_tree = \"default\",\n    grass = \"default\",\n    ocean_seastack = \"ocean_default\",\n    moon_rock = \"default\",\n    bees = \"default\",\n    ocean_shoal = \"default\",\n    pigs = \"default\",\n    moon_carrot = \"default\",\n    lightninggoat = \"default\",\n    moles = \"default\",\n    catcoon = \"default\",\n    rabbits = \"default\",\n    beefalo = \"default\",\n    buzzard = \"default\",\n    ocean_wobsterden = \"default\",\n    moon_fruitdragon = \"default\",\n    tentacles = \"default\",\n    tallbirds = \"default\",\n    angrybees = \"default\",\n    ocean_waterplant = \"ocean_default\",\n    houndmound = \"default\",\n    walrus = \"default\",\n    chess = \"default\",\n    merm = \"default\",\n    spiders = \"default\",\n    moon_spiders = \"default\",\n    spring = \"default\",\n    autumn = \"default\",\n    krampus = \"default\",\n    beefaloheat = \"default\",\n    summer = \"default\",\n    winter = \"default\",\n    ghostenabled = \"always\",\n    spawnmode = \"fixed\",\n    day = \"default\",\n    resettime = \"default\",\n    ghostsanitydrain = \"always\",\n    specialevent = \"default\",\n    portalresurection = \"none\",\n    year_of_the_beefalo = \"default\",\n    year_of_the_carrat = \"default\",\n    hallowed_nights = \"default\",\n    year_of_the_catcoon = \"default\",\n    year_of_the_varg = \"default\",\n    winters_feast = \"default\",\n    crow_carnival = \"default\",\n    year_of_the_gobbler = \"default\",\n    year_of_the_bunnyman = \"default\",\n    year_of_the_pig = \"default\",\n    spawnprotection = \"default\",\n    dropeverythingondespawn = \"default\",\n    healthpenalty = \"always\",\n    lessdamagetaken = \"none\",\n    brightmarecreatures = \"default\",\n    darkness = \"default\",\n    temperaturedamage = \"default\",\n    shadowcreatures = \"default\",\n    hunger = \"default\",\n    extrastartingitems = \"default\",\n    seasonalstartingitems = \"default\",\n    alternatehunt = \"default\",\n    frograin = \"default\",\n    meteorshowers = \"default\",\n    rifts_enabled = \"default\",\n    weather = \"default\",\n    hounds = \"default\",\n    wildfires = \"default\",\n    lightning = \"default\",\n    hunt = \"default\",\n    summerhounds = \"default\",\n    petrification = \"default\",\n    rifts_frequency = \"default\",\n    winterhounds = \"default\",\n    flowers_regrowth = \"default\",\n    basicresource_regrowth = \"none\",\n    twiggytrees_regrowth = \"default\",\n    moon_tree_regrowth = \"default\",\n    deciduoustree_regrowth = \"default\",\n    regrowth = \"default\",\n    reeds_regrowth = \"default\",\n    carrots_regrowth = \"default\",\n    palmconetree_regrowth = \"default\",\n    saltstack_regrowth = \"default\",\n    cactus_regrowth = \"default\",\n    evergreen_regrowth = \"default\",\n    lightcrab_portalrate = \"default\",\n    portal_spawnrate = \"default\",\n    powder_monkey_portalrate = \"default\",\n    palmcone_seed_portalrate = \"default\",\n    monkeytail_portalrate = \"default\",\n    bananabush_portalrate = \"default\",\n    penguins = \"default\",\n    perd = \"default\",\n    grassgekkos = \"default\",\n    birds = \"default\",\n    catcoons = \"default\",\n    moles_setting = \"default\",\n    bees_setting = \"default\",\n    fishschools = \"default\",\n    pigs_setting = \"default\",\n    rabbits_setting = \"default\",\n    bunnymen_setting = \"default\",\n    butterfly = \"default\",\n    gnarwail = \"default\",\n    wobsters = \"default\",\n    wasps = \"default\",\n    bats_setting = \"default\",\n    penguins_moon = \"default\",\n    lureplants = \"default\",\n    frogs = \"default\",\n    pirateraids = \"default\",\n    mutated_hounds = \"default\",\n    moon_spider = \"default\",\n    sharks = \"default\",\n    mosquitos = \"default\",\n    spider_warriors = \"default\",\n    hound_mounds = \"default\",\n    walrus_setting = \"default\",\n    squid = \"default\",\n    merms = \"default\",\n    cookiecutters = \"default\",\n    spiders_setting = \"default\",\n    crabking = \"default\",\n    antliontribute = \"default\",\n    malbatross = \"default\",\n    eyeofterror = \"default\",\n    liefs = \"default\",\n    spiderqueen = \"default\",\n    bearger = \"default\",\n    klaus = \"default\",\n    deciduousmonster = \"default\",\n    beequeen = \"default\",\n    dragonfly = \"default\",\n    goosemoose = \"default\",\n    fruitfly = \"default\",\n    deerclops = \"default\",\n    has_ocean = true,\n    keep_disconnected_tiles = true,\n    layout_mode = \"LinkNodesByKeys\",\n    no_joining_islands = true,\n    no_wormholes_to_disconnected_tiles = true,\n    wormhole_prefab = \"wormhole\",},\n\tplaystyle = \"endless\",\n\trandom_set_pieces = {\n\t\t\"Sculptures_2\",\n\t\t\"Sculptures_3\",\n\t\t\"Sculptures_4\",\n\t\t\"Sculptures_5\",\n\t\t\"Chessy_1\",\n\t\t\"Chessy_2\",\n\t\t\"Chessy_3\",\n\t\t\"Chessy_4\",\n\t\t\"Chessy_5\",\n\t\t\"Chessy_6\",\n\t\t\"Maxwell1\",\n\t\t\"Maxwell2\",\n\t\t\"Maxwell3\",\n\t\t\"Maxwell4\",\n\t\t\"Maxwell6\",\n\t\t\"Maxwell7\",\n\t\t\"Warzone_1\",\n\t\t\"Warzone_2\",\n\t\t\"Warzone_3\",\n\t},\n\trequired_prefabs = {\n\t\t\"multiplayer_portal\",\n\t},\n\trequired_setpieces = {\n\t\t\"Sculptures_1\",\n\t\t\"Maxwell5\",\n\t},\n\tsettings_desc = \"永不结束的饥荒沙盒模式。永远可以在绚丽之门复活。\",\n\tsettings_id = \"ENDLESS\",\n\tsettings_name = \"无尽\",\n\tsubstitutes = {},\n\tversion = 4,\n\tworldgen_desc = \"永不结束的饥荒沙盒模式。永远可以在绚丽之门复活。\",\n\tworldgen_id = \"ENDLESS\",\n\tworldgen_name = \"无尽\",\n}"
  },
  {
    "path": "static/Master/modoverrides.lua",
    "content": "return {  }"
  },
  {
    "path": "static/Master/server.ini",
    "content": "[NETWORK]\nserver_port = 10999\n\n\n[SHARD]\nis_master = true\nname = Master\nid = 1\n[ACCOUNT]\nencode_user_path = false\n"
  },
  {
    "path": "static/customcommands.lua",
    "content": "function list()\n    for i, v in ipairs(AllPlayers) do\n        print(string.format(\"[%d] (%s) %s <%s>\", i, v.userid, v.name, v.prefab))\n    end\nend\n\nfunction GetPlayerData(kuid, uuid)\n    local result = {\n        uuid = uuid,\n        kuid = kuid,\n        success = false,\n        error = nil,\n        data = {}\n    }\n    \n    -- 获取玩家\n    local player = UserToPlayer(kuid)\n    if not player then\n        result.error = \"Player not found with kuid: \" .. tostring(kuid)\n        return result\n    end\n    \n    result.success = true\n    \n    -- 基础信息\n    local data = {\n        name = player.name or player.prefab or \"Unknown\",\n        prefab = player.prefab,\n        health = {\n            current = player.components.health and player.components.health.currenthealth or 0,\n            max = player.components.health and player.components.health.maxhealth or 0,\n            percent = player.components.health and math.floor(player.components.health:GetPercent() * 100) or 0\n        },\n        hunger = {\n            current = player.components.hunger and player.components.hunger.current or 0,\n            max = player.components.hunger and player.components.hunger.max or 0,\n            percent = player.components.hunger and math.floor(player.components.hunger:GetPercent() * 100) or 0\n        },\n        sanity = {\n            current = player.components.sanity and player.components.sanity.current or 0,\n            max = player.components.sanity and player.components.sanity.max or 0,\n            percent = player.components.sanity and math.floor(player.components.sanity:GetPercent() * 100) or 0\n        },\n        temperature = player.components.temperature and math.floor(player.components.temperature.current) or 0,\n        moisture = player.components.moisture and math.floor(player.components.moisture:GetMoisture()) or 0\n    }\n    \n    local inv = player.components.inventory\n    \n    -- 手部装备\n    local handItem = inv:GetEquippedItem(EQUIPSLOTS.HANDS)\n    data.hand_equipment = handItem and {\n        prefab = handItem.prefab,\n        name = handItem.name or handItem.prefab,\n        count = handItem.components.stackable and handItem.components.stackable.stacksize or 1,\n        durability = handItem.components.finiteuses and math.floor(handItem.components.finiteuses:GetPercent() * 100) or nil,\n        fuel = handItem.components.fueled and math.floor(handItem.components.fueled:GetPercent() * 100) or nil\n    } or nil\n    \n    -- 头部装备\n    local headItem = inv:GetEquippedItem(EQUIPSLOTS.HEAD)\n    data.head_equipment = headItem and {\n        prefab = headItem.prefab,\n        name = headItem.name or headItem.prefab,\n        count = headItem.components.stackable and headItem.components.stackable.stacksize or 1,\n        durability = headItem.components.finiteuses and math.floor(headItem.components.finiteuses:GetPercent() * 100) or nil,\n        armor = headItem.components.armor and math.floor(headItem.components.armor:GetPercent() * 100) or nil\n    } or nil\n    \n    -- 身体装备（通常是背包或盔甲）\n    local bodyItem = inv:GetEquippedItem(EQUIPSLOTS.BODY)\n    local backpack = nil\n    \n    if bodyItem then\n        -- 判断是否为背包（有容器组件）\n        if bodyItem.components.container then\n            backpack = bodyItem\n            data.body_equipment = {\n                type = \"backpack\",\n                prefab = bodyItem.prefab,\n                name = bodyItem.name or bodyItem.prefab,\n                slots = bodyItem.components.container.numslots\n            }\n        else\n            -- 普通盔甲/衣服\n            data.body_equipment = {\n                type = \"armor\",\n                prefab = bodyItem.prefab,\n                name = bodyItem.name or bodyItem.prefab,\n                durability = bodyItem.components.armor and math.floor(bodyItem.components.armor:GetPercent() * 100) or nil\n            }\n        end\n    else\n        data.body_equipment = nil\n    end\n    \n    -- 背包物品\n    data.backpack_items = {}\n    if backpack and backpack.components.container then\n        local container = backpack.components.container\n        for i = 1, container.numslots do\n            local item = container.slots[i]\n            if item then\n                table.insert(data.backpack_items, {\n                    slot = i,\n                    prefab = item.prefab,\n                    name = item.name or item.prefab,\n                    count = item.components.stackable and item.components.stackable.stacksize or 1,\n                    freshness = item.components.perishable and math.floor(item.components.perishable:GetPercent() * 100) or nil,\n                    durability = item.components.finiteuses and math.floor(item.components.finiteuses:GetPercent() * 100) or nil\n                })\n            end\n        end\n    end\n    \n    -- 物品栏（15格）\n    data.inventory_items = {}\n    for i = 1, 15 do\n        local item = inv.itemslots[i]\n        if item then\n            table.insert(data.inventory_items, {\n                slot = i,\n                prefab = item.prefab,\n                name = item.name or item.prefab,\n                count = item.components.stackable and item.components.stackable.stacksize or 1,\n                freshness = item.components.perishable and math.floor(item.components.perishable:GetPercent() * 100) or nil,\n                durability = item.components.finiteuses and math.floor(item.components.finiteuses:GetPercent() * 100) or nil,\n                fuel = item.components.fueled and math.floor(item.components.fueled:GetPercent() * 100) or nil\n            })\n        end\n    end\n    \n    -- 统计信息\n    data.stats = {\n        inventory_count = #data.inventory_items,\n        backpack_count = #data.backpack_items,\n        total_items = #data.inventory_items + #data.backpack_items\n    }\n    \n    result.data = data\n    return result\nend\n\n-- JSON 编码辅助函数（简单版）\nfunction ToJSON(obj, indent)\n    indent = indent or 0\n    local spaces = string.rep(\"  \", indent)\n    local result = {}\n    \n    if type(obj) == \"table\" then\n        local isArray = #obj > 0\n        table.insert(result, isArray and \"[\" or \"{\")\n        \n        local items = {}\n        if isArray then\n            for _, v in ipairs(obj) do\n                table.insert(items, ToJSON(v, indent + 1))\n            end\n        else\n            for k, v in pairs(obj) do\n                local key = type(k) == \"string\" and ('\"' .. k .. '\":') or ('\"' .. tostring(k) .. '\":')\n                table.insert(items, spaces .. \"  \" .. key .. ToJSON(v, indent + 1))\n            end\n        end\n        \n        table.insert(result, table.concat(items, \",\\n\"))\n        table.insert(result, spaces .. (isArray and \"]\" or \"}\"))\n    elseif type(obj) == \"string\" then\n        return '\"' .. obj:gsub('\"', '\\\\\"') .. '\"'\n    elseif type(obj) == \"number\" or type(obj) == \"boolean\" then\n        return tostring(obj)\n    elseif obj == nil then\n        return \"null\"\n    end\n    \n    return table.concat(result, \"\\n\")\nend\n\n\n-- JSON 编码（压缩成一行）\nfunction ToJSONStr(obj)\n    local parts = {}\n    \n    local function serialize(o)\n        if type(o) == \"table\" then\n            local isArray = #o > 0\n            table.insert(parts, isArray and \"[\" or \"{\")\n            \n            local first = true\n            if isArray then\n                for _, v in ipairs(o) do\n                    if not first then table.insert(parts, \",\") end\n                    first = false\n                    serialize(v)\n                end\n            else\n                for k, v in pairs(o) do\n                    if not first then table.insert(parts, \",\") end\n                    first = false\n                    table.insert(parts, '\"' .. tostring(k) .. '\":')\n                    serialize(v)\n                end\n            end\n            \n            table.insert(parts, isArray and \"]\" or \"}\")\n        elseif type(o) == \"string\" then\n            -- 转义特殊字符\n            local s = o:gsub('\\\\', '\\\\\\\\'):gsub('\"', '\\\\\"'):gsub('\\n', '\\\\n'):gsub('\\r', '\\\\r'):gsub('\\t', '\\\\t')\n            table.insert(parts, '\"' .. s .. '\"')\n        elseif type(o) == \"number\" then\n            table.insert(parts, tostring(o))\n        elseif type(o) == \"boolean\" then\n            table.insert(parts, o and \"true\" or \"false\")\n        elseif o == nil then\n            table.insert(parts, \"null\")\n        end\n    end\n    \n    serialize(obj)\n    return table.concat(parts)\nend\n"
  },
  {
    "path": "static/template/caves_server.ini",
    "content": "[NETWORK]\nserver_port = {{.ServerPort}}\n\n\n[SHARD]\nis_master = {{.IsMaster}}\nname = {{.Name}}\nid = {{.Id}}\n\n\n[ACCOUNT]\nencode_user_path = {{.EncodeUserPath}}\n\n"
  },
  {
    "path": "static/template/cluster.ini",
    "content": "[GAMEPLAY]\n#游戏模式，可选 survival，endless，wilderness\ngame_mode = {{.GameMode}}\n#最大玩家人数 （上限16）\nmax_players = {{.MaxPlayers}}\n#是否开启玩家对战\npvp = {{.Pvp}}\n#没人时服务器暂停\npause_when_empty = {{.PauseWhenNobody}}\n#投票重启世界\nvote_enabled = {{.VoteEnabled}}\n#投票踢人\nvote_kick_enabled = false\n\n[NETWORK]\n#局域网游戏\nlan_only_cluster = false\n#游戏偏好 cooperative，competitive，social，madness\ncluster_intention = {{.ClusterIntention}}\n#服务器密码\ncluster_password = {{.ClusterPassword}}\n#服务器描述\ncluster_description = {{.ClusterDescription}}\n#服务器名称\ncluster_name = {{.ClusterName}}\n#离线服务器，只有局域网用户能加入，并且依赖所有Steam的任何功能都失效，比如礼物掉落\noffline_cluster = false\n#服务器语言\ncluster_language = zh\n#预留位\nwhitelist_slots = 0\n#每秒通信次数，越高体验越好，但是会增大服务负担\ntick_rate = 15\n\n[MISC]\n#是否开启控制台\nconsole_enabled = true\n#最大快照数量\nmax_snapshots = {{.MaxSnapshots}}\n\n\n[SHARD]\n#服务器共享，开启洞穴必须要开启这个\nshard_enabled = true\n#服务器监听的地址，当所有实例都运行在同一台机器，可填写 127.0.0.1，会被server.ini 覆盖\nbind_ip = 127.0.0.1\n#master 服务器的 IP，针对非 master 服务器，若与 master 服务器运行在同一台机器时，可填写 127.0.0.1，会被 server.ini 覆盖\nmaster_ip = 127.0.0.1\n#监听 master 服务器的 UDP 端口，所有连接至 master 服务器的非 master 服务器必须相同\nmaster_port = 10888\n#连接密码，每台服务器必须相同，会被server.ini 覆盖\ncluster_key = defaultPass\n\n\n[STEAM]\nsteam_group_only = false           # 只允许某 Steam 组的成员加入\nsteam_group_id = 0                 # 指定某个 Steam 组，填写组 ID\nsteam_group_admins = false         # 开启后，Steam 组的管理员拥有服务器的管理权限"
  },
  {
    "path": "static/template/cluster2.ini",
    "content": "[GAMEPLAY]\n#游戏模式，可选 survival，endless，wilderness\ngame_mode = {{.GameMode}}\n#最大玩家人数 （上限16）\nmax_players = {{.MaxPlayers}}\n#是否开启玩家对战\npvp = {{.Pvp}}\n#没人时服务器暂停\npause_when_empty = {{.PauseWhenNobody}}\n#投票重启世界\nvote_enabled = {{.VoteEnabled}}\n#投票踢人\nvote_kick_enabled = {{.VoteKickEnabled}}\n\n[NETWORK]\n#局域网游戏\nlan_only_cluster = {{.LanOnlyCluster}}\n#游戏偏好 cooperative，competitive，social，madness\ncluster_intention = {{.ClusterIntention}}\n#服务器密码\ncluster_password = {{.ClusterPassword}}\n#服务器描述\ncluster_description = {{.ClusterDescription}}\n#服务器名称\ncluster_name = {{.ClusterName}}\n#离线服务器，只有局域网用户能加入，并且依赖所有Steam的任何功能都失效，比如礼物掉落\noffline_cluster = {{.OfflineCluster}}\n#服务器语言\ncluster_language = {{.ClusterLanguage}}\n#预留位\nwhitelist_slots = {{.WhitelistSlots}}\n#每秒通信次数，越高体验越好，但是会增大服务负担\ntick_rate = {{.TickRate}}\n\n[MISC]\n#是否开启控制台\nconsole_enabled = {{.ConsoleEnabled}}\n#最大快照数量\nmax_snapshots = {{.MaxSnapshots}}\n\n\n[SHARD]\n#服务器共享，开启洞穴必须要开启这个\nshard_enabled = {{.ShardEnabled}}\n#服务器监听的地址，当所有实例都运行在同一台机器，可填写 127.0.0.1，会被server.ini 覆盖\nbind_ip = {{.BindIp}}\n#master 服务器的 IP，针对非 master 服务器，若与 master 服务器运行在同一台机器时，可填写 127.0.0.1，会被 server.ini 覆盖\nmaster_ip = {{.MasterIp}}\n#监听 master 服务器的 UDP 端口，所有连接至 master 服务器的非 master 服务器必须相同\nmaster_port = {{.MasterPort}}\n#连接密码，每台服务器必须相同，会被server.ini 覆盖\ncluster_key = {{.ClusterKey}}\n\n\n[STEAM]\n# 只允许某 Steam 组的成员加入\nsteam_group_only = {{.SteamGroupOnly}}\n# 指定某个 Steam 组，填写组 ID           \nsteam_group_id = {{.SteamGroupId}}\n# 开启后，Steam 组的管理员拥有服务器的管理权限             \nsteam_group_admins = {{.SteamGroupAdmins}}\n"
  },
  {
    "path": "static/template/master_server.ini",
    "content": "[NETWORK]\nserver_port = {{.ServerPort}}\n\n\n[SHARD]\nis_master = {{.IsMaster}}\nname = {{.Name}}\nid = {{.Id}}\n\n\n[ACCOUNT]\nencode_user_path = {{.EncodeUserPath}}"
  },
  {
    "path": "static/template/server.ini",
    "content": "[NETWORK]\nserver_port = {{.ServerPort}}\n\n\n[SHARD]\nis_master = {{.IsMaster}}\nname = {{.Name}}\nid = {{.Id}}\n\n\n[ACCOUNT]\nencode_user_path = {{.EncodeUserPath}}\n\n\n[STEAM]\nmaster_server_port = {{.MasterServerPort}}\nauthentication_port = {{.AuthenticationPort}}"
  },
  {
    "path": "static/template/test.go",
    "content": "package main\n\nimport (\n\t\"bytes\"\n\t\"dst-admin-go/vo\"\n\t\"fmt\"\n\t\"text/template\"\n\n\t\"github.com/shirou/gopsutil/disk\"\n\t\"github.com/shirou/gopsutil/host\"\n\t\"github.com/shirou/gopsutil/mem\"\n)\n\nfunc main() {\n\n\tGetHostInfo()\n\tGetCpuInfo()\n\tGetMemInfo()\n\tGetDiskInfo()\n\n\ttmpl, err := template.ParseFiles(\"cluster.ini\")\n\tCheckErr(err)\n\tbuf := new(bytes.Buffer)\n\tgameConfigVo := vo.GameConfigVO{\n\t\tClusterIntention:   \"这是一个测试\",\n\t\tClusterName:        \"饥荒萌萌哒\",\n\t\tClusterDescription: \"一起来玩啊\",\n\t\tGameMode:           \"endless\",\n\t\tPvp:                false,\n\t\tMaxPlayers:         6,\n\t\tToken:              \"dadmam,dman,dmna m,dnamd\",\n\t\tPauseWhenNobody:    false,\n\t}\n\ttmpl.Execute(buf, gameConfigVo)\n\tfmt.Printf(\"buf.String():\\n%v\\n\", buf.String())\n}\n\nfunc CheckErr(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc GetHostInfo() {\n\tinfo, _ := host.Info()\n\tfmt.Println(info)\n}\n\nfunc GetCpuInfo() {\n\n}\n\nfunc GetMemInfo() {\n\tv, _ := mem.VirtualMemory()\n\n\t// almost every return value is a struct\n\tfmt.Printf(\"Total: %v, Free:%v, UsedPercent:%f%%\\n\", v.Total, v.Free, v.UsedPercent)\n\n\t// convert to JSON. String() is also implemented\n\t//fmt.Println(v)\n}\n\nfunc GetDiskInfo() {\n\t//info, _ := disk.IOCounters() //所有硬盘的io信息\n\tdiskPart, err := disk.Partitions(false)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\t// fmt.Println(diskPart)\n\tfor _, dp := range diskPart {\n\t\tfmt.Println(dp)\n\t\tdiskUsed, _ := disk.Usage(dp.Mountpoint)\n\t\tfmt.Printf(\"分区总大小: %d MB \\n\", diskUsed.Total/1024/1024)\n\t\tfmt.Printf(\"分区使用率: %.3f %% \\n\", diskUsed.UsedPercent)\n\t\tfmt.Printf(\"分区inode使用率: %.3f %% \\n\", diskUsed.InodesUsedPercent)\n\t}\n}\n"
  }
]