feat: 脚本创作+发布+市场体系

- 数据模型新增: title(必填), description(可选), status(draft/published)
- 新增 API: POST /scripts/:id/publish, GET /api/market (搜索+分页+runtime过滤)
- 前端首页重构: 选语言 → CodeMirror 编辑器(8种语言语法高亮) → 标题/描述 → 草稿/发布
- 新增 /market 页面: 浏览已发布脚本, 搜索+过滤+分页
- 详情页新增: 发布按钮(草稿→市场), title/description 展示
- Shell 类运行时显示 source 命令(继承环境变量)
- backend GetSourceCommand 支持 bash/zsh/sh/fish 四种 shell 格式

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-05-29 14:04:15 +08:00
parent e3d380f9ab
commit e6e4357a28
16 changed files with 1051 additions and 183 deletions

View File

@@ -38,7 +38,9 @@ func main() {
api.Use(middleware.RateLimit(60))
api.POST("/scripts", middleware.RateLimit(10), handler.CreateScript(svc))
api.GET("/scripts/:id", handler.GetScript(svc))
api.POST("/scripts/:id/publish", handler.PublishScript(svc))
api.DELETE("/scripts/:id", handler.DeleteScript(svc))
api.GET("/market", handler.ListMarket(svc))
}
r.GET("/raw/:id", handler.GetRawScript(svc))

View File

@@ -35,3 +35,24 @@ func GetRuntime(name string) (RuntimeConfig, bool) {
rt, ok := RuntimeMap[name]
return rt, ok
}
func IsShellRuntime(name string) bool {
switch name {
case "bash", "zsh", "sh", "fish":
return true
}
return false
}
func GetSourceCommand(url, runtime string) string {
switch runtime {
case "bash", "zsh":
return "source <(curl " + url + ")"
case "sh":
return ". <(curl " + url + ")"
case "fish":
return "curl " + url + " | source"
default:
return ""
}
}

View File

@@ -3,6 +3,7 @@ package handler
import (
"errors"
"net/http"
"strconv"
"strings"
"github.com/gin-gonic/gin"
@@ -11,9 +12,12 @@ import (
)
type createRequest struct {
Content string `json:"content" binding:"required,max=16384"`
Runtime string `json:"runtime" binding:"required"`
ExpiresIn string `json:"expires_in" binding:"required,oneof=1h 24h 7d 30d"`
Title string `json:"title" binding:"required,max=128"`
Description string `json:"description" binding:"max=512"`
Content string `json:"content" binding:"required,max=16384"`
Runtime string `json:"runtime" binding:"required"`
ExpiresIn string `json:"expires_in" binding:"required,oneof=1h 24h 7d 30d"`
Publish bool `json:"publish"`
}
func CreateScript(svc *service.ScriptService) gin.HandlerFunc {
@@ -30,13 +34,16 @@ func CreateScript(svc *service.ScriptService) gin.HandlerFunc {
}
result, err := svc.Create(service.CreateInput{
Content: req.Content,
Runtime: req.Runtime,
ExpiresIn: req.ExpiresIn,
Title: req.Title,
Description: req.Description,
Content: req.Content,
Runtime: req.Runtime,
ExpiresIn: req.ExpiresIn,
Publish: req.Publish,
}, scheme, c.Request.Host)
if errors.Is(err, service.ErrInvalidRuntime) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid runtime, supported: bash, zsh, sh, fish, python3, node, ruby, php"})
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid runtime"})
return
}
if err != nil {
@@ -45,12 +52,16 @@ func CreateScript(svc *service.ScriptService) gin.HandlerFunc {
}
c.JSON(http.StatusCreated, gin.H{
"id": result.Script.ID,
"admin_token": result.AdminToken,
"url": result.RawURL,
"command": result.Command,
"runtime": result.Script.Runtime,
"expires_at": result.Script.ExpiresAt,
"id": result.Script.ID,
"title": result.Script.Title,
"description": result.Script.Description,
"admin_token": result.AdminToken,
"url": result.RawURL,
"command": result.Command,
"source_command": result.SourceCmd,
"runtime": result.Script.Runtime,
"status": result.Script.Status,
"expires_at": result.Script.ExpiresAt,
})
}
}
@@ -71,16 +82,89 @@ func GetScript(svc *service.ScriptService) gin.HandlerFunc {
c.JSON(http.StatusOK, gin.H{
"id": script.ID,
"title": script.Title,
"description": script.Description,
"runtime": script.Runtime,
"content": script.Content,
"content_length": len(script.Content),
"status": script.Status,
"created_at": script.CreatedAt,
"expires_at": script.ExpiresAt,
"published_at": script.PublishedAt,
"expired": false,
})
}
}
func PublishScript(svc *service.ScriptService) gin.HandlerFunc {
return func(c *gin.Context) {
id := c.Param("id")
token := c.Query("token")
if token == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "token query parameter is required"})
return
}
script, err := svc.Publish(id, token)
if errors.Is(err, service.ErrNotFound) {
c.JSON(http.StatusNotFound, gin.H{"error": "script not found or invalid token"})
return
}
if errors.Is(err, service.ErrAlreadyPublished) {
c.JSON(http.StatusBadRequest, gin.H{"error": "script already published"})
return
}
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
c.JSON(http.StatusOK, gin.H{
"id": script.ID,
"status": script.Status,
"published_at": script.PublishedAt,
})
}
}
func ListMarket(svc *service.ScriptService) gin.HandlerFunc {
return func(c *gin.Context) {
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
perPage, _ := strconv.Atoi(c.DefaultQuery("per_page", "20"))
runtime := c.Query("runtime")
search := c.Query("search")
result, err := svc.ListMarket(service.MarketQuery{
Page: page,
PerPage: perPage,
Runtime: runtime,
Search: search,
})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
items := make([]gin.H, len(result.Items))
for i, s := range result.Items {
items[i] = gin.H{
"id": s.ID,
"title": s.Title,
"description": s.Description,
"runtime": s.Runtime,
"published_at": s.PublishedAt,
}
}
c.JSON(http.StatusOK, gin.H{
"items": items,
"total": result.Total,
"page": result.Page,
"per_page": result.PerPage,
})
}
}
func DeleteScript(svc *service.ScriptService) gin.HandlerFunc {
return func(c *gin.Context) {
id := c.Param("id")
@@ -100,4 +184,4 @@ func DeleteScript(svc *service.ScriptService) gin.HandlerFunc {
c.Status(http.StatusNoContent)
}
}
}

View File

@@ -3,10 +3,14 @@ package model
import "time"
type Script struct {
ID string `gorm:"primaryKey;size:8"`
Content string `gorm:"type:text;not null"`
Runtime string `gorm:"size:16;not null;index"`
AdminToken string `gorm:"size:64;not null"`
ExpiresAt time.Time `gorm:"not null;index"`
CreatedAt time.Time `gorm:"not null;autoCreateTime"`
}
ID string `gorm:"primaryKey;size:8"`
Title string `gorm:"size:128;not null"`
Description string `gorm:"size:512"`
Content string `gorm:"type:text;not null"`
Runtime string `gorm:"size:16;not null;index"`
AdminToken string `gorm:"size:64;not null"`
Status string `gorm:"size:16;not null;default:draft;index"`
ExpiresAt time.Time `gorm:"not null;index"`
CreatedAt time.Time `gorm:"not null;autoCreateTime"`
PublishedAt *time.Time `gorm:"index"`
}

View File

@@ -14,6 +14,7 @@ import (
var (
ErrInvalidRuntime = errors.New("invalid runtime")
ErrNotFound = errors.New("script not found or expired")
ErrAlreadyPublished = errors.New("script already published")
)
type ScriptService struct {
@@ -25,15 +26,19 @@ func NewScriptService(db *gorm.DB) *ScriptService {
}
type CreateInput struct {
Content string
Runtime string
ExpiresIn string
Title string
Description string
Content string
Runtime string
ExpiresIn string
Publish bool
}
type CreateResult struct {
Script model.Script
AdminToken string
Command string
SourceCmd string
RawURL string
}
@@ -66,13 +71,25 @@ func (s *ScriptService) Create(input CreateInput, scheme, host string) (*CreateR
return nil, err
}
status := "draft"
var publishedAt *time.Time
if input.Publish {
status = "published"
now := time.Now()
publishedAt = &now
}
script := model.Script{
ID: id,
Content: input.Content,
Runtime: input.Runtime,
AdminToken: adminToken,
ExpiresAt: time.Now().Add(d),
CreatedAt: time.Now(),
ID: id,
Title: input.Title,
Description: input.Description,
Content: input.Content,
Runtime: input.Runtime,
AdminToken: adminToken,
Status: status,
ExpiresAt: time.Now().Add(d),
CreatedAt: time.Now(),
PublishedAt: publishedAt,
}
if err := s.db.Create(&script).Error; err != nil {
@@ -81,11 +98,13 @@ func (s *ScriptService) Create(input CreateInput, scheme, host string) (*CreateR
rawURL := scheme + "://" + host + "/raw/" + id
command := "curl " + rawURL + " | " + input.Runtime
sourceCmd := config.GetSourceCommand(rawURL, input.Runtime)
return &CreateResult{
Script: script,
AdminToken: adminToken,
Command: command,
SourceCmd: sourceCmd,
RawURL: rawURL,
}, nil
}
@@ -99,6 +118,79 @@ func (s *ScriptService) GetByID(id string) (*model.Script, error) {
return &script, err
}
func (s *ScriptService) Publish(id, token string) (*model.Script, error) {
var script model.Script
err := s.db.Where("id = ? AND admin_token = ? AND expires_at > ?", id, token, time.Now()).First(&script).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
if script.Status == "published" {
return nil, ErrAlreadyPublished
}
now := time.Now()
script.Status = "published"
script.PublishedAt = &now
if err := s.db.Save(&script).Error; err != nil {
return nil, err
}
return &script, nil
}
type MarketQuery struct {
Page int
PerPage int
Runtime string
Search string
}
type MarketResult struct {
Items []model.Script
Total int64
Page int
PerPage int
}
func (s *ScriptService) ListMarket(q MarketQuery) (*MarketResult, error) {
if q.Page < 1 {
q.Page = 1
}
if q.PerPage < 1 || q.PerPage > 50 {
q.PerPage = 20
}
query := s.db.Model(&model.Script{}).
Where("status = ? AND expires_at > ?", "published", time.Now())
if q.Runtime != "" && config.IsValidRuntime(q.Runtime) {
query = query.Where("runtime = ?", q.Runtime)
}
if q.Search != "" {
search := "%" + q.Search + "%"
query = query.Where("title LIKE ? OR description LIKE ?", search, search)
}
var total int64
query.Count(&total)
var scripts []model.Script
err := query.Order("published_at DESC").
Offset((q.Page - 1) * q.PerPage).
Limit(q.PerPage).
Find(&scripts).Error
return &MarketResult{
Items: scripts,
Total: total,
Page: q.Page,
PerPage: q.PerPage,
}, err
}
func (s *ScriptService) Delete(id, token string) error {
result := s.db.Where("id = ? AND admin_token = ?", id, token).Delete(&model.Script{})
if result.RowsAffected == 0 {
@@ -110,4 +202,4 @@ func (s *ScriptService) Delete(id, token string) error {
func (s *ScriptService) CleanupExpired() (int64, error) {
result := s.db.Where("expires_at <= ?", time.Now()).Delete(&model.Script{})
return result.RowsAffected, result.Error
}
}

View File

@@ -8,6 +8,19 @@
"name": "scriptforge-frontend",
"version": "0.1.0",
"dependencies": {
"@codemirror/autocomplete": "^6.20.2",
"@codemirror/commands": "^6.10.3",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/lang-php": "^6.0.2",
"@codemirror/lang-python": "^6.2.1",
"@codemirror/language": "^6.12.3",
"@codemirror/legacy-modes": "^6.5.3",
"@codemirror/lint": "^6.9.6",
"@codemirror/search": "^6.7.0",
"@codemirror/state": "^6.6.0",
"@codemirror/theme-one-dark": "^6.1.3",
"@codemirror/view": "^6.43.0",
"codemirror": "^6.0.2",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.0"
@@ -318,6 +331,179 @@
"node": ">=6.9.0"
}
},
"node_modules/@codemirror/autocomplete": {
"version": "6.20.2",
"resolved": "https://registry.npmmirror.com/@codemirror/autocomplete/-/autocomplete-6.20.2.tgz",
"integrity": "sha512-G5FPkgIiLjOgZMjqVjvuKQ1rGPtHogLldJr33eFJdVLtmwY+giGrlv/ewljLz6b9BSQLkjxuwBc6g6omDM+YxQ==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0"
}
},
"node_modules/@codemirror/commands": {
"version": "6.10.3",
"resolved": "https://registry.npmmirror.com/@codemirror/commands/-/commands-6.10.3.tgz",
"integrity": "sha512-JFRiqhKu+bvSkDLI+rUhJwSxQxYb759W5GBezE8Uc8mHLqC9aV/9aTC7yJSqCtB3F00pylrLCwnyS91Ap5ej4Q==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.6.0",
"@codemirror/view": "^6.27.0",
"@lezer/common": "^1.1.0"
}
},
"node_modules/@codemirror/lang-css": {
"version": "6.3.1",
"resolved": "https://registry.npmmirror.com/@codemirror/lang-css/-/lang-css-6.3.1.tgz",
"integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@lezer/common": "^1.0.2",
"@lezer/css": "^1.1.7"
}
},
"node_modules/@codemirror/lang-html": {
"version": "6.4.11",
"resolved": "https://registry.npmmirror.com/@codemirror/lang-html/-/lang-html-6.4.11.tgz",
"integrity": "sha512-9NsXp7Nwp891pQchI7gPdTwBuSuT3K65NGTHWHNJ55HjYcHLllr0rbIZNdOzas9ztc1EUVBlHou85FFZS4BNnw==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/lang-css": "^6.0.0",
"@codemirror/lang-javascript": "^6.0.0",
"@codemirror/language": "^6.4.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0",
"@lezer/css": "^1.1.0",
"@lezer/html": "^1.3.12"
}
},
"node_modules/@codemirror/lang-javascript": {
"version": "6.2.5",
"resolved": "https://registry.npmmirror.com/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz",
"integrity": "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/language": "^6.6.0",
"@codemirror/lint": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0",
"@lezer/javascript": "^1.0.0"
}
},
"node_modules/@codemirror/lang-php": {
"version": "6.0.2",
"resolved": "https://registry.npmmirror.com/@codemirror/lang-php/-/lang-php-6.0.2.tgz",
"integrity": "sha512-ZKy2v1n8Fc8oEXj0Th0PUMXzQJ0AIR6TaZU+PbDHExFwdu+guzOA4jmCHS1Nz4vbFezwD7LyBdDnddSJeScMCA==",
"license": "MIT",
"dependencies": {
"@codemirror/lang-html": "^6.0.0",
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@lezer/common": "^1.0.0",
"@lezer/php": "^1.0.0"
}
},
"node_modules/@codemirror/lang-python": {
"version": "6.2.1",
"resolved": "https://registry.npmmirror.com/@codemirror/lang-python/-/lang-python-6.2.1.tgz",
"integrity": "sha512-IRjC8RUBhn9mGR9ywecNhB51yePWCGgvHfY1lWN/Mrp3cKuHr0isDKia+9HnvhiWNnMpbGhWrkhuWOc09exRyw==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.3.2",
"@codemirror/language": "^6.8.0",
"@codemirror/state": "^6.0.0",
"@lezer/common": "^1.2.1",
"@lezer/python": "^1.1.4"
}
},
"node_modules/@codemirror/language": {
"version": "6.12.3",
"resolved": "https://registry.npmmirror.com/@codemirror/language/-/language-6.12.3.tgz",
"integrity": "sha512-QwCZW6Tt1siP37Jet9Tb02Zs81TQt6qQrZR2H+eGMcFsL1zMrk2/b9CLC7/9ieP1fjIUMgviLWMmgiHoJrj+ZA==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.23.0",
"@lezer/common": "^1.5.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0",
"style-mod": "^4.0.0"
}
},
"node_modules/@codemirror/legacy-modes": {
"version": "6.5.3",
"resolved": "https://registry.npmmirror.com/@codemirror/legacy-modes/-/legacy-modes-6.5.3.tgz",
"integrity": "sha512-xCsmIzH78MyWkib9jlPaaun57XNkfbMIhagfaZVd0iLTqlpw3jXaIcbZm72MTmmn64eTZpBVNjbyYh+QXnxRsg==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0"
}
},
"node_modules/@codemirror/lint": {
"version": "6.9.6",
"resolved": "https://registry.npmmirror.com/@codemirror/lint/-/lint-6.9.6.tgz",
"integrity": "sha512-6Kp7r6XfCi/D/5sdXieMfg9pJU1bUEx96WITuLU6ESaKizCz0QHFMjY/TaFSbigDdEAIgi93itLBIUETP4oK+A==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.42.0",
"crelt": "^1.0.5"
}
},
"node_modules/@codemirror/search": {
"version": "6.7.0",
"resolved": "https://registry.npmmirror.com/@codemirror/search/-/search-6.7.0.tgz",
"integrity": "sha512-ZvGm99wc/s2cITtMT15LFdn8aH/aS+V+DqyGq/N5ZlV5vWtH+nILvC2nw0zX7ByNoHHDZ2IxxdW38O0tc5nVHg==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.37.0",
"crelt": "^1.0.5"
}
},
"node_modules/@codemirror/state": {
"version": "6.6.0",
"resolved": "https://registry.npmmirror.com/@codemirror/state/-/state-6.6.0.tgz",
"integrity": "sha512-4nbvra5R5EtiCzr9BTHiTLc+MLXK2QGiAVYMyi8PkQd3SR+6ixar/Q/01Fa21TBIDOZXgeWV4WppsQolSreAPQ==",
"license": "MIT",
"dependencies": {
"@marijn/find-cluster-break": "^1.0.0"
}
},
"node_modules/@codemirror/theme-one-dark": {
"version": "6.1.3",
"resolved": "https://registry.npmmirror.com/@codemirror/theme-one-dark/-/theme-one-dark-6.1.3.tgz",
"integrity": "sha512-NzBdIvEJmx6fjeremiGp3t/okrLPYT0d9orIc7AFun8oZcRk58aejkqhv6spnz4MLAevrKNPMQYXEWMg4s+sKA==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.0.0",
"@lezer/highlight": "^1.0.0"
}
},
"node_modules/@codemirror/view": {
"version": "6.43.0",
"resolved": "https://registry.npmmirror.com/@codemirror/view/-/view-6.43.0.tgz",
"integrity": "sha512-V7ZCLQO3Jus9hzh2jVCCPW3mO4IBMr43O37PqSUYautJSnnJF41YlgLw21x0fLJTYvJ+Vkm6Gp+qKGH9pltgXA==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.6.0",
"crelt": "^1.0.6",
"style-mod": "^4.1.0",
"w3c-keyname": "^2.2.4"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.21.5",
"resolved": "https://registry.npmmirror.com/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
@@ -759,6 +945,91 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@lezer/common": {
"version": "1.5.2",
"resolved": "https://registry.npmmirror.com/@lezer/common/-/common-1.5.2.tgz",
"integrity": "sha512-sxQE460fPZyU3sdc8lafxiPwJHBzZRy/udNFynGQky1SePYBdhkBl1kOagA9uT3pxR8K09bOrmTUqA9wb/PjSQ==",
"license": "MIT"
},
"node_modules/@lezer/css": {
"version": "1.3.3",
"resolved": "https://registry.npmmirror.com/@lezer/css/-/css-1.3.3.tgz",
"integrity": "sha512-RzBo8r+/6QJeow7aPHIpGVIH59xTcJXp399820gZoMo9noQDRVpJLheIBUicYwKcsbOYoBRoLZlf2720dG/4Tg==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.3.0"
}
},
"node_modules/@lezer/highlight": {
"version": "1.2.3",
"resolved": "https://registry.npmmirror.com/@lezer/highlight/-/highlight-1.2.3.tgz",
"integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.3.0"
}
},
"node_modules/@lezer/html": {
"version": "1.3.13",
"resolved": "https://registry.npmmirror.com/@lezer/html/-/html-1.3.13.tgz",
"integrity": "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0"
}
},
"node_modules/@lezer/javascript": {
"version": "1.5.4",
"resolved": "https://registry.npmmirror.com/@lezer/javascript/-/javascript-1.5.4.tgz",
"integrity": "sha512-vvYx3MhWqeZtGPwDStM2dwgljd5smolYD2lR2UyFcHfxbBQebqx8yjmFmxtJ/E6nN6u1D9srOiVWm3Rb4tmcUA==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.1.3",
"@lezer/lr": "^1.3.0"
}
},
"node_modules/@lezer/lr": {
"version": "1.4.10",
"resolved": "https://registry.npmmirror.com/@lezer/lr/-/lr-1.4.10.tgz",
"integrity": "sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.0.0"
}
},
"node_modules/@lezer/php": {
"version": "1.0.5",
"resolved": "https://registry.npmmirror.com/@lezer/php/-/php-1.0.5.tgz",
"integrity": "sha512-W7asp9DhM6q0W6DYNwIkLSKOvxlXRrif+UXBMxzsJUuqmhE7oVU+gS3THO4S/Puh7Xzgm858UNaFi6dxTP8dJA==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.1.0"
}
},
"node_modules/@lezer/python": {
"version": "1.1.19",
"resolved": "https://registry.npmmirror.com/@lezer/python/-/python-1.1.19.tgz",
"integrity": "sha512-MhQIURHRytsNzP/YXnqpYKW6la6voAH3kyplTOOiCdjyFY6cWWGFVmYVdHIPrElqSDf4iCDktQCockB9FxuhzQ==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0"
}
},
"node_modules/@marijn/find-cluster-break": {
"version": "1.0.2",
"resolved": "https://registry.npmmirror.com/@marijn/find-cluster-break/-/find-cluster-break-1.0.2.tgz",
"integrity": "sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==",
"license": "MIT"
},
"node_modules/@nodelib/fs.scandir": {
"version": "2.1.5",
"resolved": "https://registry.npmmirror.com/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
@@ -1471,6 +1742,21 @@
"node": ">= 6"
}
},
"node_modules/codemirror": {
"version": "6.0.2",
"resolved": "https://registry.npmmirror.com/codemirror/-/codemirror-6.0.2.tgz",
"integrity": "sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/commands": "^6.0.0",
"@codemirror/language": "^6.0.0",
"@codemirror/lint": "^6.0.0",
"@codemirror/search": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.0.0"
}
},
"node_modules/commander": {
"version": "4.1.1",
"resolved": "https://registry.npmmirror.com/commander/-/commander-4.1.1.tgz",
@@ -1488,6 +1774,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/crelt": {
"version": "1.0.6",
"resolved": "https://registry.npmmirror.com/crelt/-/crelt-1.0.6.tgz",
"integrity": "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==",
"license": "MIT"
},
"node_modules/cssesc": {
"version": "3.0.0",
"resolved": "https://registry.npmmirror.com/cssesc/-/cssesc-3.0.0.tgz",
@@ -2434,6 +2726,12 @@
"node": ">=0.10.0"
}
},
"node_modules/style-mod": {
"version": "4.1.3",
"resolved": "https://registry.npmmirror.com/style-mod/-/style-mod-4.1.3.tgz",
"integrity": "sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==",
"license": "MIT"
},
"node_modules/sucrase": {
"version": "3.35.1",
"resolved": "https://registry.npmmirror.com/sucrase/-/sucrase-3.35.1.tgz",
@@ -2711,6 +3009,12 @@
}
}
},
"node_modules/w3c-keyname": {
"version": "2.2.8",
"resolved": "https://registry.npmmirror.com/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
"integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
"license": "MIT"
},
"node_modules/yallist": {
"version": "3.1.1",
"resolved": "https://registry.npmmirror.com/yallist/-/yallist-3.1.1.tgz",

View File

@@ -9,6 +9,19 @@
"preview": "vite preview"
},
"dependencies": {
"@codemirror/autocomplete": "^6.20.2",
"@codemirror/commands": "^6.10.3",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/lang-php": "^6.0.2",
"@codemirror/lang-python": "^6.2.1",
"@codemirror/language": "^6.12.3",
"@codemirror/legacy-modes": "^6.5.3",
"@codemirror/lint": "^6.9.6",
"@codemirror/search": "^6.7.0",
"@codemirror/state": "^6.6.0",
"@codemirror/theme-one-dark": "^6.1.3",
"@codemirror/view": "^6.43.0",
"codemirror": "^6.0.2",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.0"

View File

@@ -2,6 +2,7 @@ import { Routes, Route, Link } from 'react-router-dom'
import Home from './pages/Home'
import ScriptDetail from './pages/ScriptDetail'
import DeleteScript from './pages/DeleteScript'
import Market from './pages/Market'
export default function App() {
return (
@@ -11,13 +12,17 @@ export default function App() {
<Link to="/" className="text-xl font-bold tracking-tight hover:text-blue-400 transition-colors">
<span className="text-blue-500"></span> ScriptForge
</Link>
<span className="text-sm text-gray-500"></span>
<nav className="flex gap-4 text-sm">
<Link to="/" className="text-gray-400 hover:text-blue-400 transition-colors"></Link>
<Link to="/market" className="text-gray-400 hover:text-blue-400 transition-colors"></Link>
</nav>
</div>
</header>
<main className="flex-1 max-w-4xl mx-auto px-4 py-8 w-full">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/market" element={<Market />} />
<Route path="/s/:id" element={<ScriptDetail />} />
<Route path="/s/:id/delete" element={<DeleteScript />} />
</Routes>
@@ -28,4 +33,4 @@ export default function App() {
</footer>
</div>
)
}
}

View File

@@ -0,0 +1,105 @@
import { useEffect, useRef } from 'react'
import { EditorState } from '@codemirror/state'
import { EditorView, keymap, lineNumbers, highlightActiveLine } from '@codemirror/view'
import { defaultKeymap, indentWithTab, history, historyKeymap } from '@codemirror/commands'
import { syntaxHighlighting, defaultHighlightStyle, bracketMatching, foldGutter, indentOnInput, StreamLanguage } from '@codemirror/language'
import { python } from '@codemirror/lang-python'
import { javascript } from '@codemirror/lang-javascript'
import { php } from '@codemirror/lang-php'
import { oneDark } from '@codemirror/theme-one-dark'
import { closeBrackets, closeBracketsKeymap } from '@codemirror/autocomplete'
import { lintKeymap } from '@codemirror/lint'
import { searchKeymap, highlightSelectionMatches } from '@codemirror/search'
// Legacy mode imports - use require-style to avoid TS path issues
// @ts-ignore
import { shell } from '@codemirror/legacy-modes/mode/shell'
// @ts-ignore
import { ruby } from '@codemirror/legacy-modes/mode/ruby'
function getLanguageExtension(runtime: string) {
switch (runtime) {
case 'bash': case 'zsh': case 'sh': case 'fish':
return StreamLanguage.define(shell)
case 'python3':
return python()
case 'node':
return javascript()
case 'ruby':
return StreamLanguage.define(ruby)
case 'php':
return php()
default:
return StreamLanguage.define(shell)
}
}
interface Props {
value: string
onChange: (value: string) => void
runtime: string
}
export default function CodeEditor({ value, onChange, runtime }: Props) {
const ref = useRef<HTMLDivElement>(null)
const viewRef = useRef<EditorView | null>(null)
useEffect(() => {
if (!ref.current) return
const state = EditorState.create({
doc: value,
extensions: [
lineNumbers(),
highlightActiveLine(),
history(),
foldGutter(),
indentOnInput(),
bracketMatching(),
closeBrackets(),
highlightSelectionMatches(),
syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
keymap.of([
...closeBracketsKeymap,
...defaultKeymap,
...searchKeymap,
...historyKeymap,
...lintKeymap,
indentWithTab,
]),
getLanguageExtension(runtime),
oneDark,
EditorView.updateListener.of((update) => {
if (update.docChanged) {
onChange(update.state.doc.toString())
}
}),
EditorView.theme({
'&': { fontSize: '14px', height: '100%' },
'.cm-scroller': { overflow: 'auto' },
}),
],
})
const view = new EditorView({ state, parent: ref.current })
viewRef.current = view
return () => {
view.destroy()
viewRef.current = null
}
}, [runtime])
useEffect(() => {
const view = viewRef.current
if (!view) return
const currentDoc = view.state.doc.toString()
if (currentDoc !== value) {
view.dispatch({
changes: { from: 0, to: currentDoc.length, insert: value },
})
}
}, [value])
return <div ref={ref} className="h-full" />
}

View File

@@ -15,7 +15,9 @@ export default function ResultCard({ result, onReset }: Props) {
<div className="space-y-6">
<div className="text-center">
<div className="text-4xl mb-2"></div>
<h2 className="text-xl font-bold"></h2>
<h2 className="text-xl font-bold">
{result.status === 'published' ? '脚本已发布' : '草稿已创建'}
</h2>
</div>
<CommandCard command={result.command} />
@@ -34,6 +36,10 @@ export default function ResultCard({ result, onReset }: Props) {
)}
<div className="bg-gray-800/50 border border-gray-700 rounded-lg p-4 space-y-3">
<div className="flex justify-between text-sm">
<span className="text-gray-400"></span>
<span>{result.title}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-gray-400"> ID</span>
<span className="font-mono text-blue-400">{result.id}</span>
@@ -43,19 +49,14 @@ export default function ResultCard({ result, onReset }: Props) {
<span>{result.runtime}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-gray-400"></span>
<span>{new Date(result.expires_at).toLocaleString('zh-CN')}</span>
<span className="text-gray-400"></span>
<span className={result.status === 'published' ? 'text-green-400' : 'text-gray-400'}>
{result.status === 'published' ? '已发布' : '草稿'}
</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-gray-400"></span>
<a
href={detailUrl}
target="_blank"
rel="noreferrer"
className="text-blue-400 hover:underline font-mono text-xs"
>
{detailUrl}
</a>
<span className="text-gray-400"></span>
<span>{new Date(result.expires_at).toLocaleString('zh-CN')}</span>
</div>
<div className="pt-2 border-t border-gray-700">
<div className="text-xs text-gray-500 mb-1"></div>
@@ -80,7 +81,17 @@ export default function ResultCard({ result, onReset }: Props) {
>
</a>
{result.status === 'published' && (
<a
href={`${window.location.origin}/market`}
target="_blank"
rel="noreferrer"
className="px-4 py-2 bg-green-600/80 hover:bg-green-600 rounded-lg text-sm transition-colors"
>
</a>
)}
</div>
</div>
)
}
}

View File

@@ -1,76 +0,0 @@
import { useState } from 'react'
import { RUNTIME_OPTIONS, EXPIRES_OPTIONS, RuntimeOption, ExpiresIn } from '../types'
interface Props {
onSubmit: (content: string, runtime: RuntimeOption, expiresIn: ExpiresIn) => void
loading: boolean
}
export default function ScriptForm({ onSubmit, loading }: Props) {
const [content, setContent] = useState('')
const [runtime, setRuntime] = useState<RuntimeOption>('bash')
const [expiresIn, setExpiresIn] = useState<ExpiresIn>('24h')
const canSubmit = content.trim().length > 0 && content.length <= 16384 && !loading
return (
<div className="space-y-4">
<div className="flex gap-4 flex-wrap">
<div>
<label className="block text-xs text-gray-500 mb-1"></label>
<select
value={runtime}
onChange={(e) => setRuntime(e.target.value as RuntimeOption)}
className="px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-sm focus:outline-none focus:border-blue-500"
>
{RUNTIME_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
<div>
<label className="block text-xs text-gray-500 mb-1"></label>
<select
value={expiresIn}
onChange={(e) => setExpiresIn(e.target.value as ExpiresIn)}
className="px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-sm focus:outline-none focus:border-blue-500"
>
{EXPIRES_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
</div>
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="在此粘贴你的脚本..."
rows={12}
className="w-full px-4 py-3 bg-gray-800 border border-gray-700 rounded-lg text-sm font-mono focus:outline-none focus:border-blue-500 resize-y"
/>
<div className="flex items-center justify-between">
<span className="text-xs text-gray-500">
{content.length.toLocaleString()} / 16,384
{content.length > 16384 && (
<span className="text-red-400 ml-1"></span>
)}
</span>
<button
onClick={() => onSubmit(content, runtime, expiresIn)}
disabled={!canSubmit}
className="px-6 py-2.5 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-700 disabled:text-gray-500 rounded-lg text-sm font-medium transition-colors"
>
{loading ? '生成中...' : '生成运行链接'}
</button>
</div>
</div>
)
}

View File

@@ -1,9 +1,7 @@
import { CreateScriptResponse, ScriptDetail, RuntimeOption, ExpiresIn } from '../types'
const BASE = ''
import { CreateScriptResponse, ScriptDetail, RuntimeOption, ExpiresIn, MarketResponse } from '../types'
async function request<T>(url: string, options?: RequestInit): Promise<T> {
const res = await fetch(BASE + url, {
const res = await fetch(url, {
headers: { 'Content-Type': 'application/json' },
...options,
})
@@ -15,9 +13,12 @@ async function request<T>(url: string, options?: RequestInit): Promise<T> {
}
export async function createScript(params: {
title: string
description?: string
content: string
runtime: RuntimeOption
expires_in: ExpiresIn
publish: boolean
}): Promise<CreateScriptResponse> {
return request('/api/scripts', {
method: 'POST',
@@ -29,8 +30,14 @@ export async function getScript(id: string): Promise<ScriptDetail> {
return request(`/api/scripts/${id}`)
}
export async function publishScript(id: string, token: string): Promise<{ id: string; status: string }> {
return request(`/api/scripts/${id}/publish?token=${encodeURIComponent(token)}`, {
method: 'POST',
})
}
export async function deleteScript(id: string, token: string): Promise<void> {
await fetch(`${BASE}/api/scripts/${id}?token=${encodeURIComponent(token)}`, {
await fetch(`/api/scripts/${id}?token=${encodeURIComponent(token)}`, {
method: 'DELETE',
}).then((res) => {
if (!res.ok && res.status !== 204) {
@@ -39,6 +46,16 @@ export async function deleteScript(id: string, token: string): Promise<void> {
})
}
export function getCommandUrl(id: string): string {
return `${window.location.origin}/raw/${id}`
}
export async function listMarket(params: {
page?: number
per_page?: number
runtime?: string
search?: string
}): Promise<MarketResponse> {
const query = new URLSearchParams()
if (params.page) query.set('page', String(params.page))
if (params.per_page) query.set('per_page', String(params.per_page))
if (params.runtime) query.set('runtime', params.runtime)
if (params.search) query.set('search', params.search)
return request(`/api/market?${query.toString()}`)
}

View File

@@ -1,53 +1,160 @@
import { useState, useCallback } from 'react'
import ScriptForm from '../components/ScriptForm'
import CodeEditor from '../components/CodeEditor'
import ResultCard from '../components/ResultCard'
import { createScript } from '../lib/api'
import { CreateScriptResponse, RuntimeOption, ExpiresIn } from '../types'
import { CreateScriptResponse, RuntimeOption, ExpiresIn, RUNTIME_OPTIONS, EXPIRES_OPTIONS } from '../types'
export default function Home() {
const [runtime, setRuntime] = useState<RuntimeOption>('bash')
const [title, setTitle] = useState('')
const [description, setDescription] = useState('')
const [content, setContent] = useState('')
const [expiresIn, setExpiresIn] = useState<ExpiresIn>('24h')
const [publish, setPublish] = useState(false)
const [result, setResult] = useState<CreateScriptResponse | null>(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const handleSubmit = useCallback(async (content: string, runtime: RuntimeOption, expiresIn: ExpiresIn) => {
const handleSubmit = useCallback(async () => {
if (!title.trim() || !content.trim()) return
setLoading(true)
setError(null)
setResult(null)
try {
const res = await createScript({ content, runtime, expires_in: expiresIn })
const res = await createScript({
title: title.trim(),
description: description.trim(),
content,
runtime,
expires_in: expiresIn,
publish,
})
setResult(res)
} catch (e) {
setError(e instanceof Error ? e.message : '创建失败')
} finally {
setLoading(false)
}
}, [])
}, [title, description, content, runtime, expiresIn, publish])
const handleReset = useCallback(() => {
setResult(null)
setError(null)
setTitle('')
setDescription('')
setContent('')
}, [])
if (result) {
return <ResultCard result={result} onReset={handleReset} />
}
const canSubmit = title.trim().length > 0 && content.trim().length > 0 && content.length <= 16384
return (
<div>
{!result ? (
<>
<div className="mb-8 text-center">
<h1 className="text-3xl font-bold mb-2"></h1>
<p className="text-gray-400">
<code className="text-blue-400">curl | bash</code>
</p>
</div>
<ScriptForm onSubmit={handleSubmit} loading={loading} />
{error && (
<div className="mt-4 p-3 bg-red-900/50 border border-red-700 rounded-lg text-red-300 text-sm">
{error}
</div>
)}
</>
) : (
<ResultCard result={result} onReset={handleReset} />
<div className="space-y-6">
<div className="text-center mb-2">
<h1 className="text-2xl font-bold mb-1"></h1>
<p className="text-gray-400 text-sm"></p>
</div>
{/* Runtime + Expires */}
<div className="flex gap-4 flex-wrap">
<div className="flex-1 min-w-[160px]">
<label className="block text-xs text-gray-500 mb-1"></label>
<select
value={runtime}
onChange={(e) => setRuntime(e.target.value as RuntimeOption)}
className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-sm focus:outline-none focus:border-blue-500"
>
{RUNTIME_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>{opt.label}</option>
))}
</select>
</div>
<div className="flex-1 min-w-[160px]">
<label className="block text-xs text-gray-500 mb-1"></label>
<select
value={expiresIn}
onChange={(e) => setExpiresIn(e.target.value as ExpiresIn)}
className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-sm focus:outline-none focus:border-blue-500"
>
{EXPIRES_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>{opt.label}</option>
))}
</select>
</div>
</div>
{/* Title + Description */}
<div className="space-y-3">
<div>
<label className="block text-xs text-gray-500 mb-1"> <span className="text-red-400">*</span></label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="给你的脚本起个名字"
maxLength={128}
className="w-full px-4 py-2.5 bg-gray-800 border border-gray-700 rounded-lg text-sm focus:outline-none focus:border-blue-500"
/>
</div>
<div>
<label className="block text-xs text-gray-500 mb-1"></label>
<input
type="text"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="简述脚本用途"
maxLength={512}
className="w-full px-4 py-2.5 bg-gray-800 border border-gray-700 rounded-lg text-sm focus:outline-none focus:border-blue-500"
/>
</div>
</div>
{/* Code Editor */}
<div>
<label className="block text-xs text-gray-500 mb-1">
<span className="text-red-400">*</span>
<span className="ml-2">{content.length.toLocaleString()} / 16,384</span>
{content.length > 16384 && <span className="text-red-400 ml-1"></span>}
</label>
<div className="border border-gray-700 rounded-lg overflow-hidden" style={{ height: '320px' }}>
<CodeEditor value={content} onChange={setContent} runtime={runtime} />
</div>
</div>
{/* Publish toggle */}
<div className="flex items-center gap-3">
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={publish}
onChange={(e) => setPublish(e.target.checked)}
className="w-4 h-4 rounded border-gray-600 bg-gray-800 text-blue-600 focus:ring-blue-500"
/>
<span className="text-sm"></span>
</label>
{!publish && (
<span className="text-xs text-gray-500"></span>
)}
</div>
{/* Submit */}
{error && (
<div className="p-3 bg-red-900/50 border border-red-700 rounded-lg text-red-300 text-sm">
{error}
</div>
)}
<div className="flex justify-end">
<button
onClick={handleSubmit}
disabled={!canSubmit || loading}
className="px-6 py-2.5 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-700 disabled:text-gray-500 rounded-lg text-sm font-medium transition-colors"
>
{loading ? '创建中...' : (publish ? '创建并发布' : '创建草稿')}
</button>
</div>
</div>
)
}
}

View File

@@ -0,0 +1,118 @@
import { useState, useEffect, useCallback } from 'react'
import { Link } from 'react-router-dom'
import { listMarket } from '../lib/api'
import { MarketItem, RUNTIME_OPTIONS } from '../types'
export default function Market() {
const [items, setItems] = useState<MarketItem[]>([])
const [total, setTotal] = useState(0)
const [page, setPage] = useState(1)
const [runtime, setRuntime] = useState('')
const [search, setSearch] = useState('')
const [loading, setLoading] = useState(true)
const fetchMarket = useCallback(async () => {
setLoading(true)
try {
const res = await listMarket({ page, per_page: 20, runtime, search })
setItems(res.items)
setTotal(res.total)
} catch {
setItems([])
} finally {
setLoading(false)
}
}, [page, runtime, search])
useEffect(() => { fetchMarket() }, [fetchMarket])
const totalPages = Math.ceil(total / 20)
return (
<div className="space-y-6">
<div className="text-center">
<h1 className="text-2xl font-bold mb-1"></h1>
<p className="text-gray-400 text-sm"></p>
</div>
{/* Search + Filter */}
<div className="flex gap-4">
<input
type="text"
value={search}
onChange={(e) => { setSearch(e.target.value); setPage(1) }}
placeholder="搜索脚本..."
className="flex-1 px-4 py-2.5 bg-gray-800 border border-gray-700 rounded-lg text-sm focus:outline-none focus:border-blue-500"
/>
<select
value={runtime}
onChange={(e) => { setRuntime(e.target.value); setPage(1) }}
className="px-3 py-2.5 bg-gray-800 border border-gray-700 rounded-lg text-sm focus:outline-none focus:border-blue-500"
>
<option value=""></option>
{RUNTIME_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>{opt.label}</option>
))}
</select>
</div>
{/* Results */}
{loading ? (
<div className="text-center py-10 text-gray-500 animate-pulse">...</div>
) : items.length === 0 ? (
<div className="text-center py-10">
<p className="text-gray-500"></p>
<Link to="/" className="text-blue-400 hover:underline text-sm mt-2 block"></Link>
</div>
) : (
<div className="grid gap-4 sm:grid-cols-2">
{items.map((item) => (
<Link
key={item.id}
to={`/s/${item.id}`}
className="bg-gray-800/60 border border-gray-700 rounded-lg p-4 hover:border-blue-500/50 transition-colors group"
>
<div className="flex items-center gap-2 mb-2">
<span className="font-medium text-sm group-hover:text-blue-400 transition-colors">
{item.title}
</span>
<span className="px-1.5 py-0.5 bg-blue-600/20 text-blue-400 text-xs rounded border border-blue-600/30">
{item.runtime}
</span>
</div>
{item.description && (
<p className="text-gray-400 text-xs line-clamp-2">{item.description}</p>
)}
<div className="mt-2 text-xs text-gray-500 font-mono">
{item.id}
</div>
</Link>
))}
</div>
)}
{/* Pagination */}
{totalPages > 1 && (
<div className="flex justify-center gap-2">
<button
onClick={() => setPage(Math.max(1, page - 1))}
disabled={page === 1}
className="px-3 py-1 bg-gray-800 hover:bg-gray-700 disabled:bg-gray-900 disabled:text-gray-600 rounded text-sm"
>
</button>
<span className="text-sm text-gray-400 py-1">
{page} / {totalPages} ({total} )
</span>
<button
onClick={() => setPage(Math.min(totalPages, page + 1))}
disabled={page === totalPages}
className="px-3 py-1 bg-gray-800 hover:bg-gray-700 disabled:bg-gray-900 disabled:text-gray-600 rounded text-sm"
>
</button>
</div>
)}
</div>
)
}

View File

@@ -2,7 +2,7 @@ import { useState, useEffect } from 'react'
import { useParams, Link } from 'react-router-dom'
import ScriptViewer from '../components/ScriptViewer'
import CommandCard from '../components/CommandCard'
import { getScript } from '../lib/api'
import { getScript, publishScript } from '../lib/api'
import { ScriptDetail as ScriptDetailType, isShellRuntime, getSourceCommand } from '../types'
export default function ScriptDetail() {
@@ -10,6 +10,8 @@ export default function ScriptDetail() {
const [script, setScript] = useState<ScriptDetailType | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [publishing, setPublishing] = useState(false)
const [adminToken, setAdminToken] = useState('')
useEffect(() => {
if (!id) return
@@ -20,11 +22,7 @@ export default function ScriptDetail() {
}, [id])
if (loading) {
return (
<div className="flex justify-center py-20">
<div className="animate-pulse text-gray-500">...</div>
</div>
)
return <div className="flex justify-center py-20"><div className="animate-pulse text-gray-500">...</div></div>
}
if (error || !script) {
@@ -33,32 +31,55 @@ export default function ScriptDetail() {
<div className="text-6xl mb-4">😕</div>
<h2 className="text-xl font-bold mb-2"></h2>
<p className="text-gray-400 mb-6">{error}</p>
<Link to="/" className="text-blue-400 hover:underline">
</Link>
<Link to="/" className="text-blue-400 hover:underline"></Link>
</div>
)
}
const command = `curl ${window.location.origin}/raw/${script.id} | ${script.runtime}`
const rawUrl = `${window.location.origin}/raw/${script.id}`
const command = `curl ${rawUrl} | ${script.runtime}`
const showSource = isShellRuntime(script.runtime)
const sourceCommand = showSource
? getSourceCommand(`${window.location.origin}/raw/${script.id}`, script.runtime)
: null
const sourceCommand = showSource ? getSourceCommand(rawUrl, script.runtime) : null
const handlePublish = async () => {
if (!adminToken.trim()) return
setPublishing(true)
try {
await publishScript(script.id, adminToken.trim())
const updated = await getScript(script.id)
setScript(updated)
setAdminToken('')
} catch (e) {
alert(e instanceof Error ? e.message : '发布失败')
} finally {
setPublishing(false)
}
}
return (
<div>
<div className="mb-6">
<Link to="/" className="text-sm text-gray-500 hover:text-blue-400 transition-colors">
&larr;
</Link>
<Link to="/" className="text-sm text-gray-500 hover:text-blue-400 transition-colors">&larr; </Link>
<Link to="/market" className="text-sm text-gray-500 hover:text-blue-400 transition-colors ml-4"></Link>
</div>
<div className="mb-4">
<h1 className="text-2xl font-bold">{script.title}</h1>
{script.description && <p className="text-gray-400 text-sm mt-1">{script.description}</p>}
</div>
<div className="flex items-center gap-3 mb-6">
<h1 className="text-2xl font-bold font-mono">{script.id}</h1>
<span className="font-mono text-blue-400 text-sm">{script.id}</span>
<span className="px-2 py-0.5 bg-blue-600/20 text-blue-400 text-xs rounded-full border border-blue-600/30">
{script.runtime}
</span>
<span className={`px-2 py-0.5 text-xs rounded-full ${
script.status === 'published'
? 'bg-green-600/20 text-green-400 border border-green-600/30'
: 'bg-gray-600/20 text-gray-400 border border-gray-600/30'
}`}>
{script.status === 'published' ? '已发布' : '草稿'}
</span>
<span className="text-xs text-gray-500">
{new Date(script.expires_at).toLocaleString('zh-CN')}
</span>
@@ -73,23 +94,40 @@ export default function ScriptDetail() {
<p className="text-xs text-gray-500 mb-2">
使 shell
</p>
<CommandCard
command={sourceCommand}
label="继承环境变量"
variant="secondary"
/>
<CommandCard command={sourceCommand} label="继承环境变量" variant="secondary" />
</div>
)}
</div>
{/* Publish section for drafts */}
{script.status === 'draft' && (
<div className="mt-8 bg-gray-800/50 border border-gray-700 rounded-lg p-4">
<h3 className="text-sm font-medium mb-2"></h3>
<p className="text-xs text-gray-500 mb-3">稿</p>
<div className="flex gap-3">
<input
type="text"
value={adminToken}
onChange={(e) => setAdminToken(e.target.value)}
placeholder="管理令牌"
className="flex-1 px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-xs font-mono focus:outline-none focus:border-blue-500"
/>
<button
onClick={handlePublish}
disabled={publishing || !adminToken.trim()}
className="px-4 py-2 bg-green-600 hover:bg-green-700 disabled:bg-gray-700 disabled:text-gray-500 rounded-lg text-xs font-medium transition-colors"
>
{publishing ? '发布中...' : '发布'}
</button>
</div>
</div>
)}
<div className="mt-8 text-center">
<Link
to={`/s/${script.id}/delete`}
className="text-xs text-gray-600 hover:text-red-400 transition-colors"
>
<Link to={`/s/${script.id}/delete`} className="text-xs text-gray-600 hover:text-red-400 transition-colors">
</Link>
</div>
</div>
)
}
}

View File

@@ -1,19 +1,27 @@
export interface CreateScriptResponse {
id: string
title: string
description: string
admin_token: string
url: string
command: string
source_command: string
runtime: string
status: string
expires_at: string
}
export interface ScriptDetail {
id: string
title: string
description: string
runtime: string
content: string
content_length: number
status: string
created_at: string
expires_at: string
published_at: string | null
expired: boolean
}
@@ -38,6 +46,21 @@ export const EXPIRES_OPTIONS: { value: ExpiresIn; label: string }[] = [
{ value: '30d', label: '30 天' },
]
export interface MarketItem {
id: string
title: string
description: string
runtime: string
published_at: string | null
}
export interface MarketResponse {
items: MarketItem[]
total: number
page: number
per_page: number
}
const SOURCE_TEMPLATES: Record<string, string> = {
bash: 'source <(curl {url})',
zsh: 'source <(curl {url})',
@@ -51,4 +74,4 @@ export function isShellRuntime(runtime: string): boolean {
export function getSourceCommand(url: string, runtime: string): string {
return (SOURCE_TEMPLATES[runtime] ?? 'source <(curl {url})').replace('{url}', url)
}
}