修复登录续期与数据库验证回归

- 修复密码登录、续期和账号编辑链路的边界问题
- 补齐 dbverify、后端与前端单测
- 同步 Docker 与前端构建产物
This commit is contained in:
Christ committed 2026-07-09 16:08:16 +08:00
1 parent 3436acecdc
commit 25419c027f
87 files changed
+7485 -900

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
.git
.gitignore
data
browser_data
frontend/node_modules
frontend/dist
internal/webui/static
server
xianyu-server
init-admin
*.db
*.sqlite
*.sqlite3
cover.out
+7 -1
View File
@@ -24,9 +24,15 @@
/frontend/node_modules/
/frontend/.env.local
/frontend/.env.*.local
/internal/server/data/
# Frontend build artifacts (hash 化文件名,每次构建变化,不入库;index.html 与稳定 SVG 仍跟踪)
# Embedded frontend build assets (index.html references hashed files, so JS/CSS must be tracked)
/internal/webui/static/assets/
!/internal/webui/static/assets/
!/internal/webui/static/assets/*.css
!/internal/webui/static/assets/*.js
!/internal/webui/static/assets/*.svg
/internal/webui/static/assets/*.map
# OS / editor
.DS_Store
+49
View File
@@ -0,0 +1,49 @@
# syntax=docker/dockerfile:1.7
FROM node:22-trixie AS frontend
WORKDIR /src/frontend
COPY frontend/package*.json ./
RUN npm ci
COPY frontend/ ./
RUN npm run build
FROM node:22-trixie AS playwright-driver
RUN npm install -g playwright@1.57.0 \
&& mkdir -p /ms-playwright-go/package \
&& cp -a /usr/local/lib/node_modules/playwright/. /ms-playwright-go/package/ \
&& if [ -d /usr/local/lib/node_modules/playwright-core ]; then \
mkdir -p /ms-playwright-go/package/node_modules \
&& cp -a /usr/local/lib/node_modules/playwright-core /ms-playwright-go/package/node_modules/playwright-core; \
fi
FROM golang:1.26-trixie AS backend
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
COPY --from=frontend /src/internal/webui/static ./internal/webui/static
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/xianyu-server ./cmd/server
FROM debian:13-slim AS runtime
ENV TZ=Asia/Shanghai
ENV BROWSER_HEADLESS=true
ENV PLAYWRIGHT_DRIVER_PATH=/ms-playwright-go
ENV PLAYWRIGHT_NODEJS_PATH=/usr/bin/node
ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
ENV PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates \
chromium \
curl \
fonts-liberation \
fonts-noto-cjk \
nodejs \
tzdata \
&& rm -rf /var/lib/apt/lists/*
COPY --from=backend /out/xianyu-server /app/xianyu-server
COPY --from=playwright-driver /ms-playwright-go /ms-playwright-go
RUN mkdir -p /app/data /app/browser_data
EXPOSE 8080
CMD ["/app/xianyu-server", "-addr", ":8080"]
+131 -57
View File
@@ -13,6 +13,8 @@ package main
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"os"
"strings"
@@ -22,6 +24,17 @@ import (
)
func main() {
var cleanup func() error
fail := func(format string, args ...any) {
if cleanup != nil {
if err := cleanup(); err != nil {
fmt.Printf("⚠️ 清理验证数据失败: %v\n", err)
}
}
fmt.Printf(format, args...)
os.Exit(1)
}
if len(os.Args) < 2 {
fmt.Println("用法: dbverify <database-url>")
os.Exit(1)
@@ -33,8 +46,7 @@ func main() {
fmt.Printf("连接 %s ...\n", maskURL(url))
database, dialect, err := db.Open(ctx, url)
if err != nil {
fmt.Printf("❌ Open 失败: %v\n", err)
os.Exit(1)
fail("❌ Open 失败: %v\n", err)
}
defer database.Close()
fmt.Printf("✅ 迁移成功,方言=%s\n", dialect)
@@ -42,72 +54,79 @@ func main() {
store := db.NewStore(database, dialect)
// 1) 创建用户(用唯一用户名,避免在已有数据的库上因 admin 重名而失败)。
username := fmt.Sprintf("verify_%d", time.Now().UnixNano())
ok, err := store.Users.Create(ctx, username, username+"@test.local", "pw123456")
ids := newVerifyIDs(time.Now().UnixNano())
username := ids.username
accountID := ids.accountID
orderID := ids.orderID
itemID := ids.itemID
buyerID := ids.buyerID
cleanup = func() error {
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cleanupCancel()
return cleanupVerifyData(cleanupCtx, store, ids)
}
password, err := newVerifyPassword()
if err != nil {
fail("❌ 生成验证密码失败: %v\n", err)
}
ok, err := store.Users.Create(ctx, username, username+"@test.local", password)
if err != nil || !ok {
fmt.Printf("❌ 创建用户失败: err=%v ok=%v\n", err, ok)
os.Exit(1)
fail("❌ 创建用户失败: err=%v ok=%v\n", err, ok)
}
if err := store.Users.SetAdmin(ctx, username); err != nil {
fmt.Printf("❌ 设置管理员失败: %v\n", err)
os.Exit(1)
adminUser, err := store.Users.GetByUsername(ctx, username)
if err != nil {
fail("❌ 查询验证用户失败: %v\n", err)
}
adminUser, _ := store.Users.GetByUsername(ctx, username)
userID := adminUser.ID
fmt.Printf("✅ 创建用户 %s (id=%d)\n", username, userID)
fmt.Printf("✅ 创建验证用户 %s (id=%d)\n", username, userID)
// 2) 保存 cookie(dialectUpsert: ON CONFLICT/ON DUPLICATE KEY)
if err := store.Cookies.Save(ctx, "acc1", "unb=123; _m_h5_tk=tk_1;", userID); err != nil {
fmt.Printf("❌ 保存 cookie 失败: %v\n", err)
os.Exit(1)
if err := store.Cookies.Save(ctx, accountID, "unb=123; _m_h5_tk=tk_1;", userID); err != nil {
fail("❌ 保存 cookie 失败: %v\n", err)
}
if err := store.Cookies.SetStatus(ctx, accountID, false); err != nil {
fail("❌ 禁用验证账号失败: %v\n", err)
}
// 再 Save 一次验证 upsert
if err := store.Cookies.Save(ctx, "acc1", "unb=123; _m_h5_tk=tk_2;", userID); err != nil {
fmt.Printf("❌ 二次保存 cookie 失败: %v\n", err)
os.Exit(1)
if err := store.Cookies.Save(ctx, accountID, "unb=123; _m_h5_tk=tk_2;", userID); err != nil {
fail("❌ 二次保存 cookie 失败: %v\n", err)
}
v, _ := store.Cookies.GetValue(ctx, "acc1")
v, _ := store.Cookies.GetValue(ctx, accountID)
fmt.Printf("✅ cookie upsert 成功,value=%s\n", v)
// 3) 系统设置 upsert(dialectUpsert + key 保留字引用)
if err := store.Settings.Set(ctx, "theme_color", "blue"); err != nil {
fmt.Printf("❌ 系统设置 Set 失败: %v\n", err)
os.Exit(1)
fail("❌ 系统设置 Set 失败: %v\n", err)
}
if err := store.Settings.Set(ctx, "theme_color", "green"); err != nil {
fmt.Printf("❌ 系统设置二次 Set 失败: %v\n", err)
os.Exit(1)
fail("❌ 系统设置二次 Set 失败: %v\n", err)
}
fmt.Println("✅ 系统设置 upsert 成功(key 保留字处理 OK)")
// 4) 订单 upsert(INSERT IGNORE + 动态 UPDATE)
if err := store.Orders.Upsert(ctx, "order-1", db.OrderUpsertOpts{
ItemID: "item-1", BuyerID: "buyer-1", CookieID: "acc1", OrderStatus: "paid", Amount: "19.90",
if err := store.Orders.Upsert(ctx, orderID, db.OrderUpsertOpts{
ItemID: itemID, BuyerID: buyerID, CookieID: accountID, OrderStatus: "paid", Amount: "19.90",
}); err != nil {
fmt.Printf("❌ 订单 Upsert 失败: %v\n", err)
os.Exit(1)
fail("❌ 订单 Upsert 失败: %v\n", err)
}
// 二次 upsert 验证不重复插入
if err := store.Orders.Upsert(ctx, "order-1", db.OrderUpsertOpts{
if err := store.Orders.Upsert(ctx, orderID, db.OrderUpsertOpts{
OrderStatus: "shipped", ChatID: "chat-1",
}); err != nil {
fmt.Printf("❌ 订单二次 Upsert 失败: %v\n", err)
os.Exit(1)
fail("❌ 订单二次 Upsert 失败: %v\n", err)
}
fmt.Println("✅ 订单 upsert 成功(INSERT IGNORE + UPDATE OK)")
// 5) 商品信息 upsert(dialectUpsert,UNIQUE(cookie_id, item_id))
if err := store.Items.Upsert(ctx, &db.ItemInfoRow{
CookieID: "acc1", ItemID: "item-1", ItemTitle: "测试商品", ItemPrice: "19.90",
CookieID: accountID, ItemID: itemID, ItemTitle: "测试商品", ItemPrice: "19.90",
}); err != nil {
fmt.Printf("❌ 商品 Upsert 失败: %v\n", err)
os.Exit(1)
fail("❌ 商品 Upsert 失败: %v\n", err)
}
if err := store.Items.Upsert(ctx, &db.ItemInfoRow{
CookieID: "acc1", ItemID: "item-1", ItemTitle: "更新后商品", ItemPrice: "29.90",
CookieID: accountID, ItemID: itemID, ItemTitle: "更新后商品", ItemPrice: "29.90",
}); err != nil {
fmt.Printf("❌ 商品二次 Upsert 失败: %v\n", err)
os.Exit(1)
fail("❌ 商品二次 Upsert 失败: %v\n", err)
}
fmt.Println("✅ 商品信息 upsert 成功")
@@ -116,63 +135,61 @@ func main() {
Name: "测试卡组", Type: "data", DataContent: "card-1\ncard-2\ncard-3", Enabled: true, UserID: userID,
})
if err != nil {
fmt.Printf("❌ 创建卡密失败: %v\n", err)
os.Exit(1)
fail("❌ 创建卡密失败: %v\n", err)
}
fmt.Printf("✅ 创建卡密组 (id=%d)\n", cardID)
// 7) 卡密批量追加(AppendBatchData)
added, err := store.Cards.AppendBatchData(ctx, cardID, "card-4\ncard-5")
if err != nil {
fmt.Printf("❌ 追加卡密失败: %v\n", err)
os.Exit(1)
fail("❌ 追加卡密失败: %v\n", err)
}
fmt.Printf("✅ 追加卡密 %d 个\n", added)
// 8) 通知渠道 + 绑定(dialectUpsert)
chID, err := store.Notifications.CreateChannel(ctx, &db.NotificationChannelRow{
Name: "测试渠道", Type: "webhook", Config: `{"webhook_url":"http://x"}`, Enabled: true, UserID: userID,
Name: "测试渠道", Type: "webhook", Config: `{"webhook_url":"http://x"}`, Enabled: false, UserID: userID,
})
if err != nil {
fmt.Printf("❌ 创建通知渠道失败: %v\n", err)
os.Exit(1)
fail("❌ 创建通知渠道失败: %v\n", err)
}
if err := store.Notifications.SetBindings(ctx, "acc1", []int64{chID}); err != nil {
fmt.Printf("❌ 绑定通知渠道失败: %v\n", err)
os.Exit(1)
if err := store.Notifications.SetBindings(ctx, accountID, []int64{chID}); err != nil {
fail("❌ 绑定通知渠道失败: %v\n", err)
}
fmt.Printf("✅ 通知渠道 + 绑定 OK (channel=%d)\n", chID)
// 9) 自动化规则(TryStartRun 用 INSERT IGNORE + UNIQUE 防重)
ruleID, err := store.Automation.Create(ctx, db.AutomationRuleInput{
UserID: userID, CookieID: "acc1", ItemID: "item-1", Name: "付款发货",
TriggerType: "order_paid", Enabled: true, Priority: 100,
UserID: userID, CookieID: accountID, ItemID: itemID, Name: "付款发货",
TriggerType: "order_paid", Enabled: false, Priority: 100,
})
if err != nil {
fmt.Printf("❌ 创建自动化规则失败: %v\n", err)
os.Exit(1)
fail("❌ 创建自动化规则失败: %v\n", err)
}
runID, started, err := store.Automation.TryStartRun(ctx, db.AutomationRun{
RuleID: ruleID, CookieID: "acc1", TriggerType: "order_paid", TriggerKey: "order-1", Status: "running",
RuleID: ruleID, CookieID: accountID, TriggerType: "order_paid", TriggerKey: orderID, Status: "running",
})
if err != nil || !started {
fmt.Printf("❌ TryStartRun 失败: err=%v started=%v\n", err, started)
os.Exit(1)
fail("❌ TryStartRun 失败: err=%v started=%v\n", err, started)
}
// 重复触发应 started=false
_, started2, err := store.Automation.TryStartRun(ctx, db.AutomationRun{
RuleID: ruleID, CookieID: "acc1", TriggerType: "order_paid", TriggerKey: "order-1", Status: "running",
RuleID: ruleID, CookieID: accountID, TriggerType: "order_paid", TriggerKey: orderID, Status: "running",
})
if err != nil {
fmt.Printf("❌ TryStartRun 二次调用失败: %v\n", err)
os.Exit(1)
fail("❌ TryStartRun 二次调用失败: %v\n", err)
}
if started2 {
fmt.Printf("❌ TryStartRun 重复触发未防重\n")
os.Exit(1)
fail("❌ TryStartRun 重复触发未防重\n")
}
fmt.Printf("✅ 自动化规则 + 防重 OK (rule=%d run=%d)\n", ruleID, runID)
if err := cleanup(); err != nil {
fmt.Printf("❌ 清理验证数据失败: %v\n", err)
os.Exit(1)
}
cleanup = nil
fmt.Println("✅ 验证数据已清理")
fmt.Println("\n🎉 全部验证通过")
}
@@ -189,3 +206,60 @@ func maskURL(url string) string {
}
return url
}
type verifyIDs struct {
username string
accountID string
orderID string
itemID string
buyerID string
}
func newVerifyIDs(n int64) verifyIDs {
suffix := fmt.Sprintf("%d", n)
return verifyIDs{
username: "verify_" + suffix,
accountID: "acc_" + suffix,
orderID: "order_" + suffix,
itemID: "item_" + suffix,
buyerID: "buyer_" + suffix,
}
}
func newVerifyPassword() (string, error) {
var b [24]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
}
return "verify_" + hex.EncodeToString(b[:]), nil
}
func cleanupVerifyData(ctx context.Context, store *db.Store, ids verifyIDs) error {
userID := int64(0)
if user, err := store.Users.GetByUsername(ctx, ids.username); err == nil {
userID = user.ID
}
queries := []struct {
query string
args []any
}{
{`DELETE FROM automation_runs WHERE trigger_key=? OR cookie_id=?`, []any{ids.orderID, ids.accountID}},
{`DELETE FROM automation_rule_actions WHERE rule_id IN (SELECT id FROM automation_rules WHERE cookie_id=? OR user_id=?)`, []any{ids.accountID, userID}},
{`DELETE FROM automation_rules WHERE cookie_id=? OR user_id=?`, []any{ids.accountID, userID}},
{`DELETE FROM message_notifications WHERE cookie_id=? OR channel_id IN (SELECT id FROM notification_channels WHERE user_id=? AND name=?)`, []any{ids.accountID, userID, "测试渠道"}},
{`DELETE FROM notification_channels WHERE user_id=? AND name=?`, []any{userID, "测试渠道"}},
{`DELETE FROM cards WHERE user_id=? AND name=?`, []any{userID, "测试卡组"}},
{`DELETE FROM item_info WHERE cookie_id=? AND item_id=?`, []any{ids.accountID, ids.itemID}},
{`DELETE FROM orders WHERE order_id=? OR cookie_id=?`, []any{ids.orderID, ids.accountID}},
{`DELETE FROM cookie_status WHERE cookie_id=?`, []any{ids.accountID}},
{`DELETE FROM cookies WHERE id=?`, []any{ids.accountID}},
{`DELETE FROM sessions WHERE user_id=?`, []any{userID}},
{`DELETE FROM users WHERE username=? AND email=?`, []any{ids.username, ids.username + "@test.local"}},
}
for _, q := range queries {
if _, err := store.DB.ExecContext(ctx, q.query, q.args...); err != nil {
return err
}
}
return nil
}
+164 -6
View File
@@ -1,15 +1,22 @@
package main
import "testing"
import (
"context"
"errors"
"path/filepath"
"testing"
"xianyu-go/internal/db"
)
// TestMaskURL 验证带凭证的数据库 URL 脱敏:保留 scheme + host,密码替换为 ***。
func TestMaskURL(t *testing.T) {
cases := map[string]string{
"mysql://user:secret@tcp(host:3306)/db?x=1": "mysql://***@tcp(host:3306)/db?x=1",
"postgres://user:pass@host:5432/db": "postgres://***@host:5432/db",
"postgresql://u:p@h:5432/d": "postgresql://***@h:5432/d",
"sqlite://data/x.db": "sqlite://data/x.db", // 无密码,原样
"/local/path.db": "/local/path.db", // 非 URL,原样
"mysql://user:secret@tcp(host:3306)/db?x=1": "mysql://***@tcp(host:3306)/db?x=1",
"postgres://user:pass@host:5432/db": "postgres://***@host:5432/db",
"postgresql://u:p@h:5432/d": "postgresql://***@h:5432/d",
"sqlite://data/x.db": "sqlite://data/x.db", // 无密码,原样
"/local/path.db": "/local/path.db", // 非 URL,原样
}
for in, want := range cases {
if got := maskURL(in); got != want {
@@ -17,3 +24,154 @@ func TestMaskURL(t *testing.T) {
}
}
}
func TestNewVerifyIDsAreUniqueForPersistentRuns(t *testing.T) {
ids := newVerifyIDs(12345)
want := map[string]string{
"username": "verify_12345",
"accountID": "acc_12345",
"orderID": "order_12345",
"itemID": "item_12345",
"buyerID": "buyer_12345",
}
got := map[string]string{
"username": ids.username,
"accountID": ids.accountID,
"orderID": ids.orderID,
"itemID": ids.itemID,
"buyerID": ids.buyerID,
}
for key, wantValue := range want {
if got[key] != wantValue {
t.Fatalf("%s=%q want %q", key, got[key], wantValue)
}
}
if ids.username == ids.accountID || ids.accountID == ids.orderID || ids.orderID == ids.itemID {
t.Fatalf("验证用 ID 不应互相复用: %+v", ids)
}
}
func TestNewVerifyPasswordIsNotFixedDefault(t *testing.T) {
first, err := newVerifyPassword()
if err != nil {
t.Fatalf("newVerifyPassword: %v", err)
}
second, err := newVerifyPassword()
if err != nil {
t.Fatalf("newVerifyPassword second: %v", err)
}
if first == "pw123456" || second == "pw123456" {
t.Fatal("验证用户不应使用固定弱密码")
}
if first == second {
t.Fatalf("验证密码应随机生成,got %q", first)
}
}
func TestCleanupVerifyDataRemovesRowsAndVerifyDataIsDisabled(t *testing.T) {
ctx := context.Background()
database, dialect, err := db.Open(ctx, filepath.Join(t.TempDir(), "verify.db"))
if err != nil {
t.Fatalf("Open: %v", err)
}
defer database.Close()
store := db.NewStore(database, dialect)
ids := newVerifyIDs(987654321)
password, err := newVerifyPassword()
if err != nil {
t.Fatalf("newVerifyPassword: %v", err)
}
ok, err := store.Users.Create(ctx, ids.username, ids.username+"@test.local", password)
if err != nil || !ok {
t.Fatalf("Create user: ok=%v err=%v", ok, err)
}
user, err := store.Users.GetByUsername(ctx, ids.username)
if err != nil {
t.Fatalf("GetByUsername: %v", err)
}
if user.IsAdmin {
t.Fatal("dbverify 创建的验证用户不应是管理员")
}
if err := store.Cookies.Save(ctx, ids.accountID, "unb=123; _m_h5_tk=tk_1;", user.ID); err != nil {
t.Fatalf("Save cookie: %v", err)
}
if err := store.Cookies.SetStatus(ctx, ids.accountID, false); err != nil {
t.Fatalf("SetStatus false: %v", err)
}
if store.Cookies.GetStatus(ctx, ids.accountID) {
t.Fatal("dbverify 验证账号应默认禁用,避免被服务启动")
}
if err := store.Orders.Upsert(ctx, ids.orderID, db.OrderUpsertOpts{ItemID: ids.itemID, BuyerID: ids.buyerID, CookieID: ids.accountID}); err != nil {
t.Fatalf("Orders.Upsert: %v", err)
}
if err := store.Items.Upsert(ctx, &db.ItemInfoRow{CookieID: ids.accountID, ItemID: ids.itemID, ItemTitle: "测试商品"}); err != nil {
t.Fatalf("Items.Upsert: %v", err)
}
cardID, err := store.Cards.Create(ctx, &db.CardFull{Name: "测试卡组", Type: "data", DataContent: "card", Enabled: true, UserID: user.ID})
if err != nil || cardID == 0 {
t.Fatalf("Cards.Create: id=%d err=%v", cardID, err)
}
channelID, err := store.Notifications.CreateChannel(ctx, &db.NotificationChannelRow{
Name: "测试渠道", Type: "webhook", Config: `{"webhook_url":"http://x"}`, Enabled: false, UserID: user.ID,
})
if err != nil {
t.Fatalf("CreateChannel: %v", err)
}
var channelEnabled int
if err := store.DB.QueryRowContext(ctx, `SELECT enabled FROM notification_channels WHERE id=?`, channelID).Scan(&channelEnabled); err != nil {
t.Fatalf("query channel enabled: %v", err)
}
if channelEnabled != 0 {
t.Fatal("dbverify 验证通知渠道应默认禁用")
}
if err := store.Notifications.SetBindings(ctx, ids.accountID, []int64{channelID}); err != nil {
t.Fatalf("SetBindings: %v", err)
}
ruleID, err := store.Automation.Create(ctx, db.AutomationRuleInput{
UserID: user.ID, CookieID: ids.accountID, ItemID: ids.itemID, Name: "付款发货",
TriggerType: "order_paid", Enabled: false, Priority: 100,
})
if err != nil {
t.Fatalf("Automation.Create: %v", err)
}
if _, started, err := store.Automation.TryStartRun(ctx, db.AutomationRun{
RuleID: ruleID, CookieID: ids.accountID, TriggerType: "order_paid", TriggerKey: ids.orderID, Status: "running",
}); err != nil || !started {
t.Fatalf("TryStartRun: started=%v err=%v", started, err)
}
if err := cleanupVerifyData(ctx, store, ids); err != nil {
t.Fatalf("cleanupVerifyData: %v", err)
}
if _, err := store.Users.GetByUsername(ctx, ids.username); !errors.Is(err, db.ErrNotFound) {
t.Fatalf("验证用户应被清理,err=%v", err)
}
if _, err := store.Cookies.GetValue(ctx, ids.accountID); !errors.Is(err, db.ErrNotFound) {
t.Fatalf("验证账号应被清理,err=%v", err)
}
var count int
for name, query := range map[string]string{
"automation_runs": `SELECT COUNT(*) FROM automation_runs WHERE cookie_id=? OR trigger_key=?`,
"automation_rules": `SELECT COUNT(*) FROM automation_rules WHERE cookie_id=? OR item_id=?`,
"notification_links": `SELECT COUNT(*) FROM message_notifications WHERE cookie_id=?`,
"orders": `SELECT COUNT(*) FROM orders WHERE cookie_id=? OR order_id=?`,
"items": `SELECT COUNT(*) FROM item_info WHERE cookie_id=? OR item_id=?`,
} {
var err error
switch name {
case "automation_runs", "orders":
err = store.DB.QueryRowContext(ctx, query, ids.accountID, ids.orderID).Scan(&count)
case "automation_rules", "items":
err = store.DB.QueryRowContext(ctx, query, ids.accountID, ids.itemID).Scan(&count)
default:
err = store.DB.QueryRowContext(ctx, query, ids.accountID).Scan(&count)
}
if err != nil {
t.Fatalf("count %s: %v", name, err)
}
if count != 0 {
t.Fatalf("%s 未清理干净,count=%d", name, count)
}
}
}
+2
View File
@@ -29,6 +29,7 @@ import (
"xianyu-go/internal/browser"
"xianyu-go/internal/db"
"xianyu-go/internal/notify"
"xianyu-go/internal/renewal"
"xianyu-go/internal/server"
)
@@ -105,6 +106,7 @@ func main() {
logger.Error("启动账号引擎失败", "err", err)
}
go automation.NewScheduler(autoCenter).Run(ctx)
go renewal.NewScheduler(store, mgr, bm, ap, logger).Run(ctx)
// 3) HTTP 服务。
srv := server.New(store, mgr, bm, *secure, *webDir, *addr, logger, autoCenter, notifier)
+78
View File
@@ -0,0 +1,78 @@
x-app-env: &app-env
DATABASE_URL: postgres://${POSTGRES_USER:-xianyu}:${POSTGRES_PASSWORD:-xianyu_password}@postgres:5432/${POSTGRES_DB:-xianyu}?sslmode=disable
TZ: ${TZ:-Asia/Shanghai}
BROWSER_HEADLESS: ${BROWSER_HEADLESS:-true}
PLAYWRIGHT_DRIVER_PATH: ${PLAYWRIGHT_DRIVER_PATH:-/ms-playwright-go}
PLAYWRIGHT_NODEJS_PATH: ${PLAYWRIGHT_NODEJS_PATH:-/usr/bin/node}
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: ${PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD:-1}
PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH: ${PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH:-/usr/bin/chromium}
XIANYU_ADMIN_PASSWORD: ${XIANYU_ADMIN_PASSWORD:-}
x-app-volumes: &app-volumes
- app_data:/app/data
- browser_data:/app/browser_data
services:
postgres:
image: postgres:17-trixie
restart: unless-stopped
environment:
POSTGRES_DB: ${POSTGRES_DB:-xianyu}
POSTGRES_USER: ${POSTGRES_USER:-xianyu}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-xianyu_password}
TZ: ${TZ:-Asia/Shanghai}
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "${POSTGRES_PORT:-5432}:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\""]
interval: 10s
timeout: 5s
retries: 10
app:
image: ${XIANYU_IMAGE:-xianyu-go:debian13}
build:
context: .
dockerfile: Dockerfile.debian13
restart: unless-stopped
depends_on:
postgres:
condition: service_healthy
environment: *app-env
command: ["/app/xianyu-server", "-addr", ":8080"]
ports:
- "${XIANYU_HTTP_PORT:-8080}:8080"
volumes: *app-volumes
healthcheck:
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null || exit 1"]
interval: 30s
timeout: 5s
retries: 5
start_period: 30s
init-admin:
image: ${XIANYU_IMAGE:-xianyu-go:debian13}
build:
context: .
dockerfile: Dockerfile.debian13
profiles: ["init"]
restart: "no"
depends_on:
postgres:
condition: service_healthy
environment: *app-env
command:
- /bin/sh
- -c
- >-
test -n "$$XIANYU_ADMIN_PASSWORD" ||
{ echo "XIANYU_ADMIN_PASSWORD is required"; exit 1; };
exec /app/xianyu-server -init-admin -admin-password "$$XIANYU_ADMIN_PASSWORD"
volumes: *app-volumes
volumes:
postgres_data:
app_data:
browser_data:
File renamed without changes.

Before

Width:  |  Height:  |  Size: 4.5 KiB

After

Width:  |  Height:  |  Size: 4.5 KiB

+67 -32
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { AccountDetail, AIReplySettings, NotificationChannel } from '../types';
import {
@@ -28,6 +28,8 @@ import {
RefreshCw, Save, User, Clock, MessageCircle,
Upload, Key, Eye, EyeOff, Bot, Settings, AlertCircle, ExternalLink, Bell
} from 'lucide-react';
import { buildAccountLoginInfoUpdate } from './accountEdit';
import { createQRLoginPoller } from './qrPolling';
type ModalType = 'edit' | 'ai-settings' | null;
@@ -72,6 +74,37 @@ const AccountList: React.FC = () => {
custom_prompts: '',
});
const [saving, setSaving] = useState(false);
const qrPollerRef = useRef<ReturnType<typeof createQRLoginPoller> | null>(null);
const qrCloseTimerRef = useRef<ReturnType<typeof window.setTimeout> | null>(null);
if (qrPollerRef.current === null) {
qrPollerRef.current = createQRLoginPoller();
}
const clearQRCloseTimer = () => {
if (qrCloseTimerRef.current !== null) {
window.clearTimeout(qrCloseTimerRef.current);
qrCloseTimerRef.current = null;
}
};
const stopQRPolling = () => {
qrPollerRef.current?.stop();
};
const closeQRModal = () => {
stopQRPolling();
clearQRCloseTimer();
setShowQRModal(false);
};
const scheduleQRModalClose = () => {
clearQRCloseTimer();
qrCloseTimerRef.current = window.setTimeout(() => {
qrCloseTimerRef.current = null;
setShowQRModal(false);
loadAccounts();
}, 1000);
};
const refreshRuntimeStatuses = async () => {
try {
@@ -130,6 +163,13 @@ const AccountList: React.FC = () => {
return () => window.clearInterval(timer);
}, []);
useEffect(() => {
return () => {
stopQRPolling();
clearQRCloseTimer();
};
}, []);
const runtimePresentation = (account: AccountDetail) => {
if (!account.enabled || account.runtime_state === 'disabled') {
return { label: '已停用', badge: 'bg-gray-100 text-gray-500', dot: 'bg-gray-300' };
@@ -258,16 +298,9 @@ const AccountList: React.FC = () => {
}
// 更新登录信息
if (
editForm.username !== (editingAccount.username || '') ||
editForm.login_password !== (editingAccount.login_password || '') ||
editForm.show_browser !== (editingAccount.show_browser || false)
) {
promises.push(updateAccountLoginInfo(editingAccount.id, {
username: editForm.username,
login_password: editForm.login_password,
show_browser: editForm.show_browser,
}));
const loginInfo = buildAccountLoginInfoUpdate(editingAccount, editForm);
if (loginInfo) {
promises.push(updateAccountLoginInfo(editingAccount.id, loginInfo));
}
// 更新通知渠道绑定(覆盖式,总是提交以支持解绑)
@@ -308,17 +341,19 @@ const AccountList: React.FC = () => {
throw new Error('已取消覆盖当前账号授权');
}
}
await updateAccountCookie(target.id, cookies);
await updateAccountCookie(target.id, cookies, 'qr_scan');
return target.id;
}
if (!unb) {
throw new Error('扫码结果缺少账号ID,无法添加账号');
}
await addAccount(unb, cookies);
await addAccount(unb, cookies, 'qr_scan');
return unb;
};
const startQRLogin = async (target?: AccountDetail) => {
stopQRPolling();
clearQRCloseTimer();
const targetAccount = target || null;
setQrReauthTarget(targetAccount);
setShowQRModal(true);
@@ -335,10 +370,8 @@ const AccountList: React.FC = () => {
setQrSessionId(res.session_id);
setQrStatus('waiting');
const interval = setInterval(async () => {
const statusRes = await checkQRLoginStatus(res.session_id!);
if (statusRes.status === 'success') {
clearInterval(interval);
qrPollerRef.current?.start(res.session_id, checkQRLoginStatus, {
onSuccess: async (statusRes) => {
setQrStatus('success');
if (statusRes.cookies && statusRes.unb) {
try {
@@ -346,18 +379,22 @@ const AccountList: React.FC = () => {
} catch (e) {
console.error('保存扫码授权失败', e);
setQrStatus('error');
return;
}
}
setTimeout(() => {
setShowQRModal(false);
loadAccounts();
}, 1000);
} else if (statusRes.status === 'scanned') {
scheduleQRModalClose();
},
onScanned: () => {
setQrStatus('waiting'); // 已扫描,继续等待确认
} else if (statusRes.status === 'expired' || statusRes.status === 'cancelled' || statusRes.status === 'error' || statusRes.status === 'not_found') {
clearInterval(interval);
},
onTerminalError: () => {
setQrStatus('error');
} else if (statusRes.status === 'verification_required') {
},
onPollError: (error) => {
console.error('轮询扫码状态失败', error);
setQrStatus('error');
},
onVerificationRequired: (statusRes) => {
setQrStatus('verification');
setVerificationUrl(statusRes.verification_url || '');
if (statusRes.face_qr_url) {
@@ -366,8 +403,8 @@ const AccountList: React.FC = () => {
if (statusRes.verification_screenshot) {
setVerificationScreenshot(statusRes.verification_screenshot);
}
}
}, 2000);
},
});
}
} catch (e) {
setQrStatus('error');
@@ -381,12 +418,10 @@ const AccountList: React.FC = () => {
try {
const res = await completeQRVerification(qrSessionId);
if (res.success && res.cookies && res.unb) {
stopQRPolling();
await persistQRLoginResult(res.cookies, res.unb, qrReauthTarget);
setQrStatus('success');
setTimeout(() => {
setShowQRModal(false);
loadAccounts();
}, 1000);
scheduleQRModalClose();
} else {
setQrStatus('verification');
alert('验证未完成:' + (res.message || '可能验证尚未通过,请先在验证页面完成验证'));
@@ -577,7 +612,7 @@ const AccountList: React.FC = () => {
<div className="modal-overlay-centered">
<div className="modal-container relative" style={{maxWidth: '24rem'}}>
<button
onClick={() => setShowQRModal(false)}
onClick={closeQRModal}
className="absolute top-4 right-4 z-10 w-9 h-9 flex items-center justify-center bg-gray-100 hover:bg-gray-200 rounded-full transition-colors"
>
<X className="w-5 h-5 text-gray-600" />
+2
View File
@@ -401,6 +401,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
case 'success': return '成功';
case 'failed': return '失败';
case 'completed': return '已完成';
case 'partially_failed': return '部分失败';
case 'canceled': return '已取消';
default: return status || '-';
}
@@ -411,6 +412,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
case 'success':
case 'completed':
return 'bg-emerald-50 text-emerald-700 border-emerald-100';
case 'partially_failed':
case 'failed':
return 'bg-red-50 text-red-700 border-red-100';
case 'running':
-19
View File
@@ -221,25 +221,6 @@ const Settings: React.FC = () => {
</button>
</div>
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl">
<div>
<div className="font-bold text-gray-900">登录滑动验证码</div>
<div className="text-xs text-gray-500 mt-1">开启后账号密码登录需要完成滑动验证</div>
</div>
<button
onClick={() => setSettings({...settings, login_captcha_enabled: !settings.login_captcha_enabled})}
className={`w-14 h-8 rounded-full transition-all relative ${
settings.login_captcha_enabled ? 'bg-[#0094f7]' : 'bg-gray-300'
}`}
>
<div
className={`w-6 h-6 bg-white rounded-full absolute top-1 transition-all shadow-md ${
settings.login_captcha_enabled ? 'left-7' : 'left-1'
}`}
/>
</button>
</div>
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl">
<div>
<div className="font-bold text-gray-900">启用商品自动同步</div>
+36
View File
@@ -0,0 +1,36 @@
import { expect, test } from 'vitest';
import { buildAccountLoginInfoUpdate } from './accountEdit';
test('buildAccountLoginInfoUpdate omits blank password while updating other login fields', () => {
const payload = buildAccountLoginInfoUpdate(
{ id: 'acc1', enabled: true, auto_confirm: true, username: 'old-user', show_browser: true },
{ username: 'new-user', login_password: '', show_browser: false },
);
expect(payload).toEqual({
username: 'new-user',
show_browser: false,
});
});
test('buildAccountLoginInfoUpdate includes password only when user entered one', () => {
const payload = buildAccountLoginInfoUpdate(
{ id: 'acc1', enabled: true, auto_confirm: true, username: 'old-user', show_browser: false },
{ username: 'old-user', login_password: 'new-secret', show_browser: false },
);
expect(payload).toEqual({
username: 'old-user',
login_password: 'new-secret',
show_browser: false,
});
});
test('buildAccountLoginInfoUpdate skips unchanged login info', () => {
const payload = buildAccountLoginInfoUpdate(
{ id: 'acc1', enabled: true, auto_confirm: true, username: 'old-user', show_browser: false },
{ username: 'old-user', login_password: '', show_browser: false },
);
expect(payload).toBeNull();
});
+34
View File
@@ -0,0 +1,34 @@
import { AccountDetail } from '../types';
export interface AccountLoginEditForm {
username: string;
login_password: string;
show_browser: boolean;
}
export interface AccountLoginInfoPayload {
username: string;
login_password?: string;
show_browser: boolean;
}
export const buildAccountLoginInfoUpdate = (
account: AccountDetail,
form: AccountLoginEditForm,
): AccountLoginInfoPayload | null => {
const usernameChanged = form.username !== (account.username || '');
const showBrowserChanged = form.show_browser !== (account.show_browser || false);
const passwordChanged = form.login_password !== '';
if (!usernameChanged && !showBrowserChanged && !passwordChanged) {
return null;
}
const payload: AccountLoginInfoPayload = {
username: form.username,
show_browser: form.show_browser,
};
if (passwordChanged) {
payload.login_password = form.login_password;
}
return payload;
};
+98
View File
@@ -0,0 +1,98 @@
import { afterEach, expect, test, vi } from 'vitest';
import { createQRLoginPoller } from './qrPolling';
afterEach(() => {
vi.useRealTimers();
});
const flushMicrotasks = async () => {
await Promise.resolve();
await Promise.resolve();
};
test('QR poller clears the previous interval before starting another session', () => {
vi.useFakeTimers();
const checkStatus = vi.fn().mockResolvedValue({ status: 'waiting' });
const handlers = {
onSuccess: vi.fn(),
onTerminalError: vi.fn(),
onPollError: vi.fn(),
};
const poller = createQRLoginPoller();
poller.start('sid-1', checkStatus, handlers);
poller.start('sid-2', checkStatus, handlers);
vi.advanceTimersByTime(2000);
expect(checkStatus).toHaveBeenCalledTimes(1);
expect(checkStatus).toHaveBeenCalledWith('sid-2');
});
test('QR poller stops on success and terminal errors', async () => {
vi.useFakeTimers();
const checkStatus = vi.fn()
.mockResolvedValueOnce({ status: 'success', cookies: 'a=b', unb: 'acc1' })
.mockResolvedValueOnce({ status: 'expired' });
const onSuccess = vi.fn();
const onTerminalError = vi.fn();
const poller = createQRLoginPoller();
poller.start('sid-1', checkStatus, {
onSuccess,
onTerminalError,
onPollError: vi.fn(),
});
await vi.advanceTimersByTimeAsync(2000);
await flushMicrotasks();
expect(onSuccess).toHaveBeenCalledWith({ status: 'success', cookies: 'a=b', unb: 'acc1' });
expect(poller.isActive()).toBe(false);
await vi.advanceTimersByTimeAsync(4000);
expect(checkStatus).toHaveBeenCalledTimes(1);
poller.start('sid-2', checkStatus, {
onSuccess,
onTerminalError,
onPollError: vi.fn(),
});
await vi.advanceTimersByTimeAsync(2000);
await flushMicrotasks();
expect(onTerminalError).toHaveBeenCalledWith({ status: 'expired' });
expect(poller.isActive()).toBe(false);
});
test('QR poller keeps polling during verification and stops on thrown errors', async () => {
vi.useFakeTimers();
const checkStatus = vi.fn()
.mockResolvedValueOnce({
status: 'verification_required',
verification_url: 'https://verify.example',
face_qr_url: 'https://face.example',
})
.mockRejectedValueOnce(new Error('network down'));
const onVerificationRequired = vi.fn();
const onPollError = vi.fn();
const poller = createQRLoginPoller();
poller.start('sid-1', checkStatus, {
onSuccess: vi.fn(),
onTerminalError: vi.fn(),
onPollError,
onVerificationRequired,
});
await vi.advanceTimersByTimeAsync(2000);
await flushMicrotasks();
expect(onVerificationRequired).toHaveBeenCalledWith(expect.objectContaining({
status: 'verification_required',
face_qr_url: 'https://face.example',
}));
expect(poller.isActive()).toBe(true);
await vi.advanceTimersByTimeAsync(2000);
await flushMicrotasks();
expect(onPollError).toHaveBeenCalledWith(expect.any(Error));
expect(poller.isActive()).toBe(false);
});
+81
View File
@@ -0,0 +1,81 @@
export interface QRLoginStatusResult {
status?: string;
cookies?: string;
unb?: string;
verification_url?: string;
verification_screenshot?: string;
face_qr_url?: string;
}
interface QRLoginPollerTimers {
setInterval: (handler: () => void, timeout: number) => ReturnType<typeof setInterval>;
clearInterval: (id: ReturnType<typeof setInterval>) => void;
}
export interface QRLoginPollHandlers {
onSuccess: (status: QRLoginStatusResult) => void | Promise<void>;
onScanned?: (status: QRLoginStatusResult) => void;
onVerificationRequired?: (status: QRLoginStatusResult) => void;
onTerminalError: (status: QRLoginStatusResult) => void;
onPollError: (error: unknown) => void;
}
const terminalQRStatuses = new Set(['expired', 'cancelled', 'error', 'not_found']);
export const createQRLoginPoller = (
timers: QRLoginPollerTimers = {
setInterval: globalThis.setInterval.bind(globalThis),
clearInterval: globalThis.clearInterval.bind(globalThis),
},
) => {
let interval: ReturnType<typeof setInterval> | null = null;
const stop = () => {
if (interval !== null) {
timers.clearInterval(interval);
interval = null;
}
};
const start = (
sessionId: string,
checkStatus: (sessionId: string) => Promise<QRLoginStatusResult>,
handlers: QRLoginPollHandlers,
intervalMs = 2000,
) => {
stop();
interval = timers.setInterval(() => {
void (async () => {
try {
const statusRes = await checkStatus(sessionId);
if (statusRes.status === 'success') {
stop();
await handlers.onSuccess(statusRes);
return;
}
if (statusRes.status === 'scanned') {
handlers.onScanned?.(statusRes);
return;
}
if (statusRes.status === 'verification_required') {
handlers.onVerificationRequired?.(statusRes);
return;
}
if (statusRes.status && terminalQRStatuses.has(statusRes.status)) {
stop();
handlers.onTerminalError(statusRes);
}
} catch (error) {
stop();
handlers.onPollError(error);
}
})();
}, intervalMs);
};
return {
start,
stop,
isActive: () => interval !== null,
};
};
+2 -2
View File
@@ -7,8 +7,8 @@
mask 让容器背景色(蓝)也裁成超椭圆形状。
shadow 改用 filter:drop-shadow,跟随 mask 后的实际形状(box-shadow 会被 mask 裁掉)。 */
.squircle {
-webkit-mask-image: url(/static/squircle.svg);
mask-image: url(/static/squircle.svg);
-webkit-mask-image: url('./assets/squircle.svg');
mask-image: url('./assets/squircle.svg');
-webkit-mask-size: contain;
mask-size: contain;
-webkit-mask-repeat: no-repeat;
+119 -1
View File
@@ -1,5 +1,19 @@
import { afterEach, expect, test, vi } from 'vitest';
import { getItems, getOrders, getShippingRules, getValidOrders, updateShippingRule } from './api';
import {
addAccount,
cancelPasswordLogin,
checkPasswordLoginStatus,
getAccountDetails,
getItems,
getOrders,
getShippingRules,
getSystemSettings,
getValidOrders,
passwordLogin,
updateAccountCookie,
updateAccountLoginInfo,
updateShippingRule,
} from './api';
afterEach(() => vi.unstubAllGlobals());
@@ -56,6 +70,110 @@ test('getItems normalizes multi-spec flags from backend values', async () => {
});
});
test('getSystemSettings normalizes boolean strings', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({
registration_enabled: 'false',
show_default_login_info: 'true',
item_sync_enabled: '0',
ai_model: 'qwen-plus',
})));
const settings = await getSystemSettings();
expect(settings.registration_enabled).toBe(false);
expect(settings.show_default_login_info).toBe(true);
expect(settings.item_sync_enabled).toBe(false);
expect(settings.ai_model).toBe('qwen-plus');
});
test('account cookie APIs include login_method when provided', async () => {
const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(jsonResponse({ success: true })));
vi.stubGlobal('fetch', fetchMock);
await addAccount('acc1', 'unb=acc1', 'qr_scan');
expect(fetchMock).toHaveBeenCalledWith('/cookies', expect.objectContaining({
method: 'POST',
credentials: 'include',
}));
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
id: 'acc1',
value: 'unb=acc1',
login_method: 'qr_scan',
});
await updateAccountCookie('acc1', 'unb=acc1; x=1', 'qr_scan');
expect(fetchMock).toHaveBeenCalledWith('/cookies/acc1', expect.objectContaining({
method: 'PUT',
credentials: 'include',
}));
expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({
id: 'acc1',
value: 'unb=acc1; x=1',
login_method: 'qr_scan',
});
});
test('getAccountDetails normalizes show_browser and never exposes password', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
id: 'acc1',
enabled: true,
auto_confirm: true,
remark: '主账号',
pause_duration: 0,
username: 'login-user',
show_browser: '1',
login_password: 'should-not-leak',
}])));
const accounts = await getAccountDetails();
expect(accounts[0]).toMatchObject({
id: 'acc1',
username: 'login-user',
show_browser: true,
login_password: '',
});
});
test('updateAccountLoginInfo sends exactly provided fields', async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
vi.stubGlobal('fetch', fetchMock);
await updateAccountLoginInfo('acc1', { username: 'login-user', show_browser: false });
expect(fetchMock).toHaveBeenCalledWith('/cookies/acc1/login-info', expect.objectContaining({
method: 'PUT',
credentials: 'include',
}));
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
username: 'login-user',
show_browser: false,
});
});
test('password login service uses upstream-compatible routes', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(jsonResponse({ success: true, session_id: 'sid', status: 'processing' }))
.mockResolvedValueOnce(jsonResponse({ status: 'success', account_id: 'acc1', cookie_count: 2 }))
.mockResolvedValueOnce(jsonResponse({ success: true }));
vi.stubGlobal('fetch', fetchMock);
await passwordLogin({ account_id: 'acc1', account: 'u', password: 'p' });
expect(fetchMock).toHaveBeenNthCalledWith(1, '/password-login', expect.objectContaining({
method: 'POST',
credentials: 'include',
}));
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
account_id: 'acc1',
account: 'u',
password: 'p',
});
const status = await checkPasswordLoginStatus('sid');
expect(status.status).toBe('success');
expect(fetchMock).toHaveBeenNthCalledWith(2, '/password-login/check/sid', expect.objectContaining({ method: 'GET' }));
await cancelPasswordLogin('sid');
expect(fetchMock).toHaveBeenNthCalledWith(3, '/password-login/cancel/sid', expect.objectContaining({ method: 'DELETE' }));
});
test('getShippingRules exposes buyer reviewed gift rules as automation rules', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
id: 12,
+59 -6
View File
@@ -5,6 +5,22 @@ import {
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction
} from '../types';
const BOOLEAN_SETTING_KEYS = new Set([
'registration_enabled',
'show_default_login_info',
'item_sync_enabled',
]);
const normalizeSettings = (settings: Record<string, any>): SystemSettings => {
const out: Record<string, any> = { ...settings };
for (const key of BOOLEAN_SETTING_KEYS) {
if (key in out) {
out[key] = out[key] === true || out[key] === 'true' || out[key] === '1' || out[key] === 1;
}
}
return out as SystemSettings;
};
// Auth
export const login = async (data: { username?: string; password?: string; email?: string; verification_code?: string }): Promise<LoginResponse> => {
return post('/login', data);
@@ -31,8 +47,8 @@ export const updateLoginCredentials = async (data: {
};
// Accounts
export const addAccount = async (id: string, value: string): Promise<ApiResponse> => {
return post('/cookies', { id, value });
export const addAccount = async (id: string, value: string, loginMethod?: string): Promise<ApiResponse> => {
return post('/cookies', { id, value, login_method: loginMethod });
};
const accountAvatarURL = (item: any, version: string): string => {
@@ -64,7 +80,7 @@ export const getAccountDetails = async (): Promise<AccountDetail[]> => {
pause_duration: item.pause_duration,
username: item.username || '',
login_password: '',
show_browser: item.show_browser,
show_browser: item.show_browser === true || item.show_browser === 1 || item.show_browser === '1' || item.show_browser === 'true',
nickname: item.nickname || item.remark || `账号 ${item.id.substring(0,6)}`,
avatar_url: accountAvatarURL(item, avatarVersion),
profile_error: item.profile_error || '',
@@ -116,8 +132,45 @@ export const updateAccountPauseDuration = async (id: string, pauseDuration: numb
return put(`/cookies/${id}/pause-duration`, { pause_duration: pauseDuration });
};
export const updateAccountCookie = async (id: string, value: string): Promise<any> => {
return put(`/cookies/${id}`, { id, value });
export const updateAccountCookie = async (id: string, value: string, loginMethod?: string): Promise<any> => {
return put(`/cookies/${id}`, { id, value, login_method: loginMethod });
};
export interface PasswordLoginStartResponse {
success: boolean;
session_id?: string;
status?: 'processing' | 'failed';
message?: string;
}
export interface PasswordLoginStatusResponse {
status: 'processing' | 'success' | 'failed' | 'verification_required' | 'not_found' | 'error';
message?: string;
account_id?: string;
is_new_account?: boolean;
cookie_count?: number;
verification_url?: string;
screenshot_path?: string;
qr_code_url?: string;
error?: string;
reason?: string;
}
export const passwordLogin = async (data: {
account_id: string;
account: string;
password: string;
show_browser?: boolean;
}): Promise<PasswordLoginStartResponse> => {
return post('/password-login', data);
};
export const checkPasswordLoginStatus = async (sessionId: string): Promise<PasswordLoginStatusResponse> => {
return get(`/password-login/check/${sessionId}`);
};
export const cancelPasswordLogin = async (sessionId: string): Promise<ApiResponse> => {
return del(`/password-login/cancel/${sessionId}`);
};
export const refreshAccountProfile = async (id: string): Promise<any> => {
@@ -580,7 +633,7 @@ export const deleteReplyRule = async (id: string, cookieId: string): Promise<any
// Settings
export const getSystemSettings = async (): Promise<SystemSettings> => {
const res = await get<{data: SystemSettings}>('/system-settings');
return res.data || res; // handle {success:true, data: {...}} wrapper if exists
return normalizeSettings(res.data || res); // handle {success:true, data: {...}} wrapper if exists
};
export const updateSystemSettings = async (settings: Partial<SystemSettings>): Promise<ApiResponse> => {
+24 -1
View File
@@ -147,7 +147,30 @@ export default defineConfig({
sourcemap: false,
rollupOptions: {
output: {
manualChunks: undefined,
manualChunks(id) {
const modulePath = id.split(path.sep).join('/');
if (!modulePath.includes('/node_modules/')) {
return undefined;
}
if (
modulePath.includes('/react/') ||
modulePath.includes('/react-dom/') ||
modulePath.includes('/scheduler/')
) {
return 'react-vendor';
}
if (
modulePath.includes('/recharts/') ||
modulePath.includes('/victory-vendor/') ||
modulePath.includes('/d3-')
) {
return 'charts-vendor';
}
if (modulePath.includes('/lucide-react/')) {
return 'icons-vendor';
}
return 'vendor';
},
},
},
emptyOutDir: true,
+291 -30
View File
@@ -17,6 +17,10 @@ import (
"xianyu-go/internal/browser"
"xianyu-go/internal/db"
"xianyu-go/internal/engine"
"xianyu-go/internal/renewal"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/protocol"
xrenew "xianyu-go/internal/xianyu/renew"
)
// browserManager 是 adapter 所需的浏览器能力最小契约。*browser.Manager 实现该接口;
@@ -27,6 +31,10 @@ type browserManager interface {
PasswordLogin(ctx context.Context, account, password, cookieID, userDataDir string, headless bool) (map[string]string, error)
}
type browserQuickRenewer interface {
BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error)
}
// Adapter 实现 engine.Handler 与 automation.OrderDetailFetcher,
// 把系统消息、订单详情抓取和密码登录刷新接到浏览器与自动化中心。
//
@@ -38,11 +46,14 @@ type Adapter struct {
logger *slog.Logger
automation *automation.Center
notifier notifyNotifier
renewSvc xrenew.Service
cooldown *renewal.CooldownManager
mu sync.Mutex
lastLoginByCID map[string]time.Time
orderFetchMu sync.Mutex
lastOrderFetch time.Time
passwordMu sync.Mutex
passwordProcessing map[string]struct{}
}
// notifyNotifier 是 *notify.Notifier 的最小接口,避免 adapter 直接依赖 notify 包
@@ -57,7 +68,13 @@ func New(store *db.Store, bm *browser.Manager, logger *slog.Logger) *Adapter {
if logger == nil {
logger = slog.Default()
}
return &Adapter{store: store, browser: browserManagerOrNil(bm), logger: logger}
return &Adapter{
store: store,
browser: browserManagerOrNil(bm),
logger: logger,
cooldown: renewal.GlobalCooldown,
passwordProcessing: make(map[string]struct{}),
}
}
// browserManagerOrNil 把 *browser.Manager 转为接口;nil 时返回 nil 接口。
@@ -77,6 +94,9 @@ func (a *Adapter) SetNotifier(n notifyNotifier) { a.notifier = n }
// SetBrowser 覆盖浏览器实现,便于测试注入桩。
func (a *Adapter) SetBrowser(b browserManager) { a.browser = b }
// SetRenewService 覆盖轻量续期服务,便于测试注入本地 HTTP 服务。
func (a *Adapter) SetRenewService(s xrenew.Service) { a.renewSvc = s }
// HandleChatMessage 用户聊天消息由 Account 内部 ReplyService 处理,此处空实现满足接口。
func (a *Adapter) HandleChatMessage(_ context.Context, _ engine.ChatMessage) error {
return nil
@@ -157,51 +177,292 @@ func (a *Adapter) localOrderDetail(ctx context.Context, orderID string) (*automa
// OnPasswordLoginRefresh 连续失败时恢复 Cookie。
//
// 恢复顺序是“浏览器快速续期 -> 密码登录”。快速续期复用旧 Cookie 打开闲鱼,
// 尝试点“快速进入”刷新浏览器登录态;这比账号密码登录更轻,风控压力也更小。
// 恢复顺序是“轻量续期 -> 浏览器快速续期 -> 密码登录”。轻量续期/快速续期复用旧 Cookie
// 刷新登录态;这比账号密码登录更轻,风控压力也更小。
// 同一账号冷却 engine.PasswordLoginMinGap,避免短时间反复触发浏览器恢复。
func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) bool {
if a.browser == nil {
a.logger.Warn("密码登录刷新失败:浏览器自动化已禁用")
return false
cooldown := a.cooldown
if cooldown == nil {
cooldown = renewal.GlobalCooldown
}
a.mu.Lock()
if a.lastLoginByCID == nil {
a.lastLoginByCID = make(map[string]time.Time)
}
last := a.lastLoginByCID[cookieID]
if !last.IsZero() && time.Since(last) < engine.PasswordLoginMinGap {
remain := engine.PasswordLoginMinGap - time.Since(last)
a.mu.Unlock()
if ok, remain := cooldown.TryPasswordLogin(cookieID); !ok {
a.logger.Warn("密码登录刷新冷却中", "account", cookieID, "remain", remain.Round(time.Second))
a.recordPasswordLogin(ctx, cookieID, 0, "skipped_cooldown", "login_cooldown", fmt.Sprintf("密码登录刷新冷却中,还需等待 %s", remain.Round(time.Second)))
return false
}
a.mu.Unlock()
if !a.beginPasswordLogin(cookieID) {
a.logger.Warn("密码登录刷新已在处理中", "account", cookieID)
return false
}
defer a.finishPasswordLogin(cookieID)
d, err := a.store.Cookies.GetDetails(ctx, cookieID)
if err != nil {
a.logger.Warn("密码登录刷新失败:读取账号详情失败", "account", cookieID, "err", err)
a.recordPasswordLogin(ctx, cookieID, 0, "failed", "account_lookup_failed", err.Error())
return false
}
a.mu.Lock()
a.lastLoginByCID[cookieID] = time.Now()
a.mu.Unlock()
// 先走 Cookie 快速续期。只要旧 Cookie 还能触发快速进入,就不暴露账号密码登录,
// 也减少滑块/人脸/设备校验等更重风控的概率。
if a.saveRecoveredBrowserCookies(ctx, cookieID, d.UserID, func() (map[string]string, error) {
return a.browser.CookieRenew(ctx, cookieID, d.Value, !d.ShowBrowser)
}, "浏览器快速续期") {
if a.tryLightRenewBeforePassword(ctx, d) {
a.recordPasswordLogin(ctx, cookieID, d.UserID, "success", "", "密码登录前轻量续期成功")
return true
}
if strings.TrimSpace(d.Username) == "" || strings.TrimSpace(d.Password) == "" {
a.logger.Warn("密码登录刷新失败:账号未配置登录用户名或密码", "account", cookieID)
if latest, err := a.store.Cookies.GetDetails(ctx, cookieID); err == nil && latest != nil && latest.Value != "" && latest.Value != d.Value {
a.logger.Info("密码登录前检测到 DB Cookie 已被外部更新,跳过密码登录", "account", cookieID)
if a.store.Tokens != nil {
_ = a.store.Tokens.Clear(ctx, cookieID)
}
a.recordPasswordLogin(ctx, cookieID, d.UserID, "success", "cookie_already_updated_externally", "数据库中的 Cookie 已被外部更新,跳过密码登录")
return true
}
if a.browser == nil {
a.logger.Warn("密码登录刷新失败:浏览器自动化已禁用,接口轻量续期也未恢复", "account", cookieID)
a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", "browser_disabled", "浏览器自动化已禁用,接口轻量续期未恢复")
return false
}
return a.saveRecoveredBrowserCookies(ctx, cookieID, d.UserID, func() (map[string]string, error) {
return a.browser.PasswordLogin(ctx, d.Username, d.Password, cookieID, "", !d.ShowBrowser)
}, "密码登录刷新")
if strings.TrimSpace(d.Username) == "" || strings.TrimSpace(d.Password) == "" {
msg := "账号已掉线且未配置账号密码"
a.logger.Warn("密码登录刷新失败:账号未配置登录用户名或密码", "account", cookieID)
if err := a.store.Cookies.SetStatusWithReason(ctx, cookieID, false, msg); err != nil {
a.logger.Warn("未配置账号密码时停用账号失败", "account", cookieID, "err", err)
}
a.recordPasswordLogin(ctx, cookieID, d.UserID, "no_credentials", "no_credentials", msg)
return false
}
cookies, err := a.browser.PasswordLogin(ctx, d.Username, d.Password, cookieID, "", !d.ShowBrowser)
if err != nil {
a.handlePasswordLoginError(ctx, cookieID, err)
a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", passwordLoginFailureReason(err), err.Error())
return false
}
cookieStr := browser.MarshalCookies(cookies)
if strings.TrimSpace(cookieStr) == "" {
a.logger.Warn("密码登录刷新失败:浏览器未返回 cookie", "account", cookieID)
a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", "empty_cookies", "浏览器未返回 cookie")
return false
}
if err := a.store.Cookies.Save(ctx, cookieID, cookieStr, d.UserID); err != nil {
a.logger.Warn("密码登录刷新失败:保存 cookie 失败", "account", cookieID, "err", err)
a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", "cookie_update_failed", err.Error())
return false
}
if a.store.Tokens != nil {
_ = a.store.Tokens.Clear(ctx, cookieID)
}
_ = a.store.Cookies.MarkLogin(ctx, cookieID, "password", time.Now().Unix())
a.recordPasswordLogin(ctx, cookieID, d.UserID, "success", "", "账号密码登录刷新成功")
a.logger.Info("密码登录刷新 cookie 成功", "account", cookieID)
return true
}
func (a *Adapter) beginPasswordLogin(cookieID string) bool {
a.passwordMu.Lock()
defer a.passwordMu.Unlock()
if a.passwordProcessing == nil {
a.passwordProcessing = make(map[string]struct{})
}
if _, ok := a.passwordProcessing[cookieID]; ok {
return false
}
a.passwordProcessing[cookieID] = struct{}{}
return true
}
func (a *Adapter) finishPasswordLogin(cookieID string) {
a.passwordMu.Lock()
defer a.passwordMu.Unlock()
delete(a.passwordProcessing, cookieID)
}
func (a *Adapter) recordPasswordLogin(ctx context.Context, cookieID string, userID int64, status, failureReason, message string) {
if a.store == nil || a.store.LoginLogs == nil {
return
}
if err := a.store.LoginLogs.Add(ctx, db.AccountLoginLog{
CookieID: cookieID,
UserID: userID,
Method: "password",
Status: status,
Message: truncateMessage(message, 500),
TriggerReason: "令牌/Session过期",
FailureReason: failureReason,
ErrorMessage: truncateMessage(message, 500),
AccountIdentifier: cookieID,
DurationMS: 0,
CreatedAt: time.Now().Unix(),
}); err != nil {
a.logger.Warn("记录密码登录日志失败", "account", cookieID, "err", err)
}
}
func passwordLoginFailureReason(err error) string {
if err == nil {
return ""
}
msg := err.Error()
if isPasswordLoginBadCredentials(msg) {
return "bad_credentials"
}
event := browser.PasswordLoginEventFromError(err)
if event.Reason != "" {
return event.Reason
}
if event.Status == browser.PasswordLoginStatusVerificationRequired {
return "verification_required"
}
return "other"
}
func truncateMessage(s string, n int) string {
if n <= 0 || len(s) <= n {
return s
}
return s[:n]
}
func (a *Adapter) tryLightRenewBeforePassword(ctx context.Context, d *db.CookieDetail) bool {
if d == nil {
return false
}
current := d.Value
api := a.renewSvc
save := func(cookieStr string) {
if strings.TrimSpace(cookieStr) == "" || cookieStr == current {
return
}
if err := a.store.Cookies.UpdateRenewalCookie(ctx, d.ID, cookieStr, cookierefresh.MetadataWithoutSnapshot(d.MetadataJSON), time.Now().Unix()); err != nil {
a.logger.Warn("轻量续期保存 Cookie 失败", "account", d.ID, "err", err)
return
}
current = cookieStr
d.Value = cookieStr
if a.store.Tokens != nil {
_ = a.store.Tokens.Clear(ctx, d.ID)
}
}
apiRenew := func(cookieStr string) (*xrenew.Result, error) {
runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
defer cancel()
return api.RenewAPIFirst(runCtx, cookieStr)
}
browserRenew := func(cookieStr string) (string, error) {
if a.browser == nil {
return "", fmt.Errorf("浏览器自动化未启用")
}
if br, ok := a.browser.(browserQuickRenewer); ok {
runCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
return br.BrowserQuickRenew(runCtx, d.ID, cookieStr, !d.ShowBrowser)
}
m, err := a.browser.CookieRenew(ctx, d.ID, cookieStr, !d.ShowBrowser)
if err != nil {
return "", err
}
return browser.MarshalCookies(m), nil
}
hasLongLogin := strings.TrimSpace(protocol.TransCookies(current)["havana_lgc2_77"]) != ""
if hasLongLogin {
browserCookies := current
if renewed, err := browserRenew(current); err == nil && renewed != "" {
browserCookies = renewed
save(browserCookies)
} else if err != nil {
a.logger.Warn("密码登录前浏览器续期失败,继续尝试接口续期", "account", d.ID, "err", err)
}
if res, err := apiRenew(browserCookies); err == nil && res != nil {
save(res.NewCookies)
if res.Success {
a.logger.Info("密码登录前浏览器+接口续期成功,跳过密码登录", "account", d.ID)
return true
}
}
return false
}
res, err := apiRenew(current)
if err == nil && res != nil {
save(res.NewCookies)
if res.Success {
a.logger.Info("密码登录前接口续期成功,跳过密码登录", "account", d.ID)
return true
}
}
browserInput := current
if res != nil && strings.TrimSpace(res.NewCookies) != "" {
browserInput = res.NewCookies
}
browserCookies, err := browserRenew(browserInput)
if err != nil || browserCookies == "" {
return false
}
save(browserCookies)
verify, err := apiRenew(browserCookies)
if err != nil || verify == nil {
return false
}
save(verify.NewCookies)
if verify.Success {
a.logger.Info("密码登录前浏览器续期并通过接口验证,跳过密码登录", "account", d.ID)
return true
}
return false
}
func (a *Adapter) handlePasswordLoginError(ctx context.Context, cookieID string, err error) {
msg := err.Error()
a.logger.Warn("密码登录刷新失败", "account", cookieID, "err", err)
if isPasswordLoginDisableError(msg) {
_ = a.store.Cookies.SetStatusWithReason(ctx, cookieID, false, msg)
if isPasswordLoginBadCredentials(msg) {
a.markPasswordError(cookieID)
}
return
}
if isPasswordLoginRetryableVerification(msg) {
a.markPasswordError(cookieID)
}
}
func isPasswordLoginBadCredentials(msg string) bool {
return strings.Contains(msg, "账密错误") ||
strings.Contains(msg, "账号密码错误") ||
strings.Contains(msg, "用户名或密码错误") ||
strings.Contains(msg, "账号或密码错误") ||
strings.Contains(msg, "密码错误")
}
func isPasswordLoginDisableError(msg string) bool {
return isPasswordLoginBadCredentials(msg) ||
strings.Contains(msg, "账号不存在") ||
strings.Contains(msg, "账号已被冻结") ||
strings.Contains(msg, "账号被冻结") ||
strings.Contains(msg, "账户被冻结") ||
strings.Contains(msg, "账号已锁定") ||
strings.Contains(msg, "账户已锁定") ||
strings.Contains(msg, "操作过于频繁") ||
strings.Contains(msg, "登录过于频繁") ||
strings.Contains(msg, "暂时无法登录")
}
func isPasswordLoginRetryableVerification(msg string) bool {
event := browser.PasswordLoginEventFromMessage(msg)
return event.Reason == "baxia_punish_captcha" ||
event.Status == browser.PasswordLoginStatusVerificationRequired ||
strings.Contains(msg, "人工验证") ||
strings.Contains(msg, "人脸验证") ||
strings.Contains(msg, "身份验证")
}
func (a *Adapter) markPasswordError(cookieID string) {
cooldown := a.cooldown
if cooldown == nil {
cooldown = renewal.GlobalCooldown
}
cooldown.MarkPasswordError(cookieID)
}
// saveRecoveredBrowserCookies 执行浏览器恢复动作,统一校验、保存 Cookie 并清理 token 缓存。
+186 -9
View File
@@ -3,12 +3,17 @@ package adapter
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"xianyu-go/internal/automation"
"xianyu-go/internal/browser"
"xianyu-go/internal/db"
"xianyu-go/internal/renewal"
xrenew "xianyu-go/internal/xianyu/renew"
)
// fakeNotifier 记录告警调用,供 OnAccountAlert 断言。
@@ -54,10 +59,52 @@ func newAdapterTestStore(t *testing.T) (*db.Store, func()) {
ctx := context.Background()
s.Users.Create(ctx, "admin", "a@e.com", "pw")
admin, _ := s.Users.GetByUsername(ctx, "admin")
s.Cookies.Save(ctx, "cid", "unb=1; _m_h5_tk=tk;", admin.ID)
s.Cookies.Save(ctx, "cid", "unb=1; _m_h5_tk=tk; havana_lgc2_77=lgc;", admin.ID)
renewal.GlobalCooldown.Reset("cid")
return s, func() { d.Close() }
}
func verifiedRenewService(t *testing.T) (xrenew.Service, func()) {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/hasLogin.do", "/silentHasLogin.do":
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
case "/setLoginSettings.do":
http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "verified"})
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
default:
http.NotFound(w, r)
}
}))
return xrenew.Service{
HTTPClient: srv.Client(),
HasLoginURL: srv.URL + "/hasLogin.do",
SilentHasLoginURL: srv.URL + "/silentHasLogin.do",
SetLoginSettingsURL: srv.URL + "/setLoginSettings.do",
RetryDelay: -1,
}, srv.Close
}
func unverifiedRenewService(t *testing.T) (xrenew.Service, func()) {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/hasLogin.do", "/silentHasLogin.do", "/setLoginSettings.do":
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
default:
http.NotFound(w, r)
}
}))
return xrenew.Service{
HTTPClient: srv.Client(),
HasLoginURL: srv.URL + "/hasLogin.do",
SilentHasLoginURL: srv.URL + "/silentHasLogin.do",
SetLoginSettingsURL: srv.URL + "/setLoginSettings.do",
RetryDelay: -1,
}, srv.Close
}
// TestOnAccountAlert_ForwardedToNotifier 注入 notifier 后告警被转发;未注入时不 panic。
func TestOnAccountAlert_ForwardedToNotifier(t *testing.T) {
store, cleanup := newAdapterTestStore(t)
@@ -140,25 +187,60 @@ func TestFetchOrderDetail_BrowserFallback(t *testing.T) {
}
}
// TestOnPasswordLoginRefresh_BrowserNilReturnsFalse 浏览器未启用时直接返回 false。
func TestOnPasswordLoginRefresh_BrowserNilReturnsFalse(t *testing.T) {
// TestOnPasswordLoginRefresh_BrowserNilStillUsesAPIRenew 浏览器未启用时仍先尝试接口轻量续期。
func TestOnPasswordLoginRefresh_BrowserNilStillUsesAPIRenew(t *testing.T) {
store, cleanup := newAdapterTestStore(t)
defer cleanup()
a := New(store, nil, nil)
if a.OnPasswordLoginRefresh(context.Background(), "cid") {
t.Fatal("browser=nil 应返回 false")
renewSvc, closeRenew := verifiedRenewService(t)
defer closeRenew()
a.SetRenewService(renewSvc)
if !a.OnPasswordLoginRefresh(context.Background(), "cid") {
t.Fatal("browser=nil 但接口续期成功时应返回 true")
}
saved, _ := store.Cookies.GetValue(context.Background(), "cid")
if !strings.Contains(saved, "havana_lgc2_77=verified") {
t.Fatalf("接口续期 cookie 未保存: %q", saved)
}
}
// TestOnPasswordLoginRefresh_NoCredentialsReturnsFalse 有浏览器但账号未配密码时返回 false。
func TestOnPasswordLoginRefresh_NoCredentialsReturnsFalse(t *testing.T) {
// TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure 接口轻量续期也失败后才因浏览器不可用失败。
func TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure(t *testing.T) {
store, cleanup := newAdapterTestStore(t)
defer cleanup()
a := New(store, nil, nil)
a.SetBrowser(&fakeBrowser{renewErr: errors.New("quick enter unavailable")})
renewSvc, closeRenew := unverifiedRenewService(t)
defer closeRenew()
a.SetRenewService(renewSvc)
if a.OnPasswordLoginRefresh(context.Background(), "cid") {
t.Fatal("browser=nil 且接口续期失败时应返回 false")
}
logs, err := store.LoginLogs.ListByCookie(context.Background(), "cid", 10)
if err != nil || len(logs) != 1 || logs[0].FailureReason != "browser_disabled" {
t.Fatalf("浏览器不可用应记录 browser_disabled: logs=%#v err=%v", logs, err)
}
}
// TestOnPasswordLoginRefresh_NoCredentialsReturnsFalse 有浏览器但账号未配密码时返回 false 并停用账号。
func TestOnPasswordLoginRefresh_NoCredentialsReturnsFalse(t *testing.T) {
store, cleanup := newAdapterTestStore(t)
defer cleanup()
ctx := context.Background()
a := New(store, nil, nil)
renewSvc, closeRenew := unverifiedRenewService(t)
defer closeRenew()
a.SetRenewService(renewSvc)
a.SetBrowser(&fakeBrowser{renewErr: errors.New("quick enter unavailable")})
if a.OnPasswordLoginRefresh(ctx, "cid") {
t.Fatal("账号未配用户名/密码应返回 false")
}
if store.Cookies.GetStatus(ctx, "cid") {
t.Fatal("未配置账号密码应自动停用账号,避免持续重试")
}
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
if err != nil || len(logs) != 1 || logs[0].Status != "no_credentials" || logs[0].FailureReason != "no_credentials" {
t.Fatalf("无凭据应记录 no_credentials 日志: logs=%#v err=%v", logs, err)
}
}
// TestOnPasswordLoginRefresh_BrowserRenewSuccess 无账密时旧 Cookie 仍可快速续期,应保存新 Cookie 并跳过密码登录。
@@ -172,6 +254,9 @@ func TestOnPasswordLoginRefresh_BrowserRenewSuccess(t *testing.T) {
fb := &fakeBrowser{renewCookies: map[string]string{"unb": "1", "_m_h5_tk": "renewed"}}
a := New(store, nil, nil)
renewSvc, closeRenew := verifiedRenewService(t)
defer closeRenew()
a.SetRenewService(renewSvc)
a.SetBrowser(fb)
if !a.OnPasswordLoginRefresh(ctx, "cid") {
t.Fatal("快速续期成功应返回 true")
@@ -183,12 +268,16 @@ func TestOnPasswordLoginRefresh_BrowserRenewSuccess(t *testing.T) {
t.Fatalf("快速续期成功后不应密码登录,got %d", fb.loginCalls)
}
saved, _ := store.Cookies.GetValue(ctx, "cid")
if saved == "" || saved == "unb=1; _m_h5_tk=tk;" {
if !strings.Contains(saved, "_m_h5_tk=renewed") || !strings.Contains(saved, "havana_lgc2_77=verified") {
t.Fatalf("快速续期 cookie 未保存: %q", saved)
}
if _, err := store.Tokens.Get(ctx, "cid"); err != db.ErrNotFound {
t.Fatalf("Cookie 更新后应清除旧 token,got %v", err)
}
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
if err != nil || len(logs) != 1 || logs[0].Status != "success" {
t.Fatalf("快速续期应记录登录日志: logs=%#v err=%v", logs, err)
}
}
// TestOnPasswordLoginRefresh_Success 配好凭据后浏览器登录成功,cookie 被保存。
@@ -201,6 +290,9 @@ func TestOnPasswordLoginRefresh_Success(t *testing.T) {
fb := &fakeBrowser{renewErr: errors.New("quick enter unavailable"), loginCookies: map[string]string{"unb": "1", "_m_h5_tk": "fresh"}}
a := New(store, nil, nil)
renewSvc, closeRenew := unverifiedRenewService(t)
defer closeRenew()
a.SetRenewService(renewSvc)
a.SetBrowser(fb)
if !a.OnPasswordLoginRefresh(ctx, "cid") {
t.Fatal("登录成功应返回 true")
@@ -212,6 +304,17 @@ func TestOnPasswordLoginRefresh_Success(t *testing.T) {
if saved == "" {
t.Fatal("刷新的 cookie 应已保存")
}
d, err := store.Cookies.GetDetails(ctx, "cid")
if err != nil {
t.Fatalf("GetDetails: %v", err)
}
if d.LoginMethod != "password" || d.LastLoginAt == 0 {
t.Fatalf("密码登录成功后应标记登录审计字段: %+v", d)
}
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
if err != nil || len(logs) != 1 || logs[0].Status != "success" {
t.Fatalf("密码登录成功应记录日志: logs=%#v err=%v", logs, err)
}
}
// TestOnPasswordLoginRefresh_LoginError 浏览器登录返回错误时返回 false 且不保存 cookie。
@@ -223,10 +326,77 @@ func TestOnPasswordLoginRefresh_LoginError(t *testing.T) {
fb := &fakeBrowser{renewErr: errors.New("quick enter unavailable"), loginErr: errors.New("captcha required")}
a := New(store, nil, nil)
renewSvc, closeRenew := unverifiedRenewService(t)
defer closeRenew()
a.SetRenewService(renewSvc)
a.SetBrowser(fb)
if a.OnPasswordLoginRefresh(ctx, "cid") {
t.Fatal("登录失败应返回 false")
}
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
if err != nil || len(logs) != 1 || logs[0].Status != "failed" || logs[0].FailureReason != "verification_required" {
t.Fatalf("密码登录失败应记录日志: logs=%#v err=%v", logs, err)
}
}
func TestOnPasswordLoginRefresh_BaxiaFailureReason(t *testing.T) {
store, cleanup := newAdapterTestStore(t)
defer cleanup()
ctx := context.Background()
store.DB.ExecContext(ctx, `UPDATE cookies SET username='u', password='p' WHERE id='cid'`)
fb := &fakeBrowser{renewErr: errors.New("quick enter unavailable"), loginErr: errors.New("baxia-punish 风控图形验证")}
a := New(store, nil, nil)
renewSvc, closeRenew := unverifiedRenewService(t)
defer closeRenew()
a.SetRenewService(renewSvc)
a.SetBrowser(fb)
if a.OnPasswordLoginRefresh(ctx, "cid") {
t.Fatal("风控失败应返回 false")
}
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
if err != nil || len(logs) != 1 || logs[0].FailureReason != "baxia_punish_captcha" {
t.Fatalf("baxia 风控应记录专用 failure_reason: logs=%#v err=%v", logs, err)
}
if !store.Cookies.GetStatus(ctx, "cid") {
t.Fatal("baxia 风控只应冷却,不应停用账号")
}
}
func TestOnPasswordLoginRefresh_DisablesFrozenAccountError(t *testing.T) {
store, cleanup := newAdapterTestStore(t)
defer cleanup()
ctx := context.Background()
store.DB.ExecContext(ctx, `UPDATE cookies SET username='u', password='p' WHERE id='cid'`)
fb := &fakeBrowser{renewErr: errors.New("quick enter unavailable"), loginErr: errors.New("账号已被冻结")}
a := New(store, nil, nil)
renewSvc, closeRenew := unverifiedRenewService(t)
defer closeRenew()
a.SetRenewService(renewSvc)
a.SetBrowser(fb)
if a.OnPasswordLoginRefresh(ctx, "cid") {
t.Fatal("冻结账号登录失败应返回 false")
}
if store.Cookies.GetStatus(ctx, "cid") {
t.Fatal("冻结账号登录错误应停用账号")
}
}
func TestPasswordLoginProcessingLock(t *testing.T) {
store, cleanup := newAdapterTestStore(t)
defer cleanup()
a := New(store, nil, nil)
if !a.beginPasswordLogin("cid") {
t.Fatal("首次获取 processing 锁应成功")
}
if a.beginPasswordLogin("cid") {
t.Fatal("同账号重复获取 processing 锁应失败")
}
a.finishPasswordLogin("cid")
if !a.beginPasswordLogin("cid") {
t.Fatal("释放后应可再次获取 processing 锁")
}
}
// TestOnPasswordLoginRefresh_Cooldown 同一账号短时间内第二次刷新被冷却拒绝。
@@ -238,6 +408,9 @@ func TestOnPasswordLoginRefresh_Cooldown(t *testing.T) {
fb := &fakeBrowser{renewErr: errors.New("quick enter unavailable"), loginCookies: map[string]string{"unb": "1"}}
a := New(store, nil, nil)
renewSvc, closeRenew := unverifiedRenewService(t)
defer closeRenew()
a.SetRenewService(renewSvc)
a.SetBrowser(fb)
if !a.OnPasswordLoginRefresh(ctx, "cid") {
t.Fatal("首次应成功")
@@ -249,4 +422,8 @@ func TestOnPasswordLoginRefresh_Cooldown(t *testing.T) {
if fb.loginCalls != 1 {
t.Fatalf("冷却期内不应调用浏览器,got calls=%d", fb.loginCalls)
}
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
if err != nil || len(logs) != 2 || logs[0].Status != "skipped_cooldown" || logs[0].FailureReason != "login_cooldown" {
t.Fatalf("冷却拒绝应记录 skipped_cooldown 日志: logs=%#v err=%v", logs, err)
}
}
+336 -22
View File
@@ -3,9 +3,21 @@ package browser
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/playwright-community/playwright-go"
"xianyu-go/internal/xianyu/cookierefresh"
)
const (
quickRenewPageLoadWait = 3 * time.Second
quickRenewAfterClick = 5 * time.Second
quickRenewTimeoutMS = 30000
quickRenewUA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36"
)
// CookieRenew 用现有 Cookie 打开闲鱼页面,尝试通过“快速进入”刷新浏览器登录态。
@@ -13,47 +25,349 @@ import (
// 这个方法位于密码登录之前:如果 Cookie 仍保留可续期的浏览器会话,页面通常会给出
// 免输密码的快速进入入口。成功点击后提取完整 Cookie,可避免更重的账号密码登录。
func (m *Manager) CookieRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (map[string]string, error) {
if cookieStr == "" {
return nil, fmt.Errorf("Cookie为空,无法浏览器续期")
}
page, release, err := m.newPage(ctx, cookieID, cookieStr, headless)
newCookies, err := m.BrowserQuickRenew(ctx, cookieID, cookieStr, headless)
if err != nil {
return nil, err
}
return cookierefresh.ParseCookieString(newCookies), nil
}
// BrowserQuickRenew 使用持久化浏览器上下文执行“快速进入”Cookie 续期。
func (m *Manager) BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error) {
if cookieStr == "" {
return "", fmt.Errorf("Cookie为空,无法浏览器续期")
}
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, nil, quickRenewHeadless(headless))
if err != nil {
return "", err
}
defer release()
if _, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(30000),
}); err != nil {
m.logger.Warn("浏览器续期访问 IM 页面异常", "cookieID", cookieID, "err", err)
page, err := bctx.NewPage()
if err != nil {
return "", fmt.Errorf("新建 page 失败: %w", err)
}
if checkLoginSuccess(page) {
m.logger.Info("浏览器续期:已有有效登录态", "cookieID", cookieID)
return extractPageCookies(page)
defer func() { _ = page.Close() }()
if _, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(quickRenewTimeoutMS),
}); err != nil {
m.logger.Warn("浏览器续期访问首页异常", "cookieID", cookieID, "err", err)
}
time.Sleep(quickRenewPageLoadWait)
hasQuickEnter := clickQuickEnter(page)
if hasQuickEnter {
time.Sleep(quickRenewAfterClick)
} else if !checkAlreadyLoggedIn(page) {
return "", fmt.Errorf("未找到[快速进入]按钮且未检测到登录状态,需要账号密码登录")
}
if !clickQuickEnter(page) {
return nil, fmt.Errorf("未找到快速进入入口,需要密码登录")
all, err := bctx.Cookies()
if err != nil {
return "", fmt.Errorf("提取 cookie 失败: %w", err)
}
time.Sleep(5 * time.Second)
if !checkLoginSuccess(page) {
return nil, fmt.Errorf("快速进入后仍未检测到登录态")
newSnapshot := cookieSnapshotFromPlaywright(all)
if len(newSnapshot) == 0 {
return "", fmt.Errorf("点击[快速进入]后未获取到浏览器Cookie")
}
m.logger.Info("浏览器续期:快速进入成功", "cookieID", cookieID)
return extractPageCookies(page)
cookieFromBrowser := cookierefresh.CookieStringFromSnapshot(newSnapshot)
merged := cookierefresh.MergeOriginalFields(cookieStr, cookieFromBrowser)
m.logger.Info("浏览器续期成功", "cookieID", cookieID, "has_quick_enter", hasQuickEnter, "cookie_count", len(newSnapshot))
return merged, nil
}
// CookiesRefreshSnapshot 执行定时 COOKIES 续期:打开首页、刷新页面并返回完整 Cookie 快照。
func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error) {
if cookieStr == "" && len(snapshot) == 0 {
return "", nil, fmt.Errorf("Cookie为空,且无完整Cookie快照,无法执行续期")
}
bctx, release, err := m.newEphemeralRefreshContext(ctx, cookieID, cookieStr, snapshot, cookiesRefreshHeadless(headless))
if err != nil {
return "", nil, err
}
defer release()
page, err := bctx.NewPage()
if err != nil {
return "", nil, fmt.Errorf("新建 page 失败: %w", err)
}
defer func() { _ = page.Close() }()
if _, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(60000),
}); err != nil {
m.logger.Warn("COOKIES续期访问首页异常", "cookieID", cookieID, "err", err)
}
time.Sleep(2 * time.Second)
for i := 0; i < 3; i++ {
if _, err := page.Reload(playwright.PageReloadOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(60000),
}); err != nil {
m.logger.Warn("COOKIES续期 reload 异常", "cookieID", cookieID, "attempt", i+1, "err", err)
}
time.Sleep(2 * time.Second)
}
if modal, err := page.QuerySelector(".ant-modal-body"); err == nil && modal != nil {
text, _ := modal.TextContent()
if len(text) > 120 {
text = text[:120]
}
if text != "" {
return "", nil, fmt.Errorf("页面存在 ant-modal-body,判定续期失败: %s", text)
}
return "", nil, fmt.Errorf("页面存在 ant-modal-body,判定续期失败")
}
all, err := bctx.Cookies()
if err != nil {
return "", nil, fmt.Errorf("提取 cookie 失败: %w", err)
}
newSnapshot := cookieSnapshotFromPlaywright(all)
if len(newSnapshot) == 0 {
return "", nil, fmt.Errorf("页面刷新完成,但未获取到浏览器Cookie")
}
newCookies := cookierefresh.CookieStringFromSnapshot(newSnapshot)
m.logger.Info("COOKIES续期成功", "cookieID", cookieID, "cookie_count", len(newSnapshot))
return newCookies, newSnapshot, nil
}
// CookieRenewSnapshot 兼容旧调用,等价于定时 COOKIES 快照续期。
func (m *Manager) CookieRenewSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error) {
return m.CookiesRefreshSnapshot(ctx, cookieID, cookieStr, snapshot, headless)
}
func clickQuickEnter(page playwright.Page) bool {
frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...)
for _, f := range frames {
for _, sel := range loginBtnSelectors {
for _, sel := range quickEnterSelectors {
el, err := f.QuerySelector(sel)
if err == nil && el != nil {
_ = el.Click()
if err == nil && el != nil && elementVisible(el) {
if err := el.Click(); err == nil {
return true
}
}
}
buttons, err := f.QuerySelectorAll("button")
if err != nil {
continue
}
for _, btn := range buttons {
text, _ := btn.TextContent()
if strings.Contains(strings.TrimSpace(text), "快速进入") && elementVisible(btn) {
_ = btn.Click()
return true
}
}
}
return false
}
var quickEnterSelectors = []string{
`button:has-text("快速进入")`,
`button[type="submit"]:has-text("快速进入")`,
`.fm-button:has-text("快速进入")`,
`.fn-button:has-text("快速进入")`,
}
var loggedInSelectors = []string{
"div.nick",
".header-right .nick",
".rc-virtual-list-holder-inner",
`img[src*="img.alicdn.com"][class*="avatar"]`,
`img[src*="img.alicdn.com"][style*="border-radius"]`,
`.header-container img[src*="img.alicdn.com"]`,
"#nc_1_n1z",
".nc-container",
".nc_scale",
`div:has-text("请拖动下方滑块完成验证")`,
`div:has-text("请按住滑块")`,
}
func checkAlreadyLoggedIn(page playwright.Page) bool {
for _, sel := range loggedInSelectors {
el, err := page.QuerySelector(sel)
if err == nil && el != nil && elementVisible(el) {
return true
}
}
bodyText, err := page.TextContent("body")
if err == nil && strings.Contains(bodyText, "消息") && (strings.Contains(bodyText, "订单") || strings.Contains(bodyText, "发闲置")) {
return true
}
return false
}
func elementVisible(el playwright.ElementHandle) bool {
visible, err := el.IsVisible()
return err == nil && visible
}
func cleanSingletonFiles(userDataDir string) {
for _, name := range []string{"SingletonLock", "SingletonSocket", "SingletonCookie"} {
_ = os.Remove(filepath.Join(userDataDir, name))
}
}
func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (playwright.BrowserContext, func(), error) {
lock := m.accountRenewLock(cookieID)
lock.Lock()
unlock := func() { lock.Unlock() }
releaseSlot, err := m.acquireRenewSlot(ctx)
if err != nil {
unlock()
return nil, nil, err
}
if err := m.init(); err != nil {
releaseSlot()
unlock()
return nil, nil, err
}
userDataDir := filepath.Join("browser_data", "user_"+pureUserID(cookieID))
cleanSingletonFiles(userDataDir)
var bctx playwright.BrowserContext
var lastErr error
for attempt := 1; attempt <= 2; attempt++ {
bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, playwright.BrowserTypeLaunchPersistentContextOptions{
Headless: playwright.Bool(headless),
Args: chromiumLaunchArgs(),
ExecutablePath: chromiumExecutablePath(),
UserAgent: playwright.String(quickRenewUA),
Viewport: &playwright.Size{Width: 1280, Height: 720},
Locale: playwright.String(defaultLang),
TimezoneId: playwright.String(defaultTZ),
Timeout: playwright.Float(quickRenewTimeoutMS),
})
if err == nil {
break
}
lastErr = err
cleanSingletonFiles(userDataDir)
time.Sleep(time.Second)
}
if bctx == nil {
releaseSlot()
unlock()
return nil, nil, fmt.Errorf("启动持久化浏览器失败: %w", lastErr)
}
if err := bctx.AddInitScript(playwright.Script{Content: playwright.String(stealthScript())}); err != nil {
m.logger.Warn("注入 stealth 脚本失败", "err", err)
}
if len(snapshot) > 0 {
if err := bctx.AddCookies(snapshotToOptionalCookies(snapshot)); err != nil {
m.logger.Warn("浏览器续期注入 Cookie 快照失败", "cookieID", cookieID, "err", err)
}
} else if cookieStr != "" {
if err := addCookieStr(bctx, cookieStr); err != nil {
m.logger.Warn("浏览器续期注入 Cookie 字符串失败", "cookieID", cookieID, "err", err)
}
}
release := func() {
_ = bctx.Close()
releaseSlot()
unlock()
}
return bctx, release, nil
}
func (m *Manager) newEphemeralRefreshContext(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (playwright.BrowserContext, func(), error) {
releaseSlot, err := m.acquireRenewSlot(ctx)
if err != nil {
return nil, nil, err
}
if err := m.init(); err != nil {
releaseSlot()
return nil, nil, err
}
browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
Headless: playwright.Bool(headless),
Args: chromiumLaunchArgs(),
ExecutablePath: chromiumExecutablePath(),
})
if err != nil {
releaseSlot()
return nil, nil, fmt.Errorf("启动 chromium 失败: %w", err)
}
bctx, err := browser.NewContext(playwright.BrowserNewContextOptions{
UserAgent: playwright.String("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"),
Viewport: &playwright.Size{Width: 1280, Height: 720},
Locale: playwright.String(defaultLang),
TimezoneId: playwright.String(defaultTZ),
})
if err != nil {
_ = browser.Close()
releaseSlot()
return nil, nil, fmt.Errorf("创建 context 失败: %w", err)
}
if err := bctx.AddInitScript(playwright.Script{Content: playwright.String(`Object.defineProperty(navigator, 'webdriver', { get: () => undefined }); Object.defineProperty(navigator, 'languages', { get: () => ['zh-CN', 'zh', 'en'] }); window.chrome = { runtime: {} };`)}); err != nil {
m.logger.Warn("注入 COOKIES 续期 stealth 脚本失败", "cookieID", cookieID, "err", err)
}
if len(snapshot) > 0 {
if err := bctx.AddCookies(snapshotToOptionalCookies(snapshot)); err != nil {
m.logger.Warn("COOKIES续期注入 Cookie 快照失败", "cookieID", cookieID, "err", err)
}
} else if cookieStr != "" {
if err := addCookieStr(bctx, cookieStr); err != nil {
m.logger.Warn("COOKIES续期注入 Cookie 字符串失败", "cookieID", cookieID, "err", err)
}
}
release := func() {
_ = bctx.Close()
_ = browser.Close()
releaseSlot()
}
return bctx, release, nil
}
func quickRenewHeadless(headless bool) bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv("BROWSER_HEADLESS"))) {
case "true", "1", "yes", "on":
return true
case "false", "0", "no", "off":
return false
default:
return headless
}
}
func cookiesRefreshHeadless(headless bool) bool {
return quickRenewHeadless(headless)
}
func pureUserID(cookieID string) string {
cookieID = sanitize(cookieID)
parts := strings.Split(cookieID, "_")
if len(parts) >= 2 {
last := parts[len(parts)-1]
if len(last) >= 10 && allDigits(last) {
return strings.Join(parts[:len(parts)-1], "_")
}
}
if cookieID == "" {
return "unknown"
}
return cookieID
}
func allDigits(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if r < '0' || r > '9' {
return false
}
}
return true
}
+68 -7
View File
@@ -7,8 +7,12 @@ import (
"time"
"github.com/playwright-community/playwright-go"
"xianyu-go/internal/xianyu/cookierefresh"
)
var cookieDomains = []string{".goofish.com", ".taobao.com", ".alipay.com"}
// parseCookieStr 把 "k=v; k2=v2" 解析为 map。
func parseCookieStr(s string) map[string]string {
m := make(map[string]string)
@@ -35,7 +39,7 @@ func MarshalCookies(m map[string]string) string {
return cookieMarshal(m)
}
// parseCookieStrToPlaywright 把 cookie 字符串转成 playwright OptionalCookie(domain .goofish.com)。
// parseCookieStrToPlaywright 把 cookie 字符串转成 playwright OptionalCookie。
func parseCookieStrToPlaywright(s string) []playwright.OptionalCookie {
var cookies []playwright.OptionalCookie
for _, part := range strings.Split(s, ";") {
@@ -46,17 +50,74 @@ func parseCookieStrToPlaywright(s string) []playwright.OptionalCookie {
if name == "" {
continue
}
cookies = append(cookies, playwright.OptionalCookie{
Name: name,
Value: value,
Domain: playwright.String(goofishDot),
Path: playwright.String("/"),
})
for _, domain := range cookieDomains {
cookies = append(cookies, playwright.OptionalCookie{
Name: name,
Value: value,
Domain: playwright.String(domain),
Path: playwright.String("/"),
})
}
}
}
return cookies
}
func snapshotToOptionalCookies(snapshot []cookierefresh.BrowserCookie) []playwright.OptionalCookie {
var out []playwright.OptionalCookie
for _, c := range cookierefresh.NormalizeSnapshot(snapshot) {
domain := c.Domain
if domain == "" {
domain = goofishDot
}
path := c.Path
if path == "" {
path = "/"
}
oc := playwright.OptionalCookie{
Name: c.Name,
Value: c.Value,
Domain: playwright.String(domain),
Path: playwright.String(path),
HttpOnly: playwright.Bool(c.HTTPOnly),
Secure: playwright.Bool(c.Secure),
}
if c.Expires > 0 {
oc.Expires = playwright.Float(c.Expires)
}
switch c.SameSite {
case "Strict":
oc.SameSite = playwright.SameSiteAttributeStrict
case "Lax":
oc.SameSite = playwright.SameSiteAttributeLax
case "None":
oc.SameSite = playwright.SameSiteAttributeNone
}
out = append(out, oc)
}
return out
}
func cookieSnapshotFromPlaywright(cs []playwright.Cookie) []cookierefresh.BrowserCookie {
out := make([]cookierefresh.BrowserCookie, 0, len(cs))
for _, c := range cs {
bc := cookierefresh.BrowserCookie{
Name: c.Name,
Value: c.Value,
Domain: c.Domain,
Path: c.Path,
Expires: c.Expires,
HTTPOnly: c.HttpOnly,
Secure: c.Secure,
}
if c.SameSite != nil {
bc.SameSite = string(*c.SameSite)
}
out = append(out, bc)
}
return cookierefresh.NormalizeSnapshot(out)
}
// cookiesToMap 把 playwright Cookie 切片转成 map。
func cookiesToMap(cs []playwright.Cookie) map[string]string {
m := make(map[string]string, len(cs))
+11 -4
View File
@@ -22,17 +22,24 @@ func TestParseCookieStrRoundTrip(t *testing.T) {
func TestParseCookieStrToPlaywright(t *testing.T) {
cookies := parseCookieStrToPlaywright("a=1; b=2")
if len(cookies) != 2 {
t.Fatalf("应解析 2 个 cookie,got %d", len(cookies))
if len(cookies) != 2*len(cookieDomains) {
t.Fatalf("应按多个域名注入 cookie,got %d", len(cookies))
}
domains := make(map[string]bool)
for _, c := range cookies {
if c.Domain == nil || *c.Domain != goofishDot {
t.Fatalf("domain 应为 %s: %+v", goofishDot, c.Domain)
if c.Domain == nil {
t.Fatalf("domain 不能为空: %+v", c.Domain)
}
domains[*c.Domain] = true
if c.Path == nil || *c.Path != "/" {
t.Fatalf("path 应为 /: %+v", c.Path)
}
}
for _, domain := range cookieDomains {
if !domains[domain] {
t.Fatalf("缺少 domain %s: %+v", domain, domains)
}
}
}
func TestParseCookieStrEmpty(t *testing.T) {
+71 -15
View File
@@ -7,6 +7,8 @@ import (
"errors"
"fmt"
"log/slog"
"os"
"strings"
"sync"
"time"
@@ -18,13 +20,14 @@ import (
// 默认 UA、语言、时区与视口。
const (
defaultUA = xianyu.BrowserUA
defaultW = 1920
defaultH = 1080
defaultLang = "zh-CN"
defaultTZ = "Asia/Shanghai"
goofishDot = ".goofish.com"
goofishIMURL = "https://www.goofish.com/im"
defaultUA = xianyu.BrowserUA
defaultW = 1920
defaultH = 1080
defaultLang = "zh-CN"
defaultTZ = "Asia/Shanghai"
goofishDot = ".goofish.com"
goofishHomeURL = "https://www.goofish.com/"
goofishIMURL = "https://www.goofish.com/im"
)
// chromiumLaunchArgs 统一 Chromium 启动参数。
@@ -52,6 +55,22 @@ func chromiumLaunchArgs() []string {
}
}
func chromiumExecutablePath() *string {
if path := strings.TrimSpace(os.Getenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH")); path != "" {
return playwright.String(path)
}
return nil
}
func skipPlaywrightBrowserDownload() bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD"))) {
case "1", "true", "yes", "on":
return true
default:
return false
}
}
// Manager 管理浏览器生命周期与按账号复用的上下文池。
type Manager struct {
pw *playwright.Playwright
@@ -67,6 +86,10 @@ type Manager struct {
idleTTL time.Duration
creates singleflight.Group
renewMu sync.Mutex
renewLocks map[string]*sync.Mutex
renewSlots chan struct{}
// 允许测试注入自定义 playwright / 安装函数。
installFn func() error
runFn func() (*playwright.Playwright, error)
@@ -85,15 +108,21 @@ func NewManager(logger *slog.Logger) *Manager {
logger = slog.Default()
}
return &Manager{
logger: logger,
pool: make(map[string]*poolEntry),
maxSize: 3,
idleTTL: 5 * time.Minute,
logger: logger,
pool: make(map[string]*poolEntry),
maxSize: 3,
idleTTL: 5 * time.Minute,
renewLocks: make(map[string]*sync.Mutex),
renewSlots: make(chan struct{}, 3),
installFn: func() error {
return playwright.Install(&playwright.RunOptions{
opts := &playwright.RunOptions{
Browsers: []string{"chromium"},
Verbose: false,
})
}
if skipPlaywrightBrowserDownload() {
opts.SkipInstallBrowsers = true
}
return playwright.Install(opts)
},
runFn: func() (*playwright.Playwright, error) {
return playwright.Run()
@@ -101,6 +130,32 @@ func NewManager(logger *slog.Logger) *Manager {
}
}
func (m *Manager) accountRenewLock(cookieID string) *sync.Mutex {
m.renewMu.Lock()
defer m.renewMu.Unlock()
if m.renewLocks == nil {
m.renewLocks = make(map[string]*sync.Mutex)
}
lock := m.renewLocks[cookieID]
if lock == nil {
lock = &sync.Mutex{}
m.renewLocks[cookieID] = lock
}
return lock
}
func (m *Manager) acquireRenewSlot(ctx context.Context) (func(), error) {
if m.renewSlots == nil {
m.renewSlots = make(chan struct{}, 3)
}
select {
case m.renewSlots <- struct{}{}:
return func() { <-m.renewSlots }, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
// init 懒加载 playwright(首次调用时下载 driver + chromium)。
func (m *Manager) init() error {
m.once.Do(func() {
@@ -202,8 +257,9 @@ func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*pool
func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolEntry, error) {
browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
Headless: playwright.Bool(headless),
Args: chromiumLaunchArgs(),
Headless: playwright.Bool(headless),
Args: chromiumLaunchArgs(),
ExecutablePath: chromiumExecutablePath(),
})
if err != nil {
return nil, fmt.Errorf("启动 chromium 失败: %w", err)
+202 -24
View File
@@ -2,6 +2,7 @@ package browser
import (
"context"
"encoding/base64"
"fmt"
"path/filepath"
"strings"
@@ -26,10 +27,24 @@ var loginSuccessSelectors = []string{
".rc-virtual-list-holder-inner", // IM 页面侧边栏有子元素则已登录
}
const (
passwordVerificationWaitInterval = 10 * time.Second
passwordVerificationMaxWait = 5 * time.Minute
)
// PasswordLogin 用账号密码通过浏览器登录闲鱼,返回完整 cookie map。
// 移植自 xianyu_slider_stealth.login_with_password_playwright。
// userDataDir:空字符串用临时目录,非空则持久化(跨次复用 session)。
func (m *Manager) PasswordLogin(ctx context.Context, account, password, cookieID, userDataDir string, headless bool) (map[string]string, error) {
return m.passwordLogin(ctx, account, password, cookieID, userDataDir, headless, nil)
}
// PasswordLoginWithEvents 在密码登录过程中上报中间状态。
func (m *Manager) PasswordLoginWithEvents(ctx context.Context, account, password, cookieID, userDataDir string, headless bool, onEvent PasswordLoginEventHandler) (map[string]string, error) {
return m.passwordLogin(ctx, account, password, cookieID, userDataDir, headless, onEvent)
}
func (m *Manager) passwordLogin(ctx context.Context, account, password, cookieID, userDataDir string, headless bool, onEvent PasswordLoginEventHandler) (map[string]string, error) {
if err := m.init(); err != nil {
return nil, err
}
@@ -37,14 +52,16 @@ func (m *Manager) PasswordLogin(ctx context.Context, account, password, cookieID
if userDataDir == "" {
userDataDir = filepath.Join("browser_data", "user_"+sanitize(cookieID))
}
headless = quickRenewHeadless(headless)
bctx, err := m.pw.Chromium.LaunchPersistentContext(userDataDir, playwright.BrowserTypeLaunchPersistentContextOptions{
Headless: playwright.Bool(headless),
Args: chromiumLaunchArgs(),
UserAgent: playwright.String(defaultUA),
Viewport: &playwright.Size{Width: 1980, Height: 1024},
Locale: playwright.String(defaultLang),
TimezoneId: playwright.String(defaultTZ),
Headless: playwright.Bool(headless),
Args: chromiumLaunchArgs(),
ExecutablePath: chromiumExecutablePath(),
UserAgent: playwright.String(defaultUA),
Viewport: &playwright.Size{Width: 1980, Height: 1024},
Locale: playwright.String(defaultLang),
TimezoneId: playwright.String(defaultTZ),
})
if err != nil {
return nil, fmt.Errorf("启动持久化浏览器失败: %w", err)
@@ -73,11 +90,32 @@ func (m *Manager) PasswordLogin(ctx context.Context, account, password, cookieID
return extractPageCookies(page)
}
if clickQuickEnter(page) {
m.logger.Info("密码登录:已点击[快速进入],等待页面刷新", "cookieID", cookieID)
time.Sleep(quickRenewAfterClick)
cookies, err := extractPageCookies(page)
if err == nil && quickEnterCookiesUsable(cookies) {
m.logger.Info("密码登录:快速进入成功,跳过账号密码输入", "cookieID", cookieID)
return cookies, nil
}
m.logger.Info("密码登录:快速进入未获取到有效 Cookie,继续账号密码登录", "cookieID", cookieID)
if _, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(30000),
}); err != nil {
m.logger.Warn("密码登录:快速进入失败后重新访问 IM 页面异常", "cookieID", cookieID, "err", err)
}
time.Sleep(2 * time.Second)
}
// 在主页和所有 iframe 中找登录表单。
idEl, pwdEl, submitEl := findLoginForm(page)
if idEl == nil {
return nil, fmt.Errorf("未找到登录表单,可能页面结构已变更")
}
if pwdEl == nil {
return nil, fmt.Errorf("未找到密码输入框,可能页面结构已变更")
}
if err := idEl.Click(); err == nil {
_ = page.Fill(getCSSSelector(idEl, loginIDSelectors), account)
@@ -108,30 +146,170 @@ func (m *Manager) PasswordLogin(ctx context.Context, account, password, cookieID
}
if !checkLoginSuccess(page) {
// 采集错误信息。
errMsg := ""
if el, err := page.QuerySelector(".login-error-msg"); err == nil && el != nil {
errMsg, _ = el.TextContent()
}
if errMsg == "" {
c, _ := page.Content()
for _, kw := range []string{"账密错误", "账号密码错误", "用户名或密码错误", "密码错误"} {
if strings.Contains(c, kw) {
errMsg = kw
break
}
}
}
if errMsg == "" {
errMsg = "登录失败"
}
return nil, fmt.Errorf("密码登录失败: %s", errMsg)
return m.handlePasswordLoginPending(ctx, page, onEvent)
}
m.logger.Info("密码登录成功", "cookieID", cookieID)
return extractPageCookies(page)
}
func quickEnterCookiesUsable(cookies map[string]string) bool {
if len(cookies) == 0 {
return false
}
return strings.TrimSpace(cookies["unb"]) != ""
}
func (m *Manager) handlePasswordLoginPending(ctx context.Context, page playwright.Page, onEvent PasswordLoginEventHandler) (map[string]string, error) {
if msg := passwordLoginErrorFromPage(page); msg != "" {
if onEvent != nil {
onEvent(PasswordLoginEventFromMessage(msg))
}
return nil, fmt.Errorf("密码登录失败: %s", msg)
}
if event, ok := passwordBaxiaEventFromPage(page); ok {
if onEvent != nil {
onEvent(event)
}
return nil, fmt.Errorf("密码登录失败: %s", event.Message)
}
if event, ok := passwordVerificationEventFromPage(page); ok {
if onEvent != nil {
onEvent(event)
}
cookies, err := waitPasswordVerification(ctx, page, onEvent)
if err == nil {
m.logger.Info("密码登录人工验证完成")
return cookies, nil
}
return nil, err
}
errMsg := "登录失败"
if onEvent != nil {
onEvent(PasswordLoginEventFromMessage(errMsg))
}
return nil, fmt.Errorf("密码登录失败: %s", errMsg)
}
func waitPasswordVerification(ctx context.Context, page playwright.Page, onEvent PasswordLoginEventHandler) (map[string]string, error) {
ticker := time.NewTicker(passwordVerificationWaitInterval)
defer ticker.Stop()
timer := time.NewTimer(passwordVerificationMaxWait)
defer timer.Stop()
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-timer.C:
return nil, fmt.Errorf("密码登录失败: 人工验证超时")
case <-ticker.C:
}
if checkLoginSuccess(page) {
return extractPageCookies(page)
}
if msg := passwordLoginErrorFromPage(page); msg != "" {
return nil, fmt.Errorf("密码登录失败: %s", msg)
}
if event, ok := passwordBaxiaEventFromPage(page); ok {
return nil, fmt.Errorf("密码登录失败: %s", event.Message)
}
if event, ok := passwordVerificationEventFromPage(page); ok && onEvent != nil {
onEvent(event)
}
}
}
func passwordLoginErrorFromPage(page playwright.Page) string {
if el, err := page.QuerySelector(".login-error-msg"); err == nil && el != nil {
if msg, _ := el.TextContent(); strings.TrimSpace(msg) != "" {
return strings.TrimSpace(msg)
}
}
for _, htmlText := range passwordLoginHTMLs(page) {
if msg := detectPasswordLoginErrorHTML(htmlText); msg != "" {
return msg
}
}
return ""
}
func passwordBaxiaEventFromPage(page playwright.Page) (PasswordLoginEvent, bool) {
for _, htmlText := range passwordLoginHTMLs(page) {
if event, ok := detectPasswordBaxiaPunishHTML(htmlText); ok {
return event, true
}
}
return PasswordLoginEvent{}, false
}
func passwordVerificationEventFromPage(page playwright.Page) (PasswordLoginEvent, bool) {
if event, ok := passwordVerificationEventFromContent(pageContent(page), page.URL()); ok {
event.ScreenshotPath = firstNonEmptyString(event.ScreenshotPath, passwordVerificationScreenshot(page))
return event, true
}
for _, frame := range page.Frames() {
if event, ok := passwordVerificationEventFromContent(frameContent(frame), frame.URL()); ok {
event.ScreenshotPath = firstNonEmptyString(event.ScreenshotPath, passwordVerificationScreenshot(page))
return event, true
}
}
return PasswordLoginEvent{}, false
}
func passwordVerificationEventFromContent(htmlText, frameURL string) (PasswordLoginEvent, bool) {
event, ok := detectPasswordVerificationHTML(htmlText)
if !ok {
return PasswordLoginEvent{}, false
}
if event.VerificationURL == "" && looksLikeVerificationURL(frameURL) {
event.VerificationURL = frameURL
}
return event, true
}
func passwordLoginHTMLs(page playwright.Page) []string {
htmls := []string{pageContent(page)}
for _, frame := range page.Frames() {
htmls = append(htmls, frameContent(frame))
}
return htmls
}
func pageContent(page playwright.Page) string {
content, _ := page.Content()
return content
}
func frameContent(frame playwright.Frame) string {
content, _ := frame.Content()
return content
}
func passwordVerificationScreenshot(page playwright.Page) string {
raw, err := page.Screenshot(playwright.PageScreenshotOptions{
FullPage: playwright.Bool(true),
Timeout: playwright.Float(5000),
})
if err != nil || len(raw) == 0 {
return ""
}
return "data:image/png;base64," + base64.StdEncoding.EncodeToString(raw)
}
func looksLikeVerificationURL(raw string) bool {
lower := strings.ToLower(raw)
return containsAny(lower, "passport", "verify", "photo", "iv/", "identity", "login", "qrcode")
}
func firstNonEmptyString(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return value
}
}
return ""
}
func checkLoginSuccess(page playwright.Page) bool {
for _, sel := range loginSuccessSelectors {
el, err := page.QuerySelector(sel)
+103
View File
@@ -0,0 +1,103 @@
package browser
import (
"html"
"regexp"
"strings"
)
var (
htmlTagPattern = regexp.MustCompile(`(?is)<[^>]+>`)
scriptStylePattern = regexp.MustCompile(`(?is)<script[^>]*>.*?</script>|<style[^>]*>.*?</style>`)
verificationURLRe = regexp.MustCompile(`https?://[^\s"'<>\\]+`)
dataImageURLRe = regexp.MustCompile(`data:image/[^;"'\s<>]+;base64,[A-Za-z0-9+/=]+`)
escapedSlashPattern = strings.NewReplacer(`\/`, `/`, `\u0026`, `&`)
)
func detectPasswordBaxiaPunishHTML(htmlText string) (PasswordLoginEvent, bool) {
if !IsBaxiaPunishMessage(htmlText) {
return PasswordLoginEvent{}, false
}
msg := "触发闲鱼风控图形验证(baxia-punish),账号正常但暂时无法自动登录"
return PasswordLoginEvent{
Status: PasswordLoginStatusFailed,
Message: msg,
Error: msg,
Reason: "baxia_punish_captcha",
CooldownHours: 5,
}, true
}
func detectPasswordLoginErrorHTML(htmlText string) string {
text := normalizeHTMLText(htmlText)
for _, keyword := range []string{
"账密错误", "账号密码错误", "用户名或密码错误", "账号或密码错误", "密码错误",
"账号不存在", "账号已被冻结", "账号被冻结", "账户被冻结", "账号已锁定", "账户已锁定",
"操作过于频繁", "登录过于频繁", "暂时无法登录",
} {
if strings.Contains(text, keyword) {
return keyword
}
}
return ""
}
func detectPasswordVerificationHTML(htmlText string) (PasswordLoginEvent, bool) {
normalized := normalizeHTMLText(htmlText)
lower := strings.ToLower(htmlText)
if !containsAny(normalized,
"人脸验证", "人脸识别", "身份验证", "安全验证", "扫码验证", "验证二维码",
"请使用手机", "请在手机", "请在浏览器中完成验证",
) && !containsAny(lower,
"alibaba-login-box", "iframe_redirect", "iframeredirect", "photoverify", "iv/photoverify",
"verifyurl", "identity_verify", "normal_validate", "verifycode", "qrcode",
) {
return PasswordLoginEvent{}, false
}
msg := "密码登录需要人工验证,请在浏览器中完成验证后等待自动继续"
event := PasswordLoginEvent{
Status: PasswordLoginStatusVerificationRequired,
Message: msg,
Error: msg,
VerificationURL: extractPasswordVerificationURL(htmlText),
QRCodeURL: extractPasswordQRURL(htmlText),
}
return event, true
}
func extractPasswordVerificationURL(htmlText string) string {
cleaned := escapedSlashPattern.Replace(html.UnescapeString(htmlText))
matches := verificationURLRe.FindAllString(cleaned, -1)
for _, raw := range matches {
url := strings.TrimRight(raw, ".,);]")
lower := strings.ToLower(url)
if containsAny(lower, "passport", "verify", "photo", "iv/", "identity", "login", "qrcode") {
return url
}
}
return ""
}
func extractPasswordQRURL(htmlText string) string {
cleaned := escapedSlashPattern.Replace(html.UnescapeString(htmlText))
if match := dataImageURLRe.FindString(cleaned); match != "" {
return match
}
return ""
}
func normalizeHTMLText(htmlText string) string {
cleaned := scriptStylePattern.ReplaceAllString(htmlText, " ")
cleaned = htmlTagPattern.ReplaceAllString(cleaned, " ")
cleaned = escapedSlashPattern.Replace(html.UnescapeString(cleaned))
return strings.Join(strings.Fields(cleaned), " ")
}
func containsAny(s string, keywords ...string) bool {
for _, keyword := range keywords {
if strings.Contains(s, keyword) {
return true
}
}
return false
}
@@ -0,0 +1,61 @@
package browser
import "testing"
func TestDetectPasswordBaxiaPunishHTML(t *testing.T) {
html := `<div id="baxia-punish"><div class="captcha-question">请找两个松鼠</div></div>`
event, ok := detectPasswordBaxiaPunishHTML(html)
if !ok {
t.Fatal("应识别 baxia 图形验证")
}
if event.Status != PasswordLoginStatusFailed || event.Reason != "baxia_punish_captcha" || event.CooldownHours != 5 {
t.Fatalf("baxia 事件异常: %+v", event)
}
}
func TestPasswordEventFromMessageDoesNotTreatFaceRiskAsBaxia(t *testing.T) {
event := PasswordLoginEventFromMessage("账号触发风控,需要人脸验证")
if event.Reason == "baxia_punish_captcha" {
t.Fatalf("普通人脸验证不应按 baxia 冷却: %+v", event)
}
if event.Status != PasswordLoginStatusVerificationRequired {
t.Fatalf("人脸验证应标记 verification_required: %+v", event)
}
}
func TestDetectPasswordLoginErrorHTML(t *testing.T) {
msg := detectPasswordLoginErrorHTML(`<div class="login-error-msg">账号或密码错误</div>`)
if msg != "账号或密码错误" {
t.Fatalf("登录错误识别=%q", msg)
}
msg = detectPasswordLoginErrorHTML(`<span>账号已被冻结,请联系平台</span>`)
if msg != "账号已被冻结" {
t.Fatalf("冻结错误识别=%q", msg)
}
}
func TestDetectPasswordVerificationHTML(t *testing.T) {
html := `<iframe id="alibaba-login-box" src="https:\/\/passport.goofish.com\/iv\/photoVerify\/index.htm?token=abc"></iframe><div>需要人脸验证,请使用手机扫码</div>`
event, ok := detectPasswordVerificationHTML(html)
if !ok {
t.Fatal("应识别人脸验证")
}
if event.Status != PasswordLoginStatusVerificationRequired {
t.Fatalf("验证状态异常: %+v", event)
}
if event.VerificationURL != "https://passport.goofish.com/iv/photoVerify/index.htm?token=abc" {
t.Fatalf("验证 URL 提取异常: %q", event.VerificationURL)
}
}
func TestQuickEnterCookiesUsableRequiresUNB(t *testing.T) {
if quickEnterCookiesUsable(map[string]string{"_m_h5_tk": "tk"}) {
t.Fatal("快速进入未拿到 unb 不应视为成功")
}
if !quickEnterCookiesUsable(map[string]string{"unb": " 123 "}) {
t.Fatal("快速进入拿到 unb 应视为成功")
}
if quickEnterCookiesUsable(nil) {
t.Fatal("空 Cookie 不应视为成功")
}
}
+54
View File
@@ -0,0 +1,54 @@
package browser
import "strings"
const (
PasswordLoginStatusProcessing = "processing"
PasswordLoginStatusVerificationRequired = "verification_required"
PasswordLoginStatusFailed = "failed"
)
// PasswordLoginEvent 描述密码登录过程中的中间状态,供 HTTP 会话轮询接口展示。
type PasswordLoginEvent struct {
Status string
Message string
Error string
Reason string
VerificationURL string
ScreenshotPath string
QRCodeURL string
CooldownHours int
}
type PasswordLoginEventHandler func(PasswordLoginEvent)
func PasswordLoginEventFromError(err error) PasswordLoginEvent {
if err == nil {
return PasswordLoginEvent{}
}
return PasswordLoginEventFromMessage(err.Error())
}
func PasswordLoginEventFromMessage(msg string) PasswordLoginEvent {
lower := strings.ToLower(msg)
event := PasswordLoginEvent{Status: PasswordLoginStatusFailed, Message: msg, Error: msg}
switch {
case IsBaxiaPunishMessage(msg) || (strings.Contains(msg, "风控") && strings.Contains(msg, "图形验证")):
event.Reason = "baxia_punish_captcha"
event.CooldownHours = 5
case strings.Contains(msg, "人脸") || strings.Contains(lower, "verification") || strings.Contains(lower, "captcha"):
event.Status = PasswordLoginStatusVerificationRequired
}
return event
}
func IsBaxiaPunishMessage(msg string) bool {
lower := strings.ToLower(msg)
return strings.Contains(lower, "baxia") ||
strings.Contains(lower, "punish") ||
strings.Contains(lower, "scratch-captcha") ||
strings.Contains(lower, "captcha-question") ||
strings.Contains(lower, "scratch-captcha-container") ||
strings.Contains(msg, "找两个") ||
strings.Contains(msg, "松鼠")
}
@@ -0,0 +1,37 @@
package browser
import (
"errors"
"testing"
)
func TestPasswordLoginEventFromErrorVerification(t *testing.T) {
event := PasswordLoginEventFromError(errors.New("需要人脸验证"))
if event.Status != PasswordLoginStatusVerificationRequired {
t.Fatalf("status=%q want verification_required", event.Status)
}
}
func TestPasswordLoginEventFromErrorBaxia(t *testing.T) {
event := PasswordLoginEventFromError(errors.New("baxia-punish verification 风控图形验证"))
if event.Status != PasswordLoginStatusFailed || event.Reason != "baxia_punish_captcha" || event.CooldownHours != 5 {
t.Fatalf("event=%+v", event)
}
}
func TestIsBaxiaPunishMessage(t *testing.T) {
for _, msg := range []string{"baxia-punish", "scratch-captcha-container", "找两个松鼠"} {
if !IsBaxiaPunishMessage(msg) {
t.Fatalf("%q should be recognized as baxia punish", msg)
}
}
if PasswordLoginEventFromMessage("触发风控图形验证").Reason != "baxia_punish_captcha" {
t.Fatal("明确的风控图形验证应按 baxia 冷却")
}
if IsBaxiaPunishMessage("用户名或密码错误") {
t.Fatal("ordinary password error should not be recognized as baxia")
}
if IsBaxiaPunishMessage("触发风控,需要人脸验证") {
t.Fatal("ordinary face verification should not be recognized as baxia")
}
}
+80 -8
View File
@@ -1,16 +1,14 @@
package browser
import (
"testing"
)
import "testing"
// TestSanitize 特殊字符替换为下划线(用于 userDataDir 命名)。
func TestSanitize(t *testing.T) {
cases := map[string]string{
"acc_1": "acc_1",
"acc/1:2 3": "acc_1_2_3",
`a\b:c d`: "a_b_c_d",
"": "",
"acc_1": "acc_1",
"acc/1:2 3": "acc_1_2_3",
`a\b:c d`: "a_b_c_d",
"": "",
}
for in, want := range cases {
if got := sanitize(in); got != want {
@@ -31,6 +29,81 @@ func TestGetCSSSelector(t *testing.T) {
}
}
func TestPureUserIDMatchesReferenceRule(t *testing.T) {
cases := map[string]string{
"foo_1234567890": "foo",
"foo_bar_1234567890": "foo_bar",
"foo_123": "foo_123",
"foo": "foo",
"": "unknown",
"foo/bar_1234567890": "foo_bar",
}
for in, want := range cases {
if got := pureUserID(in); got != want {
t.Fatalf("pureUserID(%q)=%q want %q", in, got, want)
}
}
}
func TestQuickRenewHeadlessUsesArgumentUnlessEnvOverrides(t *testing.T) {
t.Setenv("BROWSER_HEADLESS", "")
if !quickRenewHeadless(true) {
t.Fatal("未设置环境变量时应使用传入的 headless=true")
}
if quickRenewHeadless(false) {
t.Fatal("未设置环境变量时应使用传入的 headless=false")
}
t.Setenv("BROWSER_HEADLESS", "true")
if !quickRenewHeadless(false) {
t.Fatal("BROWSER_HEADLESS=true 时应使用 headless")
}
t.Setenv("BROWSER_HEADLESS", "false")
if quickRenewHeadless(true) {
t.Fatal("BROWSER_HEADLESS=false 时应使用可视化浏览器")
}
}
func TestCookiesRefreshHeadlessUsesAccountPreference(t *testing.T) {
t.Setenv("BROWSER_HEADLESS", "")
if !cookiesRefreshHeadless(true) {
t.Fatal("定时 COOKIES 续期应尊重 headless=true")
}
if cookiesRefreshHeadless(false) {
t.Fatal("show_browser=true 时定时 COOKIES 续期应使用可视化浏览器")
}
t.Setenv("BROWSER_HEADLESS", "true")
if !cookiesRefreshHeadless(false) {
t.Fatal("环境变量应仍可强制定时 COOKIES 续期 headless")
}
}
func TestChromiumExecutablePathFromEnv(t *testing.T) {
t.Setenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH", "")
if chromiumExecutablePath() != nil {
t.Fatal("未设置 PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH 时应返回 nil")
}
t.Setenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH", " /usr/bin/chromium ")
got := chromiumExecutablePath()
if got == nil || *got != "/usr/bin/chromium" {
t.Fatalf("chromiumExecutablePath=%v", got)
}
}
func TestSkipPlaywrightBrowserDownloadFromEnv(t *testing.T) {
t.Setenv("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "")
if skipPlaywrightBrowserDownload() {
t.Fatal("默认不应跳过浏览器下载")
}
t.Setenv("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "true")
if !skipPlaywrightBrowserDownload() {
t.Fatal("true 应跳过浏览器下载")
}
t.Setenv("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "0")
if skipPlaywrightBrowserDownload() {
t.Fatal("0 不应跳过浏览器下载")
}
}
// TestCalculateSlideDistance_Fallback nil 轨道/按钮时走兜底距离。
func TestCalculateSlideDistance_Fallback(t *testing.T) {
// 无 scratch:220-259。
@@ -44,4 +117,3 @@ func TestCalculateSlideDistance_Fallback(t *testing.T) {
t.Fatalf("scratch 兜底应 55-91,got %v err=%v", dist, err)
}
}
+3 -2
View File
@@ -26,8 +26,9 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
// QR 刷新不复用账号池:一次性上下文,注入临时 cookie,访问后提取。
browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
Headless: playwright.Bool(true),
Args: chromiumLaunchArgs(),
Headless: playwright.Bool(true),
Args: chromiumLaunchArgs(),
ExecutablePath: chromiumExecutablePath(),
})
if err != nil {
return "", "", fmt.Errorf("启动 chromium 失败: %w", err)
+69
View File
@@ -0,0 +1,69 @@
package db
import (
"context"
"database/sql"
)
// AccountLoginLogs 管理账号登录审计记录。
type AccountLoginLogs struct {
DB *sql.DB
}
// Add 写入一条账号登录审计记录。
func (l *AccountLoginLogs) Add(ctx context.Context, log AccountLoginLog) error {
if log.AccountIdentifier == "" {
log.AccountIdentifier = log.CookieID
}
if log.OwnerID == 0 {
log.OwnerID = log.UserID
}
if log.ErrorMessage == "" {
log.ErrorMessage = log.Message
}
_, err := l.DB.ExecContext(ctx,
`INSERT INTO account_login_logs (
cookie_id, user_id, owner_id, account_pk, account_identifier,
username, method, status, message, trigger_reason, failure_reason,
error_message, updated_cookie_names, duration_ms, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
log.CookieID, log.UserID, log.OwnerID, log.AccountPK, log.AccountIdentifier,
log.Username, log.Method, log.Status, log.Message, log.TriggerReason, log.FailureReason,
log.ErrorMessage, log.UpdatedCookieNames, log.DurationMS, log.CreatedAt)
return err
}
// ListByCookie 按账号倒序读取登录审计记录。
func (l *AccountLoginLogs) ListByCookie(ctx context.Context, cookieID string, limit int) ([]AccountLoginLog, error) {
if limit <= 0 {
limit = 20
}
rows, err := l.DB.QueryContext(ctx,
`SELECT id, cookie_id, user_id, COALESCE(owner_id,0), COALESCE(account_pk,0),
COALESCE(account_identifier,''), COALESCE(username,''), method, status,
COALESCE(message,''), COALESCE(trigger_reason,''), COALESCE(failure_reason,''),
COALESCE(error_message,''), COALESCE(updated_cookie_names,''), COALESCE(duration_ms,0),
created_at
FROM account_login_logs
WHERE cookie_id=?
ORDER BY created_at DESC, id DESC
LIMIT ?`, cookieID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []AccountLoginLog
for rows.Next() {
var log AccountLoginLog
if err := rows.Scan(
&log.ID, &log.CookieID, &log.UserID, &log.OwnerID, &log.AccountPK,
&log.AccountIdentifier, &log.Username, &log.Method, &log.Status,
&log.Message, &log.TriggerReason, &log.FailureReason, &log.ErrorMessage,
&log.UpdatedCookieNames, &log.DurationMS, &log.CreatedAt,
); err != nil {
return nil, err
}
out = append(out, log)
}
return out, rows.Err()
}
+3 -3
View File
@@ -98,7 +98,7 @@ type AutomationActionInput struct {
func (a *AutomationRules) ListForUser(ctx context.Context, userID int64) ([]AutomationRule, error) {
rows, err := a.DB.QueryContext(ctx, `
SELECT r.id,r.user_id,r.cookie_id,r.item_id,COALESCE(i.item_title,''),r.name,r.trigger_type,r.enabled,
r.priority,r.config_json,COALESCE(r.created_at,''),COALESCE(r.updated_at,'')
r.priority,r.config_json,r.created_at,r.updated_at
FROM automation_rules r
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id
WHERE r.user_id=?
@@ -130,7 +130,7 @@ SELECT r.id,r.user_id,r.cookie_id,r.item_id,COALESCE(i.item_title,''),r.name,r.t
func (a *AutomationRules) Match(ctx context.Context, cookieID, itemID, triggerType string) ([]AutomationRule, error) {
rows, err := a.DB.QueryContext(ctx, `
SELECT r.id,r.user_id,r.cookie_id,r.item_id,COALESCE(i.item_title,''),r.name,r.trigger_type,r.enabled,
r.priority,r.config_json,COALESCE(r.created_at,''),COALESCE(r.updated_at,'')
r.priority,r.config_json,r.created_at,r.updated_at
FROM automation_rules r
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id
WHERE r.enabled=1
@@ -322,7 +322,7 @@ SELECT order_id,item_id,buyer_id,spec_name,spec_value,quantity,amount,order_stat
receiver_name,receiver_phone,receiver_address,receiver_city,version,chat_id,system_shipped,
COALESCE(paid_at,''),COALESCE(shipped_at,''),COALESCE(completed_at,''),
COALESCE(buyer_reviewed_at,''),COALESCE(last_review_request_at,''),review_request_count,
COALESCE(created_at,''),COALESCE(updated_at,'')
created_at,updated_at
FROM orders
WHERE system_shipped=1
AND COALESCE(buyer_reviewed_at,'')=''
+41 -7
View File
@@ -108,11 +108,15 @@ func (c *Cookies) GetDetails(ctx context.Context, cookieID string) (*CookieDetai
var autoConfirm, showBrowser int
var pauseDuration sql.NullInt64
err := c.DB.QueryRowContext(ctx,
`SELECT id, value, user_id, auto_confirm, remark, pause_duration, username, password,
show_browser, COALESCE(nickname,''), COALESCE(avatar_url,''), created_at
`SELECT id, value, user_id, auto_confirm, COALESCE(remark,''), pause_duration,
COALESCE(username,''), COALESCE(password,''),
show_browser, COALESCE(nickname,''), COALESCE(avatar_url,''),
COALESCE(metadata_json,''), COALESCE(last_refresh_at,0),
COALESCE(login_method,''), COALESCE(last_login_at,0), created_at
FROM cookies WHERE id=?`, cookieID).Scan(
&d.ID, &d.Value, &d.UserID, &autoConfirm, &d.Remark, &pauseDuration,
&d.Username, &d.Password, &showBrowser, &d.Nickname, &d.AvatarURL, &d.CreatedAt)
&d.Username, &d.Password, &showBrowser, &d.Nickname, &d.AvatarURL,
&d.MetadataJSON, &d.LastRefreshAt, &d.LoginMethod, &d.LastLoginAt, &d.CreatedAt)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
@@ -129,6 +133,30 @@ func (c *Cookies) GetDetails(ctx context.Context, cookieID string) (*CookieDetai
return &d, nil
}
// UpdateLoginInfo 保存账号密码登录资料。
func (c *Cookies) UpdateLoginInfo(ctx context.Context, cookieID, username, password string, showBrowser bool) error {
v := 0
if showBrowser {
v = 1
}
_, err := c.DB.ExecContext(ctx,
`UPDATE cookies
SET username=?, password=?, show_browser=?, updated_at=CURRENT_TIMESTAMP
WHERE id=?`,
username, password, v, cookieID)
return err
}
// MarkLogin 记录账号最近一次成功登录方式。
func (c *Cookies) MarkLogin(ctx context.Context, cookieID, method string, loginAt int64) error {
_, err := c.DB.ExecContext(ctx,
`UPDATE cookies
SET login_method=?, last_login_at=?, updated_at=CURRENT_TIMESTAMP
WHERE id=?`,
method, loginAt, cookieID)
return err
}
// UpdateProfile 保存账号展示资料。
func (c *Cookies) UpdateProfile(ctx context.Context, cookieID, nickname, avatarURL string) error {
_, err := c.DB.ExecContext(ctx,
@@ -164,17 +192,23 @@ func (c *Cookies) GetAutoConfirm(ctx context.Context, cookieID string) (bool, er
// SetStatus 启用/禁用账号(cookie_status 表)。
func (c *Cookies) SetStatus(ctx context.Context, cookieID string, enabled bool) error {
return c.SetStatusWithReason(ctx, cookieID, enabled, "")
}
// SetStatusWithReason 启用/禁用账号并记录禁用原因。
func (c *Cookies) SetStatusWithReason(ctx context.Context, cookieID string, enabled bool, reason string) error {
v := 0
if enabled {
v = 1
}
_, err := c.DB.ExecContext(ctx,
`INSERT INTO cookie_status (cookie_id, enabled, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)`+
`INSERT INTO cookie_status (cookie_id, enabled, disable_reason, updated_at) VALUES (?, ?, ?, CURRENT_TIMESTAMP)`+
dialectUpsert(c.Dialect, []string{"cookie_id"}, map[string]string{
"enabled": "EXCLUDED.enabled",
"updated_at": "CURRENT_TIMESTAMP",
"enabled": "EXCLUDED.enabled",
"disable_reason": "EXCLUDED.disable_reason",
"updated_at": "CURRENT_TIMESTAMP",
}),
cookieID, v)
cookieID, v, reason)
return err
}
+31 -5
View File
@@ -50,6 +50,30 @@ func (k *Keywords) Add(ctx context.Context, cookieID, keyword, reply, itemID, kw
cookieID, keyword, reply, nullable(itemID), kwType, nullable(imageURL))
}
// ReplaceForCookie 覆盖某账号的全部关键词。
func (k *Keywords) ReplaceForCookie(ctx context.Context, cookieID string, rows []KeywordRow) error {
tx, err := k.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, `DELETE FROM keywords WHERE cookie_id=?`, cookieID); err != nil {
return err
}
for _, row := range rows {
kwType := row.Type
if kwType == "" {
kwType = "text"
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO keywords (cookie_id, keyword, reply, item_id, type, image_url) VALUES (?,?,?,?,?,?)`,
cookieID, row.Keyword, row.Reply, nullable(row.ItemID), kwType, nullable(row.ImageURL)); err != nil {
return err
}
}
return tx.Commit()
}
// DeleteByIndex 按索引(0-based,按 id 顺序)删除某账号的一个关键字。
func (k *Keywords) DeleteByIndex(ctx context.Context, cookieID string, index int) error {
rows, err := k.DB.QueryContext(ctx,
@@ -229,13 +253,13 @@ func (n *Notifications) SetBindings(ctx context.Context, cookieID string, channe
return err
}
for _, channelID := range channelIDs {
var exists int
var exists bool
if err := tx.QueryRowContext(ctx,
`SELECT EXISTS(SELECT 1 FROM notification_channels WHERE id=? AND user_id=?)`,
channelID, userID).Scan(&exists); err != nil {
return err
}
if exists == 0 {
if !exists {
return ErrForbidden
}
}
@@ -263,7 +287,8 @@ type SystemSettings struct {
// Get 取单项设置。
func (s *SystemSettings) Get(ctx context.Context, key string) (string, error) {
var v string
err := s.DB.QueryRowContext(ctx, `SELECT value FROM system_settings WHERE key=?`, key).Scan(&v)
keyCol := dialectQuote(s.Dialect, "key")
err := s.DB.QueryRowContext(ctx, `SELECT value FROM system_settings WHERE `+keyCol+`=?`, key).Scan(&v)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return "", nil
@@ -275,7 +300,8 @@ func (s *SystemSettings) Get(ctx context.Context, key string) (string, error) {
// All 取全部设置(key→value)。
func (s *SystemSettings) All(ctx context.Context) (map[string]string, error) {
rows, err := s.DB.QueryContext(ctx, `SELECT key, value FROM system_settings`)
keyCol := dialectQuote(s.Dialect, "key")
rows, err := s.DB.QueryContext(ctx, `SELECT `+keyCol+`, value FROM system_settings`)
if err != nil {
return nil, err
}
@@ -307,7 +333,7 @@ func (s *SystemSettings) Set(ctx context.Context, key, value string) error {
// PublicSystemKeys 是公开设置键白名单(前端登录页等无需登录可读)。
var PublicSystemKeys = map[string]bool{
"theme_color": true, "registration_enabled": true,
"show_default_login_info": true, "login_captcha_enabled": true,
"show_default_login_info": true,
}
// Public 取公开设置子集。
+12 -3
View File
@@ -272,9 +272,8 @@ func TestSettings_Public(t *testing.T) {
if _, ok := pub["qq_reply_secret_key"]; ok {
t.Fatal("qq_reply_secret_key 不应外露")
}
// 迁移默认就位的公开 key(login_captcha_enabled 等)应可见。
if pub["login_captcha_enabled"] != "true" {
t.Fatalf("login_captcha_enabled 应为 true, got %q", pub["login_captcha_enabled"])
if _, ok := pub["login_captcha_enabled"]; ok {
t.Fatal("未实现的登录验证码开关不应公开")
}
// 白名单内其它默认 key(show_default_login_info)也应可见。
if pub["show_default_login_info"] != "true" {
@@ -305,6 +304,16 @@ func TestCookies_DeleteAndStatuses(t *testing.T) {
if _, err := s.Cookies.GetDetails(ctx, "nope"); !errors.Is(err, ErrNotFound) {
t.Fatalf("want ErrNotFound, got %v", err)
}
if _, err := s.DB.ExecContext(ctx, `UPDATE cookies SET remark=NULL, username=NULL, password=NULL WHERE id=?`, cid); err != nil {
t.Fatalf("set nullable text fields: %v", err)
}
details, err := s.Cookies.GetDetails(ctx, cid)
if err != nil {
t.Fatalf("GetDetails should tolerate NULL text fields: %v", err)
}
if details.Remark != "" || details.Username != "" || details.Password != "" {
t.Fatalf("NULL text fields should decode as empty strings: %+v", details)
}
// GetAutoConfirm 不存在 → ErrNotFound。
if _, err := s.Cookies.GetAutoConfirm(ctx, "nope"); !errors.Is(err, ErrNotFound) {
+23 -3
View File
@@ -107,7 +107,7 @@ func (b *ItemPublishBatches) Get(ctx context.Context, userID int64, id string) (
var out ItemPublishBatch
err := b.DB.QueryRowContext(ctx,
`SELECT id,user_id,default_cookie_id,filename,upload_dir,status,total_count,success_count,failed_count,
COALESCE(created_at,''),COALESCE(updated_at,'')
created_at,updated_at
FROM item_publish_batches WHERE id=? AND user_id=?`, id, userID).Scan(
&out.ID, &out.UserID, &out.DefaultCookieID, &out.Filename, &out.UploadDir, &out.Status,
&out.TotalCount, &out.SuccessCount, &out.FailedCount, &out.CreatedAt, &out.UpdatedAt)
@@ -125,7 +125,7 @@ func (b *ItemPublishBatches) Rows(ctx context.Context, batchID string) ([]ItemPu
rows, err := b.DB.QueryContext(ctx,
`SELECT id,batch_id,row_no,cookie_id,title,description,price,original_price,quantity,postage_mode,postage,
images_json,COALESCE(automation_json,'{}'),status,item_id,item_url,error_message,
raw_json,COALESCE(created_at,''),COALESCE(updated_at,'')
raw_json,created_at,updated_at
FROM item_publish_batch_rows WHERE batch_id=? ORDER BY row_no`, batchID)
if err != nil {
return nil, err
@@ -154,7 +154,7 @@ func (b *ItemPublishBatches) PendingRows(ctx context.Context, batchID string, fa
rows, err := b.DB.QueryContext(ctx,
`SELECT id,batch_id,row_no,cookie_id,title,description,price,original_price,quantity,postage_mode,postage,
images_json,COALESCE(automation_json,'{}'),status,item_id,item_url,error_message,
raw_json,COALESCE(created_at,''),COALESCE(updated_at,'')
raw_json,created_at,updated_at
FROM item_publish_batch_rows WHERE batch_id=? AND status IN `+statuses+` ORDER BY row_no`, batchID)
if err != nil {
return nil, err
@@ -221,6 +221,26 @@ func (b *ItemPublishBatches) MarkRowFailed(ctx context.Context, rowID int64, mes
return err
}
// MarkRunningFailed 将批次内仍在 running 的行标为失败。
func (b *ItemPublishBatches) MarkRunningFailed(ctx context.Context, batchID, message string) error {
_, err := b.DB.ExecContext(ctx,
`UPDATE item_publish_batch_rows
SET status='failed',error_message=?,updated_at=CURRENT_TIMESTAMP
WHERE batch_id=? AND status='running'`,
message, batchID)
return err
}
// MarkUnfinishedFailed 将批次内 pending/running 行标为失败。
func (b *ItemPublishBatches) MarkUnfinishedFailed(ctx context.Context, batchID, message string) error {
_, err := b.DB.ExecContext(ctx,
`UPDATE item_publish_batch_rows
SET status='failed',error_message=?,updated_at=CURRENT_TIMESTAMP
WHERE batch_id=? AND status IN ('pending','running')`,
message, batchID)
return err
}
// ResetFailed 将批次内所有 failed 行重置为 pending,便于失败重试。
func (b *ItemPublishBatches) ResetFailed(ctx context.Context, batchID string) error {
_, err := b.DB.ExecContext(ctx,
@@ -0,0 +1,47 @@
-- +goose Up
ALTER TABLE cookies ADD COLUMN metadata_json TEXT;
ALTER TABLE cookies ADD COLUMN last_refresh_at BIGINT NOT NULL DEFAULT 0;
ALTER TABLE cookie_status ADD COLUMN disable_reason TEXT;
CREATE TABLE IF NOT EXISTS cookie_refresh_schedules (
cookie_id VARCHAR(191) PRIMARY KEY,
expire_at BIGINT NOT NULL DEFAULT 0,
disabled TINYINT(1) NOT NULL DEFAULT 0,
consecutive_failures INT NOT NULL DEFAULT 0,
last_error TEXT NOT NULL,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
CONSTRAINT fk_cookie_refresh_schedules_cookie FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS scheduled_cookies_refresh_log (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
cookie_id VARCHAR(191) NOT NULL,
status VARCHAR(32) NOT NULL,
message TEXT NOT NULL,
updated_cookie_names TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS scheduled_login_renew_log (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
cookie_id VARCHAR(191) NOT NULL,
status VARCHAR(32) NOT NULL,
message TEXT NOT NULL,
updated_cookie_names TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS scheduled_api_cookie_renew_log (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
cookie_id VARCHAR(191) NOT NULL,
status VARCHAR(32) NOT NULL,
message TEXT NOT NULL,
updated_cookie_names TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- +goose Down
DROP TABLE IF EXISTS scheduled_api_cookie_renew_log;
DROP TABLE IF EXISTS scheduled_login_renew_log;
DROP TABLE IF EXISTS scheduled_cookies_refresh_log;
DROP TABLE IF EXISTS cookie_refresh_schedules;
@@ -0,0 +1,20 @@
-- +goose Up
ALTER TABLE cookie_refresh_schedules ADD COLUMN last_status VARCHAR(32);
ALTER TABLE cookie_refresh_schedules ADD COLUMN last_error_message TEXT;
ALTER TABLE cookie_refresh_schedules ADD COLUMN last_refresh_at BIGINT NOT NULL DEFAULT 0;
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN batch_id VARCHAR(36);
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN updated_cookie_count INT NOT NULL DEFAULT 0;
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN next_expire_at BIGINT NOT NULL DEFAULT 0;
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN error_message TEXT;
ALTER TABLE scheduled_login_renew_log ADD COLUMN batch_id VARCHAR(36);
ALTER TABLE scheduled_login_renew_log ADD COLUMN error_message TEXT;
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN batch_id VARCHAR(36);
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN updated_cookie_count INT NOT NULL DEFAULT 0;
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN response_content TEXT;
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN error_message TEXT;
-- +goose Down
SELECT 1;
@@ -0,0 +1,34 @@
-- +goose Up
ALTER TABLE cookies ADD COLUMN login_method VARCHAR(32) NOT NULL DEFAULT '';
ALTER TABLE cookies ADD COLUMN last_login_at BIGINT NOT NULL DEFAULT 0;
CREATE TABLE IF NOT EXISTS account_login_logs (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
cookie_id VARCHAR(255) NOT NULL,
user_id BIGINT NOT NULL DEFAULT 0,
owner_id BIGINT NOT NULL DEFAULT 0,
account_pk BIGINT NOT NULL DEFAULT 0,
account_identifier VARCHAR(80) NOT NULL DEFAULT '',
username VARCHAR(255) NOT NULL DEFAULT '',
method VARCHAR(32) NOT NULL DEFAULT '',
status VARCHAR(32) NOT NULL,
message TEXT NOT NULL,
trigger_reason VARCHAR(128) NOT NULL DEFAULT '',
failure_reason VARCHAR(64) NOT NULL DEFAULT '',
error_message TEXT NOT NULL,
updated_cookie_names VARCHAR(500) NOT NULL DEFAULT '',
duration_ms BIGINT NOT NULL DEFAULT 0,
created_at BIGINT NOT NULL
);
CREATE INDEX idx_account_login_logs_cookie_created
ON account_login_logs(cookie_id, created_at DESC);
CREATE INDEX idx_account_login_logs_identifier_status_created
ON account_login_logs(account_identifier, status, created_at DESC);
CREATE INDEX idx_account_login_logs_owner_created
ON account_login_logs(owner_id, created_at DESC);
-- +goose Down
DROP TABLE IF EXISTS account_login_logs;
ALTER TABLE cookies DROP COLUMN last_login_at;
ALTER TABLE cookies DROP COLUMN login_method;
@@ -0,0 +1,46 @@
-- +goose Up
ALTER TABLE cookies ADD COLUMN metadata_json TEXT DEFAULT '';
ALTER TABLE cookies ADD COLUMN last_refresh_at BIGINT NOT NULL DEFAULT 0;
ALTER TABLE cookie_status ADD COLUMN disable_reason TEXT DEFAULT '';
CREATE TABLE IF NOT EXISTS cookie_refresh_schedules (
cookie_id TEXT PRIMARY KEY REFERENCES cookies(id) ON DELETE CASCADE,
expire_at BIGINT NOT NULL DEFAULT 0,
disabled INTEGER NOT NULL DEFAULT 0,
consecutive_failures INTEGER NOT NULL DEFAULT 0,
last_error TEXT NOT NULL DEFAULT '',
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS scheduled_cookies_refresh_log (
id BIGSERIAL PRIMARY KEY,
cookie_id TEXT NOT NULL,
status TEXT NOT NULL,
message TEXT NOT NULL DEFAULT '',
updated_cookie_names TEXT NOT NULL DEFAULT '',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS scheduled_login_renew_log (
id BIGSERIAL PRIMARY KEY,
cookie_id TEXT NOT NULL,
status TEXT NOT NULL,
message TEXT NOT NULL DEFAULT '',
updated_cookie_names TEXT NOT NULL DEFAULT '',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS scheduled_api_cookie_renew_log (
id BIGSERIAL PRIMARY KEY,
cookie_id TEXT NOT NULL,
status TEXT NOT NULL,
message TEXT NOT NULL DEFAULT '',
updated_cookie_names TEXT NOT NULL DEFAULT '',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- +goose Down
DROP TABLE IF EXISTS scheduled_api_cookie_renew_log;
DROP TABLE IF EXISTS scheduled_login_renew_log;
DROP TABLE IF EXISTS scheduled_cookies_refresh_log;
DROP TABLE IF EXISTS cookie_refresh_schedules;
@@ -0,0 +1,20 @@
-- +goose Up
ALTER TABLE cookie_refresh_schedules ADD COLUMN last_status TEXT DEFAULT '';
ALTER TABLE cookie_refresh_schedules ADD COLUMN last_error_message TEXT DEFAULT '';
ALTER TABLE cookie_refresh_schedules ADD COLUMN last_refresh_at BIGINT NOT NULL DEFAULT 0;
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN batch_id TEXT DEFAULT '';
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN updated_cookie_count INTEGER NOT NULL DEFAULT 0;
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN next_expire_at BIGINT NOT NULL DEFAULT 0;
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN error_message TEXT DEFAULT '';
ALTER TABLE scheduled_login_renew_log ADD COLUMN batch_id TEXT DEFAULT '';
ALTER TABLE scheduled_login_renew_log ADD COLUMN error_message TEXT DEFAULT '';
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN batch_id TEXT DEFAULT '';
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN updated_cookie_count INTEGER NOT NULL DEFAULT 0;
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN response_content TEXT DEFAULT '';
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN error_message TEXT DEFAULT '';
-- +goose Down
SELECT 1;
@@ -0,0 +1,37 @@
-- +goose Up
ALTER TABLE cookies ADD COLUMN login_method TEXT NOT NULL DEFAULT '';
ALTER TABLE cookies ADD COLUMN last_login_at BIGINT NOT NULL DEFAULT 0;
CREATE TABLE IF NOT EXISTS account_login_logs (
id BIGSERIAL PRIMARY KEY,
cookie_id TEXT NOT NULL,
user_id BIGINT NOT NULL DEFAULT 0,
owner_id BIGINT NOT NULL DEFAULT 0,
account_pk BIGINT NOT NULL DEFAULT 0,
account_identifier TEXT NOT NULL DEFAULT '',
username TEXT NOT NULL DEFAULT '',
method TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL,
message TEXT NOT NULL DEFAULT '',
trigger_reason TEXT NOT NULL DEFAULT '',
failure_reason TEXT NOT NULL DEFAULT '',
error_message TEXT NOT NULL DEFAULT '',
updated_cookie_names TEXT NOT NULL DEFAULT '',
duration_ms BIGINT NOT NULL DEFAULT 0,
created_at BIGINT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_account_login_logs_cookie_created
ON account_login_logs(cookie_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_account_login_logs_identifier_status_created
ON account_login_logs(account_identifier, status, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_account_login_logs_owner_created
ON account_login_logs(owner_id, created_at DESC);
-- +goose Down
DROP INDEX IF EXISTS idx_account_login_logs_owner_created;
DROP INDEX IF EXISTS idx_account_login_logs_identifier_status_created;
DROP INDEX IF EXISTS idx_account_login_logs_cookie_created;
DROP TABLE IF EXISTS account_login_logs;
ALTER TABLE cookies DROP COLUMN IF EXISTS last_login_at;
ALTER TABLE cookies DROP COLUMN IF EXISTS login_method;
@@ -0,0 +1,47 @@
-- +goose Up
ALTER TABLE cookies ADD COLUMN metadata_json TEXT DEFAULT '';
ALTER TABLE cookies ADD COLUMN last_refresh_at INTEGER DEFAULT 0;
ALTER TABLE cookie_status ADD COLUMN disable_reason TEXT DEFAULT '';
CREATE TABLE IF NOT EXISTS cookie_refresh_schedules (
cookie_id TEXT PRIMARY KEY,
expire_at INTEGER NOT NULL DEFAULT 0,
disabled INTEGER NOT NULL DEFAULT 0,
consecutive_failures INTEGER NOT NULL DEFAULT 0,
last_error TEXT NOT NULL DEFAULT '',
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS scheduled_cookies_refresh_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
status TEXT NOT NULL,
message TEXT NOT NULL DEFAULT '',
updated_cookie_names TEXT NOT NULL DEFAULT '',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS scheduled_login_renew_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
status TEXT NOT NULL,
message TEXT NOT NULL DEFAULT '',
updated_cookie_names TEXT NOT NULL DEFAULT '',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS scheduled_api_cookie_renew_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
status TEXT NOT NULL,
message TEXT NOT NULL DEFAULT '',
updated_cookie_names TEXT NOT NULL DEFAULT '',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- +goose Down
DROP TABLE IF EXISTS scheduled_api_cookie_renew_log;
DROP TABLE IF EXISTS scheduled_login_renew_log;
DROP TABLE IF EXISTS scheduled_cookies_refresh_log;
DROP TABLE IF EXISTS cookie_refresh_schedules;
@@ -0,0 +1,20 @@
-- +goose Up
ALTER TABLE cookie_refresh_schedules ADD COLUMN last_status TEXT DEFAULT '';
ALTER TABLE cookie_refresh_schedules ADD COLUMN last_error_message TEXT DEFAULT '';
ALTER TABLE cookie_refresh_schedules ADD COLUMN last_refresh_at INTEGER DEFAULT 0;
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN batch_id TEXT DEFAULT '';
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN updated_cookie_count INTEGER DEFAULT 0;
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN next_expire_at INTEGER DEFAULT 0;
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN error_message TEXT DEFAULT '';
ALTER TABLE scheduled_login_renew_log ADD COLUMN batch_id TEXT DEFAULT '';
ALTER TABLE scheduled_login_renew_log ADD COLUMN error_message TEXT DEFAULT '';
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN batch_id TEXT DEFAULT '';
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN updated_cookie_count INTEGER DEFAULT 0;
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN response_content TEXT DEFAULT '';
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN error_message TEXT DEFAULT '';
-- +goose Down
SELECT 1;
@@ -0,0 +1,35 @@
-- +goose Up
ALTER TABLE cookies ADD COLUMN login_method TEXT NOT NULL DEFAULT '';
ALTER TABLE cookies ADD COLUMN last_login_at INTEGER NOT NULL DEFAULT 0;
CREATE TABLE IF NOT EXISTS account_login_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
user_id INTEGER NOT NULL DEFAULT 0,
owner_id INTEGER NOT NULL DEFAULT 0,
account_pk INTEGER NOT NULL DEFAULT 0,
account_identifier TEXT NOT NULL DEFAULT '',
username TEXT NOT NULL DEFAULT '',
method TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL,
message TEXT NOT NULL DEFAULT '',
trigger_reason TEXT NOT NULL DEFAULT '',
failure_reason TEXT NOT NULL DEFAULT '',
error_message TEXT NOT NULL DEFAULT '',
updated_cookie_names TEXT NOT NULL DEFAULT '',
duration_ms INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_account_login_logs_cookie_created
ON account_login_logs(cookie_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_account_login_logs_identifier_status_created
ON account_login_logs(account_identifier, status, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_account_login_logs_owner_created
ON account_login_logs(owner_id, created_at DESC);
-- +goose Down
DROP INDEX IF EXISTS idx_account_login_logs_owner_created;
DROP INDEX IF EXISTS idx_account_login_logs_identifier_status_created;
DROP INDEX IF EXISTS idx_account_login_logs_cookie_created;
DROP TABLE IF EXISTS account_login_logs;
+24
View File
@@ -35,5 +35,29 @@ type CookieDetail struct {
ShowBrowser bool
Nickname string
AvatarURL string
MetadataJSON string
LastRefreshAt int64
LoginMethod string
LastLoginAt int64
CreatedAt string
}
// AccountLoginLog 记录账号登录/续登尝试。
type AccountLoginLog struct {
ID int64
CookieID string
UserID int64
OwnerID int64
AccountPK int64
AccountIdentifier string
Username string
Method string
Status string
Message string
TriggerReason string
FailureReason string
ErrorMessage string
UpdatedCookieNames string
DurationMS int64
CreatedAt int64
}
+44
View File
@@ -180,6 +180,50 @@ func TestMultiDB_CookiesUpsertBool(t *testing.T) {
}
}
func TestMultiDB_SettingsQuoteKey(t *testing.T) {
for _, tg := range allTestTargets(t) {
t.Run(tg.name, func(t *testing.T) {
defer tg.cleanup()
ctx := context.Background()
s := tg.store
if err := s.Settings.Set(ctx, "theme_color", "green"); err != nil {
t.Fatalf("Settings.Set: %v", err)
}
got, err := s.Settings.Get(ctx, "theme_color")
if err != nil || got != "green" {
t.Fatalf("Settings.Get=%q err=%v want green", got, err)
}
all, err := s.Settings.All(ctx)
if err != nil || all["theme_color"] != "green" {
t.Fatalf("Settings.All=%v err=%v", all, err)
}
username := tg.name + "_settings_user_" + fmt.Sprintf("%d", atomic.AddUint64(&multidbCounter, 1))
if ok, err := s.Users.Create(ctx, username, username+"@e.com", "pw"); err != nil || !ok {
t.Fatalf("create user: ok=%v err=%v", ok, err)
}
user, _ := s.Users.GetByUsername(ctx, username)
keyCol := dialectQuote(tg.dialect, "key")
if _, err := s.DB.ExecContext(ctx,
`INSERT INTO user_settings (user_id, `+keyCol+`, value, updated_at) VALUES (?,?,?,CURRENT_TIMESTAMP)`+
dialectUpsert(tg.dialect, []string{"user_id", keyCol}, map[string]string{
"value": "EXCLUDED.value",
"updated_at": "CURRENT_TIMESTAMP",
}),
user.ID, "dashboard_range", "30"); err != nil {
t.Fatalf("insert user_settings: %v", err)
}
var value string
if err := s.DB.QueryRowContext(ctx,
`SELECT value FROM user_settings WHERE user_id=? AND `+keyCol+`=?`,
user.ID, "dashboard_range").Scan(&value); err != nil || value != "30" {
t.Fatalf("select user_settings=%q err=%v want 30", value, err)
}
})
}
}
// TestMultiDB_OrdersUpsertNullScan 验证订单部分字段 Upsert 后 Get 能正确扫描 NULL 列。
func TestMultiDB_OrdersUpsertNullScan(t *testing.T) {
for _, tg := range allTestTargets(t) {
+236
View File
@@ -0,0 +1,236 @@
package db
import (
"context"
"database/sql"
"errors"
"strings"
"time"
)
// RenewalAccount 是续期调度所需的账号视图。
type RenewalAccount struct {
ID string
Value string
UserID int64
Enabled bool
Username string
Password string
ShowBrowser bool
MetadataJSON string
LastRefreshAt int64
}
// CookieRefreshSchedule 对应 cookie_refresh_schedules。
type CookieRefreshSchedule struct {
CookieID string
ExpireAt int64
Disabled bool
ConsecutiveFailures int
LastError string
LastStatus string
LastErrorMessage string
LastRefreshAt int64
}
// RenewalLog 是三类续期任务日志的通用写入模型。
type RenewalLog struct {
BatchID string
CookieID string
Status string
Message string
ErrorMessage string
UpdatedCookieNames []string
UpdatedCookieCount int
ResponseContent string
NextExpireAt int64
}
// RenewalStore 保存续期任务计划与日志。
type RenewalStore struct {
DB *sql.DB
Dialect Dialect
}
// AllRenewalAccounts 返回所有账号,包含启用状态;浏览器 cookie 续期会用到禁用账号。
func (c *Cookies) AllRenewalAccounts(ctx context.Context) ([]RenewalAccount, error) {
rows, err := c.DB.QueryContext(ctx,
`SELECT c.id, c.value, c.user_id, COALESCE(cs.enabled, 1),
COALESCE(c.username,''), COALESCE(c.password,''), COALESCE(c.show_browser,0),
COALESCE(c.metadata_json,''), COALESCE(c.last_refresh_at,0)
FROM cookies c
LEFT JOIN cookie_status cs ON cs.cookie_id = c.id
ORDER BY c.id`)
if err != nil {
return nil, err
}
defer rows.Close()
return scanRenewalAccounts(rows)
}
// ActiveRenewalAccounts 返回启用账号,用于 WS/API 续期类任务。
func (c *Cookies) ActiveRenewalAccounts(ctx context.Context) ([]RenewalAccount, error) {
rows, err := c.DB.QueryContext(ctx,
`SELECT c.id, c.value, c.user_id, COALESCE(cs.enabled, 1),
COALESCE(c.username,''), COALESCE(c.password,''), COALESCE(c.show_browser,0),
COALESCE(c.metadata_json,''), COALESCE(c.last_refresh_at,0)
FROM cookies c
LEFT JOIN cookie_status cs ON cs.cookie_id = c.id
WHERE COALESCE(cs.enabled, 1) <> 0
ORDER BY c.id`)
if err != nil {
return nil, err
}
defer rows.Close()
return scanRenewalAccounts(rows)
}
func scanRenewalAccounts(rows *sql.Rows) ([]RenewalAccount, error) {
var out []RenewalAccount
for rows.Next() {
var a RenewalAccount
var enabled, showBrowser int
if err := rows.Scan(&a.ID, &a.Value, &a.UserID, &enabled, &a.Username, &a.Password, &showBrowser, &a.MetadataJSON, &a.LastRefreshAt); err != nil {
return nil, err
}
a.Enabled = enabled != 0
a.ShowBrowser = showBrowser != 0
out = append(out, a)
}
return out, rows.Err()
}
// UpdateRenewalCookie 保存续期后的 Cookie,同时写入浏览器快照和最后续期时间。
func (c *Cookies) UpdateRenewalCookie(ctx context.Context, cookieID, cookieValue, metadataJSON string, lastRefreshAt int64) error {
if lastRefreshAt <= 0 {
lastRefreshAt = time.Now().Unix()
}
_, err := c.DB.ExecContext(ctx,
`UPDATE cookies
SET value=?, metadata_json=?, last_refresh_at=?, updated_at=CURRENT_TIMESTAMP
WHERE id=?`,
cookieValue, metadataJSON, lastRefreshAt, cookieID)
if err != nil {
return err
}
return nil
}
// GetCookieRefreshSchedule 读取浏览器 Cookie 续期计划。
func (r *RenewalStore) GetCookieRefreshSchedule(ctx context.Context, cookieID string) (*CookieRefreshSchedule, error) {
var s CookieRefreshSchedule
var disabled int
err := r.DB.QueryRowContext(ctx,
`SELECT cookie_id, expire_at, disabled, consecutive_failures, COALESCE(last_error,''),
COALESCE(last_status,''), COALESCE(last_error_message,''), COALESCE(last_refresh_at,0)
FROM cookie_refresh_schedules WHERE cookie_id=?`, cookieID).
Scan(&s.CookieID, &s.ExpireAt, &disabled, &s.ConsecutiveFailures, &s.LastError,
&s.LastStatus, &s.LastErrorMessage, &s.LastRefreshAt)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
return nil, err
}
s.Disabled = disabled != 0
return &s, nil
}
// UpsertCookieRefreshSchedule 写入浏览器 Cookie 续期计划。
func (r *RenewalStore) UpsertCookieRefreshSchedule(ctx context.Context, s CookieRefreshSchedule) error {
disabled := 0
if s.Disabled {
disabled = 1
}
_, err := r.DB.ExecContext(ctx,
`INSERT INTO cookie_refresh_schedules
(cookie_id, expire_at, disabled, consecutive_failures, last_error,
last_status, last_error_message, last_refresh_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`+
dialectUpsert(r.Dialect, []string{"cookie_id"}, map[string]string{
"expire_at": "EXCLUDED.expire_at",
"disabled": "EXCLUDED.disabled",
"consecutive_failures": "EXCLUDED.consecutive_failures",
"last_error": "EXCLUDED.last_error",
"last_status": "EXCLUDED.last_status",
"last_error_message": "EXCLUDED.last_error_message",
"last_refresh_at": "EXCLUDED.last_refresh_at",
"updated_at": "CURRENT_TIMESTAMP",
}),
s.CookieID, s.ExpireAt, disabled, s.ConsecutiveFailures, s.LastError,
s.LastStatus, s.LastErrorMessage, s.LastRefreshAt)
return err
}
// AddBrowserCookieRenewLog 记录浏览器 Cookie 续期日志。
func (r *RenewalStore) AddBrowserCookieRenewLog(ctx context.Context, log RenewalLog) error {
if log.UpdatedCookieCount == 0 {
log.UpdatedCookieCount = len(log.UpdatedCookieNames)
}
_, err := r.DB.ExecContext(ctx,
`INSERT INTO scheduled_cookies_refresh_log
(batch_id, cookie_id, status, message, error_message, updated_cookie_names,
updated_cookie_count, next_expire_at, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
log.BatchID, log.CookieID, log.Status, log.Message, firstNonEmpty(log.ErrorMessage, log.Message),
strings.Join(log.UpdatedCookieNames, ","), log.UpdatedCookieCount, log.NextExpireAt)
return err
}
// AddLoginRenewLog 记录 login_renew 任务日志。
func (r *RenewalStore) AddLoginRenewLog(ctx context.Context, log RenewalLog) error {
_, err := r.DB.ExecContext(ctx,
`INSERT INTO scheduled_login_renew_log
(batch_id, cookie_id, status, message, error_message, updated_cookie_names, created_at)
VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
log.BatchID, log.CookieID, log.Status, log.Message, firstNonEmpty(log.ErrorMessage, log.Message),
strings.Join(log.UpdatedCookieNames, ","))
return err
}
// AddAPICookieRenewLog 记录 api_cookie_renew 任务日志。
func (r *RenewalStore) AddAPICookieRenewLog(ctx context.Context, log RenewalLog) error {
if log.UpdatedCookieCount == 0 {
log.UpdatedCookieCount = len(log.UpdatedCookieNames)
}
_, err := r.DB.ExecContext(ctx,
`INSERT INTO scheduled_api_cookie_renew_log
(batch_id, cookie_id, status, message, error_message, updated_cookie_names,
updated_cookie_count, response_content, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
log.BatchID, log.CookieID, log.Status, log.Message, firstNonEmpty(log.ErrorMessage, log.Message),
strings.Join(log.UpdatedCookieNames, ","), log.UpdatedCookieCount, log.ResponseContent)
return err
}
// RecentBrowserCookieRenewStatuses 返回最近 limit 条浏览器续期日志状态。
func (r *RenewalStore) RecentBrowserCookieRenewStatuses(ctx context.Context, cookieID string, limit int) ([]string, error) {
if limit <= 0 {
return nil, nil
}
rows, err := r.DB.QueryContext(ctx,
`SELECT status FROM scheduled_cookies_refresh_log
WHERE cookie_id=? ORDER BY id DESC LIMIT ?`, cookieID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var statuses []string
for rows.Next() {
var status string
if err := rows.Scan(&status); err != nil {
return nil, err
}
statuses = append(statuses, status)
}
return statuses, rows.Err()
}
func firstNonEmpty(values ...string) string {
for _, v := range values {
if strings.TrimSpace(v) != "" {
return v
}
}
return ""
}
+44
View File
@@ -154,3 +154,47 @@ func TestCookieSaveRequiresInit(t *testing.T) {
t.Fatalf("GetAutoConfirm=%v want false, err=%v", enabled, err)
}
}
func TestCookieLoginAudit(t *testing.T) {
s, cleanup := newTestDB(t)
defer cleanup()
ctx := context.Background()
if _, err := s.Users.Create(ctx, "admin", "a@e.com", "pw"); err != nil {
t.Fatalf("Create user: %v", err)
}
admin, _ := s.Users.GetByUsername(ctx, "admin")
if err := s.Cookies.Save(ctx, "cid", "cookievalue", admin.ID); err != nil {
t.Fatalf("Save cookie: %v", err)
}
if err := s.Cookies.UpdateLoginInfo(ctx, "cid", "login-user", "secret", true); err != nil {
t.Fatalf("UpdateLoginInfo: %v", err)
}
if err := s.Cookies.MarkLogin(ctx, "cid", "password", 12345); err != nil {
t.Fatalf("MarkLogin: %v", err)
}
d, err := s.Cookies.GetDetails(ctx, "cid")
if err != nil {
t.Fatalf("GetDetails: %v", err)
}
if d.Username != "login-user" || d.Password != "secret" || !d.ShowBrowser {
t.Fatalf("登录资料未保存: %+v", d)
}
if d.LoginMethod != "password" || d.LastLoginAt != 12345 {
t.Fatalf("登录审计字段异常: method=%q at=%d", d.LoginMethod, d.LastLoginAt)
}
if err := s.LoginLogs.Add(ctx, AccountLoginLog{CookieID: "cid", UserID: admin.ID, Method: "password", Status: "failed", Message: "wrong", CreatedAt: 10}); err != nil {
t.Fatalf("Add log failed: %v", err)
}
if err := s.LoginLogs.Add(ctx, AccountLoginLog{CookieID: "cid", UserID: admin.ID, Method: "password", Status: "success", Message: "ok", CreatedAt: 20}); err != nil {
t.Fatalf("Add log success: %v", err)
}
logs, err := s.LoginLogs.ListByCookie(ctx, "cid", 10)
if err != nil {
t.Fatalf("ListByCookie: %v", err)
}
if len(logs) != 2 || logs[0].Status != "success" || logs[1].Status != "failed" {
t.Fatalf("登录日志排序/内容异常: %#v", logs)
}
}
+4
View File
@@ -22,6 +22,8 @@ type Store struct {
WSMessages *WSMessageStore
PublishBatches *ItemPublishBatches
Tokens *AccountTokens
Renewal *RenewalStore
LoginLogs *AccountLoginLogs
}
// NewStore 基于 *sql.DB 构造聚合 store。dialect 用于业务 SQL 方言分支。
@@ -45,5 +47,7 @@ func NewStore(db *sql.DB, dialect Dialect) *Store {
WSMessages: &WSMessageStore{DB: db},
PublishBatches: &ItemPublishBatches{DB: db},
Tokens: &AccountTokens{DB: db, Dialect: dialect},
Renewal: &RenewalStore{DB: db, Dialect: dialect},
LoginLogs: &AccountLoginLogs{DB: db},
}
}
+4 -4
View File
@@ -24,12 +24,12 @@ type Users struct {
// IsSystemInitialized 系统是否已初始化(至少存在 admin 用户)。
// IsSystemInitialized 判断系统是否已有管理员账号。
func (u *Users) IsSystemInitialized(ctx context.Context) (bool, error) {
var exists int
var exists bool
err := u.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM users WHERE is_admin=1)`).Scan(&exists)
if err != nil {
return false, fmt.Errorf("检查系统初始化: %w", err)
}
return exists == 1, nil
return exists, nil
}
// GetAdmin 返回首个管理员账号。
@@ -143,12 +143,12 @@ func (u *Users) UpdateCredentials(ctx context.Context, userID int64, username, p
}
defer tx.Rollback()
var exists int
var exists bool
if err := tx.QueryRowContext(ctx,
`SELECT EXISTS(SELECT 1 FROM users WHERE username=? AND id<>?)`, username, userID).Scan(&exists); err != nil {
return err
}
if exists != 0 {
if exists {
return ErrUsernameTaken
}
+117 -25
View File
@@ -31,17 +31,19 @@ const (
MessageExpireTime = time.Hour // 去重有效期
ProcessedIDsMaxSize = 10000 // 去重表上限,超限清理
HeartbeatInterval = 15 * time.Second
// token 心跳间隔。主动刷新 token 让服务端持续续期 cookie(_m_h5_tk /
// sgcookie 等),避免 cookie 自然滑向过期。15 分钟一次,平衡保活与风控。
// 不宜过短,否则易触发阿里系滑块风控。
TokenRefreshInterval = 15 * time.Minute
TokenRefreshMinGap = time.Minute
MessageCooldown = 5 * time.Minute // 收到消息后 5 分钟内不刷 cookie
PasswordLoginMinGap = 30 * time.Minute
// token_refresh_loop 与对方项目一致,默认 20 小时一次;在线保活主要由
// cookieRefreshLoop 负责,每 180 秒刷新一次 Cookie/token。
TokenRefreshInterval = 20 * time.Hour
CookieRefreshInterval = 180 * time.Second
CookieRefreshCheckInterval = 60 * time.Second
TokenRefreshMinGap = time.Minute
MessageCooldown = 5 * time.Minute // 收到消息后 5 分钟内不刷 cookie
PasswordLoginMinGap = 5 * time.Minute
// TokenCacheTTL 缓存的 accessToken 视为有效的时长。tokenRefreshLoop 每 15min
// 刷新一次会续期该缓存;短重启 / 瞬时 mtop 失败时回退到此缓存不掉线。
TokenCacheTTL = 90 * time.Minute
// TokenCacheTTLMin/Max 控制缓存 accessToken 的随机有效期。短重启 / 瞬时
// mtop 失败时回退到此缓存不掉线;在线 Cookie 保活由 cookieRefreshLoop 续期。
TokenCacheTTLMin = 5 * time.Hour
TokenCacheTTLMax = 10 * time.Hour
// ShortConnectionThreshold 连接维持不足此时长视为短连接,疑似 token 失效,
// 清除 token 缓存下轮重新派生,避免反复用失效缓存 token。
ShortConnectionThreshold = 30 * time.Second
@@ -120,11 +122,13 @@ type Account struct {
// 运行时状态(受 mu 保护)
mu sync.Mutex
refreshMu sync.Mutex
currentToken string
deviceID string
connFailures int
lastMsgReceived time.Time
lastTokenRefresh time.Time
lastCookieRefresh time.Time
lastPasswordLogin time.Time
runtimeState string
runtimeMessage string
@@ -397,7 +401,7 @@ func (a *Account) Run(parent context.Context) error {
a.mu.Unlock()
a.setRuntimeState(RuntimeOnline, "消息服务连接正常")
// 3) 心跳 + 消息接收,并并行运行 token 定时刷新。
// 3) 心跳 + 消息接收,并并行运行 token/cookie 定时刷新。
hbCtx, hbCancel := context.WithCancel(ctx)
var hbErr error
hbDone := make(chan struct{})
@@ -413,8 +417,15 @@ func (a *Account) Run(parent context.Context) error {
close(refreshDone)
}()
cookieRefreshDone := make(chan struct{})
go func() {
a.cookieRefreshLoop(hbCtx, conn)
close(cookieRefreshDone)
}()
recvErr := conn.ReceiveLoop(ctx, a.dispatch)
hbCancel()
<-cookieRefreshDone
<-refreshDone
<-hbDone // 确保 hbErr 写入完成后再读取(消除数据竞争)。
_ = conn.Close()
@@ -576,8 +587,8 @@ func (a *Account) tryLoginStatusCheck(ctx context.Context) loginStatusCheckResul
// tryAPIRenew 是密码登录前的轻量恢复层。
// 闲鱼很多“登录态滑向过期”的场景会先允许 hasLogin/silentHasLogin/
// setLoginSettings 刷新一批 Cookie;直接上密码登录更重,也更容易触发风控。
// 因此这里先尝试接口续期:只要 Cookie 有变化就保存并清 token 缓存,让下一轮
// acquireToken 用新 Cookie 重新派生 accessToken。
// 因此这里先尝试接口续期:只有 setLoginSettings 确认成功才短路后续恢复;
// 如果只拿到部分 Cookie,仍会保存并清 token,但继续降级到浏览器/密码登录。
func (a *Account) tryAPIRenew(ctx context.Context) bool {
if a.renewer == nil {
return false
@@ -590,23 +601,26 @@ func (a *Account) tryAPIRenew(ctx context.Context) bool {
a.logger.Warn("接口续期失败", "err", err)
return false
}
if res == nil || res.NewCookies == "" || res.NewCookies == cookieStr {
if res != nil {
a.logger.Info("接口续期未产生 Cookie 更新", "success", res.Success, "message", res.Message)
}
if res == nil {
return false
}
if !a.adoptRecoveredCookie(ctx, res.NewCookies, "接口续期") {
return false
updated := false
if res.NewCookies != "" && res.NewCookies != cookieStr {
updated = a.adoptRecoveredCookie(ctx, res.NewCookies, "接口续期")
}
if res.Success {
a.setRuntimeState(RuntimeConnecting, "登录凭证已接口续期,正在重新连接")
if !updated {
a.setRuntimeState(RuntimeConnecting, "登录凭证已接口续期,正在重新连接")
}
a.logger.Info("接口续期成功", "method", res.RenewMethod, "updated", strings.Join(res.UpdatedCookieNames, ","))
return true
}
a.setRuntimeState(RuntimeConnecting, "登录凭证已有新 Cookie,正在重新验证")
a.logger.Info("接口续期返回部分 Cookie 更新,下一轮重新验证", "updated", strings.Join(res.UpdatedCookieNames, ","))
return true
if updated {
a.logger.Info("接口续期返回部分 Cookie 更新,继续降级恢复", "updated", strings.Join(res.UpdatedCookieNames, ","))
return false
}
a.logger.Info("接口续期未产生可用恢复", "success", res.Success, "message", res.Message)
return false
}
// adoptRecoveredCookie 统一接收“轻量检查/接口续期/浏览器恢复”拿到的新 Cookie。
@@ -676,8 +690,23 @@ func withRetryJitter(base time.Duration) time.Duration {
// 成功时把 token + device_id 缓存到 DB(saveTokenCache),供进程重启复用与
// 稳态重连时跳过 mtop(acquireToken 命中缓存即直接返回)。
func (a *Account) refreshToken(ctx context.Context) (string, string, error) {
a.refreshMu.Lock()
defer a.refreshMu.Unlock()
a.reloadCookieFromDB(ctx)
a.mu.Lock()
cookieStr := a.CookieStr
currentToken := a.currentToken
lastMsg := a.lastMsgReceived
if !lastMsg.IsZero() && time.Since(lastMsg) < MessageCooldown {
a.mu.Unlock()
a.logger.Info("收到消息冷却中,跳过 token/cookie 刷新", "cooldown", MessageCooldown)
if currentToken != "" {
return currentToken, cookieStr, nil
}
return "", "", fmt.Errorf("收到消息冷却中,跳过 token/cookie 刷新")
}
last := a.lastTokenRefresh
if !last.IsZero() && time.Since(last) < TokenRefreshMinGap {
remain := TokenRefreshMinGap - time.Since(last)
@@ -719,6 +748,9 @@ func (a *Account) refreshToken(ctx context.Context) (string, string, error) {
return "", "", fmt.Errorf("token API 未返回结果")
}
a.saveTokenCache(ctx, deviceID, res.AccessToken)
a.mu.Lock()
a.lastMsgReceived = time.Time{}
a.mu.Unlock()
return res.AccessToken, cookieStr, nil
}
@@ -783,12 +815,12 @@ func (a *Account) ensureDeviceIDCached(ctx context.Context) {
}
}
// saveTokenCache 把 accessToken + device_id 缓存到 DB(expire_at = now + TokenCacheTTL)。
// saveTokenCache 把 accessToken + device_id 缓存到 DB(expire_at = now + tokenCacheTTL)。
func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken string) {
if a.store == nil || a.store.Tokens == nil || accessToken == "" {
return
}
if err := a.store.Tokens.Save(ctx, a.CookieID, deviceID, accessToken, time.Now().Add(TokenCacheTTL).Unix()); err != nil {
if err := a.store.Tokens.Save(ctx, a.CookieID, deviceID, accessToken, time.Now().Add(tokenCacheTTL()).Unix()); err != nil {
a.logger.Warn("缓存 accessToken 失败", "err", err)
}
}
@@ -868,6 +900,66 @@ func (a *Account) tokenRefreshLoop(ctx context.Context, conn WSConn) {
}
}
// cookieRefreshLoop 复刻对方项目的在线 Cookie 刷新循环:
// 每 60 秒检查一次,满 180 秒才刷新;收到消息后 5 分钟内跳过;
// 单次失败 5 秒后重试一次,session 过期则主动关闭 WS 进入恢复链路。
func (a *Account) cookieRefreshLoop(ctx context.Context, conn WSConn) {
ticker := time.NewTicker(CookieRefreshCheckInterval)
defer ticker.Stop()
a.mu.Lock()
if a.lastCookieRefresh.IsZero() {
a.lastCookieRefresh = time.Now()
}
a.mu.Unlock()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
}
if ctx.Err() != nil {
return
}
a.mu.Lock()
lastRefresh := a.lastCookieRefresh
lastMsg := a.lastMsgReceived
a.mu.Unlock()
if time.Since(lastRefresh) < CookieRefreshInterval {
continue
}
if !lastMsg.IsZero() && time.Since(lastMsg) < MessageCooldown {
a.logger.Info("收到消息冷却中,跳过在线 cookie 刷新", "cooldown", MessageCooldown)
continue
}
if a.refreshOnlineCookie(ctx, conn) {
continue
}
if sleepCtx(ctx, 5*time.Second) != nil {
return
}
_ = a.refreshOnlineCookie(ctx, conn)
}
}
func (a *Account) refreshOnlineCookie(ctx context.Context, conn WSConn) bool {
token, _, err := a.refreshToken(ctx)
if err != nil {
a.logger.Warn("在线 cookie 刷新失败", "err", err)
if mtop.IsSessionExpiredErr(err) {
a.clearTokenCache(ctx)
_ = conn.Close()
}
return false
}
a.mu.Lock()
a.currentToken = token
a.lastCookieRefresh = time.Now()
a.mu.Unlock()
conn.SetAccessToken(token)
a.logger.Info("在线 cookie 刷新成功")
return true
}
// RuntimeStatus 返回账号当前连接状态的线程安全快照。
func (a *Account) RuntimeStatus() RuntimeStatus {
a.mu.Lock()
+79
View File
@@ -9,6 +9,8 @@ import (
"time"
"xianyu-go/internal/automation"
"xianyu-go/internal/db"
xrenew "xianyu-go/internal/xianyu/renew"
)
// TestStop_IdempotentAndClearsTimers Stop 重复调用幂等;调用后防抖定时器被清空。
@@ -98,6 +100,83 @@ func (a *alertCountingHandler) OnAccountAlert(_ context.Context, _, level, _, _
}
}
type stubCookieRenewer struct {
result *xrenew.Result
err error
calls int
got string
}
func (s *stubCookieRenewer) RenewAPIFirst(_ context.Context, cookiesStr string) (*xrenew.Result, error) {
s.calls++
s.got = cookiesStr
return s.result, s.err
}
func TestTryAPIRenewSuccessShortCircuitsRecovery(t *testing.T) {
acc, _, store, cleanup := newAccountForTest(t)
defer cleanup()
ctx := context.Background()
if err := store.Tokens.Save(ctx, "cid", "did-old", "tok-old", time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatalf("save token: %v", err)
}
renewer := &stubCookieRenewer{result: &xrenew.Result{
Success: true,
RenewMethod: "api",
NewCookies: "unb=123; _m_h5_tk=tk_2;",
UpdatedCookieNames: []string{"_m_h5_tk"},
}}
acc.renewer = renewer
if !acc.tryAPIRenew(ctx) {
t.Fatal("接口续期成功应短路后续恢复")
}
if renewer.calls != 1 || renewer.got != "unb=123; _m_h5_tk=tk_1;" {
t.Fatalf("renewer 调用异常: calls=%d got=%q", renewer.calls, renewer.got)
}
if got := acc.currentCookieStr(); got != "unb=123; _m_h5_tk=tk_2;" {
t.Fatalf("内存 cookie 未更新: %q", got)
}
saved, _ := store.Cookies.GetValue(ctx, "cid")
if saved != "unb=123; _m_h5_tk=tk_2;" {
t.Fatalf("DB cookie 未更新: %q", saved)
}
if _, err := store.Tokens.Get(ctx, "cid"); err != db.ErrNotFound {
t.Fatalf("接口续期更新 cookie 后应清 token,got %v", err)
}
}
func TestTryAPIRenewPartialCookiesContinueRecovery(t *testing.T) {
acc, _, store, cleanup := newAccountForTest(t)
defer cleanup()
ctx := context.Background()
if err := store.Tokens.Save(ctx, "cid", "did-old", "tok-old", time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatalf("save token: %v", err)
}
renewer := &stubCookieRenewer{result: &xrenew.Result{
Success: false,
RenewMethod: "none",
NewCookies: "unb=123; _m_h5_tk=partial;",
UpdatedCookieNames: []string{"_m_h5_tk"},
Message: "setLoginSettings 未返回 Set-Cookie",
}}
acc.renewer = renewer
if acc.tryAPIRenew(ctx) {
t.Fatal("仅有部分 Cookie 更新时不应短路后续浏览器/密码恢复")
}
if got := acc.currentCookieStr(); got != "unb=123; _m_h5_tk=partial;" {
t.Fatalf("部分 cookie 应先保存到内存: %q", got)
}
saved, _ := store.Cookies.GetValue(ctx, "cid")
if saved != "unb=123; _m_h5_tk=partial;" {
t.Fatalf("部分 cookie 应先保存到 DB: %q", saved)
}
if _, err := store.Tokens.Get(ctx, "cid"); err != db.ErrNotFound {
t.Fatalf("部分 cookie 更新后也应清 token,got %v", err)
}
}
// TestSetRuntimeError_AllBranches 覆盖验证/captcha、token 失效、默认重连三分支
// 及告警去重逻辑(仅从非验证态进入验证态时告警一次)。
func TestSetRuntimeError_AllBranches(t *testing.T) {
+45
View File
@@ -0,0 +1,45 @@
package engine
import (
"crypto/rand"
"math/big"
"os"
"strconv"
"strings"
"time"
)
const tokenCacheTTLGranularity = time.Second
func tokenCacheTTL() time.Duration {
minTTL, minOK := tokenCacheTTLEnv("TOKEN_CACHE_TTL_MIN_HOURS", TokenCacheTTLMin)
maxTTL, maxOK := tokenCacheTTLEnv("TOKEN_CACHE_TTL_MAX_HOURS", TokenCacheTTLMax)
if !minOK || !maxOK || minTTL > maxTTL {
minTTL = TokenCacheTTLMin
maxTTL = TokenCacheTTLMax
}
if maxTTL == minTTL {
return minTTL
}
steps := int64((maxTTL - minTTL) / tokenCacheTTLGranularity)
if steps <= 0 {
return minTTL
}
n, err := rand.Int(rand.Reader, big.NewInt(steps+1))
if err != nil {
return minTTL
}
return minTTL + time.Duration(n.Int64())*tokenCacheTTLGranularity
}
func tokenCacheTTLEnv(key string, fallback time.Duration) (time.Duration, bool) {
raw := strings.TrimSpace(os.Getenv(key))
if raw == "" {
return fallback, true
}
hours, err := strconv.ParseFloat(raw, 64)
if err != nil || hours <= 0 {
return fallback, false
}
return time.Duration(hours * float64(time.Hour)), true
}
+41
View File
@@ -0,0 +1,41 @@
package engine
import (
"testing"
"time"
)
func TestTokenCacheTTLFixedEnv(t *testing.T) {
t.Setenv("TOKEN_CACHE_TTL_MIN_HOURS", "2")
t.Setenv("TOKEN_CACHE_TTL_MAX_HOURS", "2")
if got := tokenCacheTTL(); got != 2*time.Hour {
t.Fatalf("tokenCacheTTL=%s want 2h", got)
}
}
func TestTokenCacheTTLMaxBelowMinFallsBackToDefaultRange(t *testing.T) {
t.Setenv("TOKEN_CACHE_TTL_MIN_HOURS", "4")
t.Setenv("TOKEN_CACHE_TTL_MAX_HOURS", "2")
got := tokenCacheTTL()
if got < TokenCacheTTLMin || got > TokenCacheTTLMax {
t.Fatalf("tokenCacheTTL=%s want within [%s,%s]", got, TokenCacheTTLMin, TokenCacheTTLMax)
}
}
func TestTokenCacheTTLInvalidEnvFallsBackToDefaultRange(t *testing.T) {
t.Setenv("TOKEN_CACHE_TTL_MIN_HOURS", "bad")
t.Setenv("TOKEN_CACHE_TTL_MAX_HOURS", "also-bad")
got := tokenCacheTTL()
if got < TokenCacheTTLMin || got > TokenCacheTTLMax {
t.Fatalf("tokenCacheTTL=%s want within [%s,%s]", got, TokenCacheTTLMin, TokenCacheTTLMax)
}
}
func TestTokenCacheTTLPartiallyInvalidEnvFallsBackToDefaultRange(t *testing.T) {
t.Setenv("TOKEN_CACHE_TTL_MIN_HOURS", "2")
t.Setenv("TOKEN_CACHE_TTL_MAX_HOURS", "bad")
got := tokenCacheTTL()
if got < TokenCacheTTLMin || got > TokenCacheTTLMax {
t.Fatalf("tokenCacheTTL=%s want within [%s,%s]", got, TokenCacheTTLMin, TokenCacheTTLMax)
}
}
+95
View File
@@ -0,0 +1,95 @@
package renewal
import (
"sync"
"time"
)
// CooldownManager 保存登录恢复相关冷却状态。
// Scheduler 和运行时 Adapter 共用同一实例,避免同一账号被重复触发密码登录。
type CooldownManager struct {
mu sync.Mutex
sessionExpiredByCookie map[string]time.Time
passwordLoginByCookie map[string]time.Time
passwordErrorByCookie map[string]time.Time
}
// GlobalCooldown 是服务进程内的统一续期冷却状态。
var GlobalCooldown = NewCooldownManager()
func NewCooldownManager() *CooldownManager {
return &CooldownManager{
sessionExpiredByCookie: make(map[string]time.Time),
passwordLoginByCookie: make(map[string]time.Time),
passwordErrorByCookie: make(map[string]time.Time),
}
}
func (m *CooldownManager) MarkSessionExpired(cookieID string) {
if m == nil {
return
}
m.mu.Lock()
defer m.mu.Unlock()
m.sessionExpiredByCookie[cookieID] = time.Now()
}
func (m *CooldownManager) IsSessionCooled(cookieID string) (bool, time.Duration) {
if m == nil {
return false, 0
}
m.mu.Lock()
defer m.mu.Unlock()
last := m.sessionExpiredByCookie[cookieID]
if last.IsZero() {
return false, 0
}
remain := sessionExpiredCooldown - time.Since(last)
return remain > 0, remain
}
func (m *CooldownManager) TryPasswordLogin(cookieID string) (bool, time.Duration) {
if m == nil {
return true, 0
}
m.mu.Lock()
defer m.mu.Unlock()
now := time.Now()
last := m.passwordLoginByCookie[cookieID]
if !last.IsZero() {
remain := passwordLoginCooldown - now.Sub(last)
if remain > 0 {
return false, remain
}
}
lastErr := m.passwordErrorByCookie[cookieID]
if !lastErr.IsZero() {
remain := passwordErrorCooldown - now.Sub(lastErr)
if remain > 0 {
return false, remain
}
}
m.passwordLoginByCookie[cookieID] = now
return true, 0
}
func (m *CooldownManager) MarkPasswordError(cookieID string) {
if m == nil {
return
}
m.mu.Lock()
defer m.mu.Unlock()
m.passwordErrorByCookie[cookieID] = time.Now()
}
func (m *CooldownManager) Reset(cookieID string) {
if m == nil {
return
}
m.mu.Lock()
defer m.mu.Unlock()
delete(m.sessionExpiredByCookie, cookieID)
delete(m.passwordLoginByCookie, cookieID)
delete(m.passwordErrorByCookie, cookieID)
}
+513
View File
@@ -0,0 +1,513 @@
package renewal
import (
"context"
crand "crypto/rand"
"encoding/hex"
"fmt"
"log/slog"
"math/big"
"reflect"
"strconv"
"strings"
"time"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
apirenew "xianyu-go/internal/xianyu/renew"
)
const (
loginRenewInterval = 600 * time.Second
cookiesRefreshInterval = 600 * time.Second
apiCookieRenewInterval = 3600 * time.Second
accountRequestInterval = time.Second
browserInitialDelayMax = 30 * time.Second
browserSuccessDelayMin = 60 * time.Second
browserSuccessDelayRange = 240 * time.Second
disabledFailureLimit = 10
sessionExpiredCooldown = 300 * time.Second
passwordLoginCooldown = 300 * time.Second
passwordErrorCooldown = 5 * time.Hour
)
const (
loginRenewEnabledSetting = "renewal.login_renew.enabled"
loginRenewIntervalSetting = "renewal.login_renew.interval_seconds"
apiCookieRenewEnabledSetting = "renewal.api_cookie_renew.enabled"
apiCookieRenewIntervalSetting = "renewal.api_cookie_renew.interval_seconds"
cookiesRefreshEnabledSetting = "renewal.cookies_refresh.enabled"
cookiesRefreshIntervalSetting = "renewal.cookies_refresh.interval_seconds"
)
type AccountStarter interface {
Start(ctx context.Context, cookieID, cookieValue string) error
}
type BrowserRenewer interface {
BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error)
CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error)
}
type PasswordRefresher interface {
OnPasswordLoginRefresh(ctx context.Context, cookieID string) bool
}
type Scheduler struct {
store *db.Store
starter AccountStarter
browser BrowserRenewer
refresher PasswordRefresher
logger *slog.Logger
mtop *mtop.ClientImpl
api apirenew.Service
cooldown *CooldownManager
}
func NewScheduler(store *db.Store, starter AccountStarter, browser BrowserRenewer, refresher PasswordRefresher, logger *slog.Logger) *Scheduler {
if logger == nil {
logger = slog.Default()
}
return &Scheduler{
store: store,
starter: starter,
browser: browserRenewerOrNil(browser),
refresher: refresher,
logger: logger,
mtop: mtop.NewClient(),
api: apirenew.Service{},
cooldown: GlobalCooldown,
}
}
func browserRenewerOrNil(browser BrowserRenewer) BrowserRenewer {
if browser == nil {
return nil
}
v := reflect.ValueOf(browser)
switch v.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
if v.IsNil() {
return nil
}
}
return browser
}
func (s *Scheduler) Run(ctx context.Context) {
if s == nil || s.store == nil {
return
}
go s.runFixed(ctx, "login_renew", loginRenewEnabledSetting, loginRenewIntervalSetting, false, loginRenewInterval, s.executeLoginRenew)
go s.runFixed(ctx, "api_cookie_renew", apiCookieRenewEnabledSetting, apiCookieRenewIntervalSetting, true, apiCookieRenewInterval, s.executeAPICookieRenew)
go s.runFixed(ctx, "cookies_refresh", cookiesRefreshEnabledSetting, cookiesRefreshIntervalSetting, false, cookiesRefreshInterval, s.executeBrowserCookieRefresh)
}
func (s *Scheduler) runFixed(ctx context.Context, name, settingKey, intervalKey string, defaultEnabled bool, defaultInterval time.Duration, fn func(context.Context)) {
if s.settingEnabled(ctx, settingKey, defaultEnabled) {
fn(ctx)
}
for {
interval := s.settingInterval(ctx, intervalKey, defaultInterval)
timer := time.NewTimer(interval)
select {
case <-ctx.Done():
timer.Stop()
return
case <-timer.C:
}
if !s.settingEnabled(ctx, settingKey, defaultEnabled) {
continue
}
s.logger.Info("执行续期任务", "task", name)
fn(ctx)
}
}
func (s *Scheduler) executeLoginRenew(ctx context.Context) {
batchID := newBatchID()
accounts, err := s.store.Cookies.ActiveRenewalAccounts(ctx)
if err != nil {
s.logger.Warn("login_renew 加载账号失败", "err", err)
return
}
for i, account := range accounts {
if s.isSessionCooled(account.ID) {
s.logger.Info("login_renew session 冷却中,跳过", "account", account.ID)
continue
}
s.loginRenewOne(ctx, batchID, account)
if i < len(accounts)-1 {
_ = sleepCtx(ctx, accountRequestInterval)
}
}
}
func (s *Scheduler) loginRenewOne(ctx context.Context, batchID string, account db.RenewalAccount) {
runCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
res, err := s.mtop.CheckLoginStatusContext(runCtx, account.Value)
if err != nil {
s.addLoginLog(ctx, batchID, account.ID, "failed", err.Error(), nil)
s.logger.Warn("login_renew 失败", "account", account.ID, "err", err)
return
}
if res == nil {
s.addLoginLog(ctx, batchID, account.ID, "failed", "loginuser.get 未返回结果", nil)
return
}
updated := cookierefresh.ChangedCookieNames(account.Value, res.UpdatedCookies)
if res.UpdatedCookies != "" && res.UpdatedCookies != account.Value {
metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)
if err := s.store.Cookies.UpdateRenewalCookie(ctx, account.ID, res.UpdatedCookies, metadata, time.Now().Unix()); err != nil {
s.addLoginLog(ctx, batchID, account.ID, "failed", "保存 Cookie 失败: "+err.Error(), updated)
return
}
s.clearToken(ctx, account.ID)
}
s.addLoginLog(ctx, batchID, account.ID, res.Status, res.Message, updated)
if res.Status == mtop.LoginStatusSessionExpired || res.Status == mtop.LoginStatusTokenEmpty {
s.markSessionExpired(account.ID)
s.triggerPasswordLoginAsync(account.ID)
}
}
func (s *Scheduler) executeAPICookieRenew(ctx context.Context) {
batchID := newBatchID()
accounts, err := s.store.Cookies.ActiveRenewalAccounts(ctx)
if err != nil {
s.logger.Warn("api_cookie_renew 加载账号失败", "err", err)
return
}
for i, account := range accounts {
s.apiCookieRenewOne(ctx, batchID, account)
if i < len(accounts)-1 {
_ = sleepCtx(ctx, accountRequestInterval)
}
}
}
func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, account db.RenewalAccount) {
res, err := s.renewAPI(ctx, account.Value)
if err != nil {
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: err.Error()})
s.logger.Warn("api_cookie_renew 失败", "account", account.ID, "err", err)
return
}
if res == nil {
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "接口续期未返回结果"})
return
}
if res.Success {
updated := cookierefresh.ChangedCookieNames(account.Value, res.NewCookies)
if res.NewCookies != "" && res.NewCookies != account.Value {
if !s.saveRenewedCookies(ctx, account.ID, res.NewCookies, cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)) {
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "保存 Cookie 失败", UpdatedCookieNames: updated})
return
}
}
status := "success"
if len(updated) > 0 {
status = "cookie_updated"
}
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: status, Message: res.Message, UpdatedCookieNames: updated, ResponseContent: res.ResponseText})
return
}
if res.NewCookies != "" && res.NewCookies != account.Value {
updated := cookierefresh.ChangedCookieNames(account.Value, res.NewCookies)
if !s.saveRenewedCookies(ctx, account.ID, res.NewCookies, cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)) {
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "保存部分 Cookie 失败", UpdatedCookieNames: updated})
return
}
s.logger.Info("api_cookie_renew 保留接口返回的部分 Cookie 更新", "account", account.ID, "updated", strings.Join(updated, ","))
}
browserInput := firstNonEmpty(res.NewCookies, account.Value)
var browserCookies string
var browserErr error
if s.browser != nil {
bctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
browserCookies, browserErr = s.browser.BrowserQuickRenew(bctx, account.ID, browserInput, !account.ShowBrowser)
cancel()
} else {
browserErr = fmt.Errorf("浏览器自动化未启用")
}
if browserErr == nil && browserCookies != "" {
verify, verifyErr := s.renewAPI(ctx, browserCookies)
if verifyErr == nil && verify != nil && verify.Success {
finalCookies := firstNonEmpty(verify.NewCookies, browserCookies)
updated := cookierefresh.ChangedCookieNames(account.Value, finalCookies)
if finalCookies != account.Value {
if !s.saveRenewedCookies(ctx, account.ID, finalCookies, cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)) {
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "保存 Cookie 失败", UpdatedCookieNames: updated})
return
}
}
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "browser_renewed", Message: "接口续期失败,浏览器续期成功,setLoginSettings验证通过", UpdatedCookieNames: updated, ResponseContent: verify.ResponseText})
return
}
updated := cookierefresh.ChangedCookieNames(account.Value, browserCookies)
if len(updated) > 0 {
_ = s.saveRenewedCookies(ctx, account.ID, browserCookies, cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON))
}
res.Message = "接口续期和浏览器续期均失败,需要账号密码登录"
}
s.markSessionExpired(account.ID)
s.triggerPasswordLoginAsync(account.ID)
msg := res.Message
if browserErr != nil {
msg = msg + ";浏览器续期失败: " + browserErr.Error()
}
updated := cookierefresh.ChangedCookieNames(account.Value, firstNonEmpty(browserCookies, res.NewCookies))
s.addAPILog(ctx, db.RenewalLog{
BatchID: batchID,
CookieID: account.ID,
Status: "need_password_login",
ErrorMessage: msg,
UpdatedCookieNames: updated,
ResponseContent: res.ResponseText,
})
}
func (s *Scheduler) executeBrowserCookieRefresh(ctx context.Context) {
batchID := newBatchID()
accounts, err := s.store.Cookies.AllRenewalAccounts(ctx)
if err != nil {
s.logger.Warn("cookies_refresh 加载账号失败", "err", err)
return
}
now := time.Now().Unix()
for _, account := range accounts {
if !account.Enabled && s.disabledAccountShouldSkip(ctx, account.ID) {
continue
}
schedule, err := s.store.Renewal.GetCookieRefreshSchedule(ctx, account.ID)
if err != nil {
expireAt := now + int64(randomDuration(browserInitialDelayMax).Seconds())
schedule = &db.CookieRefreshSchedule{CookieID: account.ID, ExpireAt: expireAt, LastStatus: "initialized"}
_ = s.store.Renewal.UpsertCookieRefreshSchedule(ctx, *schedule)
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{
BatchID: batchID,
CookieID: account.ID,
Status: "initialized",
Message: "首次初始化续期时间",
NextExpireAt: expireAt,
})
continue
}
if schedule.Disabled || schedule.ExpireAt > now {
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{
BatchID: batchID,
CookieID: account.ID,
Status: "success",
Message: fmt.Sprintf("未到期,跳过,剩余 %d 秒", schedule.ExpireAt-now),
NextExpireAt: schedule.ExpireAt,
})
continue
}
s.browserCookieRefreshOne(ctx, batchID, account, *schedule)
}
}
func (s *Scheduler) browserCookieRefreshOne(ctx context.Context, batchID string, account db.RenewalAccount, schedule db.CookieRefreshSchedule) {
if s.browser == nil {
schedule.LastStatus = "failed"
schedule.LastErrorMessage = "浏览器自动化未启用"
_ = s.store.Renewal.UpsertCookieRefreshSchedule(ctx, schedule)
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: schedule.LastErrorMessage})
return
}
runCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
oldSnapshot := cookierefresh.SnapshotFromMetadata(account.MetadataJSON)
newCookies, newSnapshot, err := s.browser.CookiesRefreshSnapshot(runCtx, account.ID, account.Value, oldSnapshot, !account.ShowBrowser)
if err != nil {
schedule.ConsecutiveFailures++
schedule.LastStatus = "failed"
schedule.LastError = err.Error()
schedule.LastErrorMessage = err.Error()
_ = s.store.Renewal.UpsertCookieRefreshSchedule(ctx, schedule)
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: err.Error(), NextExpireAt: schedule.ExpireAt})
s.logger.Warn("cookies_refresh 失败", "account", account.ID, "err", err)
return
}
metadata := cookierefresh.MetadataWithSnapshot(account.MetadataJSON, newSnapshot)
updated := cookierefresh.ChangedSnapshotLabels(oldSnapshot, newSnapshot)
if err := s.store.Cookies.UpdateRenewalCookie(ctx, account.ID, newCookies, metadata, time.Now().Unix()); err != nil {
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "保存 Cookie 失败: " + err.Error(), UpdatedCookieNames: updated})
return
}
s.clearToken(ctx, account.ID)
if !account.Enabled {
if err := s.store.Cookies.SetStatusWithReason(ctx, account.ID, true, ""); err != nil {
s.logger.Warn("cookies_refresh 自动启用账号失败", "account", account.ID, "err", err)
} else if s.starter != nil {
if err := s.starter.Start(ctx, account.ID, newCookies); err != nil {
s.logger.Warn("cookies_refresh 启动账号失败", "account", account.ID, "err", err)
}
}
}
nextExpire := time.Now().Add(browserSuccessDelay()).Unix()
schedule.Disabled = false
schedule.ConsecutiveFailures = 0
schedule.LastError = ""
schedule.LastStatus = "success"
schedule.LastErrorMessage = ""
schedule.LastRefreshAt = time.Now().Unix()
schedule.ExpireAt = nextExpire
_ = s.store.Renewal.UpsertCookieRefreshSchedule(ctx, schedule)
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{
BatchID: batchID,
CookieID: account.ID,
Status: "success",
Message: fmt.Sprintf("页面校验通过,全量获取到 %d 个浏览器Cookie", len(newSnapshot)),
UpdatedCookieNames: updated,
NextExpireAt: nextExpire,
})
}
func (s *Scheduler) renewAPI(ctx context.Context, cookieStr string) (*apirenew.Result, error) {
runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
defer cancel()
return s.api.RenewAPIFirst(runCtx, cookieStr)
}
func (s *Scheduler) saveRenewedCookies(ctx context.Context, cookieID, cookieStr, metadata string) bool {
if err := s.store.Cookies.UpdateRenewalCookie(ctx, cookieID, cookieStr, metadata, time.Now().Unix()); err != nil {
s.logger.Warn("保存续期 Cookie 失败", "account", cookieID, "err", err)
return false
}
s.clearToken(ctx, cookieID)
return true
}
func (s *Scheduler) addLoginLog(ctx context.Context, batchID, cookieID, status, message string, updated []string) {
_ = s.store.Renewal.AddLoginRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: cookieID, Status: status, Message: message, UpdatedCookieNames: updated})
}
func (s *Scheduler) addAPILog(ctx context.Context, log db.RenewalLog) {
_ = s.store.Renewal.AddAPICookieRenewLog(ctx, log)
}
func (s *Scheduler) markSessionExpired(cookieID string) {
s.cooldown.MarkSessionExpired(cookieID)
}
func (s *Scheduler) isSessionCooled(cookieID string) bool {
ok, _ := s.cooldown.IsSessionCooled(cookieID)
return ok
}
func (s *Scheduler) triggerPasswordLoginAsync(cookieID string) {
if s.refresher == nil {
return
}
go s.refresher.OnPasswordLoginRefresh(context.Background(), cookieID)
}
func (s *Scheduler) disabledAccountShouldSkip(ctx context.Context, cookieID string) bool {
statuses, err := s.store.Renewal.RecentBrowserCookieRenewStatuses(ctx, cookieID, disabledFailureLimit)
if err != nil || len(statuses) < disabledFailureLimit {
return false
}
for _, status := range statuses {
if status != "failed" {
return false
}
}
return true
}
func (s *Scheduler) settingEnabled(ctx context.Context, key string, defaultEnabled bool) bool {
if s.store == nil || s.store.Settings == nil {
return defaultEnabled
}
value, err := s.store.Settings.Get(ctx, key)
if err != nil || strings.TrimSpace(value) == "" {
return defaultEnabled
}
switch strings.ToLower(strings.TrimSpace(value)) {
case "1", "true", "yes", "on", "enabled":
return true
case "0", "false", "no", "off", "disabled":
return false
default:
return defaultEnabled
}
}
func (s *Scheduler) settingInterval(ctx context.Context, key string, defaultInterval time.Duration) time.Duration {
if s.store == nil || s.store.Settings == nil {
return defaultInterval
}
value, err := s.store.Settings.Get(ctx, key)
if err != nil || strings.TrimSpace(value) == "" {
return defaultInterval
}
value = strings.TrimSpace(value)
if seconds, err := strconv.ParseFloat(value, 64); err == nil && seconds > 0 {
return time.Duration(seconds * float64(time.Second))
}
if d, err := time.ParseDuration(value); err == nil && d > 0 {
return d
}
return defaultInterval
}
func (s *Scheduler) clearToken(ctx context.Context, cookieID string) {
if s.store.Tokens == nil {
return
}
if err := s.store.Tokens.Clear(ctx, cookieID); err != nil {
s.logger.Warn("续期后清除 token 缓存失败", "account", cookieID, "err", err)
}
}
func browserSuccessDelay() time.Duration {
return browserSuccessDelayMin + randomDuration(browserSuccessDelayRange)
}
func randomDuration(max time.Duration) time.Duration {
if max <= 0 {
return 0
}
n, err := crand.Int(crand.Reader, big.NewInt(int64(max)))
if err != nil {
return 0
}
return time.Duration(n.Int64())
}
func newBatchID() string {
var b [16]byte
if _, err := crand.Read(b[:]); err != nil {
return fmt.Sprintf("%d", time.Now().UnixNano())
}
return hex.EncodeToString(b[:])
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return value
}
}
return ""
}
func sleepCtx(ctx context.Context, d time.Duration) error {
if d <= 0 {
return nil
}
timer := time.NewTimer(d)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}
+383
View File
@@ -0,0 +1,383 @@
package renewal
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
apirenew "xianyu-go/internal/xianyu/renew"
)
func newSchedulerTestStore(t *testing.T) (*db.Store, func()) {
t.Helper()
d, _, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "renewal.db"))
if err != nil {
t.Fatalf("Open: %v", err)
}
return db.NewStore(d, db.DialectSQLite), func() { d.Close() }
}
type schedulerFakeBrowser struct {
quickCookies string
quickErr error
quickCalls int
quickInputs []string
}
func (f *schedulerFakeBrowser) BrowserQuickRenew(_ context.Context, _ string, cookieStr string, _ bool) (string, error) {
f.quickCalls++
f.quickInputs = append(f.quickInputs, cookieStr)
return f.quickCookies, f.quickErr
}
func (f *schedulerFakeBrowser) CookiesRefreshSnapshot(_ context.Context, _, _ string, _ []cookierefresh.BrowserCookie, _ bool) (string, []cookierefresh.BrowserCookie, error) {
return "", nil, errors.New("not implemented")
}
type schedulerFakePasswordRefresher struct {
calls atomic.Int32
ch chan string
}
func (f *schedulerFakePasswordRefresher) OnPasswordLoginRefresh(_ context.Context, cookieID string) bool {
f.calls.Add(1)
if f.ch != nil {
select {
case f.ch <- cookieID:
default:
}
}
return true
}
func (f *schedulerFakePasswordRefresher) waitCookie(t *testing.T, want string) {
t.Helper()
select {
case got := <-f.ch:
if got != want {
t.Fatalf("password refresher cookieID=%q want %q", got, want)
}
case <-time.After(time.Second):
t.Fatalf("password refresher 未触发")
}
}
type apiRenewLogSnapshot struct {
status string
message string
errorMessage string
updatedCookieNames string
responseContent string
}
func createSchedulerAccount(t *testing.T, store *db.Store, cookieID, cookieValue string) db.RenewalAccount {
t.Helper()
ctx := context.Background()
username := "user_" + strings.ReplaceAll(cookieID, "-", "_")
if ok, err := store.Users.Create(ctx, username, username+"@example.com", "pw"); err != nil || !ok {
t.Fatalf("Create user: ok=%v err=%v", ok, err)
}
user, err := store.Users.GetByUsername(ctx, username)
if err != nil {
t.Fatalf("GetByUsername: %v", err)
}
if err := store.Cookies.Save(ctx, cookieID, cookieValue, user.ID); err != nil {
t.Fatalf("Save cookie: %v", err)
}
return db.RenewalAccount{ID: cookieID, Value: cookieValue, UserID: user.ID, Enabled: true}
}
func lastAPIRenewLog(t *testing.T, store *db.Store, cookieID string) apiRenewLogSnapshot {
t.Helper()
var log apiRenewLogSnapshot
err := store.DB.QueryRowContext(context.Background(),
`SELECT status, COALESCE(message,''), COALESCE(error_message,''), COALESCE(updated_cookie_names,''), COALESCE(response_content,'')
FROM scheduled_api_cookie_renew_log
WHERE cookie_id=?
ORDER BY id DESC LIMIT 1`, cookieID).
Scan(&log.status, &log.message, &log.errorMessage, &log.updatedCookieNames, &log.responseContent)
if err != nil {
t.Fatalf("query api renew log: %v", err)
}
return log
}
func schedulerRenewServiceFromServer(srv *httptest.Server) apirenew.Service {
return apirenew.Service{
HTTPClient: srv.Client(),
HasLoginURL: srv.URL + "/hasLogin.do",
SilentHasLoginURL: srv.URL + "/silentHasLogin.do",
SetLoginSettingsURL: srv.URL + "/setLoginSettings.do",
RetryDelay: -1,
}
}
func TestSchedulerIntervalsAligned(t *testing.T) {
if loginRenewInterval != 10*time.Minute {
t.Fatalf("loginRenewInterval=%s want 10m", loginRenewInterval)
}
if cookiesRefreshInterval != 10*time.Minute {
t.Fatalf("cookiesRefreshInterval=%s want 10m", cookiesRefreshInterval)
}
if apiCookieRenewInterval != time.Hour {
t.Fatalf("apiCookieRenewInterval=%s want 1h", apiCookieRenewInterval)
}
}
func TestSchedulerDefaultsMatchUpstreamConfig(t *testing.T) {
store, cleanup := newSchedulerTestStore(t)
defer cleanup()
ctx := context.Background()
s := NewScheduler(store, nil, nil, nil, nil)
if s.settingEnabled(ctx, loginRenewEnabledSetting, false) {
t.Fatal("login_renew 未配置时应默认关闭")
}
if s.settingEnabled(ctx, cookiesRefreshEnabledSetting, false) {
t.Fatal("cookies_refresh 未配置时应默认关闭")
}
if !s.settingEnabled(ctx, apiCookieRenewEnabledSetting, true) {
t.Fatal("api_cookie_renew 未配置时应默认开启")
}
}
func TestNewSchedulerTreatsTypedNilBrowserAsDisabled(t *testing.T) {
store, cleanup := newSchedulerTestStore(t)
defer cleanup()
ctx := context.Background()
account := createSchedulerAccount(t, store, "cid-typed-nil-browser", "unb=1; cookie2=c2")
refresher := &schedulerFakePasswordRefresher{ch: make(chan string, 1)}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/hasLogin.do", "/silentHasLogin.do", "/setLoginSettings.do":
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
var typedNilBrowser *schedulerFakeBrowser
s := NewScheduler(store, nil, typedNilBrowser, refresher, nil)
if s.browser != nil {
t.Fatal("typed nil BrowserRenewer 应被规范化为 nil")
}
s.api = schedulerRenewServiceFromServer(srv)
s.cooldown = NewCooldownManager()
s.apiCookieRenewOne(ctx, "batch-typed-nil-browser", account)
refresher.waitCookie(t, "cid-typed-nil-browser")
log := lastAPIRenewLog(t, store, "cid-typed-nil-browser")
if log.status != "need_password_login" || !strings.Contains(log.errorMessage, "浏览器自动化未启用") {
t.Fatalf("typed nil browser 应按浏览器禁用处理: %+v", log)
}
}
func TestSchedulerSettingEnabledOverrides(t *testing.T) {
store, cleanup := newSchedulerTestStore(t)
defer cleanup()
ctx := context.Background()
s := NewScheduler(store, nil, nil, nil, nil)
if err := store.Settings.Set(ctx, loginRenewEnabledSetting, "enabled"); err != nil {
t.Fatalf("Set enabled: %v", err)
}
if !s.settingEnabled(ctx, loginRenewEnabledSetting, false) {
t.Fatal("enabled 应开启任务")
}
if err := store.Settings.Set(ctx, loginRenewEnabledSetting, "off"); err != nil {
t.Fatalf("Set off: %v", err)
}
if s.settingEnabled(ctx, loginRenewEnabledSetting, true) {
t.Fatal("off 应关闭任务")
}
}
func TestSchedulerSettingIntervalOverrides(t *testing.T) {
store, cleanup := newSchedulerTestStore(t)
defer cleanup()
ctx := context.Background()
s := NewScheduler(store, nil, nil, nil, nil)
if got := s.settingInterval(ctx, loginRenewIntervalSetting, loginRenewInterval); got != loginRenewInterval {
t.Fatalf("未配置间隔应返回默认值: %s", got)
}
if err := store.Settings.Set(ctx, loginRenewIntervalSetting, "30"); err != nil {
t.Fatalf("Set seconds: %v", err)
}
if got := s.settingInterval(ctx, loginRenewIntervalSetting, loginRenewInterval); got != 30*time.Second {
t.Fatalf("秒数间隔=%s want 30s", got)
}
if err := store.Settings.Set(ctx, loginRenewIntervalSetting, "2m"); err != nil {
t.Fatalf("Set duration: %v", err)
}
if got := s.settingInterval(ctx, loginRenewIntervalSetting, loginRenewInterval); got != 2*time.Minute {
t.Fatalf("duration 间隔=%s want 2m", got)
}
if err := store.Settings.Set(ctx, loginRenewIntervalSetting, "-1"); err != nil {
t.Fatalf("Set invalid: %v", err)
}
if got := s.settingInterval(ctx, loginRenewIntervalSetting, loginRenewInterval); got != loginRenewInterval {
t.Fatalf("非法间隔应回退默认值: %s", got)
}
}
func TestAPICookieRenewOneSavesPartialCookiesBeforePasswordLogin(t *testing.T) {
store, cleanup := newSchedulerTestStore(t)
defer cleanup()
ctx := context.Background()
account := createSchedulerAccount(t, store, "cid-partial", "unb=1; cookie2=c2")
refresher := &schedulerFakePasswordRefresher{ch: make(chan string, 1)}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/hasLogin.do":
http.SetCookie(w, &http.Cookie{Name: "sgcookie", Value: "s1"})
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
case "/silentHasLogin.do":
http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "tk_1"})
_, _ = w.Write([]byte(`{"content":{"success":true},"marker":"silent-partial"}`))
case "/setLoginSettings.do":
_, _ = w.Write([]byte(`{"content":{"success":false}}`))
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
s := NewScheduler(store, nil, nil, refresher, nil)
s.api = schedulerRenewServiceFromServer(srv)
s.cooldown = NewCooldownManager()
s.apiCookieRenewOne(ctx, "batch-partial", account)
refresher.waitCookie(t, "cid-partial")
got, err := store.Cookies.GetValue(ctx, "cid-partial")
if err != nil {
t.Fatalf("GetValue: %v", err)
}
for _, want := range []string{"sgcookie=s1", "_m_h5_tk=tk_1"} {
if !strings.Contains(got, want) {
t.Fatalf("部分 Cookie 未保存,缺少 %s: %q", want, got)
}
}
log := lastAPIRenewLog(t, store, "cid-partial")
if log.status != "need_password_login" {
t.Fatalf("status=%q want need_password_login, log=%+v", log.status, log)
}
if !strings.Contains(log.updatedCookieNames, "sgcookie") || !strings.Contains(log.updatedCookieNames, "_m_h5_tk") {
t.Fatalf("updated_cookie_names 未记录部分更新: %+v", log)
}
if !strings.Contains(log.responseContent, "silent-partial") {
t.Fatalf("response_content 应记录 silentHasLogin 响应: %+v", log)
}
}
func TestAPICookieRenewOneSavesBrowserCookiesWhenVerifyFails(t *testing.T) {
store, cleanup := newSchedulerTestStore(t)
defer cleanup()
ctx := context.Background()
account := createSchedulerAccount(t, store, "cid-browser-fail", "unb=1; cookie2=c2")
browser := &schedulerFakeBrowser{quickCookies: "unb=1; cookie2=c2; sgcookie=s1; _m_h5_tk=tk_1; browser=b1"}
refresher := &schedulerFakePasswordRefresher{ch: make(chan string, 1)}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/hasLogin.do":
http.SetCookie(w, &http.Cookie{Name: "sgcookie", Value: "s1"})
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
case "/silentHasLogin.do":
http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "tk_1"})
_, _ = w.Write([]byte(`{"content":{"success":true},"marker":"silent-browser-fail"}`))
case "/setLoginSettings.do":
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
s := NewScheduler(store, nil, browser, refresher, nil)
s.api = schedulerRenewServiceFromServer(srv)
s.cooldown = NewCooldownManager()
s.apiCookieRenewOne(ctx, "batch-browser-fail", account)
refresher.waitCookie(t, "cid-browser-fail")
if browser.quickCalls != 1 {
t.Fatalf("BrowserQuickRenew calls=%d want 1", browser.quickCalls)
}
if len(browser.quickInputs) != 1 || !strings.Contains(browser.quickInputs[0], "sgcookie=s1") || !strings.Contains(browser.quickInputs[0], "_m_h5_tk=tk_1") {
t.Fatalf("浏览器续期输入未使用接口部分更新: %#v", browser.quickInputs)
}
got, err := store.Cookies.GetValue(ctx, "cid-browser-fail")
if err != nil {
t.Fatalf("GetValue: %v", err)
}
for _, want := range []string{"sgcookie=s1", "_m_h5_tk=tk_1", "browser=b1"} {
if !strings.Contains(got, want) {
t.Fatalf("浏览器 Cookie 未保存,缺少 %s: %q", want, got)
}
}
log := lastAPIRenewLog(t, store, "cid-browser-fail")
if log.status != "need_password_login" {
t.Fatalf("status=%q want need_password_login, log=%+v", log.status, log)
}
if !strings.Contains(log.updatedCookieNames, "browser") {
t.Fatalf("updated_cookie_names 未记录浏览器更新: %+v", log)
}
}
func TestAPICookieRenewOneBrowserRenewedAfterVerifySuccess(t *testing.T) {
store, cleanup := newSchedulerTestStore(t)
defer cleanup()
ctx := context.Background()
account := createSchedulerAccount(t, store, "cid-browser-ok", "unb=1; cookie2=c2")
browser := &schedulerFakeBrowser{quickCookies: "unb=1; cookie2=c2; browser=b1"}
var setLoginCalls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/hasLogin.do":
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
case "/silentHasLogin.do":
_, _ = w.Write([]byte(`{"content":{"success":true},"marker":"silent-browser-ok"}`))
case "/setLoginSettings.do":
if setLoginCalls.Add(1) == 2 {
http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "lgc"})
}
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
s := NewScheduler(store, nil, browser, nil, nil)
s.api = schedulerRenewServiceFromServer(srv)
s.cooldown = NewCooldownManager()
s.apiCookieRenewOne(ctx, "batch-browser-ok", account)
if browser.quickCalls != 1 || setLoginCalls.Load() != 2 {
t.Fatalf("browser calls=%d setLoginCalls=%d", browser.quickCalls, setLoginCalls.Load())
}
got, err := store.Cookies.GetValue(ctx, "cid-browser-ok")
if err != nil {
t.Fatalf("GetValue: %v", err)
}
for _, want := range []string{"browser=b1", "havana_lgc2_77=lgc"} {
if !strings.Contains(got, want) {
t.Fatalf("最终 Cookie 缺少 %s: %q", want, got)
}
}
log := lastAPIRenewLog(t, store, "cid-browser-ok")
if log.status != "browser_renewed" {
t.Fatalf("status=%q want browser_renewed, log=%+v", log.status, log)
}
if !strings.Contains(log.responseContent, "silent-browser-ok") {
t.Fatalf("response_content 应记录验证阶段 silentHasLogin 响应: %+v", log)
}
}
+23 -11
View File
@@ -96,9 +96,12 @@ func (s *Server) listCookieDetails(w http.ResponseWriter, r *http.Request) {
"auto_confirm": d.AutoConfirm,
"remark": d.Remark,
"pause_duration": d.PauseDuration,
"show_browser": d.ShowBrowser,
"username": d.Username,
"nickname": cachedAccountNickname(d),
"avatar_url": d.AvatarURL,
"login_method": d.LoginMethod,
"last_login_at": d.LastLoginAt,
"profile_error": "",
"ai_enabled": false,
})
@@ -130,6 +133,8 @@ func (s *Server) getCookieDetails(w http.ResponseWriter, r *http.Request) {
"username": d.Username,
"nickname": cachedAccountNickname(d),
"avatar_url": d.AvatarURL,
"login_method": d.LoginMethod,
"last_login_at": d.LastLoginAt,
"profile_error": "",
"has_cookie": true,
})
@@ -162,8 +167,9 @@ func (s *Server) refreshCookieProfile(w http.ResponseWriter, r *http.Request) {
// addCookie 添加账号 cookie。
func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
var req struct {
ID string `json:"id"`
Value string `json:"value"`
ID string `json:"id"`
Value string `json:"value"`
LoginMethod string `json:"login_method"`
}
if err := decodeJSON(r, &req); err != nil || req.ID == "" || req.Value == "" {
writeErr(w, http.StatusBadRequest, "缺少 id 或 value")
@@ -181,6 +187,11 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
if d, err := s.Store.Cookies.GetDetails(r.Context(), req.ID); err == nil {
s.refreshAccountProfile(r.Context(), d)
}
loginMethod := normalizeLoginMethod(req.LoginMethod)
if loginMethod == "" {
loginMethod = loginMethodManual
}
s.markSuccessfulLogin(r.Context(), req.ID, sess.UserID, loginMethod, "账号登录成功")
if s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), req.ID) {
if err := s.Manager.Restart(r.Context(), req.ID); err != nil {
s.Logger.Error("更新后重启账号失败", "cookie_id", req.ID, "err", err)
@@ -196,7 +207,8 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
return
}
var req struct {
Value string `json:"value"`
Value string `json:"value"`
LoginMethod string `json:"login_method"`
}
if err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
@@ -214,6 +226,9 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
if d, err := s.Store.Cookies.GetDetails(r.Context(), cid); err == nil {
s.refreshAccountProfile(r.Context(), d)
}
if loginMethod := normalizeLoginMethod(req.LoginMethod); loginMethod != "" {
s.markSuccessfulLogin(r.Context(), cid, sess.UserID, loginMethod, "账号登录成功")
}
if s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), cid) {
if err := s.Manager.Restart(r.Context(), cid); err != nil {
s.Logger.Error("更新后重启账号失败", "cookie_id", cid, "err", err)
@@ -225,7 +240,8 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
// updateCookieLoginInfo 更新账号登录信息(用户名/密码/显示浏览器)。
func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
detail, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
var req struct {
@@ -242,14 +258,10 @@ func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
if password == "" {
password = req.LoginPassword
}
sb := 0
if req.ShowBrowser {
sb = 1
if password == "" && detail != nil {
password = detail.Password
}
_, err := s.Store.DB.ExecContext(r.Context(),
`UPDATE cookies SET username=?, password=?, show_browser=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`,
req.Username, password, sb, cid)
if err != nil {
if err := s.Store.Cookies.UpdateLoginInfo(r.Context(), cid, req.Username, password, req.ShowBrowser); err != nil {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
+133 -6
View File
@@ -93,6 +93,35 @@ func TestGetCookieDetails(t *testing.T) {
}
}
func TestListCookieDetailsIncludesShowBrowser(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
ctx := context.Background()
if err := store.Cookies.UpdateLoginInfo(ctx, "acc1", "login-user", "secret", true); err != nil {
t.Fatalf("UpdateLoginInfo: %v", err)
}
h := srv.Router()
cookie := loginHelper(t, h)
req := httptest.NewRequest(http.MethodGet, "/cookies/details", nil)
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
var details []map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &details); err != nil {
t.Fatalf("decode details: %v", err)
}
if len(details) != 1 || details[0]["show_browser"] != true {
t.Fatalf("账号列表应返回 show_browser=true: %+v", details)
}
if _, ok := details[0]["login_password"]; ok {
t.Fatalf("账号列表不应返回登录密码: %+v", details[0])
}
}
// TestGetCookieDetailsBadCookie 无权账号 403。
func TestGetCookieDetailsBadCookie(t *testing.T) {
srv, _, cleanup := newTestServer(t)
@@ -111,8 +140,9 @@ func TestGetCookieDetailsBadCookie(t *testing.T) {
// TestUpdateCookie 更新 cookie 值。
func TestUpdateCookie(t *testing.T) {
srv, _, cleanup := newTestServer(t)
srv, store, cleanup := newTestServer(t)
defer cleanup()
ctx := context.Background()
h := srv.Router()
cookie := loginHelper(t, h)
@@ -124,6 +154,50 @@ func TestUpdateCookie(t *testing.T) {
if rec.Code != 200 {
t.Fatalf("update status=%d body=%s", rec.Code, rec.Body.String())
}
d, err := store.Cookies.GetDetails(ctx, "acc1")
if err != nil {
t.Fatalf("GetDetails: %v", err)
}
if d.LoginMethod != "" || d.LastLoginAt != 0 {
t.Fatalf("普通 Cookie 更新不应刷新登录审计字段: method=%q last=%d", d.LoginMethod, d.LastLoginAt)
}
}
func TestUpdateCookieQRLoginEnablesAccount(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
ctx := context.Background()
if err := store.Cookies.SetStatusWithReason(ctx, "acc1", false, "token 失效"); err != nil {
t.Fatalf("SetStatusWithReason: %v", err)
}
h := srv.Router()
cookie := loginHelper(t, h)
body := `{"value":"unb=123; _m_h5_tk=qr_2;","login_method":"qr_scan"}`
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("update status=%d body=%s", rec.Code, rec.Body.String())
}
if !store.Cookies.GetStatus(ctx, "acc1") {
t.Fatal("扫码登录成功后应重新启用账号")
}
var reason string
if err := store.DB.QueryRowContext(ctx, `SELECT disable_reason FROM cookie_status WHERE cookie_id='acc1'`).Scan(&reason); err != nil {
t.Fatalf("query disable_reason: %v", err)
}
if reason != "" {
t.Fatalf("扫码登录成功后应清空禁用原因,got %q", reason)
}
d, err := store.Cookies.GetDetails(ctx, "acc1")
if err != nil {
t.Fatalf("GetDetails: %v", err)
}
if d.LoginMethod != "qr_scan" || d.LastLoginAt == 0 {
t.Fatalf("扫码登录应刷新登录审计字段: %+v", d)
}
}
// TestUpdateCookieBadJSON 非法 JSON 400。
@@ -144,8 +218,9 @@ func TestUpdateCookieBadJSON(t *testing.T) {
// TestUpdateCookieLoginInfo 更新登录信息。
func TestUpdateCookieLoginInfo(t *testing.T) {
srv, _, cleanup := newTestServer(t)
srv, store, cleanup := newTestServer(t)
defer cleanup()
ctx := context.Background()
h := srv.Router()
cookie := loginHelper(t, h)
@@ -157,6 +232,29 @@ func TestUpdateCookieLoginInfo(t *testing.T) {
if rec.Code != 200 {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
d, err := store.Cookies.GetDetails(ctx, "acc1")
if err != nil {
t.Fatalf("GetDetails: %v", err)
}
if d.Username != "u1" || d.Password != "p1" || !d.ShowBrowser {
t.Fatalf("登录信息未正确保存: %+v", d)
}
body = `{"username":"u2","login_password":"","show_browser":false}`
req = httptest.NewRequest(http.MethodPut, "/cookies/acc1/login-info", strings.NewReader(body))
req.AddCookie(cookie)
rec = httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
d, err = store.Cookies.GetDetails(ctx, "acc1")
if err != nil {
t.Fatalf("GetDetails after empty password: %v", err)
}
if d.Username != "u2" || d.Password != "p1" || d.ShowBrowser {
t.Fatalf("空密码更新应保留原密码并更新其他字段: %+v", d)
}
}
// TestUpdateCookieLoginInfoBadJSON 非法 JSON 400。
@@ -295,6 +393,35 @@ func TestAddCookieBad(t *testing.T) {
}
}
func TestAddCookieDefaultsManualLoginAudit(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
ctx := context.Background()
h := srv.Router()
cookie := loginHelper(t, h)
body := `{"id":"acc-manual","value":"unb=456; _m_h5_tk=manual_1;"}`
req := httptest.NewRequest(http.MethodPost, "/cookies", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("add status=%d body=%s", rec.Code, rec.Body.String())
}
d, err := store.Cookies.GetDetails(ctx, "acc-manual")
if err != nil {
t.Fatalf("GetDetails: %v", err)
}
if d.LoginMethod != "manual" || d.LastLoginAt == 0 {
t.Fatalf("手动新增 Cookie 应记录 manual 登录审计字段: %+v", d)
}
logs, err := store.LoginLogs.ListByCookie(ctx, "acc-manual", 10)
if err != nil || len(logs) != 1 || logs[0].Method != "manual" || logs[0].TriggerReason != "手动Cookie录入" {
t.Fatalf("手动新增 Cookie 应记录登录日志: logs=%#v err=%v", logs, err)
}
}
// TestAddCookieBadJSON 非法 JSON 400。
func TestAddCookieBadJSON(t *testing.T) {
srv, _, cleanup := newTestServer(t)
@@ -347,10 +474,10 @@ func TestCachedAccountNickname(t *testing.T) {
// TestNormalizeProfileAvatarURL 头像 URL 归一。
func TestNormalizeProfileAvatarURL(t *testing.T) {
cases := map[string]string{
"": "",
"//img.alicdn.com/x.jpg": "https://img.alicdn.com/x.jpg",
"http://img.alicdn.com/x.jpg": "https://img.alicdn.com/x.jpg",
"https://img.alicdn.com/x.jpg": "https://img.alicdn.com/x.jpg",
"": "",
"//img.alicdn.com/x.jpg": "https://img.alicdn.com/x.jpg",
"http://img.alicdn.com/x.jpg": "https://img.alicdn.com/x.jpg",
"https://img.alicdn.com/x.jpg": "https://img.alicdn.com/x.jpg",
" https://img.alicdn.com/x.jpg ": "https://img.alicdn.com/x.jpg",
}
for in, want := range cases {
+116 -17
View File
@@ -273,7 +273,9 @@ func (s *Server) startItemPublishBatch(w http.ResponseWriter, r *http.Request) {
// #nosec G118 -- 批处理必须在请求结束后继续,并由 30 分钟超时保证退出。
go func() {
jobCtx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
s.registerPublishBatchCancel(batch.ID, cancel)
defer cancel()
defer s.unregisterPublishBatchCancel(batch.ID)
s.runItemPublishBatch(jobCtx, sess.UserID, batch.ID, false)
}()
writeJSON(w, http.StatusOK, map[string]any{"success": true, "batch_id": batch.ID})
@@ -306,6 +308,9 @@ func (s *Server) cancelItemPublishBatch(w http.ResponseWriter, r *http.Request)
writeErr(w, http.StatusInternalServerError, "取消任务失败")
return
}
s.cancelPublishBatch(batchID)
_ = s.Store.PublishBatches.MarkUnfinishedFailed(r.Context(), batchID, "任务已取消")
_ = s.Store.PublishBatches.Recount(r.Context(), batchID)
writeJSON(w, http.StatusOK, map[string]any{"success": true})
}
@@ -328,7 +333,9 @@ func (s *Server) retryFailedItemPublishBatch(w http.ResponseWriter, r *http.Requ
// #nosec G118 -- 批处理必须在请求结束后继续,并由 30 分钟超时保证退出。
go func() {
jobCtx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
s.registerPublishBatchCancel(batchID, cancel)
defer cancel()
defer s.unregisterPublishBatchCancel(batchID)
s.runItemPublishBatch(jobCtx, sess.UserID, batchID, false)
}()
writeJSON(w, http.StatusOK, map[string]any{"success": true, "batch_id": batchID})
@@ -374,36 +381,122 @@ func (s *Server) runItemPublishBatch(ctx context.Context, userID int64, batchID
}
client := s.mtopClient()
for idx, row := range rows {
status, err := s.Store.PublishBatches.BatchStatus(ctx, batchID)
if err != nil || status == "canceled" {
_ = s.Store.PublishBatches.Recount(ctx, batchID)
if ctx.Err() != nil {
s.finishInterruptedPublishBatch(ctx, userID, batchID)
return
}
_ = s.Store.PublishBatches.MarkRowRunning(ctx, row.ID)
if err := s.publishBatchRow(ctx, userID, client, row); err != nil {
_ = s.Store.PublishBatches.MarkRowFailed(ctx, row.ID, err.Error())
wctx, cancel := publishStatusContext(ctx)
status, err := s.Store.PublishBatches.BatchStatus(wctx, batchID)
cancel()
if err != nil || status == "canceled" {
wctx, cancel := publishStatusContext(ctx)
if status == "canceled" {
_ = s.Store.PublishBatches.MarkUnfinishedFailed(wctx, batchID, "任务已取消")
}
_ = s.Store.PublishBatches.Recount(wctx, batchID)
cancel()
return
}
_ = s.Store.PublishBatches.Recount(ctx, batchID)
wctx, cancel = publishStatusContext(ctx)
_ = s.Store.PublishBatches.MarkRowRunning(wctx, row.ID)
cancel()
if err := s.publishBatchRow(ctx, userID, client, row); err != nil {
message := err.Error()
if status, _ := s.Store.PublishBatches.BatchStatus(context.Background(), batchID); status == "canceled" {
message = "任务已取消"
}
wctx, cancel := publishStatusContext(ctx)
_ = s.Store.PublishBatches.MarkRowFailed(wctx, row.ID, message)
cancel()
}
wctx, cancel = publishStatusContext(ctx)
_ = s.Store.PublishBatches.Recount(wctx, batchID)
cancel()
if idx < len(rows)-1 {
delay := time.Duration(10+idx%21) * time.Second
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
timer.Stop()
s.finishInterruptedPublishBatch(ctx, userID, batchID)
return
case <-timer.C:
}
}
}
_ = s.Store.PublishBatches.Recount(ctx, batchID)
batch, err := s.Store.PublishBatches.Get(ctx, userID, batchID)
if err == nil && batch.Status != "canceled" {
finalStatus := "completed"
if batch.SuccessCount == 0 && batch.FailedCount > 0 {
finalStatus = "failed"
}
_ = s.Store.PublishBatches.SetBatchStatus(ctx, batchID, finalStatus)
s.finishPublishBatch(ctx, userID, batchID)
}
func (s *Server) registerPublishBatchCancel(batchID string, cancel context.CancelFunc) {
s.publishMu.Lock()
defer s.publishMu.Unlock()
if s.publishCancels == nil {
s.publishCancels = make(map[string]context.CancelFunc)
}
if old := s.publishCancels[batchID]; old != nil {
old()
}
s.publishCancels[batchID] = cancel
}
func (s *Server) unregisterPublishBatchCancel(batchID string) {
s.publishMu.Lock()
defer s.publishMu.Unlock()
delete(s.publishCancels, batchID)
}
func (s *Server) cancelPublishBatch(batchID string) {
s.publishMu.Lock()
cancel := s.publishCancels[batchID]
s.publishMu.Unlock()
if cancel != nil {
cancel()
}
}
func publishStatusContext(parent context.Context) (context.Context, context.CancelFunc) {
if parent != nil && parent.Err() == nil {
return context.WithTimeout(parent, 5*time.Second)
}
return context.WithTimeout(context.Background(), 5*time.Second)
}
func (s *Server) finishInterruptedPublishBatch(ctx context.Context, userID int64, batchID string) {
wctx, cancel := publishStatusContext(ctx)
defer cancel()
if status, _ := s.Store.PublishBatches.BatchStatus(wctx, batchID); status == "canceled" {
_ = s.Store.PublishBatches.MarkUnfinishedFailed(wctx, batchID, "任务已取消")
_ = s.Store.PublishBatches.Recount(wctx, batchID)
return
}
_ = s.Store.PublishBatches.MarkUnfinishedFailed(wctx, batchID, "任务超时或已中断")
_ = s.Store.PublishBatches.Recount(wctx, batchID)
s.finishPublishBatch(wctx, userID, batchID)
}
func (s *Server) finishPublishBatch(ctx context.Context, userID int64, batchID string) {
wctx, cancel := publishStatusContext(ctx)
defer cancel()
_ = s.Store.PublishBatches.Recount(wctx, batchID)
batch, err := s.Store.PublishBatches.Get(wctx, userID, batchID)
if err != nil || batch.Status == "canceled" {
return
}
finalStatus := finalPublishBatchStatus(batch)
_ = s.Store.PublishBatches.SetBatchStatus(wctx, batchID, finalStatus)
}
func finalPublishBatchStatus(batch *db.ItemPublishBatch) string {
if batch == nil {
return "failed"
}
if batch.FailedCount > 0 {
if batch.SuccessCount > 0 {
return "partially_failed"
}
return "failed"
}
return "completed"
}
func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.Client, row db.ItemPublishBatchRow) error {
@@ -444,6 +537,12 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
}
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
if status, _ := s.Store.PublishBatches.BatchStatus(ctx, row.BatchID); status == "canceled" {
return context.Canceled
}
if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
if err := s.Store.Cookies.Save(ctx, row.CookieID, res.UpdatedCookies, userID); err != nil {
s.Logger.Error("发布商品后保存刷新 cookie 失败", "cookie_id", row.CookieID, "err", err)
@@ -762,9 +861,9 @@ func (s *Server) cookieValueForUser(ctx context.Context, userID int64, cookieID
}
func (s *Server) cardOwnedByUser(ctx context.Context, userID int64, cardID int64) bool {
var exists int
var exists bool
err := s.Store.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM cards WHERE id=? AND user_id=?)`, cardID, userID).Scan(&exists)
return err == nil && exists != 0
return err == nil && exists
}
func (s *Server) publishUploadRoot() string {
+39 -4
View File
@@ -6,6 +6,7 @@ import (
"github.com/go-chi/chi/v5"
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
)
// mountKeywordsReal 关键字端点。
@@ -98,11 +99,45 @@ func (s *Server) addKeywordWithItemID(w http.ResponseWriter, r *http.Request) {
return
}
var req struct {
Keyword string `json:"keyword"`
Reply string `json:"reply"`
ItemID string `json:"item_id"`
Keyword string `json:"keyword"`
Reply string `json:"reply"`
ItemID string `json:"item_id"`
Keywords *[]struct {
Keyword string `json:"keyword"`
Reply string `json:"reply"`
ItemID string `json:"item_id"`
Type string `json:"type"`
ImageURL string `json:"image_url"`
} `json:"keywords"`
}
if err := decodeJSON(r, &req); err != nil || req.Keyword == "" {
if err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
if req.Keywords != nil {
rows := make([]db.KeywordRow, 0, len(*req.Keywords))
for _, item := range *req.Keywords {
if item.Keyword == "" {
writeErr(w, http.StatusBadRequest, "keyword 必填")
return
}
rows = append(rows, db.KeywordRow{
CookieID: cid,
Keyword: item.Keyword,
Reply: item.Reply,
ItemID: item.ItemID,
Type: item.Type,
ImageURL: item.ImageURL,
})
}
if err := s.Store.Keywords.ReplaceForCookie(r.Context(), cid, rows); err != nil {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
return
}
if req.Keyword == "" {
writeErr(w, http.StatusBadRequest, "keyword 必填")
return
}
+87
View File
@@ -0,0 +1,87 @@
package server
import (
"context"
"strings"
"time"
"xianyu-go/internal/db"
)
const (
loginMethodManual = "manual"
loginMethodPassword = "password"
loginMethodQRScan = "qr_scan"
loginStatusSuccess = "success"
loginStatusFailed = "failed"
)
func normalizeLoginMethod(method string) string {
switch strings.ToLower(strings.TrimSpace(method)) {
case "manual", "cookie", "manual_cookie":
return loginMethodManual
case "password", "password_login":
return loginMethodPassword
case "qr", "qr_login", "qr_scan":
return loginMethodQRScan
default:
return strings.ToLower(strings.TrimSpace(method))
}
}
func (s *Server) markSuccessfulLogin(ctx context.Context, cookieID string, userID int64, method, message string) {
method = normalizeLoginMethod(method)
if method == "" {
return
}
at := time.Now().Unix()
if err := s.Store.Cookies.MarkLogin(ctx, cookieID, method, at); err != nil {
if s.Logger != nil {
s.Logger.Warn("记录账号登录方式失败", "cookie_id", cookieID, "method", method, "err", err)
}
return
}
if method == loginMethodPassword || method == loginMethodQRScan {
if err := s.Store.Cookies.SetStatusWithReason(ctx, cookieID, true, ""); err != nil && s.Logger != nil {
s.Logger.Warn("成功登录后启用账号失败", "cookie_id", cookieID, "method", method, "err", err)
}
}
s.addLoginLog(ctx, cookieID, userID, method, loginStatusSuccess, "", message, at)
}
func (s *Server) addLoginLog(ctx context.Context, cookieID string, userID int64, method, status, failureReason, message string, at int64) {
if s.Store == nil || s.Store.LoginLogs == nil {
return
}
if at == 0 {
at = time.Now().Unix()
}
if err := s.Store.LoginLogs.Add(ctx, db.AccountLoginLog{
CookieID: cookieID,
UserID: userID,
OwnerID: userID,
AccountIdentifier: cookieID,
Method: normalizeLoginMethod(method),
Status: status,
Message: truncate(message, 500),
TriggerReason: loginTriggerReason(method),
FailureReason: failureReason,
ErrorMessage: truncate(message, 500),
CreatedAt: at,
}); err != nil && s.Logger != nil {
s.Logger.Warn("记录账号登录日志失败", "cookie_id", cookieID, "method", method, "status", status, "err", err)
}
}
func loginTriggerReason(method string) string {
switch normalizeLoginMethod(method) {
case loginMethodManual:
return "手动Cookie录入"
case loginMethodPassword:
return "账号密码登录"
case loginMethodQRScan:
return "扫码登录"
default:
return ""
}
}
+2 -2
View File
@@ -71,11 +71,11 @@ func (s *Server) requireChannelOwner(w http.ResponseWriter, r *http.Request, cha
writeErr(w, http.StatusUnauthorized, "未授权访问")
return false
}
var exists int
var exists bool
err := s.Store.DB.QueryRowContext(r.Context(),
`SELECT EXISTS(SELECT 1 FROM notification_channels WHERE id=? AND user_id=?)`,
channelID, sess.UserID).Scan(&exists)
if err != nil || exists == 0 {
if err != nil || !exists {
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
return false
}
+429
View File
@@ -0,0 +1,429 @@
package server
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"net/http"
"strings"
"time"
"github.com/go-chi/chi/v5"
"xianyu-go/internal/auth"
"xianyu-go/internal/browser"
"xianyu-go/internal/db"
)
type passwordLoginRunner interface {
PasswordLogin(ctx context.Context, account, password, cookieID, userDataDir string, headless bool) (map[string]string, error)
}
type passwordLoginEventRunner interface {
PasswordLoginWithEvents(ctx context.Context, account, password, cookieID, userDataDir string, headless bool, onEvent browser.PasswordLoginEventHandler) (map[string]string, error)
}
const (
passwordLoginSessionMaxAge = time.Hour
passwordLoginProcessingTimeout = 5 * time.Minute
passwordLoginBaxiaPunishReason = "baxia_punish_captcha"
passwordLoginBaxiaPunishCooldown = 5
)
type passwordLoginSession struct {
ID string
AccountID string
Account string
UserID int64
Status string
Message string
Error string
Reason string
VerificationURL string
ScreenshotPath string
QRCodeURL string
CooldownHours int
IsNewAccount bool
CookieCount int
ShowBrowser bool
CreatedAt time.Time
cancel context.CancelFunc
}
func (s *Server) mountPasswordLogin(r chi.Router) {
r.Post("/password-login", s.startPasswordLogin)
r.Get("/password-login/check/{session_id}", s.checkPasswordLogin)
r.Delete("/password-login/cancel/{session_id}", s.cancelPasswordLogin)
}
func (s *Server) startPasswordLogin(w http.ResponseWriter, r *http.Request) {
var req struct {
AccountID string `json:"account_id"`
CookieID string `json:"cookie_id"`
Account string `json:"account"`
Username string `json:"username"`
Password string `json:"password"`
ShowBrowser bool `json:"show_browser"`
}
if err := decodeJSON(r, &req); err != nil {
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "请求格式错误"})
return
}
accountID := firstNonEmpty(req.AccountID, req.CookieID)
account := firstNonEmpty(req.Account, req.Username)
accountID = strings.TrimSpace(accountID)
account = strings.TrimSpace(account)
if accountID == "" || account == "" || req.Password == "" {
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "账号ID、登录账号和密码不能为空"})
return
}
if s.PasswordLogin == nil {
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "浏览器登录服务不可用"})
return
}
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return
}
if ok, message := s.canStartPasswordLogin(r.Context(), sess.UserID, accountID); !ok {
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": message})
return
}
s.cleanupExpiredPasswordLoginSessions()
if sid := s.currentPasswordLoginSession(accountID); sid != "" {
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
"session_id": sid,
"status": "processing",
"message": "账号正在处理中,请稍候...",
})
return
}
sessionID, err := newPasswordSessionID()
if err != nil {
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "创建登录会话失败"})
return
}
ctx, cancel := context.WithCancel(context.Background())
loginSession := &passwordLoginSession{
ID: sessionID,
AccountID: accountID,
Account: account,
UserID: sess.UserID,
Status: "processing",
Message: "登录处理中,请稍候...",
ShowBrowser: req.ShowBrowser,
CreatedAt: time.Now(),
cancel: cancel,
}
s.passwordMu.Lock()
s.passwordSessions[sessionID] = loginSession
s.passwordProcessing[accountID] = sessionID
s.passwordMu.Unlock()
go s.runPasswordLoginSession(ctx, loginSession, req.Password)
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
"session_id": sessionID,
"status": "processing",
"message": "登录任务已启动,请等待...",
})
}
func (s *Server) checkPasswordLogin(w http.ResponseWriter, r *http.Request) {
sessionID := chi.URLParam(r, "session_id")
s.cleanupExpiredPasswordLoginSessions()
s.passwordMu.Lock()
session, ok := s.passwordSessions[sessionID]
if !ok {
s.passwordMu.Unlock()
writeJSON(w, http.StatusOK, map[string]any{"status": "not_found", "message": "会话不存在或已过期"})
return
}
response := passwordSessionResponse(session)
if session.Status == "success" || session.Status == "failed" {
delete(s.passwordSessions, sessionID)
delete(s.passwordProcessing, session.AccountID)
}
s.passwordMu.Unlock()
writeJSON(w, http.StatusOK, response)
}
func (s *Server) cancelPasswordLogin(w http.ResponseWriter, r *http.Request) {
sessionID := chi.URLParam(r, "session_id")
s.passwordMu.Lock()
session, ok := s.passwordSessions[sessionID]
if !ok {
s.passwordMu.Unlock()
writeJSON(w, http.StatusOK, map[string]any{"success": false, "code": 404, "message": "会话不存在", "data": nil})
return
}
if session.cancel != nil {
session.cancel()
}
delete(s.passwordSessions, sessionID)
delete(s.passwordProcessing, session.AccountID)
s.passwordMu.Unlock()
writeJSON(w, http.StatusOK, map[string]any{"success": true, "code": 200, "message": "登录会话已取消", "data": nil})
}
func (s *Server) runPasswordLoginSession(ctx context.Context, session *passwordLoginSession, password string) {
var (
cookies map[string]string
err error
)
headless := !session.ShowBrowser
if runner, ok := s.PasswordLogin.(passwordLoginEventRunner); ok {
cookies, err = runner.PasswordLoginWithEvents(ctx, session.Account, password, session.AccountID, "", headless, func(event browser.PasswordLoginEvent) {
s.applyPasswordLoginEvent(session, event)
})
} else {
cookies, err = s.PasswordLogin.PasswordLogin(ctx, session.Account, password, session.AccountID, "", headless)
}
if err != nil {
event := browser.PasswordLoginEventFromError(err)
status := event.Status
if status == "" {
status = "failed"
}
reason := passwordLoginReason(err)
s.failPasswordLoginSession(session, status, err.Error(), reason, event.CooldownHours)
s.addLoginLog(context.Background(), session.AccountID, session.UserID, loginMethodPassword, loginStatusFailed, reason, err.Error(), 0)
return
}
accountID, isNew, err := s.savePasswordLoginCookies(ctx, session, password, cookies)
if err != nil {
s.failPasswordLoginSession(session, "failed", "保存登录结果失败: "+err.Error(), "", 0)
s.addLoginLog(context.Background(), session.AccountID, session.UserID, loginMethodPassword, loginStatusFailed, "cookie_update_failed", err.Error(), 0)
return
}
s.completePasswordLoginSession(session, func(current *passwordLoginSession) {
current.Status = "success"
current.Message = "账号 " + accountID + " 登录成功"
current.AccountID = accountID
current.IsNewAccount = isNew
current.CookieCount = len(cookies)
})
}
func (s *Server) savePasswordLoginCookies(ctx context.Context, session *passwordLoginSession, password string, cookies map[string]string) (string, bool, error) {
if len(cookies) == 0 {
return "", false, errors.New("浏览器未返回 cookie")
}
accountID := cookieAccountID(cookies, session.AccountID)
cookieValue := browser.MarshalCookies(cookies)
_, err := s.Store.Cookies.GetDetails(ctx, accountID)
isNew := errors.Is(err, db.ErrNotFound)
if err != nil && !errors.Is(err, db.ErrNotFound) {
return "", false, err
}
if err := s.Store.Cookies.Save(ctx, accountID, cookieValue, session.UserID); err != nil {
return "", false, err
}
if err := s.Store.Cookies.UpdateLoginInfo(ctx, accountID, session.Account, password, session.ShowBrowser); err != nil {
return "", false, err
}
s.markSuccessfulLogin(ctx, accountID, session.UserID, loginMethodPassword, "账号密码登录成功")
if s.Store.Tokens != nil {
_ = s.Store.Tokens.Clear(ctx, accountID)
}
if d, err := s.Store.Cookies.GetDetails(ctx, accountID); err == nil {
s.refreshAccountProfile(ctx, d)
}
if s.Manager != nil && s.Store.Cookies.GetStatus(ctx, accountID) {
if err := s.Manager.Restart(ctx, accountID); err != nil && s.Logger != nil {
s.Logger.Warn("密码登录后重启账号失败", "cookie_id", accountID, "err", err)
}
}
return accountID, isNew, nil
}
func (s *Server) canStartPasswordLogin(ctx context.Context, userID int64, accountID string) (bool, string) {
d, err := s.Store.Cookies.GetDetails(ctx, accountID)
if err == nil {
if d.UserID != userID {
return false, "无权限操作该账号"
}
if !s.Store.Cookies.GetStatus(ctx, accountID) {
return false, "账号已禁用,请先在账号管理中启用"
}
return true, ""
}
if errors.Is(err, db.ErrNotFound) {
return true, ""
}
return false, "查询账号失败"
}
func (s *Server) currentPasswordLoginSession(accountID string) string {
s.passwordMu.Lock()
defer s.passwordMu.Unlock()
return s.passwordProcessing[accountID]
}
func (s *Server) completePasswordLoginSession(session *passwordLoginSession, mutate func(*passwordLoginSession)) {
s.finishPasswordLoginSession(session, mutate)
}
func (s *Server) updatePasswordLoginSession(session *passwordLoginSession, mutate func(*passwordLoginSession)) bool {
s.passwordMu.Lock()
defer s.passwordMu.Unlock()
current, ok := s.passwordSessions[session.ID]
if !ok || current != session {
return false
}
mutate(current)
return true
}
func (s *Server) finishPasswordLoginSession(session *passwordLoginSession, mutate func(*passwordLoginSession)) {
s.passwordMu.Lock()
defer s.passwordMu.Unlock()
current, ok := s.passwordSessions[session.ID]
if !ok || current != session {
return
}
originalAccountID := current.AccountID
mutate(current)
delete(s.passwordProcessing, originalAccountID)
delete(s.passwordProcessing, current.AccountID)
}
func (s *Server) applyPasswordLoginEvent(session *passwordLoginSession, event browser.PasswordLoginEvent) {
if event.Status == "" {
return
}
apply := func(current *passwordLoginSession) {
current.Status = event.Status
current.Message = firstNonEmpty(event.Message, current.Message)
current.Error = firstNonEmpty(event.Error, current.Error)
current.Reason = firstNonEmpty(event.Reason, current.Reason)
current.VerificationURL = firstNonEmpty(event.VerificationURL, current.VerificationURL)
current.ScreenshotPath = firstNonEmpty(event.ScreenshotPath, current.ScreenshotPath)
current.QRCodeURL = firstNonEmpty(event.QRCodeURL, current.QRCodeURL)
if event.CooldownHours > 0 {
current.CooldownHours = event.CooldownHours
}
}
if passwordLoginEventIsTerminal(event.Status) {
s.finishPasswordLoginSession(session, apply)
return
}
s.updatePasswordLoginSession(session, apply)
}
func (s *Server) failPasswordLoginSession(session *passwordLoginSession, status, message, reason string, cooldownHours int) {
s.completePasswordLoginSession(session, func(current *passwordLoginSession) {
current.Status = status
current.Message = message
current.Error = message
current.Reason = reason
current.CooldownHours = cooldownHours
})
}
func passwordLoginEventIsTerminal(status string) bool {
return status == "success" || status == browser.PasswordLoginStatusFailed
}
func (s *Server) cleanupExpiredPasswordLoginSessions() {
now := time.Now()
s.passwordMu.Lock()
defer s.passwordMu.Unlock()
for sessionID, session := range s.passwordSessions {
age := now.Sub(session.CreatedAt)
if session.Status == "processing" && age > passwordLoginProcessingTimeout {
if session.cancel != nil {
session.cancel()
}
session.Status = "failed"
session.Message = "登录处理超时,请稍后重试"
session.Error = session.Message
delete(s.passwordProcessing, session.AccountID)
}
if age <= passwordLoginSessionMaxAge {
continue
}
if session.cancel != nil {
session.cancel()
}
delete(s.passwordSessions, sessionID)
delete(s.passwordProcessing, session.AccountID)
}
}
func passwordSessionResponse(session *passwordLoginSession) map[string]any {
resp := map[string]any{
"status": session.Status,
"message": session.Message,
}
if session.Status == "success" {
resp["account_id"] = session.AccountID
resp["is_new_account"] = session.IsNewAccount
resp["cookie_count"] = session.CookieCount
}
if session.Status == "failed" {
resp["error"] = session.Error
if session.Reason != "" {
resp["reason"] = session.Reason
}
if session.CooldownHours > 0 {
resp["cooldown_hours"] = session.CooldownHours
}
}
if session.Status == "verification_required" {
resp["verification_url"] = session.VerificationURL
resp["screenshot_path"] = session.ScreenshotPath
resp["qr_code_url"] = session.QRCodeURL
resp["error"] = session.Error
if session.CooldownHours > 0 {
resp["cooldown_hours"] = session.CooldownHours
}
}
return resp
}
func newPasswordSessionID() (string, error) {
var b [18]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b[:]), nil
}
func cookieAccountID(cookies map[string]string, fallback string) string {
for k, v := range cookies {
if strings.EqualFold(strings.TrimSpace(k), "unb") && strings.TrimSpace(v) != "" {
return strings.TrimSpace(v)
}
}
return fallback
}
func loginStatusForPasswordError(err error) string {
return browser.PasswordLoginEventFromError(err).Status
}
func passwordLoginReason(err error) string {
if err == nil {
return ""
}
msg := err.Error()
if strings.Contains(msg, "账密错误") || strings.Contains(msg, "账号密码错误") ||
strings.Contains(msg, "用户名或密码错误") || strings.Contains(msg, "密码错误") {
return "bad_credentials"
}
event := browser.PasswordLoginEventFromError(err)
if event.Reason != "" {
return event.Reason
}
if event.Status == browser.PasswordLoginStatusVerificationRequired {
return "verification_required"
}
return "other"
}
@@ -0,0 +1,384 @@
package server
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"xianyu-go/internal/browser"
"xianyu-go/internal/db"
)
type fakePasswordLoginRunner struct {
mu sync.Mutex
cookies map[string]string
err error
block chan struct{}
events []browser.PasswordLoginEvent
calls int
lastAccount string
lastHeadless bool
}
func (f *fakePasswordLoginRunner) PasswordLogin(ctx context.Context, account, password, cookieID, userDataDir string, headless bool) (map[string]string, error) {
f.mu.Lock()
f.calls++
f.lastAccount = account
f.lastHeadless = headless
f.mu.Unlock()
if f.block != nil {
select {
case <-f.block:
case <-ctx.Done():
return nil, ctx.Err()
}
}
return f.cookies, f.err
}
func (f *fakePasswordLoginRunner) PasswordLoginWithEvents(ctx context.Context, account, password, cookieID, userDataDir string, headless bool, onEvent browser.PasswordLoginEventHandler) (map[string]string, error) {
for _, event := range f.events {
onEvent(event)
}
return f.PasswordLogin(ctx, account, password, cookieID, userDataDir, headless)
}
func (f *fakePasswordLoginRunner) snapshot() (int, string, bool) {
f.mu.Lock()
defer f.mu.Unlock()
return f.calls, f.lastAccount, f.lastHeadless
}
func loginForPasswordTest(t *testing.T, h http.Handler) *http.Cookie {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"admin","password":"pw"}`))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || len(rec.Result().Cookies()) == 0 {
t.Fatalf("login status=%d body=%s", rec.Code, rec.Body.String())
}
return rec.Result().Cookies()[0]
}
func startPasswordLoginForTest(t *testing.T, h http.Handler, cookie *http.Cookie, body string) map[string]any {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/password-login", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("start status=%d body=%s", rec.Code, rec.Body.String())
}
var out map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatalf("decode start: %v body=%s", err, rec.Body.String())
}
return out
}
func checkPasswordLoginForTest(t *testing.T, h http.Handler, cookie *http.Cookie, sessionID string) map[string]any {
t.Helper()
req := httptest.NewRequest(http.MethodGet, "/password-login/check/"+sessionID, nil)
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("check status=%d body=%s", rec.Code, rec.Body.String())
}
var out map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatalf("decode check: %v body=%s", err, rec.Body.String())
}
return out
}
func cancelPasswordLoginForTest(t *testing.T, h http.Handler, cookie *http.Cookie, sessionID string) {
t.Helper()
req := httptest.NewRequest(http.MethodDelete, "/password-login/cancel/"+sessionID, nil)
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("cancel status=%d body=%s", rec.Code, rec.Body.String())
}
}
func waitPasswordLoginStatus(t *testing.T, h http.Handler, cookie *http.Cookie, sessionID, want string) map[string]any {
t.Helper()
var out map[string]any
for i := 0; i < 50; i++ {
out = checkPasswordLoginForTest(t, h, cookie, sessionID)
if out["status"] == want {
return out
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("status did not reach %q, last=%+v", want, out)
return nil
}
func waitLoginLogCount(t *testing.T, store *db.Store, cookieID string, want int) []db.AccountLoginLog {
t.Helper()
var logs []db.AccountLoginLog
var err error
for i := 0; i < 50; i++ {
logs, err = store.LoginLogs.ListByCookie(context.Background(), cookieID, 10)
if err == nil && len(logs) >= want {
return logs
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("login logs did not reach %d: logs=%#v err=%v", want, logs, err)
return nil
}
func TestPasswordLoginSessionSuccessSavesCookiesAndAudit(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
fake := &fakePasswordLoginRunner{cookies: map[string]string{"unb": "acc1", "_m_h5_tk": "fresh"}}
srv.PasswordLogin = fake
h := srv.Router()
cookie := loginForPasswordTest(t, h)
if err := store.Tokens.Save(context.Background(), "acc1", "did", "token", time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatalf("save token: %v", err)
}
start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"login-user","password":"secret","show_browser":false}`)
if start["success"] != true || start["status"] != "processing" {
t.Fatalf("start response=%+v", start)
}
sessionID, _ := start["session_id"].(string)
if sessionID == "" {
t.Fatalf("missing session_id: %+v", start)
}
done := waitPasswordLoginStatus(t, h, cookie, sessionID, "success")
if done["account_id"] != "acc1" || done["is_new_account"] != false {
t.Fatalf("success response=%+v", done)
}
calls, account, headless := fake.snapshot()
if calls != 1 || account != "login-user" || !headless {
t.Fatalf("PasswordLogin 调用异常: calls=%d account=%q headless=%v", calls, account, headless)
}
saved, _ := store.Cookies.GetValue(context.Background(), "acc1")
if !strings.Contains(saved, "_m_h5_tk=fresh") {
t.Fatalf("cookie 未保存: %q", saved)
}
d, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatalf("GetDetails: %v", err)
}
if d.Username != "login-user" || d.Password != "secret" || d.ShowBrowser || d.LoginMethod != "password" || d.LastLoginAt == 0 {
t.Fatalf("登录信息/审计字段异常: %+v", d)
}
if _, err := store.Tokens.Get(context.Background(), "acc1"); !errors.Is(err, db.ErrNotFound) {
t.Fatalf("密码登录成功应清 token,got %v", err)
}
logs, err := store.LoginLogs.ListByCookie(context.Background(), "acc1", 10)
if err != nil || len(logs) != 1 || logs[0].Status != "success" {
t.Fatalf("登录日志异常: logs=%#v err=%v", logs, err)
}
}
func TestPasswordLoginUnavailableWhenBrowserManagerNil(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
h := srv.Router()
cookie := loginForPasswordTest(t, h)
start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
if start["success"] != false || start["message"] != "浏览器登录服务不可用" {
t.Fatalf("nil 浏览器应返回不可用且不启动登录: %+v", start)
}
}
func TestPasswordLoginSessionShowBrowserRunsVisibleAndSavesPreference(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
fake := &fakePasswordLoginRunner{cookies: map[string]string{"unb": "acc1", "_m_h5_tk": "fresh"}}
srv.PasswordLogin = fake
h := srv.Router()
cookie := loginForPasswordTest(t, h)
start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"login-user","password":"secret","show_browser":true}`)
sessionID, _ := start["session_id"].(string)
if sessionID == "" {
t.Fatalf("missing session_id: %+v", start)
}
waitPasswordLoginStatus(t, h, cookie, sessionID, "success")
calls, account, headless := fake.snapshot()
if calls != 1 || account != "login-user" || headless {
t.Fatalf("show_browser=true 应使用可视浏览器: calls=%d account=%q headless=%v", calls, account, headless)
}
d, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatalf("GetDetails: %v", err)
}
if !d.ShowBrowser {
t.Fatalf("show_browser=true 应按原请求落库: %+v", d)
}
}
func TestPasswordLoginDuplicateStartReturnsProcessingSession(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
fake := &fakePasswordLoginRunner{block: make(chan struct{}), cookies: map[string]string{"unb": "acc1"}}
srv.PasswordLogin = fake
h := srv.Router()
cookie := loginForPasswordTest(t, h)
first := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
second := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
if first["session_id"] == "" || second["session_id"] != first["session_id"] || second["status"] != "processing" {
t.Fatalf("重复启动应返回同一 processing 会话: first=%+v second=%+v", first, second)
}
cancelPasswordLoginForTest(t, h, cookie, first["session_id"].(string))
waitLoginLogCount(t, store, "acc1", 1)
}
func TestPasswordLoginVerificationRequiredKeepsProcessingLock(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
fake := &fakePasswordLoginRunner{
block: make(chan struct{}),
events: []browser.PasswordLoginEvent{{
Status: browser.PasswordLoginStatusVerificationRequired,
Message: "需要人脸验证,请查看验证截图",
Error: "需要人脸验证",
ScreenshotPath: "/tmp/face.png",
}},
cookies: map[string]string{"unb": "acc1"},
}
srv.PasswordLogin = fake
h := srv.Router()
cookie := loginForPasswordTest(t, h)
first := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
sessionID := first["session_id"].(string)
waitPasswordLoginStatus(t, h, cookie, sessionID, "verification_required")
second := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
if second["session_id"] != sessionID {
t.Fatalf("验证码等待期间应继续复用同一会话: first=%+v second=%+v", first, second)
}
if calls, _, _ := fake.snapshot(); calls != 1 {
t.Fatalf("验证码等待期间不应启动第二个浏览器任务,calls=%d", calls)
}
cancelPasswordLoginForTest(t, h, cookie, sessionID)
waitLoginLogCount(t, store, "acc1", 1)
}
func TestPasswordLoginProcessingTimeoutReleasesAccount(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
fake := &fakePasswordLoginRunner{block: make(chan struct{}), cookies: map[string]string{"unb": "acc1"}}
srv.PasswordLogin = fake
h := srv.Router()
cookie := loginForPasswordTest(t, h)
first := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
sessionID := first["session_id"].(string)
srv.passwordMu.Lock()
srv.passwordSessions[sessionID].CreatedAt = time.Now().Add(-(passwordLoginProcessingTimeout + time.Second))
srv.passwordMu.Unlock()
second := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
if second["session_id"] == "" || second["session_id"] == sessionID {
t.Fatalf("processing 超时后应创建新会话: first=%+v second=%+v", first, second)
}
oldStatus := checkPasswordLoginForTest(t, h, cookie, sessionID)
if oldStatus["status"] != "failed" {
t.Fatalf("超时旧会话应标记 failed: %+v", oldStatus)
}
cancelPasswordLoginForTest(t, h, cookie, second["session_id"].(string))
waitLoginLogCount(t, store, "acc1", 2)
}
func TestPasswordLoginSessionExpiresAfterOneHour(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
fake := &fakePasswordLoginRunner{block: make(chan struct{}), cookies: map[string]string{"unb": "acc1"}}
srv.PasswordLogin = fake
h := srv.Router()
cookie := loginForPasswordTest(t, h)
start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
sessionID := start["session_id"].(string)
srv.passwordMu.Lock()
srv.passwordSessions[sessionID].CreatedAt = time.Now().Add(-(passwordLoginSessionMaxAge + time.Second))
srv.passwordMu.Unlock()
done := checkPasswordLoginForTest(t, h, cookie, sessionID)
if done["status"] != "not_found" {
t.Fatalf("1小时后会话应过期: %+v", done)
}
waitLoginLogCount(t, store, "acc1", 1)
}
func TestPasswordLoginVerificationRequired(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
srv.PasswordLogin = &fakePasswordLoginRunner{
events: []browser.PasswordLoginEvent{{
Status: browser.PasswordLoginStatusVerificationRequired,
Message: "需要人脸验证,请查看验证截图",
Error: "需要人脸验证",
ScreenshotPath: "/tmp/face.png",
}},
err: errors.New("需要人脸验证"),
}
h := srv.Router()
cookie := loginForPasswordTest(t, h)
start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
sessionID := start["session_id"].(string)
done := waitPasswordLoginStatus(t, h, cookie, sessionID, "verification_required")
if done["error"] == "" {
t.Fatalf("verification_required 应带 error: %+v", done)
}
if done["screenshot_path"] != "/tmp/face.png" {
t.Fatalf("verification_required 应带截图: %+v", done)
}
again := checkPasswordLoginForTest(t, h, cookie, sessionID)
if again["status"] != "verification_required" {
t.Fatalf("验证态会话应保留: %+v", again)
}
logs := waitLoginLogCount(t, store, "acc1", 1)
if logs[0].FailureReason != "verification_required" {
t.Fatalf("验证态应记录 failure_reason: %#v", logs)
}
}
func TestPasswordLoginBaxiaReason(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
srv.PasswordLogin = &fakePasswordLoginRunner{err: errors.New("baxia-punish 风控图形验证")}
h := srv.Router()
cookie := loginForPasswordTest(t, h)
start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
sessionID := start["session_id"].(string)
done := waitPasswordLoginStatus(t, h, cookie, sessionID, "failed")
if done["reason"] != "baxia_punish_captcha" || done["cooldown_hours"] != float64(5) {
t.Fatalf("baxia 错误应带 reason/cooldown: %+v", done)
}
logs, err := store.LoginLogs.ListByCookie(context.Background(), "acc1", 10)
if err != nil || len(logs) != 1 || logs[0].FailureReason != "baxia_punish_captcha" {
t.Fatalf("baxia 错误应记录专用 failure_reason: logs=%#v err=%v", logs, err)
}
}
+157 -6
View File
@@ -20,6 +20,25 @@ import (
// minimalPNG 是一张 1x1 PNG,供发布批次图片 zip 复用。
var minimalPNG = []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82}
func TestFinalPublishBatchStatus(t *testing.T) {
cases := []struct {
name string
in db.ItemPublishBatch
want string
}{
{name: "completed", in: db.ItemPublishBatch{SuccessCount: 2}, want: "completed"},
{name: "failed", in: db.ItemPublishBatch{FailedCount: 2}, want: "failed"},
{name: "partially failed", in: db.ItemPublishBatch{SuccessCount: 1, FailedCount: 1}, want: "partially_failed"},
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
if got := finalPublishBatchStatus(&tt.in); got != tt.want {
t.Fatalf("got %q want %q", got, tt.want)
}
})
}
}
// buildImageZip 构造含一张图片的 zip 字节流。
func buildImageZip(t *testing.T) []byte {
t.Helper()
@@ -59,6 +78,33 @@ func previewPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie) stri
return res["preview_id"].(string)
}
func previewTwoRowPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie) string {
t.Helper()
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
_ = mw.WriteField("default_cookie_id", "acc1")
csvField, _ := mw.CreateFormFile("file", "products.csv")
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,img/a.png\nacc1,商品B,13.50,5,img/a.png\n"))
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
zipField.Write(buildImageZip(t))
_ = mw.Close()
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
req.Header.Set("Content-Type", mw.FormDataContentType())
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("preview status=%d body=%s", rec.Code, rec.Body.String())
}
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["valid"].(float64) != 2 {
t.Fatalf("预检应 2 行有效,got %+v", res)
}
return res["preview_id"].(string)
}
// TestRunItemPublishBatch_FailureMarksRowFailed 启动批次后,mock mtop 对发布请求返回失败,
// 验证 runItemPublishBatch/publishBatchRow 把行标记为 failed。
func TestRunItemPublishBatch_FailureMarksRowFailed(t *testing.T) {
@@ -118,8 +164,83 @@ func TestRunItemPublishBatch_FailureMarksRowFailed(t *testing.T) {
h.ServeHTTP(rec, req)
var got map[string]any
json.Unmarshal(rec.Body.Bytes(), &got)
if got["status"] == nil {
t.Fatalf("批次详情异常: %+v", got)
if got["status"] != "failed" {
t.Fatalf("status=%v want failed body=%+v", got["status"], got)
}
if got["failed"] != float64(1) {
t.Fatalf("failed=%v want 1 body=%+v", got["failed"], got)
}
rows, _ := got["rows"].([]any)
if len(rows) != 1 {
t.Fatalf("rows=%+v want 1 row", got["rows"])
}
row, _ := rows[0].(map[string]any)
if row["status"] != "failed" || row["error_message"] == "" {
t.Fatalf("row should be failed with error message: %+v", row)
}
}
func TestCancelItemPublishBatchMarksUnfinishedRowsFailed(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
select {
case <-req.Context().Done():
return nil, req.Context().Err()
case <-time.After(300 * time.Millisecond):
}
return &http.Response{
StatusCode: http.StatusOK,
Header: make(http.Header),
Body: io.NopCloser(strings.NewReader(`{"ret":["SUCCESS::调用成功"],"data":{"itemId":"late-item"}}`)),
Request: req,
}, nil
}))
h := srv.Router()
cookie := loginHelper(t, h)
batchID := previewTwoRowPublishBatch(t, h, cookie)
startReq := httptest.NewRequest(http.MethodPost, "/items/publish-batches", strings.NewReader(`{"preview_id":"`+batchID+`"}`))
startReq.AddCookie(cookie)
startRec := httptest.NewRecorder()
h.ServeHTTP(startRec, startReq)
if startRec.Code != http.StatusOK {
t.Fatalf("start status=%d body=%s", startRec.Code, startRec.Body.String())
}
cancelReq := httptest.NewRequest(http.MethodPost, "/items/publish-batches/"+batchID+"/cancel", nil)
cancelReq.AddCookie(cookie)
cancelRec := httptest.NewRecorder()
h.ServeHTTP(cancelRec, cancelReq)
if cancelRec.Code != http.StatusOK {
t.Fatalf("cancel status=%d body=%s", cancelRec.Code, cancelRec.Body.String())
}
deadline := time.Now().Add(2 * time.Second)
var got map[string]any
for time.Now().Before(deadline) {
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/"+batchID, nil)
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("detail status=%d body=%s", rec.Code, rec.Body.String())
}
json.Unmarshal(rec.Body.Bytes(), &got)
if got["pending"] == float64(0) && got["running"] == float64(0) {
break
}
time.Sleep(20 * time.Millisecond)
}
if got["status"] != "canceled" {
t.Fatalf("status=%v want canceled body=%+v", got["status"], got)
}
if got["pending"] != float64(0) || got["running"] != float64(0) {
t.Fatalf("取消后不应残留 pending/running: %+v", got)
}
if got["failed"] != got["total"] {
t.Fatalf("取消后未完成行应全部失败: total=%v failed=%v body=%+v", got["total"], got["failed"], got)
}
}
@@ -129,10 +250,17 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
defer cleanup()
// 所有 mtop 调用返回 SUCCESS;发布调用返回 itemId。
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
body := `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"123456","itemUrl":"https://x/item/123456"}}`
// 类目推荐接口需要返回 catId 才能继续后续步骤。
if strings.Contains(req.URL.RawQuery, "recommend") || strings.Contains(req.URL.RawQuery, "category") {
body = `{"ret":["SUCCESS::调用成功"],"data":{"catId":"100","categoryId":"100"}}`
u := req.URL.String()
body := `{"ret":["SUCCESS::调用成功"],"data":{}}`
switch {
case strings.Contains(u, "stream-upload.goofish.com"):
body = `{"object":{"url":"https://img.alicdn.com/published.png","pix":"800_800"}}`
case strings.Contains(u, "mtop.taobao.idle.local.poi.get"):
body = `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[{"address":"北京"}]}}`
case strings.Contains(u, "mtop.taobao.idle.kgraph.property.recommend"):
body = `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"100","catName":"数码"}}}`
case strings.Contains(u, "mtop.idle.pc.idleitem.publish"):
body = `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"123456","url":"https://x/item/123456","picUrl":"https://img.alicdn.com/published.png","categoryId":"100","categoryName":"数码","title":"商品A","priceText":"12.50","quantity":"5"}}`
}
return &http.Response{
StatusCode: http.StatusOK,
@@ -177,6 +305,29 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
if status == "running" {
t.Fatal("批次应在 8s 内完成")
}
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/"+batchID, nil)
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("detail status=%d body=%s", rec.Code, rec.Body.String())
}
var got map[string]any
json.Unmarshal(rec.Body.Bytes(), &got)
if got["status"] != "completed" {
t.Fatalf("status=%v want completed body=%+v", got["status"], got)
}
if got["success"] != float64(1) {
t.Fatalf("success=%v want 1 body=%+v", got["success"], got)
}
rows, _ := got["rows"].([]any)
if len(rows) != 1 {
t.Fatalf("rows=%+v want 1 row", got["rows"])
}
row, _ := rows[0].(map[string]any)
if row["status"] != "success" || row["item_id"] == "" {
t.Fatalf("row should be success with item_id: %+v", row)
}
}
// TestCreatePublishAutomationRules 覆盖自动化规则创建(通过成功发布路径间接覆盖)。
+125 -2
View File
@@ -1,15 +1,23 @@
package server
import (
"context"
"errors"
"net/http"
"strings"
"github.com/go-chi/chi/v5"
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/protocol"
)
// mountQRLoginReal 扫码登录端点(纯 HTTP,不需要浏览器)。
func (s *Server) mountQRLoginReal(r chi.Router) {
r.Post("/qr-login/generate", s.generateQRLogin)
r.Get("/qr-login/check/{session_id}", s.checkQRLoginStatus)
r.Get("/qr-login/status/{session_id}", s.checkQRLoginStatusAndPersist)
r.Post("/qr-login/complete-verification/{session_id}", s.completeQRVerification)
}
@@ -42,6 +50,40 @@ func (s *Server) checkQRLoginStatus(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, result)
}
// checkQRLoginStatusAndPersist 兼容上游 /status 语义:扫码成功后由后端幂等保存账号。
func (s *Server) checkQRLoginStatusAndPersist(w http.ResponseWriter, r *http.Request) {
sessionID := chi.URLParam(r, "session_id")
if sessionID == "" {
writeErr(w, http.StatusBadRequest, "缺少 session_id")
return
}
result := cloneQRStatus(s.QRLogin.GetSessionStatus(sessionID))
if qrStatus(result) != "success" {
writeJSON(w, http.StatusOK, result)
return
}
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return
}
persisted, err := s.persistQRLoginSuccess(r.Context(), sess.UserID, sessionID, result)
if err != nil {
if s.Logger != nil {
s.Logger.Warn("保存扫码登录结果失败", "session_id", sessionID, "err", err)
}
result["success"] = false
result["status"] = "error"
result["message"] = "保存扫码登录结果失败: " + err.Error()
writeJSON(w, http.StatusOK, result)
return
}
result["success"] = true
result["account_id"] = persisted.AccountID
result["is_new_account"] = persisted.IsNew
writeJSON(w, http.StatusOK, result)
}
// completeQRVerification 用户完成风控验证后调用,提取真实 cookie 并入库。
func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request) {
sessionID := chi.URLParam(r, "session_id")
@@ -58,9 +100,90 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
})
return
}
writeJSON(w, http.StatusOK, map[string]any{
resp := map[string]any{
"success": true,
"cookies": cookies,
"unb": unb,
})
}
sess := auth.SessionFromContext(r.Context())
if sess != nil {
persisted, persistErr := s.persistQRLoginSuccess(r.Context(), sess.UserID, sessionID, map[string]any{
"status": "success",
"cookies": cookies,
"unb": unb,
})
if persistErr != nil {
if s.Logger != nil {
s.Logger.Warn("保存扫码验证结果失败", "session_id", sessionID, "err", persistErr)
}
resp["success"] = false
resp["message"] = "保存扫码登录结果失败: " + persistErr.Error()
writeJSON(w, http.StatusOK, resp)
return
}
resp["account_id"] = persisted.AccountID
resp["is_new_account"] = persisted.IsNew
}
writeJSON(w, http.StatusOK, resp)
}
func (s *Server) persistQRLoginSuccess(ctx context.Context, userID int64, sessionID string, result map[string]any) (qrLoginPersistence, error) {
s.qrMu.Lock()
defer s.qrMu.Unlock()
if s.qrPersisted == nil {
s.qrPersisted = make(map[string]qrLoginPersistence)
}
if persisted, ok := s.qrPersisted[sessionID]; ok {
return persisted, nil
}
cookies := qrString(result, "cookies")
accountID := strings.TrimSpace(firstNonEmpty(qrString(result, "unb"), protocol.TransCookies(cookies)["unb"]))
if cookies == "" || accountID == "" {
return qrLoginPersistence{}, errors.New("扫码结果缺少 cookies 或 unb")
}
_, err := s.Store.Cookies.GetDetails(ctx, accountID)
isNew := errors.Is(err, db.ErrNotFound)
if err != nil && !errors.Is(err, db.ErrNotFound) {
return qrLoginPersistence{}, err
}
if err := s.Store.Cookies.Save(ctx, accountID, cookies, userID); err != nil {
if errors.Is(err, db.ErrForbidden) {
return qrLoginPersistence{}, errors.New("该账号ID已存在且不属于当前用户")
}
return qrLoginPersistence{}, err
}
s.markSuccessfulLogin(ctx, accountID, userID, loginMethodQRScan, "扫码登录成功")
if s.Store.Tokens != nil {
_ = s.Store.Tokens.Clear(ctx, accountID)
}
if d, err := s.Store.Cookies.GetDetails(ctx, accountID); err == nil {
s.refreshAccountProfile(ctx, d)
}
if s.Manager != nil && s.Store.Cookies.GetStatus(ctx, accountID) {
if err := s.Manager.Restart(ctx, accountID); err != nil && s.Logger != nil {
s.Logger.Warn("扫码登录后重启账号失败", "cookie_id", accountID, "err", err)
}
}
persisted := qrLoginPersistence{AccountID: accountID, IsNew: isNew}
s.qrPersisted[sessionID] = persisted
return persisted, nil
}
func cloneQRStatus(src map[string]any) map[string]any {
dst := make(map[string]any, len(src))
for k, v := range src {
dst[k] = v
}
return dst
}
func qrStatus(result map[string]any) string {
status, _ := result["status"].(string)
return status
}
func qrString(result map[string]any, key string) string {
value, _ := result[key].(string)
return strings.TrimSpace(value)
}
+169
View File
@@ -3,16 +3,56 @@ package server
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"xianyu-go/internal/db"
)
type fakeQRLoginService struct {
status map[string]any
generateErr error
completeCookies string
completeUNB string
completeErr error
}
func (f *fakeQRLoginService) GenerateQRCode(context.Context) (string, string, error) {
if f.generateErr != nil {
return "", "", f.generateErr
}
return "qr-session", "data:image/png;base64,abc", nil
}
func (f *fakeQRLoginService) GetSessionStatus(sessionID string) map[string]any {
if sessionID == "no-such-session" {
return map[string]any{"status": "not_found"}
}
out := make(map[string]any, len(f.status)+1)
for k, v := range f.status {
out[k] = v
}
if _, ok := out["session_id"]; !ok {
out["session_id"] = sessionID
}
return out
}
func (f *fakeQRLoginService) CompleteVerification(context.Context, string) (string, string, error) {
if f.completeErr != nil {
return "", "", f.completeErr
}
return f.completeCookies, f.completeUNB, nil
}
// TestGenerateQRLogin 生成扫码登录二维码。
func TestGenerateQRLogin(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{}
h := srv.Router()
cookie := loginHelper(t, h)
@@ -34,6 +74,7 @@ func TestGenerateQRLogin(t *testing.T) {
func TestCheckQRLoginStatusEmptySession(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{}
h := srv.Router()
cookie := loginHelper(t, h)
@@ -52,6 +93,7 @@ func TestCheckQRLoginStatusEmptySession(t *testing.T) {
func TestCompleteQRVerificationBadSession(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{completeErr: errors.New("会话不存在")}
h := srv.Router()
cookie := loginHelper(t, h)
@@ -69,6 +111,88 @@ func TestCompleteQRVerificationBadSession(t *testing.T) {
}
}
func TestQRLoginStatusPersistsSuccessIdempotently(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
srv.QRLogin = &fakeQRLoginService{status: map[string]any{
"status": "success",
"cookies": "unb=qr-new; _m_h5_tk=qr-token;",
"unb": "qr-new",
}}
h := srv.Router()
cookie := loginHelper(t, h)
for i := 0; i < 2; i++ {
req := httptest.NewRequest(http.MethodGet, "/qr-login/status/s1", nil)
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
var res map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
t.Fatalf("decode response: %v", err)
}
if res["success"] != true || res["account_id"] != "qr-new" {
t.Fatalf("扫码状态保存响应异常: %+v", res)
}
}
d, err := store.Cookies.GetDetails(context.Background(), "qr-new")
if err != nil {
t.Fatalf("GetDetails qr-new: %v", err)
}
if d.LoginMethod != "qr_scan" || d.LastLoginAt == 0 {
t.Fatalf("扫码登录应标记登录审计字段: %+v", d)
}
logs, err := store.LoginLogs.ListByCookie(context.Background(), "qr-new", 10)
if err != nil || len(logs) != 1 || logs[0].Status != "success" || logs[0].Method != "qr_scan" {
t.Fatalf("重复轮询不应重复记录登录日志: logs=%#v err=%v", logs, err)
}
}
func TestCompleteQRVerificationPersistsAndReenablesAccount(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
ctx := context.Background()
srv.Manager = nil
srv.QRLogin = &fakeQRLoginService{
completeCookies: "unb=acc1; _m_h5_tk=qr-fresh;",
completeUNB: "acc1",
}
if err := store.Cookies.SetStatusWithReason(ctx, "acc1", false, "token 失效"); err != nil {
t.Fatalf("SetStatusWithReason: %v", err)
}
if err := store.Tokens.Save(ctx, "acc1", "did", "token", 9999999999); err != nil {
t.Fatalf("Save token: %v", err)
}
h := srv.Router()
cookie := loginHelper(t, h)
req := httptest.NewRequest(http.MethodPost, "/qr-login/complete-verification/s1", nil)
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
var res map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
t.Fatalf("decode response: %v", err)
}
if res["success"] != true || res["account_id"] != "acc1" {
t.Fatalf("完成验证响应异常: %+v", res)
}
if !store.Cookies.GetStatus(ctx, "acc1") {
t.Fatal("扫码验证成功后应重新启用账号")
}
if _, err := store.Tokens.Get(ctx, "acc1"); !errors.Is(err, db.ErrNotFound) {
t.Fatalf("扫码验证成功后应清 token,got %v", err)
}
}
// TestKeywordsListAndDelete 关键字列表与删除(覆盖 listKeywords / listKeywordsWithItemID / listKeywordsWithType)。
func TestKeywordsListAndDelete(t *testing.T) {
srv, _, cleanup := newTestServer(t)
@@ -137,6 +261,51 @@ func TestAddKeywordBadJSON(t *testing.T) {
}
}
func TestReplaceKeywordsWithItemID(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
h := srv.Router()
cookie := loginHelper(t, h)
postBatch := func(body string) []map[string]any {
req := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("replace status=%d body=%s", rec.Code, rec.Body.String())
}
listReq := httptest.NewRequest(http.MethodGet, "/keywords-with-item-id/acc1", nil)
listReq.AddCookie(cookie)
listRec := httptest.NewRecorder()
h.ServeHTTP(listRec, listReq)
if listRec.Code != http.StatusOK {
t.Fatalf("list status=%d body=%s", listRec.Code, listRec.Body.String())
}
var rows []map[string]any
if err := json.Unmarshal(listRec.Body.Bytes(), &rows); err != nil {
t.Fatal(err)
}
return rows
}
rows := postBatch(`{"keywords":[{"keyword":"在吗","reply":"在的","item_id":""},{"keyword":"价格","reply":"50","item_id":"it1"}]}`)
if len(rows) != 2 || rows[1]["item_id"] != "it1" {
t.Fatalf("批量新增异常: %+v", rows)
}
rows = postBatch(`{"keywords":[{"keyword":"在吗","reply":"稍等","item_id":""}]}`)
if len(rows) != 1 || rows[0]["reply"] != "稍等" {
t.Fatalf("批量覆盖编辑异常: %+v", rows)
}
rows = postBatch(`{"keywords":[]}`)
if len(rows) != 0 {
t.Fatalf("空数组应清空关键词: %+v", rows)
}
}
// TestDeleteKeywordNotFound 不存在关键字 404。
func TestDeleteKeywordNotFound(t *testing.T) {
srv, _, cleanup := newTestServer(t)
+61 -23
View File
@@ -12,6 +12,7 @@ import (
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/go-chi/chi/v5"
@@ -28,20 +29,42 @@ import (
"xianyu-go/internal/xianyu/qrlogin"
)
type qrLoginService interface {
GenerateQRCode(ctx context.Context) (sessionID string, qrCodeURL string, err error)
GetSessionStatus(sessionID string) map[string]any
CompleteVerification(ctx context.Context, sessionID string) (cookies string, unb string, err error)
}
type qrLoginPersistence struct {
AccountID string
IsNew bool
}
// Server 聚合 HTTP 服务依赖。Automation 与 Notifier 由构造函数注入,
// 不再允许外部直接改字段,避免运行时被替换成 nil。
type Server struct {
Store *db.Store
Auth *auth.Service
Manager *account.Manager
automation *automation.Center
Browser *browser.Manager
notifier *notify.Notifier
MTop mtop.Client
QRLogin *qrlogin.Manager
Logger *slog.Logger
WebDir string // 前端静态资源目录(含 index.html)
Addr string
Store *db.Store
Auth *auth.Service
Manager *account.Manager
automation *automation.Center
Browser *browser.Manager
PasswordLogin passwordLoginRunner
notifier *notify.Notifier
MTop mtop.Client
QRLogin qrLoginService
Logger *slog.Logger
WebDir string // 前端静态资源目录(含 index.html)
Addr string
publishMu sync.Mutex
publishCancels map[string]context.CancelFunc
passwordMu sync.Mutex
passwordSessions map[string]*passwordLoginSession
passwordProcessing map[string]string
qrMu sync.Mutex
qrPersisted map[string]qrLoginPersistence
}
// New 构造。autoCenter/notifier 由调用方完成创建后注入(创建顺序:
@@ -57,20 +80,33 @@ func New(store *db.Store, manager *account.Manager, bm *browser.Manager, secure
})
}
return &Server{
Store: store,
Auth: &auth.Service{Store: store, Logger: logger, Secure: secure},
Manager: manager,
automation: autoCenter,
Browser: bm,
notifier: notifier,
MTop: mtop.NewClient(),
QRLogin: qrMgr,
Logger: logger,
WebDir: webDir,
Addr: addr,
Store: store,
Auth: &auth.Service{Store: store, Logger: logger, Secure: secure},
Manager: manager,
automation: autoCenter,
Browser: bm,
PasswordLogin: passwordLoginRunnerForBrowser(bm),
notifier: notifier,
MTop: mtop.NewClient(),
QRLogin: qrMgr,
Logger: logger,
WebDir: webDir,
Addr: addr,
publishCancels: make(map[string]context.CancelFunc),
passwordSessions: make(map[string]*passwordLoginSession),
passwordProcessing: make(map[string]string),
qrPersisted: make(map[string]qrLoginPersistence),
}
}
func passwordLoginRunnerForBrowser(bm *browser.Manager) passwordLoginRunner {
if bm == nil {
return nil
}
return bm
}
// mtopClient 返回注入的 mtop 客户端;未注入时退回默认 HTTP 实现(保证零值可用)。
func (s *Server) mtopClient() mtop.Client {
if s.MTop != nil {
@@ -110,6 +146,8 @@ func (s *Server) Router() http.Handler {
s.mountCookies(r)
// 扫码登录
s.mountQRLoginReal(r)
// 密码登录
s.mountPasswordLogin(r)
// 订单
s.mountOrdersReal(r)
// 订单分析(仪表盘)
@@ -275,7 +313,7 @@ func isAPIPath(path string) bool {
"/system-settings", "/ai-reply", "/ai-models",
"/user-settings",
"/item-reply", "/itemReplays",
"/qr-login",
"/qr-login", "/password-login",
"/static/", // 静态资源(由 /static/* handler 处理,不进 catch-all)
}
for _, p := range apiPrefixes {
+4 -2
View File
@@ -331,8 +331,9 @@ func (s *Server) mountUserReal(r chi.Router) {
func (s *Server) listUserSettings(w http.ResponseWriter, r *http.Request) {
sess := authSess(r)
keyCol := db.DialectQuote(s.Store.Dialect, "key")
rows, err := s.Store.DB.QueryContext(r.Context(),
`SELECT key, value FROM user_settings WHERE user_id=?`, sess.UserID)
`SELECT `+keyCol+`, value FROM user_settings WHERE user_id=?`, sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
@@ -356,8 +357,9 @@ func (s *Server) getUserSetting(w http.ResponseWriter, r *http.Request) {
sess := authSess(r)
key := chi.URLParam(r, "key")
var v string
keyCol := db.DialectQuote(s.Store.Dialect, "key")
err := s.Store.DB.QueryRowContext(r.Context(),
`SELECT value FROM user_settings WHERE user_id=? AND key=?`, sess.UserID, key).Scan(&v)
`SELECT value FROM user_settings WHERE user_id=? AND `+keyCol+`=?`, sess.UserID, key).Scan(&v)
if err != nil {
writeJSON(w, http.StatusOK, map[string]any{"value": ""})
return
@@ -0,0 +1,59 @@
import{r as d,b as fo,R as Sp}from"./react-vendor-DZnRGM0-.js";import{c as Z,g as Qt,u as cu,w as Ip,a as P,s as Ca,b as Te,t as Ep,p as re,d as Qe,e as q,f as kp,D as G,I as su,r as Xf,E as jp,h as Cp,i as Tp,j as ir,k as dn,l as $p,m as Mp,n as Dp,P as _p}from"./vendor-w5t2K9ux.js";var Np=["dangerouslySetInnerHTML","onCopy","onCopyCapture","onCut","onCutCapture","onPaste","onPasteCapture","onCompositionEnd","onCompositionEndCapture","onCompositionStart","onCompositionStartCapture","onCompositionUpdate","onCompositionUpdateCapture","onFocus","onFocusCapture","onBlur","onBlurCapture","onChange","onChangeCapture","onBeforeInput","onBeforeInputCapture","onInput","onInputCapture","onReset","onResetCapture","onSubmit","onSubmitCapture","onInvalid","onInvalidCapture","onLoad","onLoadCapture","onError","onErrorCapture","onKeyDown","onKeyDownCapture","onKeyPress","onKeyPressCapture","onKeyUp","onKeyUpCapture","onAbort","onAbortCapture","onCanPlay","onCanPlayCapture","onCanPlayThrough","onCanPlayThroughCapture","onDurationChange","onDurationChangeCapture","onEmptied","onEmptiedCapture","onEncrypted","onEncryptedCapture","onEnded","onEndedCapture","onLoadedData","onLoadedDataCapture","onLoadedMetadata","onLoadedMetadataCapture","onLoadStart","onLoadStartCapture","onPause","onPauseCapture","onPlay","onPlayCapture","onPlaying","onPlayingCapture","onProgress","onProgressCapture","onRateChange","onRateChangeCapture","onSeeked","onSeekedCapture","onSeeking","onSeekingCapture","onStalled","onStalledCapture","onSuspend","onSuspendCapture","onTimeUpdate","onTimeUpdateCapture","onVolumeChange","onVolumeChangeCapture","onWaiting","onWaitingCapture","onAuxClick","onAuxClickCapture","onClick","onClickCapture","onContextMenu","onContextMenuCapture","onDoubleClick","onDoubleClickCapture","onDrag","onDragCapture","onDragEnd","onDragEndCapture","onDragEnter","onDragEnterCapture","onDragExit","onDragExitCapture","onDragLeave","onDragLeaveCapture","onDragOver","onDragOverCapture","onDragStart","onDragStartCapture","onDrop","onDropCapture","onMouseDown","onMouseDownCapture","onMouseEnter","onMouseLeave","onMouseMove","onMouseMoveCapture","onMouseOut","onMouseOutCapture","onMouseOver","onMouseOverCapture","onMouseUp","onMouseUpCapture","onSelect","onSelectCapture","onTouchCancel","onTouchCancelCapture","onTouchEnd","onTouchEndCapture","onTouchMove","onTouchMoveCapture","onTouchStart","onTouchStartCapture","onPointerDown","onPointerDownCapture","onPointerMove","onPointerMoveCapture","onPointerUp","onPointerUpCapture","onPointerCancel","onPointerCancelCapture","onPointerEnter","onPointerEnterCapture","onPointerLeave","onPointerLeaveCapture","onPointerOver","onPointerOverCapture","onPointerOut","onPointerOutCapture","onGotPointerCapture","onGotPointerCaptureCapture","onLostPointerCapture","onLostPointerCaptureCapture","onScroll","onScrollCapture","onWheel","onWheelCapture","onAnimationStart","onAnimationStartCapture","onAnimationEnd","onAnimationEndCapture","onAnimationIteration","onAnimationIterationCapture","onTransitionEnd","onTransitionEndCapture"];function vo(e){if(typeof e!="string")return!1;var t=Np;return t.includes(e)}var Lp=["aria-activedescendant","aria-atomic","aria-autocomplete","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colspan","aria-controls","aria-current","aria-describedby","aria-details","aria-disabled","aria-errormessage","aria-expanded","aria-flowto","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext","className","color","height","id","lang","max","media","method","min","name","style","target","width","role","tabIndex","accentHeight","accumulate","additive","alignmentBaseline","allowReorder","alphabetic","amplitude","arabicForm","ascent","attributeName","attributeType","autoReverse","azimuth","baseFrequency","baselineShift","baseProfile","bbox","begin","bias","by","calcMode","capHeight","clip","clipPath","clipPathUnits","clipRule","colorInterpolation","colorInterpolationFilters","colorProfile","colorRendering","contentScriptType","contentStyleType","cursor","cx","cy","d","decelerate","descent","diffuseConstant","direction","display","divisor","dominantBaseline","dur","dx","dy","edgeMode","elevation","enableBackground","end","exponent","externalResourcesRequired","fill","fillOpacity","fillRule","filter","filterRes","filterUnits","floodColor","floodOpacity","focusable","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontStyle","fontVariant","fontWeight","format","from","fx","fy","g1","g2","glyphName","glyphOrientationHorizontal","glyphOrientationVertical","glyphRef","gLine truncated
A`).concat(i,",").concat(i,",0,1,1,").concat(2*o,",").concat(a,`
H`).concat(He,"M").concat(2*o,",").concat(a,`
A`).concat(i,",").concat(i,",0,1,1,").concat(o,",").concat(a),className:"recharts-legend-icon"});if(u==="rect")return d.createElement("path",{stroke:"none",fill:l,d:"M0,".concat(He/8,"h").concat(He,"v").concat(He*3/4,"h").concat(-He,"z"),className:"recharts-legend-icon"});if(d.isValidElement(t.legendIcon)){var c=wd({},t);return delete c.legendIcon,d.cloneElement(t.legendIcon,c)}return d.createElement(bd,{fill:l,cx:a,cy:a,size:He,sizeType:"diameter",type:u})}function qy(e){var t=e.payload,r=e.iconSize,n=e.layout,a=e.formatter,i=e.inactiveColor,o=e.iconType,l=e.labelStyle,u={x:0,y:0,width:He,height:He},c={display:n==="horizontal"?"inline-block":"block",marginRight:10},s={display:"inline-block",verticalAlign:"middle",marginRight:4};return t.map((f,v)=>{var h=f.formatter||a,m=Z({"recharts-legend-item":!0,["legend-item-".concat(v)]:!0,inactive:f.inactive});if(f.type==="none")return null;var p=typeof l=="object"?wd({},l):{};p.color=f.inactive?i:p.color||f.color;var y=h?h(f.value,f,v):f.value;return d.createElement("li",Zn({className:m,style:c,key:"legend-item-".concat(v)},hn(e,f,v)),d.createElement(ho,{width:r,height:r,viewBox:u,style:s,"aria-label":"".concat(f.value," legend icon")},d.createElement(Yy,{data:f,iconType:o,inactiveColor:i})),d.createElement("span",{className:"recharts-legend-item-text",style:p},y))})}var Xy=e=>{var t=Ae(e,Vy),r=t.payload,n=t.layout,a=t.align;if(!r||!r.length)return null;var i={padding:0,margin:0,textAlign:n==="horizontal"?a:"left"};return d.createElement("ul",{className:"recharts-default-legend",style:i},d.createElement(qy,Zn({},t,{payload:r})))};function Ad(e,t,r){return t===!0?cu(e,r):typeof t=="function"?cu(e,t):e}var bo=d.createContext(null),Zy=e=>e,ee=()=>{var e=d.useContext(bo);return e?e.store.dispatch:Zy},Fn=()=>{},Qy=()=>Fn,Jy=(e,t)=>e===t;function M(e){var t=d.useContext(bo),r=d.useMemo(()=>t?n=>{if(n!=null)return e(n)}:Fn,[t,e]);return Ip.useSyncExternalStoreWithSelector(t?t.subscription.addNestedSub:Qy,t?t.store.getState:Fn,t?t.store.getState:Fn,r,Jy)}var Pd=e=>e.legend.settings,eg=e=>e.legend.size,tg=e=>e.legend.payload,rg=P([tg,Pd],(e,t)=>{var r=t.itemSorter,n=e.flat(1);return r?Ca(n,r):n});function ng(){return M(rg)}function ag(e,t){return ug(e)||lg(e,t)||og(e,t)||ig()}function ig(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function og(e,t){if(e){if(typeof e=="string")return bu(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?bu(e,t):void 0}}function bu(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function lg(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function ug(e){if(Array.isArray(e))return e}var $n=1;function xu(e,t){return Math.abs(e.height-t.height)>$n||Math.abs(e.left-t.left)>$n||Math.abs(e.top-t.top)>$n||Math.abs(e.width-t.width)>$n}function wu(e){var t=e.getBoundingClientRect();return{height:t.height,left:t.left,top:t.top,width:t.width}}function Od(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=d.useState({height:0,left:0,top:0,width:0}),r=ag(t,2),n=r[0],a=r[1],i=d.useRef(null),o=d.useRef(n);o.current=n;var l=d.useCallback(u=>{if(i.current!=null&&(i.current.disconnect(),i.current=null),u!=null){var c=wu(u);if(xu(c,o.current)&&a(c),typeof ResizeObserver<"u"){var s=new ResizeObserver(()=>{var f=wu(u);xu(f,o.current)&&a(f)});s.observe(u),i.current=s}}},[...e]);return d.useEffect(()=>()=>{var u;(u=i.current)===null||u===void 0||u.disconnect()},[]),[n,l]}var cg={layoutType:"horizontal",width:0,height:0,margin:{top:5,right:5,bottom:5,left:5},scale:1},Sd=Te({name:"chartLayout",initialState:cg,reducers:{setLayout(e,t){e.layoutType=t.payload},setChartSize(e,t){e.width=t.payload.width,e.height=t.payload.height},setMargin(e,t){var r,n,a,i;e.margin.top=(r=t.payload.top)!==null&&r!==void 0?r:0,e.margin.right=(n=t.payload.right)!==null&&n!==void 0?n:0,e.margin.bottom=(a=t.payload.bottom)!==null&&a!==void 0?a:0,e.margin.left=(i=t.payload.left)!==null&&i!==void 0?i:0},setScale(e,t){e.scale=t.payload}}}),Da=Sd.actions,sg=Da.setMargin,fg=Da.setLayout,dg=Da.setChartSize,vg=Da.setScale,hg=Sd.reducer;function Id(e,t,r){return Array.isArray(e)&&e&&t+r!==0?e.slice(t,r+1):e}function H(e){return Number.isFinite(e)}function ct(e){return typeof e=="number"&&e>0&&Number.isFinite(e)}function Au(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function gr(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Au(Object(r),!0).forEach(function(n){mg(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Au(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function mg(e,t,r){return(t=pg(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function pg(e){var t=yg(e,"string");return typeof t=="symbol"?t:t+""}function yg(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Q(e,t,r){return ie(e)||ie(t)?r:ut(t)?Qt(e,t,r):typeof t=="function"?t(e):r}var gg=(e,t,r)=>{if(t&&r){var n=r.width,a=r.height,i=t.align,o=t.verticalAlign,l=t.layout;if((l==="vertical"||l==="horizontal"&&o==="middle")&&i!=="center"&&$(e[i]))return gr(gr({},e),{},{[i]:e[i]+(n||0)});if((l==="horizontal"||l==="vertical"&&i==="center")&&o!=="middle"&&$(e[o]))return gr(gr({},e),{},{[o]:e[o]+(a||0)})}return e},ft=(e,t)=>e==="horizontal"&&t==="xAxis"||e==="vertical"&&t==="yAxis"||e==="centric"&&t==="angleAxis"||e==="radial"&&t==="radiusAxis",Ed=(e,t,r,n)=>{if(n)return e.map(l=>l.coordinate);var a,i,o=e.map(l=>(l.coordinate===t&&(a=!0),l.coordinate===r&&(i=!0),l.coordinate));return a||o.push(t),i||o.push(r),o},kd=(e,t,r)=>{if(!e)return null;var n=e.duplicateDomain,a=e.type,i=e.range,o=e.scale,l=e.realScaleType,u=e.isCategorical,c=e.categoricalDomain,s=e.tickCount,f=e.ticks,v=e.niceTicks,h=e.axisType;if(!o)return null;var m=l==="scaleBand"&&o.bandwidth?o.bandwidth()/2:2,p=a==="category"&&o.bandwidth?o.bandwidth()/m:0;if(p=h==="angleAxis"&&i&&i.length>=2?we(i[0]-i[1])*2*p:p,f||v){var y=(f||v||[]).map((g,x)=>{var A=n?n.indexOf(g):g,w=o.map(A);return H(w)?{coordinate:w+p,value:g,offset:p,index:x}:null}).filter(_e);return y}return u&&c?c.map((g,x)=>{var A=o.map(g);return H(A)?{coordinate:A+p,value:g,index:x,offset:p}:null}).filter(_e):o.ticks&&s!=null?o.ticks(s).map((g,x)=>{var A=o.map(g);return H(A)?{coordinate:A+p,value:g,index:x,offset:p}:null}).filter(_e):o.domain().map((g,x Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Jg(e,t){if(e){if(typeof e=="string")return Tu(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Tu(e,t):void 0}}function Tu(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function eb(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function tb(e){if(Array.isArray(e))return e}function rb(e,t){if(e==null)return{};var r,n,a=nb(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function nb(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}var Dd=d.createContext(it.initialDimension);function ab(e){return ct(e.width)&&ct(e.height)}function _d(e){var t=e.children,r=e.width,n=e.height,a=d.useMemo(()=>({width:r,height:n}),[r,n]);return ab(a)?d.createElement(Dd.Provider,{value:a},t):null}var wo=()=>d.useContext(Dd),ib=d.forwardRef((e,t)=>{var r=e.aspect,n=e.initialDimension,a=n===void 0?it.initialDimension:n,i=e.width,o=e.height,l=e.minWidth,u=l===void 0?it.minWidth:l,c=e.minHeight,s=e.maxHeight,f=e.children,v=e.debounce,h=v===void 0?it.debounce:v,m=e.id,p=e.className,y=e.onResize,g=e.style,x=g===void 0?{}:g,A=rb(e,Gg),w=d.useRef(null),O=d.useRef();O.current=y,d.useImperativeHandle(t,()=>w.current);var b=d.useState({containerWidth:a.width,containerHeight:a.height}),S=Zg(b,2),I=S[0],k=S[1],E=d.useCallback((W,F)=>{k(L=>{var V=Math.round(W),K=Math.round(F);return L.containerWidth===V&&L.containerHeight===K?L:{containerWidth:V,containerHeight:K}})},[]);d.useEffect(()=>{if(w.current==null||typeof ResizeObserver>"u")return or;var W=le=>{var de,ae=le[0];if(ae!=null){var Me=ae.contentRect,Be=Me.width,qe=Me.height;E(Be,qe),(de=O.current)===null||de===void 0||de.call(O,Be,qe)}};h>0&&(W=Ep(W,h,{trailing:!0,leading:!1}));var F=new ResizeObserver(W),L=w.current.getBoundingClientRect(),V=L.width,K=L.height;return E(V,K),F.observe(w.current),()=>{F.disconnect()}},[E,h]);var T=I.containerWidth,j=I.containerHeight;Qn(!r||r>0,"The aspect(%s) must be greater than zero.",r);var N=Md(T,j,{width:i,height:o,aspect:r,maxHeight:s}),_=N.calculatedWidth,R=N.calculatedHeight;return Qn(T<0||j<0||_!=null&&_>0||R!=null&&R>0,`The width(%s) and height(%s) of chart should be greater than 0,
please check the style of container, or the props width(%s) and height(%s),
or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the
height and width.`,_,R,i,o,u,c,r),d.createElement("div",Jn({id:m?"".concat(m):void 0,className:Z("recharts-responsive-container",p),style:Cu(Cu({},x),{},{width:i,height:o,minWidth:u,minHeight:c,maxHeight:s}),ref:w},A),d.createElement("div",{style:Hg({width:i,height:o})},d.createElement(_d,{width:_,height:R},f)))}),lD=d.forwardRef((e,t)=>{var r=wo();if(ct(r.width)&&ct(r.height))return e.children;var n=Vg({width:e.width,height:e.height,aspect:e.aspect}),a=n.width,i=n.height,o=Md(void 0,void 0,{width:a,height:i,aspect:e.aspect,maxHeight:e.maxHeight}),l=o.calculatedWidth,u=o.calculatedHeight;return $(l)&&$(u)?d.createElement(_d,{width:l,height:u},e.children):d.createElement(ib,Jn({},e,{width:a,height:i,ref:t}))});function Ao(e){if(e)return{x:e.x,y:e.y,upperWidth:"upperWidth"in e?e.upperWidth:e.width,lowerWidth:"lowerWidth"in e?e.lowerWidth:e.width,width:e.width,height:e.height}}var Ba=()=>{var e,t=$e(),r=M(Bg),n=M(Ra),a=(e=M(La))===null||e===void 0?void 0:e.padding;return!t||!n||!a?r:{width:n.width-a.left-a.right,height:n.height-a.top-a.bottom,x:a.left,y:a.top}},ob={top:0,bottom:0,left:0,right:0,width:0,height:0,brushBottom:0},Nd=()=>{var e;return(e=M(ge))!==null&&e!==void 0?e:ob},Po=()=>M(At),Oo=()=>M(Pt),lb=()=>M(e=>e.layout.margin),Y=e=>e.layout.layoutType,lr=()=>M(Y),So=()=>{var e=lr();if(e==="horizontal"||e==="vertical")return e},Io=e=>{var t=e.layout.layoutType;if(t==="centric"||t==="radial")return t},ub=()=>M(Io),cb=()=>{var e=lr();return e!==void 0},pn=e=>{var t=ee(),r=$e(),n=e.width,a=e.height,i=wo(),o=n,l=a;return i&&(o=i.width>0?i.width:n,l=i.height>0?i.height:a),d.useEffect(()=>{!r&&ct(o)&&ct(l)&&t(dg({width:o,height:l}))},[t,r,o,l]),null},sb={settings:{layout:"horizontal",align:"center",verticalAlign:"bottom",itemSorter:"value"},size:{width:0,height:0},payload:[]},Ld=Te({name:"legend",initialState:sb,reducers:{setLegendSize(e,t){e.size.width=t.payload.width,e.size.height=t.payload.height},setLegendSettings(e,t){e.settings.align=t.payload.align,e.settings.layout=t.payload.layout,e.settings.verticalAlign=t.payload.verticalAlign,e.settings.itemSorter=t.payload.itemSorter},addLegendPayload:{reducer(e,t){e.payload.push(q(t.payload))},prepare:re()},replaceLegendPayload:{reducer(e,t){var r=t.payload,n=r.prev,a=r.next,i=Qe(e).payload.indexOf(q(n));i>-1&&(e.payload[i]=q(a))},prepare:re()},removeLegendPayload:{reducer(e,t){var r=Qe(e).payload.indexOf(q(t.payload));r>-1&&e.payload.splice(r,1)},prepare:re()}}}),yn=Ld.actions,$u=yn.setLegendSize,fb=yn.setLegendSettings,Rd=yn.addLegendPayload,Bd=yn.replaceLegendPayload,zd=yn.removeLegendPayload,db=Ld.reducer,vb=new Set(["axisLine","tickLine","activeBar","activeDot","activeLabel","activeShape","allowEscapeViewBox","background","cursor","dot","label","line","margin","padding","position","shape","style","tick","wrapperStyle","radius","throttledEvents"]);function hb(e,t){return e==null&&t==null?!0:typeof e=="number"&&typeof t=="number"?e===t||e!==e&&t!==t:e===t}function Tr(e,t){var r=new Set([...Object.keys(e),...Object.keys(t)]);for(var n of r)if(vb.has(n)){if(e[n]==null&&t[n]==null)continue;if(!kp(e[n],t[n]))return!1}else if(!hb(e[n],t[n]))return!1;return!0}var mb=["contextPayload"];function Bi(){return Bi=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Bi.apply(null,arguments)}function pb(e,t){return xb(e)||bb(e,t)||gb(e,t)||yb()}function yb(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function gb(e,t){if(e){if(typeof e=="string")return Mu(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Mu(e,t):void 0}}function Mu(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function bb(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function xb(e){if(Array.isArray(e))return e}function Du(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Pr(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Du(Object(r),!0).forEach(function(n){wb(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Du(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function wb(e,t,r){return(t=Ab(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Ab(e){var t=Pb(e,"string");return typeof t=="symbol"?t:t+""}function Pb(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Ob(e,t){if(e==null)return{};var r,n,a=Sb(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function Sb(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}function Ib(e){return e.value}function Eb(e){var t=e.contextPayload,r=Ob(e,mb),n=Ad(t,e.payloadUniqBy,Ib),a=Pr(Pr({},r),{},{payload:n});return d.isValidElement(e.content)?d.cloneElement(e.content,a):typeof e.content=="function"?d.createElement(e.content,a):d.createElement(Xy,a)}function kb(e,t,r,n,a,i){var o=t.layout,l=t.align,u=t.verticalAlign,c,s;return(!e||(e.left===void 0||e.left===null)&&(e.right===void 0||e.right===null))&&(l==="center"&&o==="vertical"?c={left:((n||0)-i.width)/2}:c=l==="right"?{right:r&&r.right||0}:{left:r&&r.left||0}),(!e||(e.top===void 0||e.top===null)&&(e.bottom===void 0||e.bottom===null))&&(u==="middle"?s={top:((a||0)-i.height)/2}:s=u==="bottom"?{bottom:r&&r.bottom||0}:{top:r&&r.top||0}),Pr(Pr({},c),s)}function jb(e){var t=e.align,r=e.layout,n=e.verticalAlign,a=e.itemSorter,i=ee();return d.useLayoutEffect(()=>{i(fb({align:t,layout:r,verticalAlign:n,itemSorter:a}))},[i,t,r,n,a]),null}function Cb(e){var t=e.width,r=e.height,n=ee();return d.useLayoutEffect(()=>{n($u({width:t,height:r}))},[n,t,r]),d.useLayoutEffect(()=>()=>{n($u({width:0,height:0}))},[n]),null}function Tb(e,t,r,n){return e==="vertical"&&t!=null?{height:t}:e==="horizontal"?{width:r||n}:null}var $b={align:"center",iconSize:14,inactiveColor:"#ccc",itemSorter:"value",labelStyle:{},layout:"horizontal",verticalAlign:"bottom"};function Mb(e){var t=Ae(e,$b),r=ng(),n=Vp(),a=lb(),i=t.width,o=t.height,l=t.wrapperStyle,u=t.portal,c=Od([r]),s=pb(c,2),f=s[0],v=s[1],h=Po(),m=Oo();if(h==null||m==null)return null;var p=h-((a==null?void 0:a.left)||0)-((a==null?void 0:a.right)||0),y=Tb(t.layout,o,i,p),g=u?l:Pr(Pr({position:"absolute",width:(y==null?void 0:y.width)||i||"auto",height:(y==null?void 0:y.height)||o||"auto"},kb(l,t,a,h,m,f)),l),x=u??n;if(x==null||r==null)return null;var A=d.createElement("div",{className:"recharts-legend-wrapper",style:g,ref:v},d.createElement(jb,{layout:t.layout,align:t.align,verticalAlign:t.verticalAlign,itemSorter:t.itemSorter}),!u&&d.createElement(Cb,{width:f.width,height:f.height}),d.createElement(Eb,Bi({},t,y,{margin:a,chartWidth:h,chartHeight:m,contextPayload:r})));return fo.createPortal(A,x)}var Db=d.memo(Mb,Tr);Db.displayName="Legend";function zi(){return zi=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},zi.apply(null,arguments)}function _u(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Kr(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?_u(Object(r),!0).forEach(func Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function zb(e,t){if(e){if(typeof e=="string")return Nu(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Nu(e,t):void 0}}function Nu(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Kb(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function Wb(e){if(Array.isArray(e))return e}function Fb(e){return Array.isArray(e)&&ut(e[0])&&ut(e[1])?e.join(" ~ "):e}var fr={separator:" : ",contentStyle:{margin:0,padding:10,backgroundColor:"#fff",border:"1px solid #ccc",whiteSpace:"nowrap"},itemStyle:{display:"block",paddingTop:4,paddingBottom:4,color:"#000"},labelStyle:{},accessibilityLayer:!1};function Ub(e,t){return t==null?e:Ca(e,t)}var Hb=e=>{var t=e.separator,r=t===void 0?fr.separator:t,n=e.contentStyle,a=e.itemStyle,i=e.labelStyle,o=i===void 0?fr.labelStyle:i,l=e.payload,u=e.formatter,c=e.itemSorter,s=e.wrapperClassName,f=e.labelClassName,v=e.label,h=e.labelFormatter,m=e.accessibilityLayer,p=m===void 0?fr.accessibilityLayer:m,y=()=>{if(l&&l.length){var I={padding:0,margin:0},k=Ub(l,c),E=k.map((T,j)=>{if(!T||T.type==="none")return null;var N=T.formatter||u||Fb,_=T.value,R=T.name,W=_,F=R;if(N){var L=N(_,R,T,j,l);if(Array.isArray(L)){var V=Rb(L,2);W=V[0],F=V[1]}else if(L!=null)W=L;else return null}var K=Kr(Kr({},fr.itemStyle),{},{color:T.color||fr.itemStyle.color},a);return d.createElement("li",{className:"recharts-tooltip-item",key:"tooltip-item-".concat(j),style:K},ut(F)?d.createElement("span",{className:"recharts-tooltip-item-name"},F):null,ut(F)?d.createElement("span",{className:"recharts-tooltip-item-separator"},r):null,d.createElement("span",{className:"recharts-tooltip-item-value"},W),d.createElement("span",{className:"recharts-tooltip-item-unit"},T.unit||""))});return d.createElement("ul",{className:"recharts-tooltip-item-list",style:I},E)}return null},g=Kr(Kr({},fr.contentStyle),n),x=Kr({margin:0},o),A=!ie(v),w=A?v:"",O=Z("recharts-default-tooltip",s),b=Z("recharts-tooltip-label",f);A&&h&&l!==void 0&&l!==null&&(w=h(v,l));var S=p?{role:"status","aria-live":"assertive"}:{};return d.createElement("div",zi({className:O,style:g},S),d.createElement("p",{className:b,style:x},d.isValidElement(w)?w:"".concat(w)),y())},Wr="recharts-tooltip-wrapper",Vb={visibility:"hidden"};function Gb(e){var t=e.coordinate,r=e.translateX,n=e.translateY;return Z(Wr,{["".concat(Wr,"-right")]:$(r)&&t&&$(t.x)&&r>=t.x,["".concat(Wr,"-left")]:$(r)&&t&&$(t.x)&&r<t.x,["".concat(Wr,"-bottom")]:$(n)&&t&&$(t.y)&&n>=t.y,["".concat(Wr,"-top")]:$(n)&&t&&$(t.y)&&n<t.y})}function Lu(e){var t=e.allowEscapeViewBox,r=e.coordinate,n=e.key,a=e.offset,i=e.position,o=e.reverseDirection,l=e.tooltipDimension,u=e.viewBox,c=e.viewBoxDimension;if(i&&$(i[n]))return i[n];var s=r[n]-l-(a>0?a:0),f=r[n]+a;if(t[n])return o[n]?s:f;var v=u[n];if(v==null)return 0;if(o[n]){var h=s,m=v;return h<m?Math.max(f,v):Math.max(s,v)}if(c==null)return 0;var p=f+l,y=v+c;return p>y?Math.max(s,v):Math.max(f,v)}function Yb(e){var t=e.translateX,r=e.translateY,n=e.useTranslate3d;return{transform:n?"translate3d(".concat(t,"px, ").concat(r,"px, 0)"):"translate(".concat(t,"px, ").concat(r,"px)")}}function qb(e){var t=e.allowEscapeViewBox,r=e.coordinate,n=e.offsetTop,a=e.offsetLeft,i=e.position,o=e.reverseDirection,l=e.tooltipBox,u=e.useTranslate3d,c=e.viewBox,s,f,v;return l.height>0&&l.width>0&&r?(f=Lu({allowEscapeViewBox:t,coordinate:r,key:"x",offset:a,position:i,reverseDirection:o,tooltipDimension:l.width,viewBox:c,viewBoxDimension:c.width}),v=Lu({allowEscapeViewBox:t,coordinate:r,key:"y",offset:n,position:i,reverseDirection:o,tooltipDimension:l.height,viewBox:c,viewBoxDimension:c.height}),s=Yb({translateX:f,translateY:v,useTranslate3d:u})):s=Vb,{cssProperties:s,cssClasses:Gb({translateX:f,translateY:v,coordinate:r})}}var Xb=()=>!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout),gn={isSsr:Xb()};function Zb(e,t){return t0(e)||e0(e,t)||Jb(e,t)||Qb()}function Qb(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Jb(e,t){if(e){if(typeof e=="string")return Ru(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Ru(e,t):void 0}}function Ru(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function e0(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function t0(e){if(Array.isArray(e))return e}function Kd(){var e=d.useState(()=>gn.isSsr||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches),t=Zb(e,2),r=t[0],n=t[1];return d.useEffect(()=>{if(window.matchMedia){var a=window.matchMedia("(prefers-reduced-motion: reduce)"),i=()=>{n(a.matches)};return a.addEventListener("change",i),()=>{a.removeEventListener("change",i)}}},[]),r}function Bu(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function dr(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Bu(Object(r),!0).forEach(function(n){r0(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Bu(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function r0(e,t,r){return(t=n0(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function n0(e){var t=a0(e,"string");return typeof t=="symbol"?t:t+""}function a0(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function i0(e,t){return c0(e)||u0(e,t)||l0(e,t)||o0()}function o0(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function l0(e,t){if(e){if(typeof e=="string")return zu(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?zu(e,t):void 0}}function zu(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function u0(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function c0(e){if(Array.isArray(e))return e}function s0(e){if(!(e.prefersReducedMotion&&e.isAnimationActive==="auto")&&e.isAnimationActive&&e.active){var t=typeof e.animationEasing=="string"?e.animationEasing:"ease";return"transform ".concat(e.animationDuration,"ms ").concat(t)}}function f0(e){var t,r,n,a,i,o,l=Kd(),u=d.useState(()=>({dismissed:!1,dismissedAtCoordinate:{x:0,y:0}})),c=i0(u,2),s=c[0],f=c[1];d.useEffect(()=>{var g=x=>{if(x.key==="Escape"){var A,w,O,b;f({dismissed:!0,dismissedAtCoordinate:{x:(A=(w=e.coordinate)===null||w===void 0?void 0:w.x)!==null&&A!==void 0?A:0,y:(O=(b=e.coordinate)===null||b===void 0?void 0:b.y)!==null&&O!==void 0?O:0}})}};return document.addEventListener("keydown",g),()=>{document.removeEventListener("keydown",g)}},[(t=e.coordinate)===null||t===void 0?void 0:t.x,(r=e.coordinate)===null||r===void 0?void 0:r.y]),s.dismissed&&(((n=(a=e.coordinate)===null||a===void 0?void 0:a.x)!==null&&n!==void 0?n:0)!==s.dismissedAtCoordinate.x||((i=(o=e.coordinate)===null||o===void 0?void 0:o.y)!==null&&i!==void 0?i:0)!==s.dismissedAtCoordinate.y)&&f(dr(dr({},s),{},{dismissed:!1}));var v=qb({allowEscapeViewBox:e.allowEscapeViewBox,coordinate:e.coordinate,offsetLeft:typeof e.offset=="number"?e.offset:e.offset.x,offsetTop:typeof e.offset=="number"?e.offset:e.offset.y,position:e.position,reverseDirection:e.reverseDirection,tooltipBox:{height:e.lastBoundingBox.height,width:e.lastBoundingBox.width},useTranslate3d:e.useTranslate3d,viewBox:e.viewBox}),h=v.cssClasses,m=v.cssProperties,p=e.hasPortalFromProps?{}:dr(dr({transition:s0({prefersReducedMotion:l,isAnimationActive:e.isAnimationActive,active:e.active,animationDuration:e.animationDuration,animationEasing:e.animationEasing})},m),{},{pointerEvents:"none",position:"absolute",top:0,left:0}),y=dr(dr({},p),{},{visibility:!s.dismissed&&e.active&&e.hasPayload?"visible":"hidden"},e.wrapperStyle);return d.createElement("div",{xmlns:"http://www.w3.org/1999/xhtml",tabIndex:-1,className:h,style:y,ref:e.innerRef},e.children)}var d0=d.memo(f0),Wd=()=>{var e;return(e=M(t=>t.rootProps.accessibilityLayer))!==null&&e!==void 0?e:!0};function Ki(){return Ki=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Ki.apply(null,arguments)}function Ku(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Wu(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Ku(Object(r),!0).forEach(function(n){v0(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Ku(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function v0(e,t,r){return(t=h0(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function h0(e){var t=m0(e,"string");return typeof t=="symbol"?t:t+""}function m0(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Fu={curveBasisClosed:fy,curveBasisOpen:dy,curveBasis:sy,curveBumpX:Xp,curveBumpY:Zp,curveLinearClosed:vy,curveLinear:$a,curveMonotoneX:hy,curveMonotoneY:my,curveNatural:py,curveStep:yy,curveStepAfter:by,curveStepBefore:gy},ea=e=>H(e.x)&&H(e.y),Uu=e=>e.base!=null&&ea(e.base)&&ea(e),Fr=e=>e.x,Ur=e=>e.y,p0=(e,t)=>{if(typeof e=="function")return e;var r="curve".concat(vn(e));if((r==="curveMonotone"||r==="curveBump")&&t){var n=Fu["".concat(r).concat(t==="vertical"?"Y":"X")];if(n)return n}return Fu[r]||$a},Hu={connectNulls:!1,type:"linear"},y0=e=>{var t=e.type,r=t===void 0?Hu.type:t,n=e.points,a=n===void 0?[]:n,i=e.baseLine,o=e.layout,l=e.connectNulls,u=l===void 0?Hu.connectNulls:l,c=p0(r,o),s=u?a.filter(ea):a;if(Array.isArray(i)){var f,v=a.map((g,x)=>Wu(Wu({},g),{},{base:i[x]}));o==="vertical"?f=Tn().y(Ur).x1(Fr).x0(g Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function H0(e,t){if(e){if(typeof e=="string")return Qu(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Qu(e,t):void 0}}function Qu(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function V0(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function G0(e){if(Array.isArray(e))return e}var Y0={begin:0,duration:1e3,easing:"ease",isActive:!0,canBegin:!0,onAnimationEnd:()=>{},onAnimationStart:()=>{}},Ju=0,pi=1;function Vd(e){var t=Ae(e,Y0),r=t.animationId,n=t.isActive,a=t.canBegin,i=t.duration,o=t.easing,l=t.begin,u=t.onAnimationEnd,c=t.onAnimationStart,s=t.children,f=Kd(),v=n==="auto"?!gn.isSsr&&!f:n,h=_0(t.animationController),m=d.useState(v?Ju:pi),p=F0(m,2),y=p[0],g=p[1];return d.useEffect(()=>{v||g(pi)},[v]),d.useEffect(()=>{var x=M0(o);if(!v||!a||x==null)return or;var A=new W0,w=new K0({animationId:r,easing:x,animationDuration:i,animationBegin:l,onAnimationStart:c,onAnimationEnd:u,from:Ju,to:pi});return h(A,w,g)},[h,r,v,a,i,o,l,c,u]),s(Number(y))}function Gd(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"animation-",r=d.useRef(nn(t)),n=d.useRef(e);return n.current!==e&&(r.current=nn(t),n.current=e),r.current}var q0=e=>e.replace(/([A-Z])/g,t=>"-".concat(t.toLowerCase())),X0=(e,t,r)=>e.map(n=>"".concat(q0(n)," ").concat(t,"ms ").concat(r)).join(","),Z0=["radius"],Q0=["radius"],ec,tc,rc,nc,ac,ic,oc,lc,uc,cc;function sc(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function fc(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?sc(Object(r),!0).forEach(function(n){J0(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):sc(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function J0(e,t,r){return(t=ex(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ex(e){var t=tx(e,"string");return typeof t=="symbol"?t:t+""}function tx(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function ra(){return ra=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ra.apply(null,arguments)}function dc(e,t){if(e==null)return{};var r,n,a=rx(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function rx(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}function nx(e,t){return lx(e)||ox(e,t)||ix(e,t)||ax()}function ax(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ix(e,t){if(e){if(typeof e=="string")return vc(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?vc(e,t):void 0}}function vc(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ox(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function lx(e){if(Array.isArray(e))return e}function rt(e,t){return t||(t=e.slice(0)),Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}}))}var hc=(e,t,r,n,a)=>{var i=Tt(r),o=Tt(n),l=Math.min(Math.abs(i)/2,Math.abs(o)/2),u=o>=0?1:-1,c=i>=0?1:-1,s=o>=0&&i>=0||o<0&&i<0?1:0,f;if(l>0&&Array.isArray(a)){for(var v=[0,0,0,0],h=0,m=4;h<m;h++){var p,y=(p=a[h])!==null&&p!==void 0?p:0;v[h]=y>l?l:y}f=Se(ec||(ec=rt(["M",",",""])),e,t+u*v[0]),v[0]>0&&(f+=Se(tc||(tc=rt(["A ",",",",0,0,",",",",",""])),v[0],v[0],s,e+c*v[0],t)),f+=Se(rc||(rc=rt(["L ",",",""])),e+r-c*v[1],t),v[1]>0&&(f+=Se(nc||(nc=rt(["A ",",",",0,0,",`,
`,",",""])),v[1],v[1],s,e+r,t+u*v[1])),f+=Se(ac||(ac=rt(["L ",",",""])),e+r,t+n-u*v[2]),v[2]>0&&(f+=Se(ic||(ic=rt(["A ",",",",0,0,",`,
`,",",""])),v[2],v[2],s,e+r-c*v[2],t+n)),f+=Se(oc||(oc=rt(["L ",",",""])),e+c*v[3],t+n),v[3]>0&&(f+=Se(lc||(lc=rt(["A ",",",",0,0,",`,
`,",",""])),v[3],v[3],s,e,t+n-u*v[3])),f+="Z"}else if(l>0&&a===+a&&a>0){var g=Math.min(l,a);f=Se(uc||(uc=rt(["M ",",",`
A `,",",",0,0,",",",",",`
L `,",",`
A `,",",",0,0,",",",",",`
L `,",",`
A `,",",",0,0,",",",",",`
L `,",",`
A `,",",",0,0,",",",","," Z"])),e,t+u*g,g,g,s,e+c*g,t,e+r-c*g,t,g,g,s,e+r,t+u*g,e+r,t+n-u*g,g,g,s,e+r-c*g,t+n,e+c*g,t+n,g,g,s,e,t+n-u*g)}else f=Se(cc||(cc=rt(["M ",","," h "," v "," h "," Z"])),e,t,r,n,-r);return f},mc={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},Yd=e=>{var t=Ae(e,mc),r=d.useRef(null),n=d.useState(-1),a=nx(n,2),i=a[0],o=a[1];d.useEffect(()=>{if(r.current&&r.current.getTotalLength)try{var L=r.current.getTotalLength();L&&o(L)}catch{}},[]);var l=t.x,u=t.y,c=t.width,s=t.height,f=t.radius,v=t.className,h=t.animationEasing,m=t.animationDuration,p=t.animationBegin,y=t.isAnimationActive,g=t.isUpdateAnimationActive,x=d.useRef(c),A=d.useRef(s),w=d.useRef(l),O=d.useRef(u),b=d.useMemo(()=>({x:l,y:u,width:c,height:s,radius:f}),[l,u,c,s,f]),S=Gd(b,"rectangle-");if(l!==+l||u!==+u||c!==+c||s!==+s||c===0||s===0)return null;var I=Z("recharts-rectangle",v);if(!g){var k=Ke(t);k.radius;var E=dc(k,Z0);return d.createElement("path",ra({},E,{x:Tt(l),y:Tt(u),width:Tt(c),height:Tt(s),radius:typeof f=="number"?f:void 0,className:I,d:hc(l,u,c,s,f)}))}var T=x.current,j=A.current,N=w.current,_=O.current,R="0px ".concat(i===-1?1:i,"px"),W="".concat(i,"px ").concat(i,"px"),F=X0(["strokeDasharray"],m,typeof h=="string"?h:mc.animationEasing);return d.createElement(Vd,{animationId:S,key:S,canBegin:i>0,duration:m,easing:h,isActive:g,begin:p},L=>{var V=ue(T,c,L),K=ue(j,s,L),le=ue(N,l,L),de=ue(_,u,L);r.current&&(x.current=V,A.current=K,w.current=le,O.current=de);var ae;y?L>0?ae={transition:F,strokeDasharray:W}:ae={strokeDasharray:R}:ae={strokeDasharray:W};var Me=Ke(t);Me.radius;var Be=dc(Me,Q0);return d.createElement("path",ra({},Be,{radius:typeof f=="number"?f:void 0,className:I,d:hc(le,de,V,K,f),ref:r,style:fc(fc({},ae),t.style)}))})};function pc(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function yc(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?pc(Object(r),!0).forEach(function(n){ux(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):pc(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function ux(e,t,r){return(t=cx(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function cx(e){var t=sx(e,"string");return typeof t=="symbol"?t:t+""}function sx(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var na=Math.PI/180,fx=e=>e*180/Math.PI,ve=(e,t,r,n)=>({x:e+Math.cos(-na*n)*r,y:t+Math.sin(-na*n)*r}),qd=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(t-(n.left||0)-(n.right||0)),Math.abs(r-(n.top||0)-(n.bottom||0)))/2},dx=(e,t)=>{var r=e.x,n=e.y,a=t.x,i=t.y;return Math.sqrt((r-a)**2+(n-i)**2)},vx=(e,t)=>{var r=e.x,n=e.y,a=t.cx,i=t.cy,o=dx({x:r,y:n},{x:a,y:i});if(o<=0)return{radius:o,angle:0};var l=(r-a)/o,u=Math.acos(l);return n>i&&(u=2*Math.PI-u),{radius:o,angle:fx(u),angleInRadian:u}},hx=e=>{var t=e.startAngle,r=e.endAngle,n=Math.floor(t/360),a=Math.floor(r/360),i=Math.min(n,a);return{startAngle:t-i*360,endAngle:r-i*360}},mx=(e,t)=>{var r=t.startAngle,n=t.endAngle,a=Math.floor(r/360),i=Math.floor(n/360),o=Math.min(a,i);return e+o*360},px=(e,t)=>{var r=e.relativeX,n=e.relativeY,a=vx({x:r,y:n},t),i=a.radius,o=a.angle,l=t.innerRadius,u=t.outerRadius;if(i<l||i>u||i===0)return null;var c=hx(t),s=c.startAngle,f=c.endAngle,v=o,h;if(s<=f){for(;v>f;)v-=360;for(;v<s;)v+=360;h=v>=s&&v<=f}else{for(;v>s;)v-=360;for(;v<f;)v+=360;h=v>=f&&v<=s}return h?yc(yc({},t),{},{radius:i,angle:mx(v,t)}):null};function Xd(e){var t=e.cx,r=e.cy,n=e.radius,a=e.startAngle,i=e.endAngle,o=ve(t,r,n,a),l=ve(t,r,n,i);return{points:[o,l],cx:t,cy:r,radius:n,startAngle:a,endAngle:i}}var gc,bc,xc,wc,Ac,Pc,Oc;function Fi(){return Fi=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Fi.apply(null,arguments)}function Gt(e,t){return t||(t=e.slice(0)),Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}}))}var yx=(e,t)=>{var r=we(t-e),n=Math.min(Math.abs(t-e),359.999);return r*n},Dn=e=>{var t=e.cx,r=e.cy,n=e.radius,a=e.angle,i=e.sign,o=e.isExternal,l=e.cornerRadius,u=e.cornerIsExternal,c=l*(o?1:-1)+n,s=Math.asin(l/c)/na,f=u?a:a+i*s,v=ve(t,r,c,f),h=ve(t,r,n,f),m=u?a-i*s:a,p=ve(t,r,c*Math.cos(s*na),m);return{center:v,circleTangency:h,lineTangency:p,theta:s}},Zd=e=>{var t=e.cx,r=e.cy,n=e.innerRadius,a=e.outerR Line truncated
A `,",",`,0,
`,",",`,
`,",",`
`])),c.x,c.y,a,a,+(Math.abs(l)>180),+(i>u),s.x,s.y);if(n>0){var v=ve(t,r,n,i),h=ve(t,r,n,u);f+=Se(bc||(bc=Gt(["L ",",",`
A `,",",`,0,
`,",",`,
`,","," Z"])),h.x,h.y,n,n,+(Math.abs(l)>180),+(i<=u),v.x,v.y)}else f+=Se(xc||(xc=Gt(["L ",","," Z"])),t,r);return f},gx=e=>{var t=e.cx,r=e.cy,n=e.innerRadius,a=e.outerRadius,i=e.cornerRadius,o=e.forceCornerRadius,l=e.cornerIsExternal,u=e.startAngle,c=e.endAngle,s=we(c-u),f=Dn({cx:t,cy:r,radius:a,angle:u,sign:s,cornerRadius:i,cornerIsExternal:l}),v=f.circleTangency,h=f.lineTangency,m=f.theta,p=Dn({cx:t,cy:r,radius:a,angle:c,sign:-s,cornerRadius:i,cornerIsExternal:l}),y=p.circleTangency,g=p.lineTangency,x=p.theta,A=l?Math.abs(u-c):Math.abs(u-c)-m-x;if(A<0)return o?Se(wc||(wc=Gt(["M ",",",`
a`,",",",0,0,1,",`,0
a`,",",",0,0,1,",`,0
`])),h.x,h.y,i,i,i*2,i,i,-i*2):Zd({cx:t,cy:r,innerRadius:n,outerRadius:a,startAngle:u,endAngle:c});var w=Se(Ac||(Ac=Gt(["M ",",",`
A`,",",",0,0,",",",",",`
A`,",",",0,",",",",",",",`
A`,",",",0,0,",",",",",`
`])),h.x,h.y,i,i,+(s<0),v.x,v.y,a,a,+(A>180),+(s<0),y.x,y.y,i,i,+(s<0),g.x,g.y);if(n>0){var O=Dn({cx:t,cy:r,radius:n,angle:u,sign:s,isExternal:!0,cornerRadius:i,cornerIsExternal:l}),b=O.circleTangency,S=O.lineTangency,I=O.theta,k=Dn({cx:t,cy:r,radius:n,angle:c,sign:-s,isExternal:!0,cornerRadius:i,cornerIsExternal:l}),E=k.circleTangency,T=k.lineTangency,j=k.theta,N=l?Math.abs(u-c):Math.abs(u-c)-I-j;if(N<0&&i===0)return"".concat(w,"L").concat(t,",").concat(r,"Z");w+=Se(Pc||(Pc=Gt(["L",",",`
A`,",",",0,0,",",",",",`
A`,",",",0,",",",",",",",`
A`,",",",0,0,",",",",","Z"])),T.x,T.y,i,i,+(s<0),E.x,E.y,n,n,+(N>180),+(s>0),b.x,b.y,i,i,+(s<0),S.x,S.y)}else w+=Se(Oc||(Oc=Gt(["L",",","Z"])),t,r);return w},bx={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},Qd=e=>{var t=Ae(e,bx),r=t.cx,n=t.cy,a=t.innerRadius,i=t.outerRadius,o=t.cornerRadius,l=t.forceCornerRadius,u=t.cornerIsExternal,c=t.startAngle,s=t.endAngle,f=t.className;if(i<a||c===s)return null;var v=Z("recharts-sector",f),h=i-a,m=Ce(o,h,0,!0),p;return m>0&&Math.abs(c-s)<360?p=gx({cx:r,cy:n,innerRadius:a,outerRadius:i,cornerRadius:Math.min(m,h/2),forceCornerRadius:l,cornerIsExternal:u,startAngle:c,endAngle:s}):p=Zd({cx:r,cy:n,innerRadius:a,outerRadius:i,startAngle:c,endAngle:s}),d.createElement("path",Fi({},Ke(t),{className:v,d:p}))};function xx(e,t,r){if(e==="horizontal")return[{x:t.x,y:r.top},{x:t.x,y:r.top+r.height}];if(e==="vertical")return[{x:r.left,y:t.y},{x:r.left+r.width,y:t.y}];if(xd(t)){if(e==="centric"){var n=t.cx,a=t.cy,i=t.innerRadius,o=t.outerRadius,l=t.angle,u=ve(n,a,i,l),c=ve(n,a,o,l);return[{x:u.x,y:u.y},{x:c.x,y:c.y}]}return Xd(t)}}var tt=e=>e.chartData,bn=P([tt],e=>{var t=e.chartData!=null?e.chartData.length-1:0;return{chartData:e.chartData,computedData:e.computedData,dataEndIndex:t,dataStartIndex:0}}),za=(e,t,r,n)=>n?bn(e):tt(e),Jd=(e,t,r)=>r?bn(e):tt(e),wx=P([za],e=>{var t=e.chartData,r=e.dataStartIndex,n=e.dataEndIndex;return t!=null?t.slice(r,n+1):[]}),Ax=P([bn],e=>{var t=e.chartData,r=e.dataStartIndex,n=e.dataEndIndex;return t!=null?t.slice(r,n+1):[]}),Px=P([tt],e=>{var t=e.chartData,r=e.dataStartIndex,n=e.dataEndIndex;return t!=null?t.slice(r,n+1):[]});function Eo(e,t){return Ex(e)||Ix(e,t)||Sx(e,t)||Ox()}function Ox(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Sx(e,t){if(e){if(typeof e=="string")return Sc(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Sc(e,t):void 0}}function Sc(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Ix(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function Ex(e){if(Array.isArray(e))return e}function ot(e){if(Array.isArray(e)&&e.length===2){var t=Eo(e,2),r=t[0],n=t[1];if(H(r)&&H(n))return!0}return!1}function Ic(e,t,r){return r?e:[Math.min(e[0],t[0]),Math.max(e[1],t[1])]}function ev(e,t){if(t&&typeof e!="function"&&Array.isArray(e)&&e.length===2){var r=Eo(e,2),n=r[0],a=r[1],i,o;if(H(n))i=n;else if(typeof n=="function")return;if(H(a))o=a;else if(typeof a=="function")return;var l=[i,o];if(ot(l))return l}}function kx(e,t,r){if(!(!r&&t==null)){if(typeof e=="function"&&t!=null)try{var n=e(t,r);if(ot(n))return Ic(n,t,r)}catch{}if(Array.isArray(e)&&e.length===2){var a=Eo(e,2),i=a[0],o=a[1],l,u;if(i==="auto")t!=null&&(l=Math.min(...t));else if($(i))l=i;else if(typeof i=="function")try{t!=null&&(l=i(t==null?void 0:t[0]))}catch{}else if(typeof i=="string"&&Su.test(i)){var c=Su.exec(i);if(c==null||c[1]==null||t==null)l=void 0;else{var s=+c[1];l=t[0]-s}}else l=t==null?void 0:t[0];if(o==="auto")t!=null&&(u=Math.max(...t));else if($(o))u=o;else if(typeof o=="function")try{t!=null&&(u=o(t==null?void 0:t[1]))}catch{}else if(typeof o=="string"&&Iu.test(o)){var f=Iu.exec(o);if(f==null||f[1]==null||t==null)u=void 0;else{var v=+f[1];u=t[1]+v}}else u=t==null?void 0:t[1];var h=[l,u];if(ot(h))return t==null?h:Ic(h,t,r)}}}function tv(e){var t;return e===0?t=1:t=Math.floor(new G(e).abs().log(10).toNumber())+1,t}function rv(e,t,r){for(var n=new G(e),a=0,i=[];n.lt(t)&&a<1e5;)i.push(n.toNumber()),n=n.add(r),a++;return i}function an(e,t){return $x(e)||Tx(e,t)||Cx(e,t)||jx()}function jx(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Cx(e,t){if(e){if(typeof e=="string")return Ec(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Ec(e,t):void 0}}function Ec(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Tx(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function $x(e){if(Array.isArray(e))return e}var nv=e=>{var t=an(e,2),r=t[0],n=t[1],a=r,i=n;return r>n&&(a=n,i=r),[a,i]},ko=(e,t,r)=>{if(e.lte(0))return new G(0);var n=tv(e.toNumber()),a=new G(10).pow(n),i=e.div(a),o=n!==1?.05:.1,l=new G(Math.ceil(i.div(o).toNumber())).add(r).mul(o),u=l.mul(a);return t?new G(u.toNumber()):new G(Math.ceil(u.toNumber()))},av=(e,t,r)=>{var n;if(e.lte(0))return new G(0);var a=[1,2,2.5,5],i=e.toNumber(),o=Math.floor(new G(i).abs().log(10).toNumber()),l=new G(10).pow(o),u=e.div(l).toNumber(),c=a.findIndex(h=>h>=u-1e-10);if(c===-1&&(l=l.mul(10),c=0),c+=r,c>=a.length){var s=Math.floor(c/a.length);c%=a.length,l=l.mul(new G(10).pow(s))}var f=(n=a[c])!==null&&n!==void 0?n:1,v=new G(f).mul(l);return t?v:new G(Math.ceil(v.toNumber()))},Mx=(e,t,r)=>{var n=new G(1),a=new G(e);if(!a.isint()&&r){var i=Math.abs(e);i<1?(n=new G(10).pow(tv(e)-1),a=new G(Math.floor(a.div(n).toNumber())).mul(n)):i>1&&(a=new G(Math.floor(e)))}else e===0?a=new G(Math.floor((t-1)/2)):r||(a=new G(Math.floor(e)));for(var o=Math.floor((t-1)/2),l=[],u=0;u<t;u++)l.push(a.add(new G(u-o).mul(n)).toNumber());return l},iv=function(t,r,n,a){var i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0,o=arguments.length>5&&arguments[5]!==void 0?arguments[5]:ko;if(!Number.isFinite((r-t)/(n-1)))return{step:new G(0),tickMin:new G(0),tickMax:new G(0)};var l=o(new G(r).sub(t).div(n-1),a,i),u;t<=0&&r>=0?u=new G(0):(u=new G(t).add(r).div(2),u=u.sub(new G(u).mod(l)));var c=Math.ceil(u.sub(t).div(l).toNumber()),s=Math.ceil(new G(r).sub(u).div(l).toNumber()),f=c+s+1;return f>n?iv(t,r,n,a,i+1,o):(f<n&&(s=r>0?s+(n-f):s,c=r>0?c:c+(n-f)),{step:l,tickMin:u.sub(new G(c).mul(l)),tickMax:u.add(new G(s).mul(l))})},kc=function(t){var r=an(t,2),n=r[0],a=r[1],i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"auto",u=Math.max(i,2),c=nv([n,a]),s=an(c,2),f=s[0],v=s[1];if(f===-1/0||v===1/0){var h=v===1/0?[f,...Array(i-1).fill(1/0)]:[...Array(i-1).fill(-1/0),v];return n>a?h.reverse():h}if(f===v)return Mx(f,i,o);var m=l==="snap125"?av:ko,p=iv(f,v,u,o,0,m),y=p.step,g=p.tickMin,x=p.tickMax,A=rv(g,x.add(new G(.1).mul(y)),y);return n>a?A.reverse():A},jc=function(t,r){var n=an(t,2),a=n[0],i=n[1],o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"auto",u=nv([a,i]),c=an(u,2),s=c[0],f=c[1];if(s===-1/0||f===1/0)return[a,i];if(s===f)return[s];var v=l==="snap125"?av:ko,h=Math.max(r,2),m=v(new G(f).sub(s).div(h-1),o,0),p=[...rv(new G(s),new G(f),m),f];return o===!1&&(p=p.map(y=>Math.round(y))),a>i?p.reverse():p},ov=e=>e.rootProps.maxBarSize,Dx=e=>e.rootProps.barGap,lv=e=>e.rootProps.barCategoryGap,_x=e=>e.rootProps.barSize,xn=e=>e.rootProps.stackOffset,uv=e=>e.rootProps.reverseStackOrder,jo=e=>e.options.chartName,Co=e=>e.rootProps.syncId,cv=e=>e.rootProps.syncMethod,To=e=>e.options.eventEmitter,Nx=e=>e.rootProps.baseValue,he={grid:-100,barBackground:-50,area:100,cursorRectangle:200,bar:300,line:400,axis:500,scatter:600,activeBar:1e3,cursorLine:1100,activeDot:1200,label:2e3},Wt={allowDecimals:!1,allowDataOverflow:!1,angleAxisId:0,reversed:!1,scale:"auto",tick:!0,type:"auto"},nt={allowDataOverflow:!1,allowDecimals:!1,allowDuplicatedCategory:!0,includeHidden:!1,radiusAxisId:0,reversed:!1,scale:"auto",tick:!0,tickCount:5,type:"auto"},Ka=(e,t)=>{if(!(!e||!t))return e!=null&&e.reversed?[t[1],t[0]]:t};function Wa(e,t,r){if(r!=="auto")return r;if(e!=null)return ft(e,t)?"category":"number"}function Cc(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function aa(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Cc(Object(r),!0).forEach(function(n){Lx(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Cc(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Lx(e,t,r){return(t= Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function OP(e,t){if(e){if(typeof e=="string")return ps(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?ps(e,t):void 0}}function ps(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function SP(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function IP(e){if(Array.isArray(e))return e}var Zi=[0,"auto"],me={allowDataOverflow:!1,allowDecimals:!0,allowDuplicatedCategory:!0,angle:0,dataKey:void 0,domain:void 0,height:30,hide:!0,id:0,includeHidden:!1,interval:"preserveEnd",minTickGap:5,mirror:!1,name:void 0,orientation:"bottom",padding:{left:0,right:0},reversed:!1,scale:"auto",tick:!0,tickCount:5,tickFormatter:void 0,ticks:void 0,type:"category",unit:void 0,niceTicks:"auto"},eh=(e,t)=>e.cartesianAxis.xAxis[t],St=(e,t)=>{var r=eh(e,t);return r??me},pe={allowDataOverflow:!1,allowDecimals:!0,allowDuplicatedCategory:!0,angle:0,dataKey:void 0,domain:Zi,hide:!0,id:0,includeHidden:!1,interval:"preserveEnd",minTickGap:5,mirror:!1,name:void 0,orientation:"left",padding:{top:0,bottom:0},reversed:!1,scale:"auto",tick:!0,tickCount:5,tickFormatter:void 0,ticks:void 0,type:"number",unit:void 0,niceTicks:"auto",width:mn},th=(e,t)=>e.cartesianAxis.yAxis[t],It=(e,t)=>{var r=th(e,t);return r??pe},EP={domain:[0,"auto"],includeHidden:!1,reversed:!1,allowDataOverflow:!1,allowDuplicatedCategory:!1,dataKey:void 0,id:0,name:"",range:[64,64],scale:"auto",type:"number",unit:""},ol=(e,t)=>{var r=e.cartesianAxis.zAxis[t];return r??EP},fe=(e,t,r)=>{switch(t){case"xAxis":return St(e,r);case"yAxis":return It(e,r);case"zAxis":return ol(e,r);case"angleAxis":return $o(e,r);case"radiusAxis":return Mo(e,r);default:throw new Error("Unexpected axis type: ".concat(t))}},kP=(e,t,r)=>{switch(t){case"xAxis":return St(e,r);case"yAxis":return It(e,r);default:throw new Error("Unexpected axis type: ".concat(t))}},Dr=(e,t,r)=>{switch(t){case"xAxis":return St(e,r);case"yAxis":return It(e,r);case"angleAxis":return $o(e,r);case"radiusAxis":return Mo(e,r);default:throw new Error("Unexpected axis type: ".concat(t))}},rh=e=>e.graphicalItems.cartesianItems.some(t=>t.type==="bar")||e.graphicalItems.polarItems.some(t=>t.type==="radialBar");function ll(e,t){return r=>{switch(e){case"xAxis":return"xAxisId"in r&&r.xAxisId===t;case"yAxis":return"yAxisId"in r&&r.yAxisId===t;case"zAxis":return"zAxisId"in r&&r.zAxisId===t;case"angleAxis":return"angleAxisId"in r&&r.angleAxisId===t;case"radiusAxis":return"radiusAxisId"in r&&r.radiusAxisId===t;default:return!1}}}var ei=e=>e.graphicalItems.cartesianItems,jP=P([oe,wn],ll),ul=(e,t,r)=>e.filter(r).filter(n=>(t==null?void 0:t.includeHidden)===!0?!0:!n.hide),_r=P([ei,fe,jP],ul,{memoizeOptions:{resultEqualityCheck:Ga}}),nh=P([_r],e=>e.filter(t=>t.type==="area"||t.type==="bar").filter(Ha)),ah=e=>e.filter(t=>!("stackId"in t)||t.stackId===void 0),CP=P([_r],ah),cl=e=>e.map(t=>t.data).filter(Boolean).flat(1),TP=P([_r],e=>e.some(t=>!t.data)),ih=P([_r],cl,{memoizeOptions:{resultEqualityCheck:Ga}}),sl=(e,t)=>{var r=t.chartData,n=r===void 0?[]:r,a=t.dataStartIndex,i=t.dataEndIndex;return e.length>0?e:n.slice(a,i+1)},fl=P([ih,za],sl),oh=(e,t,r)=>(t==null?void 0:t.dataKey)!=null?e.map(n=>({value:Q(n,t.dataKey)})):r.length>0?r.map(n=>n.dataKey).flatMap(n=>e.map(a=>({value:Q(a,n)}))):e.map(n=>({value:n})),lh=(e,t,r,n,a,i)=>{var o=n.chartData,l=o===void 0?[]:o,u=n.dataStartIndex,c=n.dataEndIndex,s=oh(e,t,r);if(a&&(t==null?void 0:t.dataKey)!=null&&i.length>0){var f=l.slice(u,c+1),v=f.map(h=>({value:Q(h,t.dataKey)})).filter(h=>h.value!=null);return[...v,...s]}return s},In=P([fl,fe,_r,za,TP,ih],lh);function wr(e){if(ut(e)||e instanceof Date){var t=Number(e);if(H(t))return t}}function ys(e){if(Array.isArray(e)){var t=[wr(e[0]),wr(e[1])];return ot(t)?t:void 0}var r=wr(e);if(r!=null)return[r,r]}function st(e){return e.map(wr).filter(_e)}function $P(e,t){var r=wr(e),n=wr(t);return r==null&&n==null?0:r==null?-1:n==null?1:r-n}var MP=P([In],e=>e==null?void 0:e.map(t=>t.value).sort($P));function uh(e,t){switch(e){case"xAxis":return t.direction==="x";case"yAxis":return t.direction==="y";default:return!1}}function DP(e,t,r){if(!r)return[];if(!r.length)return[];var n;if(typeof t=="number"&&!Je(t))n=t;else if(Array.isArray(t)){var a=st(t);a.length>0&&(n=Math.max(...a))}return n==null?[]:st(r.flatMap(i=>{var o=Q(e,i.dataKey),l,u;if(Array.isArray(o)){var c=Jv(o,2);l=c[0],u=c[1]}else l=u=o;if(!(!H(l)||!H(u)))return[n-l,n+u]}))}var xe=e=>{var t=Pe(e),r=$r(e);return Dr(e,t,r)},Er=P([xe],e=>e==null?void Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function MS(e,t){if(e){if(typeof e=="string")return _s(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_s(e,t):void 0}}function _s(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function DS(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function _S(e){if(Array.isArray(e))return e}function NS(e){return e.dataKey}function LS(e,t){return d.isValidElement(e)?d.cloneElement(e,t):typeof e=="function"?d.createElement(e,t):d.createElement(Hb,t)}var Ns=[],RS={allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",axisId:0,contentStyle:{},cursor:!0,filterNull:!0,includeHidden:!1,isAnimationActive:"auto",itemSorter:"name",itemStyle:{},labelStyle:{},offset:10,reverseDirection:{x:!1,y:!1},separator:" : ",trigger:"hover",useTranslate3d:!1,wrapperStyle:{}};function uD(e){var t,r,n=Ae(e,RS),a=n.active,i=n.allowEscapeViewBox,o=n.animationDuration,l=n.animationEasing,u=n.content,c=n.filterNull,s=n.isAnimationActive,f=n.offset,v=n.payloadUniqBy,h=n.position,m=n.reverseDirection,p=n.useTranslate3d,y=n.wrapperStyle,g=n.cursor,x=n.shared,A=n.trigger,w=n.defaultIndex,O=n.portal,b=n.axisId,S=ee(),I=typeof w=="number"?String(w):w;d.useEffect(()=>{S(jO({shared:x,trigger:A,axisId:b,active:a,defaultIndex:I}))},[S,x,A,b,a,I]);var k=Ba(),E=Wd(),T=PO(x),j=(t=M(z=>K1(z,T,A,I)))!==null&&t!==void 0?t:{},N=j.activeIndex,_=j.isActive,R=M(z=>z1(z,T,A,I)),W=M(z=>tm(z,T,A,I)),F=M(z=>B1(z,T,A,I)),L=R,V=sS(),K=(r=a??_)!==null&&r!==void 0?r:!1,le=Od([L,K]),de=TS(le,2),ae=de[0],Me=de[1],Be=T==="axis"?W:void 0;ES(T,A,F,Be,N,K);var qe=O??V;if(qe==null||k==null||T==null)return null;var Xe=L??Ns;K||(Xe=Ns),c&&Xe.length&&(Xe=Ad(Xe.filter(z=>z.value!=null&&(z.hide!==!0||n.includeHidden)),v,NS));var zr=Xe.length>0,D=Ds(Ds({},n),{},{payload:Xe,label:Be,active:K,activeIndex:N,coordinate:F,accessibilityLayer:E}),U=d.createElement(d0,{allowEscapeViewBox:i,animationDuration:o,animationEasing:l,isAnimationActive:s,active:K,coordinate:F,hasPayload:zr,offset:f,position:h,reverseDirection:m,useTranslate3d:p,viewBox:k,wrapperStyle:y,lastBoundingBox:ae,innerRef:Me,hasPortalFromProps:!!O},LS(u,D));return d.createElement(d.Fragment,null,fo.createPortal(U,qe),K&&d.createElement(cS,{cursor:g,tooltipEventType:T,coordinate:F,payload:Xe,index:N}))}var oi=e=>null;oi.displayName="Cell";function BS(e,t,r){return(t=zS(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function zS(e){var t=KS(e,"string");return typeof t=="symbol"?t:t+""}function KS(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}class WS{constructor(t){BS(this,"cache",new Map),this.maxSize=t}get(t){var r=this.cache.get(t);return r!==void 0&&(this.cache.delete(t),this.cache.set(t,r)),r}set(t,r){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.maxSize){var n=this.cache.keys().next().value;n!=null&&this.cache.delete(n)}this.cache.set(t,r)}clear(){this.cache.clear()}size(){return this.cache.size}}function Ls(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function FS(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Ls(Object(r),!0).forEach(function(n){US(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Ls(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function US(e,t,r){return(t=HS(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function HS(e){var t=VS(e,"string");return typeof t=="symbol"?t:t+""}function VS(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var GS={cacheSize:2e3,enableCache:!0},om=FS({},GS),Rs=new WS(om.cacheSize),YS={position:"absolute",top:"-20000px",left:0,padding:0,margin:0,border:"none",whiteSpace:"pre"},Bs="recharts_measurement_span";function qS(e,t){var r=t.fontSize||"",n=t.fontFamily||"",a=t.fontWeight||"",i= Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ZS(e,t){if(e){if(typeof e=="string")return Ks(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Ks(e,t):void 0}}function Ks(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function QS(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t===0){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function JS(e){if(Array.isArray(e))return e}function eI(e,t,r){return(t=tI(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function tI(e){var t=rI(e,"string");return typeof t=="symbol"?t:t+""}function rI(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Ws=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([*/])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,Fs=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([+-])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,nI=/^(px|cm|vh|vw|em|rem|%|mm|in|pt|pc|ex|ch|vmin|vmax|Q)$/,aI=/(-?\d+(?:\.\d+)?)([a-zA-Z%]+)?/,iI={cm:96/2.54,mm:96/25.4,pt:96/72,pc:96/6,in:96,Q:96/(2.54*40),px:1},oI=["cm","mm","pt","pc","in","Q","px"];function lI(e){return oI.includes(e)}var br="NaN";function uI(e,t){return e*iI[t]}class Ie{static parse(t){var r,n=(r=aI.exec(t))!==null&&r!==void 0?r:[],a=xa(n,3),i=a[1],o=a[2];return i==null?Ie.NaN:new Ie(parseFloat(i),o??"")}constructor(t,r){this.num=t,this.unit=r,this.num=t,this.unit=r,Je(t)&&(this.unit=""),r!==""&&!nI.test(r)&&(this.num=NaN,this.unit=""),lI(r)&&(this.num=uI(t,r),this.unit="px")}add(t){return this.unit!==t.unit?new Ie(NaN,""):new Ie(this.num+t.num,this.unit)}subtract(t){return this.unit!==t.unit?new Ie(NaN,""):new Ie(this.num-t.num,this.unit)}multiply(t){return this.unit!==""&&t.unit!==""&&this.unit!==t.unit?new Ie(NaN,""):new Ie(this.num*t.num,this.unit||t.unit)}divide(t){return this.unit!==""&&t.unit!==""&&this.unit!==t.unit?new Ie(NaN,""):new Ie(this.num/t.num,this.unit||t.unit)}toString(){return"".concat(this.num).concat(this.unit)}isNaN(){return Je(this.num)}}lm=Ie;eI(Ie,"NaN",new lm(NaN,""));function um(e){if(e==null||e.includes(br))return br;for(var t=e;t.includes("*")||t.includes("/");){var r,n=(r=Ws.exec(t))!==null&&r!==void 0?r:[],a=xa(n,4),i=a[1],o=a[2],l=a[3],u=Ie.parse(i??""),c=Ie.parse(l??""),s=o==="*"?u.multiply(c):u.divide(c);if(s.isNaN())return br;t=t.replace(Ws,s.toString())}for(;t.includes("+")||/.-\d+(?:\.\d+)?/.test(t);){var f,v=(f=Fs.exec(t))!==null&&f!==void 0?f:[],h=xa(v,4),m=h[1],p=h[2],y=h[3],g=Ie.parse(m??""),x=Ie.parse(y??""),A=p==="+"?g.add(x):g.subtract(x);if(A.isNaN())return br;t=t.replace(Fs,A.toString())}return t}var Us=/\(([^()]*)\)/;function cI(e){for(var t=e,r;(r=Us.exec(t))!=null;){var n=r,a=xa(n,2),i=a[1];t=t.replace(Us,um(i))}return t}function sI(e){var t=e.replace(/\s+/g,"");return t=cI(t),t=um(t),t}function fI(e){try{return sI(e)}catch{return br}}function Si(e){var t=fI(e.slice(5,-1));return t===br?"":t}var dI=["x","y","lineHeight","capHeight","fill","scaleToFit","textAnchor","verticalAnchor"],vI=["dx","dy","angle","className","breakAll"];function eo(){return eo=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},eo.apply(null,arguments)}function Hs(e,t){if(e==null)return{};var r,n,a=hI(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function hI(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}function Vs(e,t){return gI(e)||yI(e,t)||pI(e,t)||mI()}function mI(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function pI(e,t){if(e){if(typeof e=="string")return Gs(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Gs(e,t):void 0}}function Gs(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function yI(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t===0){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function gI(e){if(Array.isArray(e))return e}var cm=/[ \f\n\r\t\v\u2028\u2029]+/,sm=e=>{var t=e.children,r=e.breakAll,n=e.style;try{var a=[];ie(t)||(r?a=t.toString().split(""):a=t.toString().split(cm));var i=a.map(l=>({word:l,width:tn(l,n).width})),o=r?0:tn(" ",n).width;return{wordsWithComputedWidth:i,spaceWidth:o}}catch{return null}};function fm(e){return e==="start"||e==="middle"||e==="end"||e==="inherit"}function bI(e){return ie(e)||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}var dm=(e,t,r,n)=>e.reduce((a,i)=>{var o=i.word,l=i.width,u=a[a.length-1];if(u&&l!=null&&(t==null||n||u.width+l+r<Number(t)))u.words.push(o),u.width+=l+r;else{var c={words:[o],width:l};a.push(c)}return a},[]),vm=e=>e.reduce((t,r)=>t.width>r.width?t:r),xI="…",Ys=(e,t,r,n,a,i,o,l)=>{var u=e.slice(0,t),c=sm({breakAll:r,style:n,children:u+xI});if(!c)return[!1,[]];var s=dm(c.wordsWithComputedWidth,i,o,l),f=s.length>a||vm(s).width>Number(i);return[f,s]},wI=(e,t,r,n,a)=>{var i=e.maxLines,o=e.children,l=e.style,u=e.breakAll,c=$(i),s=String(o),f=dm(t,n,r,a);if(!c||a)return f;var v=f.length>i||vm(f).width>Number(n);if(!v)return f;for(var h=0,m=s.length-1,p=0,y;h<=m&&p<=s.length-1;){var g=Math.floor((h+m)/2),x=g-1,A=Ys(s,x,u,l,i,n,r,a),w=Vs(A,2),O=w[0],b=w[1],S=Ys(s,g,u,l,i,n,r,a),I=Vs(S,1),k=I[0];if(!O&&!k&&(h=g+1),O&&k&&(m=g-1),!O&&k){y=b;break}p++}return y||f},qs=e=>{var t=ie(e)?[]:e.toString().split(cm);return[{words:t,width:void 0}]},AI=e=>{var t=e.width,r=e.scaleToFit,n=e.children,a=e.style,i=e.breakAll,o=e.maxLines;if((t||r)&&!gn.isSsr){var l,u,c=sm({breakAll:i,children:n,style:a});if(c){var s=c.wordsWithComputedWidth,f=c.spaceWidth;l=s,u=f}else return qs(n);return wI({breakAll:i,children:n,maxLines:o,style:a},l,u,t,!!r)}return qs(n)},hm="#808080",PI={angle:0,breakAll:!1,capHeight:"0.71em",fill:hm,lineHeight:"1em",scaleToFit:!1,textAnchor:"start",verticalAnchor:"end",x:0,y:0},li=d.forwardRef((e,t)=>{var r=Ae(e,PI),n=r.x,a=r.y,i=r.lineHeight,o=r.capHeight,l=r.fill,u=r.scaleToFit,c=r.textAnchor,s=r.verticalAnchor,f=Hs(r,dI),v=d.useMemo(()=>AI({breakAll:f.breakAll,children:f.children,maxLines:f.maxLines,scaleToFit:u,style:f.style,width:f.width}),[f.breakAll,f.children,f.maxLines,u,f.style,f.width]),h=f.dx,m=f.dy,p=f.angle,y=f.className,g=f.breakAll,x=Hs(f,vI);if(!ut(n)||!ut(a)||v.length===0)return null;var A=Number(n)+($(h)?h:0),w=Number(a)+($(m)?m:0);if(!H(A)||!H(w))return null;var O;switch(s){case"start":O=Si("calc(".concat(o,")"));break;case"middle":O=Si("calc(".concat((v.length-1)/2," * -").concat(i," + (").concat(o," / 2))"));break;default:O=Si("calc(".concat(v.length-1," * -").concat(i,")"));break}var b=[],S=v[0];if(u&&S!=null){var I=S.width,k=f.width;b.push("scale(".concat($(k)&&$(I)?k/I:1,")"))}return p&&b.push("rotate(".concat(p,", ").concat(A,", ").concat(w,")")),b.length&&(x.transform=b.join(" ")),d.createElement("text",eo({},Ke(x),{ref:t,x:A,y:w,className:Z("recharts-text",y),textAnchor:c,fill:l.includes("url")?hm:l}),v.map((E,T)=>{var j=E.words.join(g?"":" ");return d.createElement("tspan",{x:A,dy:T===0?O:i,key:"".concat(j,"-").concat(T)},j)}))});li.displayName="Text";function Xs(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function at(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Xs(Object(r),!0).forEach(function(n){OI(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Xs(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function OI(e,t,r){return(t=SI(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function SI(e){var t=II(e,"string");return typeof t=="symbol"?t:t+""}function II(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Line truncated
A`).concat(m,",").concat(m,",0,1,").concat(x?0:1,`,
`).concat(w.x,",").concat(w.y),b=ie(e.id)?nn("recharts-radial-line-"):e.id;return d.createElement("text",mt({},n,{dominantBaseline:"central",className:Z("recharts-radial-bar-label",o)}),d.createElement("defs",null,d.createElement("path",{id:b,d:O})),d.createElement("textPath",{xlinkHref:"#".concat(b)},r))},zI=(e,t,r)=>{var n=e.cx,a=e.cy,i=e.innerRadius,o=e.outerRadius,l=e.startAngle,u=e.endAngle,c=(l+u)/2;if(r==="outside"){var s=ve(n,a,o+t,c),f=s.x,v=s.y;return{x:f,y:v,textAnchor:f>=n?"start":"end",verticalAnchor:"middle"}}if(r==="center")return{x:n,y:a,textAnchor:"middle",verticalAnchor:"middle"};if(r==="centerTop")return{x:n,y:a,textAnchor:"middle",verticalAnchor:"start"};if(r==="centerBottom")return{x:n,y:a,textAnchor:"middle",verticalAnchor:"end"};var h=(i+o)/2,m=ve(n,a,h,c),p=m.x,y=m.y;return{x:p,y,textAnchor:"middle",verticalAnchor:"middle"}},Un=e=>e!=null&&"cx"in e&&$(e.cx),KI={angle:0,offset:5,zIndex:he.label,position:"middle",textBreakAll:!1};function WI(e){if(!Un(e))return e;var t=e.cx,r=e.cy,n=e.outerRadius,a=n*2;return{x:t-n,y:r-n,width:a,upperWidth:a,lowerWidth:a,height:a}}function jt(e){var t=Ae(e,KI),r=t.viewBox,n=t.parentViewBox,a=t.position,i=t.value,o=t.children,l=t.content,u=t.className,c=u===void 0?"":u,s=t.textBreakAll,f=t.labelRef,v=NI(),h=pm(),m=a==="center"?h:v??h,p,y,g;r==null?p=m:Un(r)?p=r:p=Ao(r);var x=WI(p);if(!p||ie(i)&&ie(o)&&!d.isValidElement(l)&&typeof l!="function")return null;var A=Qr(Qr({},t),{},{viewBox:p});if(d.isValidElement(l)){A.labelRef;var w=Zs(A,kI);return d.cloneElement(l,w)}if(typeof l=="function"){A.content;var O=Zs(A,jI);if(y=d.createElement(l,O),d.isValidElement(y))return y}else y=LI(t);var b=Ke(t);if(Un(p)){if(a==="insideStart"||a==="insideEnd"||a==="end")return BI(t,a,y,b,p);g=zI(p,t.offset,t.position)}else{if(!x)return null;var S=EI({viewBox:x,position:a,offset:t.offset,parentViewBox:Un(n)?void 0:n});g=Qr(Qr({x:S.x,y:S.y,textAnchor:S.horizontalAnchor,verticalAnchor:S.verticalAnchor},S.width!==void 0?{width:S.width}:{}),S.height!==void 0?{height:S.height}:{})}return d.createElement(Re,{zIndex:t.zIndex},d.createElement(li,mt({ref:f,className:Z("recharts-label",c)},b,g,{textAnchor:fm(b.textAnchor)?b.textAnchor:g.textAnchor,breakAll:s}),y))}jt.displayName="Label";var FI=(e,t,r)=>{if(!e)return null;var n={viewBox:t,labelRef:r};return e===!0?d.createElement(jt,mt({key:"label-implicit"},n)):ut(e)?d.createElement(jt,mt({key:"label-implicit",value:e},n)):d.isValidElement(e)?e.type===jt?d.cloneElement(e,Qr({key:"label-implicit"},n)):d.createElement(jt,mt({key:"label-implicit",content:e},n)):Nl(e)?d.createElement(jt,mt({key:"label-implicit",content:e},n)):e&&typeof e=="object"?d.createElement(jt,mt({},e,{key:"label-implicit"},n)):null};function UI(e){var t=e.label,r=e.labelRef,n=pm();return FI(t,n,r)||null}var HI=["valueAccessor"],VI=["dataKey","clockWise","id","textBreakAll","zIndex"];function wa(){return wa=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},wa.apply(null,arguments)}function Js(e,t){if(e==null)return{};var r,n,a=GI(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function GI(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}var YI=e=>{var t=Array.isArray(e.value)?e.value[e.value.length-1]:e.value;if(bI(t))return t},ym=d.createContext(void 0),gm=ym.Provider,bm=d.createContext(void 0),qI=bm.Provider;function XI(){return d.useContext(ym)}function ZI(){return d.useContext(bm)}function Hn(e){var t=e.valueAccessor,r=t===void 0?YI:t,n=Js(e,HI),a=n.dataKey;n.clockWise;var i=n.id,o=n.textBreakAll,l=n.zIndex,u=Js(n,VI),c=XI(),s=ZI(),f=c||s;return!f||!f.length?null:d.createElement(Re,{zIndex:l??he.label},d.createElement(se,{className:"recharts-label-list"},f.map((v,h)=>{var m,p=ie(a)?r(v,h):Q(v.payload,a),y=ie(i)?{}:{id:"".concat(i,"-").concat(h)};return d.createElement(jt,wa({key:"label-".concat(h)},Ke(v),u,y,{fill:(m=n.fill)!==null&&m!==void 0?m:v.fill,parentViewBox:v.parentViewBox,value:p,textBreakAll:o,viewBox:v.viewBox,index:h,zIndex:0}))})))}Hn.displayName="LabelList";function Ll(e){var t=e.label;return t?t===!0?d.createElement(Hn,{key:"labelList-implicit"}):d.isValidElement(t)||Nl(t)?d.createElement(Hn,{key:"labelList-implicit",content:t}):typeof t=="object"?d.createElement(Hn,wa({key:"labelList-implicit"},t,{type:String(t.type)})):null:null}function to(){return to=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},to.apply(null,arguments)}var xm=e=>{var t=e.cx,r=e.cy,n=e.r,a=e.className,i=Z("recharts-dot",a);return $(t)&&$(r)&&$(n)?d.createElement("circle",to({},Le(e),go(e),{className:i,cx:t,cy:r,r:n})):nul Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function OE(e,t){if(e){if(typeof e=="string")return uf(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?uf(e,t):void 0}}function uf(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function SE(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function IE(e){if(Array.isArray(e))return e}var Vl="index",Gl="append";function Yl(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[],n=[];for(var a of r)n.push({status:"removed",prev:a});for(var i=0;i<t.length;i++){var o=e[i],l=t[i];o!=null?n.push({status:"matched",prev:o,next:l}):n.push({status:"added",next:l})}return n}function EE(e,t){var r=e.length/t.length,n=t.map((a,i)=>e[Math.floor(i*r)]);return Yl(n,t)}function kE(e,t){var r=t.map((n,a)=>e[a]);return Yl(r,t)}function jE(e,t){for(var r=new Map,n=0;n<e.length;n++){var a=e[n];if(a!=null){var i=t(a,n);i!=null&&!r.has(i)&&r.set(i,a)}}return r}function CE(e,t,r){var n=jE(e,r),a=new Set,i=t.map((f,v)=>{var h=r(f,v);if(h!=null){var m=n.get(h);if(m!==void 0)return a.add(h),m}}),o=[];for(var l of n){var u=AE(l,2),c=u[0],s=u[1];a.has(c)||o.push(s)}return Yl(i,t,o)}function ro(e,t,r){return t==null?null:e==null?t.map(n=>({status:"added",next:n})):r===Vl?EE(e,t):r===Gl?kE(e,t):CE(e,t,r)}function Cm(e,t){var r=d.useRef(e),n=d.useRef(t.current),a=d.useRef(!0);r.current!==e&&(r.current=e,n.current=t.current,a.current=!1);var i=d.useCallback(function(o,l){var u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(l===0){a.current=!0;return}l===1&&(n.current=o),l>0&&a.current&&u&&(t.current=o)},[t]);return{startValue:n.current,syncStepValue:i}}function TE(e,t){return _E(e)||DE(e,t)||ME(e,t)||$E()}function $E(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ME(e,t){if(e){if(typeof e=="string")return cf(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?cf(e,t):void 0}}function cf(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function DE(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function _E(e){if(Array.isArray(e))return e}function ql(e,t){var r=d.useState(!1),n=TE(r,2),a=n[0],i=n[1],o=d.useCallback(()=>{typeof e=="function"&&e(),i(!0)},[e]),l=d.useCallback(()=>{typeof t=="function"&&t(),i(!1)},[t]);return{isAnimating:a,handleAnimationStart:o,handleAnimationEnd:l}}function Xl(e){var t,r=e.animationInput,n=e.animationIdPrefix,a=e.items,i=e.previousItemsRef,o=e.isAnimationActive,l=e.animationBegin,u=e.animationDuration,c=e.animationEasing,s=e.onAnimationStart,f=e.onAnimationEnd,v=e.animationInterpolateFn,h=e.animationMatchBy,m=e.shouldUpdatePreviousRef,p=e.children,y=e.layout,g=Gd(r,n),x=Cm(g,i),A=(t=x.startValue)!==null&&t!==void 0?t:null,w=ro(A,a,h??Vl);return d.createElement(Vd,{animationId:g,begin:l,duration:u,isActive:o,easing:c,onAnimationEnd:f,onAnimationStart:s,key:g},O=>{var b=A==null,S=a==null?a:v(w,O,y),I=m?m(O):O>0;return x.syncStepValue(S,O,I),S==null?null:p(S,O,b)})}var Ei;function NE(e,t){return zE(e)||BE(e,t)||RE(e,t)||LE()}function LE(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function RE(e,t){if(e){if(typeof e=="string")return sf(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?sf(e,t):void 0}}function sf(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function BE(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function zE(e){if(Array.isArray(e))return e}var KE=()=>{var e=d.useState(()=>nn("uid-")),t=NE(e,1),r=t[0];return r},Tm=(Ei=Sp.useId)!==null&&Ei!==void 0?Ei:KE;function WE(e,t){var r=Tm();return t||(e?"".concat(e,"-").concat(r):r)}var FE=d.createContext(void 0),Zl=e=>{var t=e.id,r=e.type,n=e.children,a=WE("recharts-".concat(r),t);return d.createElement(FE.Provider,{value:a},n(a))},UE={cartesianItems:[],polarItems:[]},$m=Te({name:"graphicalItems",initialState:UE,reducers:{addCartesianGraphicalItem:{reducer(e,t){e.cartesianItems.push(q(t.payload))},prepare:re()},replaceCartesianGraphicalItem:{reducer(e,t){var r=t.payload,n=r.prev,a=r.next,i=Qe(e).cartesianItems.indexOf(q(n));i>-1&&(e.cartesianItems[i]=q(a))},prepare:re()},removeCartesianGraphicalItem:{reducer(e,t){var r=Qe(e).cartesianItems.indexOf(q(t.payload));r>-1&&e.cartesianItems.splice(r,1)},prepare:re()},addPolarGraphicalItem:{reducer(e,t){e.polarItems.push(q(t.payload))},prepare:re()},removePolarGraphicalItem:{reducer(e,t){var r=Qe(e).polarItems.indexOf(q(t.payload));r>-1&&e.polarItems.splice(r,1)},prepare:re()},replacePolarGraphicalItem:{reducer(e,t){var r=t.payload,n=r.prev,a=r.next,i=Qe(e).polarItems.indexOf(q(n));i>-1&&(e.polarItems[i]=q(a))},prepare:re()}}}),Rr=$m.actions,HE=Rr.addCartesianGraphicalItem,VE=Rr.replaceCartesianGraphicalItem,GE=Rr.removeCartesianGraphicalItem,YE=Rr.addPolarGraphicalItem,qE=Rr.removePolarGraphicalItem,XE=Rr.replacePolarGraphicalItem,ZE=$m.reducer,QE=e=>{var t=ee(),r=d.useRef(null);return d.useLayoutEffect(()=>{r.current===null?t(HE(e)):r.current!==e&&t(VE({prev:r.current,next:e})),r.current=e},[t,e]),d.useLayoutEffect(()=>()=>{r.current&&(t(GE(r.current)),r.current=null)},[t]),null},Mm=d.memo(QE),JE=e=>{var t=ee(),r=d.useRef(null);return d.useLayoutEffect(()=>{r.current===null?t(YE(e)):r.current!==e&&t(XE({prev:r.current,next:e})),r.current=e},[t,e]),d.useLayoutEffect(()=>()=>{r.current&&(t(qE(r.current)),r.current=null)},[t]),null},ek=d.memo(JE),tk=["key"],rk=["onMouseEnter","onClick","onMouseLeave"],nk=["id"],ak=["id"];function nr(){return nr=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},nr.apply(null,arguments)}function fi(e,t){if(e==null)return{};var r,n,a=ik(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function ik(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}function ff(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function ne(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?ff(Object(r),!0).forEach(function(n){ok(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ff(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function ok(e,t,r){return(t=lk(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function lk(e){var t=uk(e,"string");return typeof t=="symbol"?t:t+""}function uk(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Dm=Qd;function ck(e){var t=d.useMemo(()=>zl(e.children,oi),[e.children]),r=M(n=>dE(n,e.id,t));return r==null?null:d.createElement(wE,{legendPayload:r})}function sk(e){if(!(e==null||typeof e=="boolean"||typeof e=="function")){if(d.isValidElement(e)){var t,r=(t=e.props)===null||t===void 0?void 0:t.fill;return typeof r=="string"?r:void 0}var n=e.fill;return typeof n=="string"?n:void 0}}var fk=d.memo(e=>{var t=e.dataKey,r=e.nameKey,n=e.sectors,a=e.stroke,i=e.strokeWidth,o=e.fill,l=e.name,u=e.hide,c=e.tooltipType,s=e.id Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ij(e,t){if(e){if(typeof e=="string")return yf(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?yf(e,t):void 0}}function yf(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function oj(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function lj(e){if(Array.isArray(e))return e}var gf=(e,t,r)=>{var n=r??e;if(!ie(n))return Ce(n,t,0)},uj=(e,t,r)=>{var n={},a=e.filter(Ha),i=e.filter(c=>c.stackId==null),o=a.reduce((c,s)=>{var f=c[s.stackId];return f==null&&(f=[]),f.push(s),c[s.stackId]=f,c},n),l=Object.entries(o).map(c=>{var s,f=nj(c,2),v=f[0],h=f[1],m=h.map(y=>y.dataKey),p=gf(t,r,(s=h[0])===null||s===void 0?void 0:s.barSize);return{stackId:v,dataKeys:m,barSize:p}}),u=i.map(c=>{var s=[c.dataKey].filter(v=>v!=null),f=gf(t,r,c.barSize);return{stackId:void 0,dataKeys:s,barSize:f}});return[...l,...u]};function bf(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function zn(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?bf(Object(r),!0).forEach(function(n){cj(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):bf(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function cj(e,t,r){return(t=sj(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function sj(e){var t=fj(e,"string");return typeof t=="symbol"?t:t+""}function fj(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function dj(e,t,r,n,a){var i,o=n.length;if(!(o<1)){var l=Ce(e,r,0,!0),u,c=[];if(H((i=n[0])===null||i===void 0?void 0:i.barSize)){var s=!1,f=r/o,v=n.reduce((x,A)=>x+(A.barSize||0),0);v+=(o-1)*l,v>=r&&(v-=(o-1)*l,l=0),v>=r&&f>0&&(s=!0,f*=.9,v=o*f);var h=Math.round((r-v)/2),m={offset:h-l,size:0};u=n.reduce((x,A)=>{var w,O={stackId:A.stackId,dataKeys:A.dataKeys,position:{offset:m.offset+m.size+l,size:s?f:(w=A.barSize)!==null&&w!==void 0?w:0}},b=[...x,O];return m=O.position,b},c)}else{var p=Ce(t,r,0,!0);r-2*p-(o-1)*l<=0&&(l=0);var y=(r-2*p-(o-1)*l)/o;y>1&&(y=Math.round(y));var g=H(a)?Math.min(y,a):y;u=n.reduce((x,A,w)=>[...x,{stackId:A.stackId,dataKeys:A.dataKeys,position:{offset:p+(y+l)*w+(y-g)/2,size:g}}],c)}return u}}var vj=(e,t,r,n,a,i,o)=>{var l=ie(o)?t:o,u=dj(r,n,a!==i?a:i,e,l);return a!==i&&u!=null&&(u=u.map(c=>zn(zn({},c),{},{position:zn(zn({},c.position),{},{offset:c.position.offset-a/2})}))),u},hj=(e,t)=>{var r=Ua(t);if(!(!e||r==null||t==null)){var n=t.stackId;if(n!=null){var a=e[n];if(a){var i=a.stackedData;if(i)return i.find(o=>o.key===r)}}}},mj=(e,t)=>{if(!(e==null||t==null)){var r=e.find(n=>n.stackId===t.stackId&&t.dataKey!=null&&n.dataKeys.includes(t.dataKey));if(r!=null)return r.position}};function pj(e,t){return e&&typeof e=="object"&&"zIndex"in e&&typeof e.zIndex=="number"&&H(e.zIndex)?e.zIndex:t}var Lm=e=>{var t=e.chartData,r=ee(),n=$e();return d.useEffect(()=>n?()=>{}:(r(Ts(t)),()=>{r(Ts(void 0))}),[t,r,n]),null},xf={x:0,y:0,width:0,height:0,padding:{top:0,right:0,bottom:0,left:0}},Rm=Te({name:"brush",initialState:xf,reducers:{setBrushSettings(e,t){return t.payload==null?xf:t.payload}}});Rm.actions.setBrushSettings;var yj=Rm.reducer;function gj(e){return(e%180+180)%180}var bj=function(t){var r=t.width,n=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=gj(a),o=i*Math.PI/180,l=Math.atan(n/r),u=o>l&&o<Math.PI-l?n/Math.sin(o):r/Math.cos(o);return Math.abs(u)},xj={dots:[],areas:[],lines:[]},Bm=Te({name:"referenceElements",initialState:xj,reducers:{addDot:(e,t)=>{e.dots.push(t.payload)},removeDot:(e,t)=>{var r=Qe(e).dots.findIndex(n=>n===t.payload);r!==-1&&e.dots.splice(r,1)},addArea:(e,t)=>{e.areas.push(t.payload)},removeArea:(e,t)=>{var r=Qe(e).areas.findIndex(n=>n===t.payload);r!==-1&&e.areas.splice(r,1)},addLine:(e,t)=>{e.lines.push(q(t.payload))},removeLine:(e,t)=>{var r=Qe(e).lines.findIndex(n=>n===t.payload);r!==-1&&e.lines.splice(r,1)}}}),Br=Bm.actions;Br.addDot;Br.removeDot;Br.addArea;Br.removeArea;Br.addLine;Br.removeLine;var wj=Bm.reducer;function Aj(e,t){return Ij(e)||Sj(e,t)||Oj(e,t)||Pj()}function Pj(){ Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Oj(e,t){if(e){if(typeof e=="string")return wf(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?wf(e,t):void 0}}function wf(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Sj(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function Ij(e){if(Array.isArray(e))return e}var Ej=d.createContext(void 0),kj=e=>{var t=e.children,r=d.useState("".concat(nn("recharts"),"-clip")),n=Aj(r,1),a=n[0],i=Ql();if(i==null)return null;var o=i.x,l=i.y,u=i.width,c=i.height;return d.createElement(Ej.Provider,{value:a},d.createElement("defs",null,d.createElement("clipPath",{id:a},d.createElement("rect",{x:o,y:l,height:c,width:u}))),t)};function zm(e,t){if(t<1)return[];if(t===1)return e;for(var r=[],n=0;n<e.length;n+=t){var a=e[n];a!==void 0&&r.push(a)}return r}function jj(e,t,r){var n={width:e.width+t.width,height:e.height+t.height};return bj(n,r)}function Cj(e,t,r){var n=r==="width",a=e.x,i=e.y,o=e.width,l=e.height;return t===1?{start:n?a:i,end:n?a+o:i+l}:{start:n?a+o:i+l,end:n?a:i}}function fn(e,t,r,n,a){if(e*t<e*n||e*t>e*a)return!1;var i=r();return e*(t-e*i/2-n)>=0&&e*(t+e*i/2-a)<=0}function Tj(e,t){return zm(e,t+1)}function $j(e,t,r,n,a){for(var i=(n||[]).slice(),o=t.start,l=t.end,u=0,c=1,s=o,f=function(){var m=n==null?void 0:n[u];if(m===void 0)return{v:zm(n,c)};var p=u,y,g=()=>(y===void 0&&(y=r(m,p)),y),x=m.coordinate,A=u===0||fn(e,x,g,s,l);A||(u=0,s=o,c+=1),A&&(s=x+e*(g()/2+a),u+=c)},v;c<=i.length;)if(v=f(),v)return v.v;return[]}function Mj(e,t,r,n,a){var i=(n||[]).slice(),o=i.length;if(o===0)return[];for(var l=t.start,u=t.end,c=1;c<=o;c++){for(var s=(o-1)%c,f=l,v=!0,h=function(){var w=n[p];if(w==null)return 0;var O=p,b,S=()=>(b===void 0&&(b=r(w,O)),b),I=w.coordinate,k=p===s||fn(e,I,S,f,u);if(!k)return v=!1,1;k&&(f=I+e*(S()/2+a))},m,p=s;p<o&&(m=h(),!(m!==0&&m===1));p+=c);if(v){for(var y=[],g=s;g<o;g+=c){var x=n[g];x!=null&&y.push(x)}return y}}return[]}function Af(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function ke(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Af(Object(r),!0).forEach(function(n){Dj(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Af(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Dj(e,t,r){return(t=_j(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _j(e){var t=Nj(e,"string");return typeof t=="symbol"?t:t+""}function Nj(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Lj(e,t,r,n,a){for(var i=(n||[]).slice(),o=i.length,l=t.start,u=t.end,c=function(v){var h=i[v];if(h==null)return 1;var m=h,p,y=()=>(p===void 0&&(p=r(h,v)),p);if(v===o-1){var g=e*(m.coordinate+e*y()/2-u);i[v]=m=ke(ke({},m),{},{tickCoord:g>0?m.coordinate-g*e:m.coordinate})}else i[v]=m=ke(ke({},m),{},{tickCoord:m.coordinate});if(m.tickCoord!=null){var x=fn(e,m.tickCoord,y,l,u);x&&(u=m.tickCoord-e*(y()/2+a),i[v]=ke(ke({},m),{},{isShow:!0}))}},s=o-1;s>=0;s--)c(s);return i}function Rj(e,t,r,n,a,i){var o=(n||[]).slice(),l=o.length,u=t.start,c=t.end;if(i){var s=n[l-1];if(s!=null){var f=r(s,l-1),v=e*(s.coordinate+e*f/2-c);if(o[l-1]=s=ke(ke({},s),{},{tickCoord:v>0?s.coordinate-v*e:s.coordinate}),s.tickCoord!=null){var h=fn(e,s.tickCoord,()=>f,u,c);h&&(c=s.tickCoord-e*(f/2+a),o[l-1]=ke(ke({},s),{},{isShow:!0}))}}}for(var m=i?l-1:l,p=function(x){var A=o[x];if(A==null)return 1;var w=A,O,b=()=>(O===void 0&&(O=r(A,x)),O);if(x===0){var S=e*(w.coordinate-e*b()/2-u);o[x]=w=ke(ke({},w),{},{tickCoord:S<0?w.coordinate-S*e:w.coordinate})}else o[x]=w=ke(ke({},w),{},{tickCoord:w.coordinate});if(w.tickCoord!=null){var I=fn(e,w.tickCoord,b,u,c);I&&(u=w.tickCoord+e*(b()/2+a),o[x]=ke(ke({},w),{},{isShow:!0}))}},y=0;y<m;y++)p(y);return o}function Jl(e,t,r){var n=e.tick,a=e.ticks,i=e.viewBox,o=e.minTickGap,l=e.orientation,u=e.interval,c=e.tickFormatter,s=e.unit,f=e.angle;if(!a||!a.length||!n)return[];if($(u)||gn.isSsr){var v;return(v=Tj(a,$(u)?u:0))!==null&&v!==void 0?v:[]}var h=[],m=l==="top"||l==="bottom"?"width":"h Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Vj(e,t){if(e){if(typeof e=="string")return Of(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Of(e,t):void 0}}function Of(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Gj(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function Yj(e){if(Array.isArray(e))return e}function qj(e,t){if(e==null)return{};var r,n,a=Xj(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function Xj(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}function ar(){return ar=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ar.apply(null,arguments)}function Sf(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function ce(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Sf(Object(r),!0).forEach(function(n){Zj(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Sf(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Zj(e,t,r){return(t=Qj(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Qj(e){var t=Jj(e,"string");return typeof t=="symbol"?t:t+""}function Jj(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var gt={x:0,y:0,width:0,height:0,viewBox:{x:0,y:0,width:0,height:0},orientation:"bottom",ticks:[],stroke:"#666",tickLine:!0,axisLine:!0,tick:!0,mirror:!1,minTickGap:5,tickSize:6,tickMargin:2,interval:"preserveEnd",zIndex:he.axis};function eC(e){var t=e.x,r=e.y,n=e.width,a=e.height,i=e.orientation,o=e.mirror,l=e.axisLine,u=e.otherSvgProps;if(!l)return null;var c=ce(ce(ce({},u),Le(l)),{},{fill:"none"});if(i==="top"||i==="bottom"){var s=+(i==="top"&&!o||i==="bottom"&&o);c=ce(ce({},c),{},{x1:t,y1:r+s*a,x2:t+n,y2:r+s*a})}else{var f=+(i==="left"&&!o||i==="right"&&o);c=ce(ce({},c),{},{x1:t+f*n,y1:r,x2:t+f*n,y2:r+a})}return d.createElement("line",ar({},c,{className:Z("recharts-cartesian-axis-line",Qt(l,"className"))}))}function tC(e,t,r,n,a,i,o,l,u){var c,s,f,v,h,m,p=l?-1:1,y=e.tickSize||o,g=$(e.tickCoord)?e.tickCoord:e.coordinate;switch(i){case"top":c=s=e.coordinate,v=r+ +!l*a,f=v-p*y,m=f-p*u,h=g;break;case"left":f=v=e.coordinate,s=t+ +!l*n,c=s-p*y,h=c-p*u,m=g;break;case"right":f=v=e.coordinate,s=t+ +l*n,c=s+p*y,h=c+p*u,m=g;break;default:c=s=e.coordinate,v=r+ +l*a,f=v+p*y,m=f+p*u,h=g;break}return{line:{x1:c,y1:f,x2:s,y2:v},tick:{x:h,y:m}}}function rC(e,t){switch(e){case"left":return t?"start":"end";case"right":return t?"end":"start";default:return"middle"}}function nC(e,t){switch(e){case"left":case"right":return"middle";case"top":return t?"start":"end";default:return t?"end":"start"}}function aC(e){var t=e.option,r=e.tickProps,n=e.value,a,i=Z(r.className,"recharts-cartesian-axis-tick-value");if(d.isValidElement(t))a=d.cloneElement(t,ce(ce({},r),{},{className:i}));else if(typeof t=="function")a=t(ce(ce({},r),{},{className:i}));else{var o="recharts-cartesian-axis-tick-value";typeof t!="boolean"&&(o=Z(o,Om(t))),a=d.createElement(li,ar({},r,{className:o}),n)}return a}function iC(e){var t=e.ticks,r=e.axisType,n=e.axisId,a=ee();return d.useEffect(()=>{if(n==null||r==null)return or;var i=t.map(o=>({value:o.value,coordinate:o.coordinate,offset:o.offset,index:o.index}));return a(Kj({ticks:i,axisId:n,axisType:r})),()=>{a(Wj({axisId:n,axisType:r}))}},[a,t,n,r]),null}var oC=d.forwardRef((e,t)=>{var r=e.ticks,n=r===void 0?[]:r,a=e.tick,i=e.tickLine,o=e.stroke,l=e.tickFormatter,u=e.unit,c=e.padding,s=e.tickTextProps,f=e.orientation,v=e.mirror,h=e.x,m=e.y,p=e.width,y=e.height,g=e.tickSize,x=e.tickMargin,A=e.fontSize,w=e.letterSpacing,O=e.getTicksConfig,b=e.events,S=e.axisType,I=e.axisId,k=Jl(ce(ce({},O),{},{ticks:n}),A,w),E=Le(O),T=Jt(a),j=fm(E.textAnchor)?E.textAnchor:rC(f,v),N=nC(f,v),_={};typeof i==" Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function VT(e,t){if(e){if(typeof e=="string")return Cf(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Cf(e,t):void 0}}function Cf(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function GT(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function YT(e){if(Array.isArray(e))return e}function Lt(){return Lt=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Lt.apply(null,arguments)}function Tf(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function ye(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Tf(Object(r),!0).forEach(function(n){qT(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Tf(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function qT(e,t,r){return(t=XT(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function XT(e){var t=ZT(e,"string");return typeof t=="symbol"?t:t+""}function ZT(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Ia(e,t){if(e==null)return{};var r,n,a=QT(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function QT(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}var JT=e=>{var t=e.dataKey,r=e.name,n=e.fill,a=e.legendType,i=e.hide;return[{inactive:i,dataKey:t,type:a,color:n,value:Cr(r,t),payload:e}]},e$=d.memo(e=>{var t=e.dataKey,r=e.stroke,n=e.strokeWidth,a=e.fill,i=e.name,o=e.hide,l=e.unit,u=e.tooltipType,c=e.id,s={dataDefinedOnItem:void 0,getPosition:or,settings:{stroke:r,strokeWidth:n,fill:a,dataKey:t,nameKey:void 0,name:Cr(i,t),hide:o,type:u,color:a,unit:l,graphicalItemId:c}};return d.createElement(Hl,{tooltipEntrySettings:s})});function t$(e){var t=M(Nt),r=e.data,n=e.dataKey,a=e.background,i=e.allOtherBarProps,o=i.onMouseEnter,l=i.onMouseLeave,u=i.onClick,c=Ia(i,KT),s=Wl(o,n,i.id),f=Fl(l),v=Ul(u,n,i.id);if(!a||r==null)return null;var h=Jt(a);return d.createElement(Re,{zIndex:pj(a,he.barBackground)},r.map((m,p)=>{m.value;var y=m.background;m.tooltipPosition;var g=Ia(m,WT);if(!y)return null;var x=s(m,m.originalDataIndex),A=f(m,m.originalDataIndex),w=v(m,m.originalDataIndex),O=ye(ye(ye(ye(ye({option:a,isActive:String(m.originalDataIndex)===t},g),{},{fill:"#eee"},y),h),hn(c,m,p)),{},{onMouseEnter:x,onMouseLeave:A,onClick:w,dataKey:n,index:p,className:"recharts-bar-background-rectangle"});return d.createElement(au,Lt({key:"background-bar-".concat(p)},O))}))}function r$(e){var t=e.showLabels,r=e.children,n=e.rects,a=n==null?void 0:n.map(i=>{var o={x:i.x,y:i.y,width:i.width,lowerWidth:i.width,upperWidth:i.width,height:i.height};return ye(ye({},o),{},{value:i.value,payload:i.payload,parentViewBox:i.parentViewBox,viewBox:o,fill:i.fill})});return d.createElement(gm,{value:t?a:void 0},r)}function n$(e){var t=e.shape,r=e.activeBar,n=e.baseProps,a=e.entry,i=e.index,o=e.dataKey,l=M(Nt),u=M(jl),c=r&&String(a.originalDataIndex)===l&&(u==null||o===u),s=d.useState(!1),f=jf(s,2),v=f[0],h=f[1],m=d.useState(!1),p=jf(m,2),y=p[0],g=p[1];d.useEffect(()=>{var S;return c?(h(!0),S=requestAnimationFrame(()=>{g(!0)})):g(!1),()=>{cancelAnimationFrame(S)}},[c]);var x=d.useCallback(()=>{c||h(!1)},[c]),A=c&&y,w=c||v,O;c?r===!0?O=t:O=r:O=t;var b=d.createElement(au,Lt({},n,{name:String(n.name)},a,{isActive:A,option:O,index:i,dataKey:o,animationElapsedTime:e.animationElapsedTime,isAnimating:e.isAnimating,isEntrance:e.isEntrance,onTransitionEnd:x}));return w?d.createElement(Re,{zIndex:he.activeBar},d.createElement(rp,{index:a.originalDataIndex},b)):b}function a$(e){var t=e.shape,r=e.baseProps,n=e.entry,a=e.index,i=e.dataKey;return d.createElement(au,Lt({},r,{name:String(r.name)},n,{isActive:!1,option:t,index:a,dataKey:i,animationElapsedTime:e.animationElapsedTime,isAnima Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function hM(e,t){if(e){if(typeof e=="string")return Ff(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Ff(e,t):void 0}}function Ff(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function mM(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function pM(e){if(Array.isArray(e))return e}function yM(){var e=ee(),t=d.useState(null),r=dM(t,2),n=r[0],a=r[1],i=M(Cg);return d.useEffect(()=>{if(n!=null){var o=n.getBoundingClientRect(),l=o.width/n.offsetWidth;H(l)&&l!==i&&e(vg(l))}},[n,e,i]),a}function Uf(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function gM(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Uf(Object(r),!0).forEach(function(n){bM(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Uf(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function bM(e,t,r){return(t=xM(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function xM(e){var t=wM(e,"string");return typeof t=="symbol"?t:t+""}function wM(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Mt(){return Mt=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Mt.apply(null,arguments)}function ka(e,t){return SM(e)||OM(e,t)||PM(e,t)||AM()}function AM(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function PM(e,t){if(e){if(typeof e=="string")return Hf(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Hf(e,t):void 0}}function Hf(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function OM(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,o,l=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(u=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);u=!0);}catch(s){c=!0,a=s}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return l}}function SM(e){if(Array.isArray(e))return e}var IM=()=>(IS(),null);function ja(e){if(typeof e=="number")return e;if(typeof e=="string"){var t=parseFloat(e);if(!Number.isNaN(t))return t}return 0}var EM=d.forwardRef((e,t)=>{var r,n,a=d.useRef(null),i=d.useState({containerWidth:ja((r=e.style)===null||r===void 0?void 0:r.width),containerHeight:ja((n=e.style)===null||n===void 0?void 0:n.height)}),o=ka(i,2),l=o[0],u=o[1],c=d.useCallback((f,v)=>{u(h=>{var m=Math.round(f),p=Math.round(v);return h.containerWidth===m&&h.containerHeight===p?h:{containerWidth:m,containerHeight:p}})},[]),s=d.useCallback(f=>{if(typeof t=="function"&&t(f),a.current!=null&&(a.current.disconnect(),a.current=null),f!=null&&typeof ResizeObserver<"u"){var v=f.getBoundingClientRect(),h=v.width,m=v.height;c(h,m);var p=g=>{var x=g[0];if(x!=null){var A=x.contentRect,w=A.width,O=A.height;c(w,O)}},y=new ResizeObserver(p);y.observe(f),a.current=y}},[t,c]);return d.useEffect(()=>()=>{var f=a.current;f!=null&&f.disconnect()},[c]),d.createElement(d.Fragment,null,d.createElement(pn,{width:l.containerWidth,height:l.containerHeight}),d.createElement("div",Mt({ref:s},e)))}),kM=d.forwardRef((e,t)=>{var r=e.width,n=e.height,a=d.useState({containerWidth:ja(r),containerHeight:ja(n)}),i=ka(a,2),o=i[0],l=i[1],u=d.useCallback((s,f)=>{l(v=>{var h=Math.round(s),m=Math.round(f);return v.containerWidth===h&&v.containerHeight===m?v:{containerWidth:h,containerHeight:m}})},[]),c=d.useCallback(s=>{if(typeof t=="function"&&t(s),s!=null){var f=s.getBoundingClientRect(),v=f.width,h=f.height;u(v,h)}},[t,u]);return d.createElement(d.Fragment,null,d.createElement(pn,{width:o.containerWidth,height:o.containerHeight}),d.createElement("div",Mt({ref:c},e)))}),jM=d.forwardRef((e,t)=>{var r=e.width,n=e.height;return d.createElement(d.Fragment,null,d.createElement(pn,{width:r,height:n}),d.createElement("div",Mt({ref:t},e)))}),CM=d.forwardRef((e,t)=>{var r=e.width,n=e.height;return typeof r=="string"||typeof n=="string"?d.createElement(kM,Mt({},e,{ref:t})):typeof r=="number"&&typeof n=="number"?d.createElement(jM,Mt({},e,{width:r,height:n,ref:t})):d.createElement(d.Fragment,null,d.createElement(pn,{width:r,height:n}),d.createElement("div",Mt({ref:t},e)))});function TM(e){return e?EM:CM}var $M=d.forwardRef((e,t)=>{var r=e.children,n=e.className,a=e.height,i=e.onClick,o=e.onContextMenu,l=e.onDoubleClick,u=e.onMouseDown,c=e.onMouseEnter,s=e.onMouseLeave,f=e.onMouseMove,v=e.onMouseUp,h=e.onTouchEnd,m=e.onTouchMove,p=e.onTouchStart,y=e.style,g=e.width,x=e.responsive,A=e.dispatchTouchEvents,w=A===void 0?!0:A,O=d.useRef(null),b=ee(),S=d.useState(null),I=ka(S,2),k=I[0],E=I[1],T=d.useState(null),j=ka(T,2),N=j[0],_=j[1],R=yM(),W=wo(),F=(W==null?void 0:W.width)>0?W.width:g,L=(W==null?void 0:W.height)>0?W.height:a,V=d.useCallback(B=>{R(B),typeof t=="function"&&t(B),E(B),_(B),B!=null&&(O.current=B)},[R,t,E,_]),K=d.useCallback(B=>{b(ip(B)),b(Ue({handler:i,reactEvent:B}))},[b,i]),le=d.useCallback(B=>{b(uo(B)),b(Ue({handler:c,reactEvent:B}))},[b,c]),de=d.useCallback(B=>{b(Dh()),b(Ue({handler:s,reactEvent:B}))},[b,s]),ae=d.useCallback(B=>{b(uo(B)),b(Ue({handler:f,reactEvent:B}))},[b,f]),Me=d.useCallback(()=>{b(fp())},[b]),Be=d.useCallback(()=>{b(dp())},[b]),qe=d.useCallback(B=>{b(sp(B.key))},[b]),Xe=d.useCallback(B=>{b(Ue({handler:o,reactEvent:B}))},[b,o]),zr=d.useCallback(B=>{b(Ue({handler:l,reactEvent:B}))},[b,l]),D=d.useCallback(B=>{b(Ue({handler:u,reactEvent:B}))},[b,u]),U=d.useCallback(B=>{b(Ue({handler:v,reactEvent:B}))},[b,v]),z=d.useCallback(B=>{b(Ue({handler:p,reactEvent:B}))},[b,p]),C=d.useCallback(B=>{w&&b(mp(B)),b(Ue({handler:m,reactEvent:B}))},[b,w,m]),Ee=d.useCallback(B=>{b(Ue({handler:h,reactEvent:B}))},[b,h]),J=TM(x);return d.createElement(nm.Provider,{value:k},d.createElement(Jf.Provider,{value:N},d.createElement(J,{width:F??(y==null?void 0:y.width),height:L??(y==null?void 0:y.height),className:Z("recharts-wrapper",n),style:gM({position:"relative",cursor:"default",width:F,height:L},y),onClick:K,onContextMenu:Xe,onDoubleClick:zr,onFocus:Me,onBlur:Be,onKeyDown:qe,onMouseDown:D,onMouseEnter:le,onMouseLeave:de,onMouseMove:ae,onMouseUp:U,onTouchEnd:Ee,onTouchMove:C,onTouchStart:z,ref:V},d Line truncated
@@ -0,0 +1,346 @@
import{r as s}from"./react-vendor-DZnRGM0-.js";/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const _=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),M=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(a,c,o)=>o?o.toUpperCase():c.toLowerCase()),y=t=>{const a=M(t);return a.charAt(0).toUpperCase()+a.slice(1)},k=(...t)=>t.filter((a,c,o)=>!!a&&a.trim()!==""&&o.indexOf(a)===c).join(" ").trim(),v=t=>{for(const a in t)if(a.startsWith("aria-")||a==="role"||a==="title")return!0};/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/var x={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const g=s.forwardRef(({color:t="currentColor",size:a=24,strokeWidth:c=2,absoluteStrokeWidth:o,className:n="",children:h,iconNode:r,...d},i)=>s.createElement("svg",{ref:i,...x,width:a,height:a,stroke:t,strokeWidth:o?Number(c)*24/Number(a):c,className:k("lucide",n),...!h&&!v(d)&&{"aria-hidden":"true"},...d},[...r.map(([p,l])=>s.createElement(p,l)),...Array.isArray(h)?h:[h]]));/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const e=(t,a)=>{const c=s.forwardRef(({className:o,...n},h)=>s.createElement(g,{ref:h,iconNode:a,className:k(`lucide-${_(y(t))}`,`lucide-${t}`,o),...n}));return c.displayName=y(t),c};/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const m=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],H1=e("activity",m);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const u=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],L1=e("arrow-right",u);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const w=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],V1=e("bell",w);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const $=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],P1=e("bot",$);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const N=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],S1=e("box",N);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const f=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],U1=e("check",f);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const b=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],E1=e("chevron-down",b);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const C=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],B1=e("chevron-left",C);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const q=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],D1=e("chevron-right",q);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const z=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],R1=e("circle-alert",z);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const A=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],T1=e("circle-check",A);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const j=[["path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0",key:"5ilxe3"}],["path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0",key:"11zvb9"}],["path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7",key:"1iw5b2"}],["path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8",key:"c0bmvh"}],["path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69",key:"1ruxm7"}],["path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8",key:"qkgqxc"}],["path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69",key:"1mcia2"}],["path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7",key:"1fvljs"}]],Z1=e("circle-dashed",j);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const H=[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],I1=e("clock-3",H);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const L=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],K1=e("clock",L);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const V=[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]],O1=e("cloud-upload",V);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const P=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],W1=e("code",P);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const S=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],F1=e("copy",S);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const U=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],G1=e("credit-card",U);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const E=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],Q1=e("database",E);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const B=[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]],J1=e("dollar-sign",B);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const D=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],X1=e("external-link",D);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const R=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],Y1=e("eye-off",R);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const T=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],e0=e("eye",T);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Z=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]],a0=e("file-down",Z);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const I=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],t0=e("file-text",I);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const K=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]],c0=e("gift",K);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const O=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],o0=e("image",O);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const W=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],h0=e("key",W);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const F=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],s0=e("layers",F);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const G=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],n0=e("layout-dashboard",G);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Q=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],d0=e("link-2",Q);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const J=[["path",{d:"M16 5H3",key:"m91uny"}],["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 19H3",key:"zzsher"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]],y0=e("list-plus",J);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const X=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],k0=e("loader-circle",X);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Y=[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]],r0=e("lock-keyhole",Y);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const e1=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],i0=e("lock",e1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const a1=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],p0=e("log-out",a1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const t1=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],l0=e("mail",t1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const c1=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],_0=e("message-circle",c1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const o1=[["path",{d:"m16 16 2 2 4-4",key:"gfu2re"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],M0=e("package-check",o1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const h1=[["path",{d:"M16 16h6",key:"100bgy"}],["path",{d:"M19 13v6",key:"85cyf1"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],v0=e("package-plus",h1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const s1=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],x0=e("package",s1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const n1=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],g0=e("pen",n1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const d1=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],m0=e("plus",d1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const y1=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],u0=e("power",y1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const k1=[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]],w0=e("qr-code",k1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const r1=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],$0=e("refresh-cw",r1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const i1=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],N0=e("save",i1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const p1=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],f0=e("search",p1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const l1=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],b0=e("send",l1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const _1=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],C0=e("settings",_1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const M1=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],q0=e("shield-check",M1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const v1=[["path",{d:"M16 10a4 4 0 0 1-8 0",key:"1ltviw"}],["path",{d:"M3.103 6.034h17.794",key:"awc11p"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z",key:"o988cm"}]],z0=e("shopping-bag",v1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const x1=[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]],A0=e("shopping-cart",x1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const g1=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],j0=e("sparkles",g1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const m1=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],H0=e("square-pen",m1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const u1=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],L0=e("trash-2",u1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const w1=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],V0=e("trending-up",w1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const $1=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]],P0=e("truck",$1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const N1=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],S0=e("upload",N1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const f1=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],U0=e("user-round",f1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const b1=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],E0=e("user",b1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const C1=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],B0=e("users",C1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const q1=[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]],D0=e("webhook",q1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const z1=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],R0=e("x",z1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const A1=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],T0=e("zap",A1);export{E1 as $,H1 as A,S1 as B,G1 as C,J1 as D,X1 as E,t0 as F,W1 as G,y0 as H,o0 as I,a0 as J,h0 as K,n0 as L,v0 as M,O1 as N,T1 as O,x0 as P,w0 as Q,$0 as R,z0 as S,V0 as T,B0 as U,Z1 as V,d0 as W,R0 as X,L1 as Y,T0 as Z,Q1 as _,V1 as a,r0 as a0,U0 as a1,q0 as a2,_0 as a3,I1 as a4,c0 as a5,s0 as a6,b0 as a7,l0 as a8,D0 as a9,i0 as aa,C0 as b,j0 as c,p0 as d,A0 as e,M0 as f,k0 as g,E0 as h,U1 as i,P1 as j,R1 as k,K1 as l,g0 as m,u0 as n,L0 as o,Y1 as p,e0 as q,N0 as r,m0 as s,P0 as t,f0 as u,H0 as v,B1 as w,D1 as x,S0 as y,F1 as z};
@@ -0,0 +1,19 @@
import{j as e,r as o,b as ue,c as ut,d as pt}from"./react-vendor-DZnRGM0-.js";import{L as ht,U as Js,S as Ys,C as us,B as Gs,Z as ps,a as qe,b as bs,c as Ks,d as gt,A as Ns,D as bt,e as vs,P as Xs,f as Ge,E as Zs,T as yt,g as _e,Q as is,h as hs,i as Fe,j as Te,k as ls,l as ws,R as ke,m as Hs,n as ft,o as Ae,X as xe,K as jt,p as Ye,q as Be,r as Le,s as De,t as _s,u as Nt,v as ze,w as vt,x as wt,y as Je,z as _t,F as ks,I as Cs,G as Ss,H as kt,J as Ct,M as os,N as Ze,O as et,V as St,W as $t,Y as gs,_ as It,$ as At,a0 as $s,a1 as Dt,a2 as st,a3 as as,a4 as tt,a5 as Lt,a6 as Pt,a7 as ys,a8 as at,a9 as Ft,aa as Rt}from"./icons-vendor-BmeuAUrP.js";import{R as He,B as Et,X as Is,Y as As,T as ds,a as Ot,C as cs,A as Mt,b as Tt,c as qt,P as Ds,d as Ls,L as Bt}from"./charts-vendor-B_BfwiL0.js";import"./vendor-w5t2K9ux.js";(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const u of document.querySelectorAll('link[rel="modulepreload"]'))h(u);new MutationObserver(u=>{for(const m of u)if(m.type==="childList")for(const w of m.addedNodes)w.tagName==="LINK"&&w.rel==="modulepreload"&&h(w)}).observe(document,{childList:!0,subtree:!0});function r(u){const m={};return u.integrity&&(m.integrity=u.integrity),u.referrerPolicy&&(m.referrerPolicy=u.referrerPolicy),u.crossOrigin==="use-credentials"?m.credentials="include":u.crossOrigin==="anonymous"?m.credentials="omit":m.credentials="same-origin",m}function h(u){if(u.ep)return;u.ep=!0;const m=r(u);fetch(u.href,m)}})();const zt=({activeTab:s,onNavigate:a,onLogout:r})=>{const h=[{id:"dashboard",icon:ht,label:"仪表盘"},{id:"accounts",icon:Js,label:"账号管理"},{id:"orders",icon:Ys,label:"订单管理"},{id:"cards",icon:us,label:"卡密库存"},{id:"items",icon:Gs,label:"商品列表"},{id:"rules",icon:ps,label:"自动化规则"},{id:"notifications",icon:qe,label:"通知设置"},{id:"settings",icon:bs,label:"系统与AI"}];return e.jsxs("div",{className:"w-64 h-screen fixed left-0 top-0 bg-white border-r border-gray-100 flex flex-col justify-between z-20 shadow-[4px_0_24px_rgba(0,0,0,0.02)]",children:[e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-12 px-2",children:[e.jsx("div",{className:"w-10 h-10 bg-[#0094f7] squircle flex items-center justify-center shrink-0 p-1.5",style:{filter:"drop-shadow(0 4px 12px rgba(0,148,247,0.25))"},children:e.jsx("img",{src:"/static/ydisks-logo.svg",alt:"Ydisks",className:"w-full h-full"})}),e.jsxs("h1",{className:"text-xl font-extrabold tracking-tight text-gray-900",children:["Ydisks闲鱼助手 ",e.jsx("span",{className:"text-xs bg-[#0094f7] text-white px-1.5 py-0.5 rounded ml-1",children:"PRO"})]})]}),e.jsx("nav",{className:"space-y-2",children:h.map(u=>{const m=u.icon,w=s===u.id;return e.jsxs("button",{onClick:()=>a(u.id),className:`w-full flex items-center gap-3 px-4 py-3.5 rounded-2xl transition-all duration-300 group relative overflow-hidden ${w?"bg-[#0094f7] text-white font-bold shadow-lg shadow-blue-100 transform scale-[1.02]":"text-gray-500 hover:bg-gray-50 hover:text-gray-900"}`,children:[e.jsx(m,{className:`w-5 h-5 transition-colors ${w?"text-white":"text-gray-400 group-hover:text-gray-600"}`}),e.jsx("span",{className:"text-sm tracking-wide",children:u.label}),w&&e.jsx(Ks,{className:"w-4 h-4 absolute right-3 text-white/30 animate-pulse"})]},u.id)})})]}),e.jsx("div",{className:"p-6 border-t border-gray-50",children:e.jsxs("button",{onClick:r,className:"w-full flex items-center gap-3 px-4 py-3 text-gray-500 hover:text-red-500 hover:bg-red-50 rounded-2xl transition-all duration-200 font-medium",children:[e.jsx(gt,{className:"w-5 h-5"}),e.jsx("span",{className:"text-sm",children:"退出登录"})]})})]})},Ut=s=>{if(!s)return"";const a=new URLSearchParams;for(const[h,u]of Object.entries(s))u!=null&&a.set(h,String(u));const r=a.toString();return r?`?${r}`:""},ns=async(s,a,r={})=>{const h=Ut(r.params),u=`${a}${h}`,m=await fetch(u,{method:s,credentials:"include",headers:{...r.body===void 0?{}:{"Content-Type":"application/json"}},body:r.body===void 0?void 0:JSON.stringify(r.body)}),I=(m.headers.get("content-type")||"").includes("application/json");if(!m.ok){const p=I?await m.json().catch(()=>{}):await m.text().catch(()=>{}),W=typeof p=="string"?p:(p==null?void 0:p.detail)||(p==null?void 0:p.message)||(p==null?void 0:p.msg);throw new Error(W||`请求失败: ${m.status}`)}return I?await m.json():await m.text()},ie=async(s,a)=>ns("GET",s,{params:a}),de=async(s,a)=>ns("POST",s,{body:a}),fe=async(s,a)=>ns("PUT",s,{body:a}),Ee=async(s,a)=>ns("DELETE",s,{params:a}),fs=async(s,a)=>{const r=await fetch(s,{method:"POST",credentials:"include",body:a}),m=(r.headers.get("content-type")||"").includes("application/json")?await r.json().catch(()=>{}):await r.text().catch(()=>{});if(!r.ok){const w=typeof m=="string"?m:(m==null?void 0:m.detail)||(m==null?void 0:m.message)||(m==null?void 0:m.msg),I=new Error(w||"请求失败: "+r.status);throw I.payload=m,Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(bs,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>$(null),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:q,children:"取消"}),e.jsxs("button",{onClick:Ce,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:q,children:[q?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(Le,{className:"w-4 h-4"}),q?"保存中...":"保存"]})]})})]})}),document.body)]})},Bs=({status:s})=>{const a={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-[#0094f7] text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600"},r={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${a[s]||a.cancelled}`,children:r[s]||s})},Xa=()=>{const[s,a]=o.useState([]),[r,h]=o.useState([]),[u,m]=o.useState([]),[w,I]=o.useState({}),[p,W]=o.useState("all"),[b,Y]=o.useState(""),[G,M]=o.useState(1),[E,X]=o.useState(1),[re,Z]=o.useState(!1),[R,te]=o.useState(!1),[T,F]=o.useState(!1),[L,Q]=o.useState(!1),[A,$]=o.useState(null),[d,z]=o.useState(null),[H,J]=o.useState({}),[U,C]=o.useState(!1),[k,c]=o.useState(""),[j,N]=o.useState(!1),[q,D]=o.useState(null),[ee,O]=o.useState(null),[i,P]=o.useState(null),[ae,ne]=o.useState(null),x=t=>{if(!b.trim())return t;const g=b.toLowerCase().trim();return t.filter(S=>{var l,v,le,$e,Se,ve;return((l=S.order_id)==null?void 0:l.toLowerCase().includes(g))||((v=S.item_id)==null?void 0:v.toLowerCase().includes(g))||((le=S.buyer_id)==null?void 0:le.toLowerCase().includes(g))||(($e=S.item_title)==null?void 0:$e.toLowerCase().includes(g))||((Se=S.receiver_name)==null?void 0:Se.toLowerCase().includes(g))||((ve=S.receiver_phone)==null?void 0:ve.toLowerCase().includes(g))})},y=async()=>{Z(!0);try{if(b.trim()){let t=[],g=1,S=!0;for(;S;){const l=await Fs(void 0,p,g,100);t=[...t,...l.data],S=g<l.total_pages,g++}h(t),a(x(t)),X(1)}else{const t=await Fs(void 0,p,G,20);h(t.data),a(x(t.data)),X(t.total_pages)}}catch(t){console.error("加载订单失败:",t)}finally{Z(!1)}};o.useEffect(()=>{a(x(r))},[r,b]);const V=(t,g)=>{if(g&&g.trim())return g;if(w[t])return w[t];const S=u.find(l=>{if(g&&l.item_title){const v=g.toLowerCase(),le=l.item_title.toLowerCase();return le.includes(v)||v.includes(le)}return!1});return S!=null&&S.item_title?S.item_title:"未知商品"},se=t=>{const g={};t.forEach(S=>{S.item_id&&(g[S.item_id]=S.item_title||S.item_id)}),I(g)};o.useEffect(()=>{y(),Ue().then(t=>{m(t),se(t)}).catch(t=>{console.error("加载商品列表失败:",t)})},[p,G,b]);const B=async()=>{Z(!0);try{const t=await da();await y(),t!=null&&t.message&&alert(t.message)}catch(t){console.error("同步订单失败:",t),alert((t==null?void 0:t.message)||"同步失败,请重试")}finally{Z(!1)}},pe=t=>{c(t),D(null),C(!0)},je=async t=>{var g;N(!0),D(null);try{const S=await xa([k],t),l=(g=S==null?void 0:S.results)==null?void 0:g[0];l!=null&&l.success?(D({success:!0,message:l.message}),y()):D({success:!1,message:(l==null?void 0:l.message)||"发货失败"})}catch(S){D({success:!1,message:(S==null?void 0:S.message)||"请求失败"})}finally{N(!1)}},he=t=>{$(t),te(!0)},we=t=>{z({...t}),F(!0)},Ce=async()=>{if(!(!d||!d.order_id))try{const t={};d.status!==void 0&&(t.order_status=d.status),d.buyer_id!==void 0&&(t.buyer_id=d.buyer_id),d.amount!==void 0&&(t.amount=d.amount),d.receiver_name!==void 0&&(t.receiver_name=d.receiver_name),d.receiver_phone!==void 0&&(t.receiver_phone=d.receiver_phone),d.receiver_address!==void 0&&(t.receiver_address=d.receiver_address),d.item_id!==void 0&&(t.item_id=d.item_id),d.quantity!==void 0&&(t.quantity=d.quantity),await ia(d.order_id,t),F(!1),z(null),y()}catch(t){console.error("更新订单失败:",t),alert("更新失败,请重试")}},Ne=async()=>{if(ee)try{const t=new FormData;t.append("file",ee),await ma(t),Q(!1),O(null),y(),alert("订单导入成功")}catch(t){alert((t==null?void 0:t.message)||"导入失败,请检查文件格式")}},ge=async t=>{P(t);t Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(V=>V.map(se=>`"${String(se).replace(/"/g,'""')}"`).join(",")).join(`
`),ne=new Blob(["\uFEFF"+ae],{type:"text/csv;charset=utf-8"}),x=URL.createObjectURL(ne),y=document.createElement("a");y.href=x,y.download="卡密组批量导入模板.csv",document.body.appendChild(y),y.click(),y.remove(),URL.revokeObjectURL(x)},D=async()=>{if(re){F(!0),te(null);try{const i=await ya(re);if(te(i),i.created>0){const P=await Ie();a(P)}}catch(i){te({error:(i==null?void 0:i.message)||"上传失败"})}finally{F(!1)}}},ee=async()=>{if(!(!L||!A.trim())){F(!0),z(null);try{const i=await fa(L,A);z({added:i.added}),$("");const P=await Ie();a(P)}catch(i){alert("追加失败:"+((i==null?void 0:i.message)||"未知错误"))}finally{F(!1)}}},O=()=>{var i;X("create"),Z(null),te(null),Q((i=N[0])!=null&&i.id?String(N[0].id):""),$(""),z(null),M(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:O,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Je,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>m(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(De,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-8 py-5 w-[18%]",children:"卡密名称"}),e.jsx("th",{className:"px-6 py-5 w-[12%]",children:"卡密组ID"}),e.jsx("th",{className:"px-6 py-5 w-[10%]",children:"类型"}),e.jsx("th",{className:"px-6 py-5 w-[22%]",children:"内容/库存"}),e.jsx("th",{className:"px-6 py-5 w-[18%]",children:"描述"}),e.jsx("th",{className:"px-6 py-5 w-[10%]",children:"状态"}),e.jsx("th",{className:"px-6 py-5 w-[10%] text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:s.map(i=>{let P="";return i.type==="data"&&i.data_content?P=`库存: ${i.data_content.split(`
`).filter(ne=>ne.trim()).length} 条`:i.type==="text"&&i.text_content?P=i.text_content.substring(0,20)+(i.text_content.length>20?"...":""):i.type==="api"&&i.api_config?P=i.api_config.url:i.type==="image"&&i.image_url&&(P="图片链接"),e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-8 py-5",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-gray-50 rounded-xl group-hover:bg-white transition-colors",children:e.jsx(H,{type:i.type})}),e.jsx("span",{className:"font-bold text-gray-900",children:i.name})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("button",{onClick:()=>j(i.id),className:"inline-flex items-center gap-2 rounded-xl bg-gray-100 px-3 py-2 font-mono text-xs font-extrabold text-gray-700 hover:bg-gray-200 transition-colors",title:"复制卡密组ID,用于批量铺货表格",children:[i.id,e.jsx(_t,{className:"w-3.5 h-3.5"})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${i.type==="text"?"bg-blue-50 text-blue-600":i.type==="data"?"bg-purple-50 text-purple-600":i.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:i.type==="text"?"文本":i.type==="data"?"批量":i.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:"text-sm text-gray-600 font-mono block truncate",title:P,children:P})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:"text-sm text-gray-500 block max-w-[200px] truncate",title:i.description||"-",children:i.description||"-"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("button",{onClick:()=>c(i),className:`w-12 h-8 rounded-full relative transition-colors ${i.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${i.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("button",{onClick:()=>J(i),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(ze,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>C(i.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",children:e.jsx(Ae,{className:"w-5 h-5"})})]})})]},i.id)})})]})}),s.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(Xs,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:"暂无卡密配置,请点击右上角添加。"})]})]}),r&&w&&ue.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>h(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(xe,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:p.name||"",onChange:i=>W({...p,name:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:p.type||"text",onChange:i=>W({...p,type:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),e.jsx("option",{value:"api",children:"API接口"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),p.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:p.api_url||"",onChange:i=>W({...p,api_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求方法"}),e.jsxs("select",{value:p.api_method||"GET",onChange:i=>W({...p,api_method:i.target.value}),className:"w-full ios-input px-4 py-Line truncated
卡号1:密码1
卡号2:密码2
或者
兑换码1
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:p.data_content?p.data_content.split(`
`).filter(i=>i.trim()).length:0})," 条"]})]})]}),p.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:p.image_url||"",onChange:i=>W({...p,image_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),p.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:p.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:i=>{i.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:p.delay_seconds||0,onChange:i=>W({...p,delay_seconds:parseInt(i.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:p.description||"",onChange:i=>W({...p,description:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>W({...p,enabled:!p.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${p.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${p.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>h(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:U,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Le,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),u&&ue.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>m(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(xe,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:b.name,onChange:i=>Y({...b,name:i.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>Y({...b,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${b.type==="data"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(us,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>Y({...b,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${b.type==="text"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(ks,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>Y({...b,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${b.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-Line truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),b.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-[#0094f7]",children:b.content.split(`
`).filter(i=>i.trim()).length})," 条"]})]}),b.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:b.api_method,onChange:i=>Y({...b,api_method:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:b.api_timeout,onChange:i=>Y({...b,api_timeout:parseInt(i.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:b.api_headers,onChange:i=>Y({...b,api_headers:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:b.api_params,onChange:i=>Y({...b,api_params:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:b.description,onChange:i=>Y({...b,description:i.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:b.delay_seconds,onChange:i=>Y({...b,delay_seconds:parseInt(i.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>m(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:k,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(De,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),G&&ue.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>M(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(xe,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>X("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${E==="create"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(kt,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>X("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${E==="append"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Je,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),E==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image/api;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:q,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text- Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),d&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",d.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>M(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),E==="create"?e.jsxs("button",{onClick:D,disabled:!re||T,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[T?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(Je,{className:"w-4 h-4"}),T?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:ee,disabled:!L||!A.trim()||T||N.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[T?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(De,{className:"w-4 h-4"}),T?"处理中...":"追加卡密"]})]})]})}),document.body)]})},Ha=s=>{const a=String(s||"").trim();return a?/^[¥¥]/.test(a)?a:`¥${a}`:"-"},el=({onConfigureDelivery:s})=>{const[a,r]=o.useState([]),[h,u]=o.useState([]),[m,w]=o.useState([]),[I,p]=o.useState(""),[W,b]=o.useState(!1),[Y,G]=o.useState(!1),[M,E]=o.useState(!1),[X,re]=o.useState(!1),[Z,R]=o.useState(!1),[te,T]=o.useState(!1),[F,L]=o.useState(!1),[Q,A]=o.useState("upload"),[$,d]=o.useState(null),[z,H]=o.useState(null),[J,U]=o.useState(null),[C,k]=o.useState(null),[c,j]=o.useState(null),[N,q]=o.useState({}),[D,ee]=o.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[O,i]=o.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),P=async()=>{const l=await Ue();r(l)},ae=async()=>{u(await rs())};o.useEffect(()=>{Promise.all([js(),Ue(),rs()]).then(([l,v,le])=>{w(l),r(v),u(le)}).catch(l=>console.error("加载商品配置失败:",l))},[]),o.useEffect(()=>{if(!F||!(C!=null&&C.id)||C.status!=="running")return;const l=window.setInterval(async()=>{try{const v=await es(C.id);k(v),v.status!=="running"&&(A("done"),await P(),await ae())}catch(v){console.error("刷新批量铺货进度失败:",v)}},3e3);return()=>window.clearInterval(l)},[F,C==null?void 0:C.id,C==null?void 0:C.status]);const ne=async()=>{if(!I)return alert("请先选择账号");b(!0);try{const l=await ja(I);await P(),alert((l==null?void 0:l.message)||"商品同步完成")}catch(l){console.error("同步商品失败:",l),alert((l==null?void 0:l.message)||"同步失败,请重试")}finally{b(!1)}},x=l=>{j(l),q({...l}),re(!0)},y=async()=>{if(c)try{await $a(c.cookie_id,c.item_id,{item_title:N.item_title||"",item_description:N.item_description||"",item_category:N.item_category||"",item_price:N.item_price||"",item_detail:N.item_detail||c.item_detail||""}),await P(),await ae(),re(!1),j(null)}catch(l){console.error("更新商品失败:",l),alert("更新失败,请重试")}},V=async l=>{if(confirm(`确认删除商品"${l.item_title}"吗?`))try{await Na(l.cookie_id,l.item_id),r(v=>v.filter(le=>!(le.cookie_id===l.cookie_id&&le.item_id===l.item_id)))}catch(v){console.error("删除商品失败:",v),alert("删除失败,请重试")}},se=async()=>{try{if(!D.cookie_id||!D.item_id){alert("请选择账号并填写商品ID");return}await va(D.cookie_id,{item_id:D.item_id,item_title:D.item_title,item_price:D.item_price,item_detail:D.item_image?JSON.stringify({item_image:D.item_image}):""}),await P(),R(!1),ee({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(l){console.error("添加商品失败:",l),alert("添加失败,请重试")}},B=async()=>{if(!O.cookie_id)return alert("请选择发布账号");if(!O.title.trim())return alert("请填写商品标题");if(!O.price.trim())return alert("请填写商品价格");if(!O.quantity||Number(O.quantity)<=0)return alert("库存数量必须大于 0");if(O.images.length===0)return alert("至少上传 1 张商品图片");if(O.postage_mode==="fixed"&&!O.postage.trim())return alert("请填写一口价邮费");G(!0);try{const l=await wa(O);if(await P(),T(!1),i({cookie_id:I||"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),l!=null&&l.item_id){const v={id:l.item_id,cookie_id:O.cookie_id,item_id:l.item_id,item_title:l.item_title||O.title,item_price:l.item_price||O.price,item_image:l.item_image};s(v),alert("商品发布成功,ID: "+l.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(l){console.error("发布商品失败:",l);const v=l==null?void 0:l.payload;if((v==null?void 0:v.code)==="stock_permission_missing"){alert("发布失败:该账号没有库存发 Line truncated
`),$e=new Blob(["\uFEFF"+le],{type:"text/csv;charset=utf-8"}),Se=URL.createObjectURL($e),ve=document.createElement("a");ve.href=Se,ve.download="批量铺货模板.csv",document.body.appendChild(ve),ve.click(),ve.remove(),URL.revokeObjectURL(Se)},ge=()=>{ee(l=>({...l,cookie_id:I||l.cookie_id})),R(!0)},be=()=>{i(l=>({...l,cookie_id:I||l.cookie_id})),T(!0)},t=l=>h.filter(v=>v.cookie_id===l.cookie_id&&v.item_id===l.item_id),g=l=>{switch(l){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return l||"-"}},S=l=>{switch(l){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("select",{className:"ios-input px-4 py-3 rounded-xl text-sm",value:I,onChange:l=>p(l.target.value),children:[e.jsx("option",{value:"",children:"选择账号以同步"}),m.map(l=>e.jsx("option",{value:l.id,children:l.nickname},l.id))]}),e.jsxs("button",{onClick:ne,disabled:W||!I,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(ke,{className:`w-4 h-4 ${W?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:ge,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(De,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:be,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-600 text-white hover:bg-emerald-700 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(os,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:pe,className:"px-5 py-3 rounded-2xl font-bold bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(Ze,{className:"w-4 h-4"}),"批量铺货"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[a.map(l=>{const v=t(l),le=v.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex-col",children:[e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:[e.jsx("button",{onClick:()=>x(l),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-[#0094f7] hover:text-white transition-colors",title:"编辑",children:e.jsx(ze,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>V(l),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md hover:bg-red-100 text-red-500 transition-colors",title:"删除",children:e.jsx(Ae,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"aspect-square bg-gray-100 rounded-xl mb-2.5 overflow-hidden relative",children:[l.item_image?e.jsx("img",{src:l.item_image,alt:"",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(Gs,{className:"w-8 h-8"})}),e.jsx("div",{className:"absolute top-1.5 left-1.5 bg-black/50 backdrop-blur-md text-white text-[10px] font-bold px-1.5 py-0.5 rounded-md",children:Ha(l.item_price)})]}),e.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4",children:l.item_title}),e.jsxs("div",{className:"flex justify-between items-center text-[10px] text-gray-500 mb-2",children:[e.jsxs("span",{className:"bg-gray-100 px-1.5 py-0.5 rounded truncate max-w-[80px]",children:["ID: ",l.item_id]}),e.jsxs("span",{className:`inline-flex items-center gap-1 font-bold ${le?"text-emerald-600":"text-amber-600"}`,children:[le?e.jsx(et,{className:"w-3 h-3"}):e.jsx(St,{className:"w-3 h-3"}),le?`${v.length} 规则`:"未配置"]})]}),e.jsx("div",{className:"space-y-2 mt-auto",children:e.jsxs("button",{onClick:()=>s(l),className:`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${le?"bg-gray-900 text-white hover:bg-black":"bg-[#0094f7] text-white hover:bg-[#0071e3] shadow-md shadow-blue-100Line truncated
@@ -1,502 +0,0 @@
var bT=Object.defineProperty;var wT=(e,t,n)=>t in e?bT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var sd=(e,t,n)=>wT(e,typeof t!="symbol"?t+"":t,n);function jT(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const l in r)if(l!=="default"&&!(l in e)){const s=Object.getOwnPropertyDescriptor(r,l);s&&Object.defineProperty(e,l,s.get?s:{enumerable:!0,get:()=>r[l]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const s of l)if(s.type==="childList")for(const d of s.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&r(d)}).observe(document,{childList:!0,subtree:!0});function n(l){const s={};return l.integrity&&(s.integrity=l.integrity),l.referrerPolicy&&(s.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?s.credentials="include":l.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(l){if(l.ep)return;l.ep=!0;const s=n(l);fetch(l.href,s)}})();function Ky(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Yp={exports:{}},Bo={};/**
* @license React
* react-jsx-runtime.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Jw;function _T(){if(Jw)return Bo;Jw=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,l,s){var d=null;if(s!==void 0&&(d=""+s),l.key!==void 0&&(d=""+l.key),"key"in l){s={};for(var f in l)f!=="key"&&(s[f]=l[f])}else s=l;return l=s.ref,{$$typeof:e,type:r,key:d,ref:l!==void 0?l:null,props:s}}return Bo.Fragment=t,Bo.jsx=n,Bo.jsxs=n,Bo}var ej;function NT(){return ej||(ej=1,Yp.exports=_T()),Yp.exports}var c=NT(),Gp={exports:{}},ze={};/**
* @license React
* react.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var tj;function ST(){if(tj)return ze;tj=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),l=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),d=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),h=Symbol.for("react.memo"),v=Symbol.for("react.lazy"),y=Symbol.for("react.activity"),b=Symbol.iterator;function w(P){return P===null||typeof P!="object"?null:(P=b&&P[b]||P["@@iterator"],typeof P=="function"?P:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,S={};function A(P,Q,ne){this.props=P,this.context=Q,this.refs=S,this.updater=ne||j}A.prototype.isReactComponent={},A.prototype.setState=function(P,Q){if(typeof P!="object"&&typeof P!="function"&&P!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,P,Q,"setState")},A.prototype.forceUpdate=function(P){this.updater.enqueueForceUpdate(this,P,"forceUpdate")};function C(){}C.prototype=A.prototype;function M(P,Q,ne){this.props=P,this.context=Q,this.refs=S,this.updater=ne||j}var k=M.prototype=new C;k.constructor=M,_(k,A.prototype),k.isPureReactComponent=!0;var D=Array.isArray;function E(){}var $={H:null,A:null,T:null,S:null},U=Object.prototype.hasOwnProperty;function K(P,Q,ne){var I=ne.ref;return{$$typeof:e,type:P,key:Q,ref:I!==void 0?I:null,props:ne}}function T(P,Q){return K(P.type,Q,P.props)}function re(P){return typeof P=="object"&&P!==null&&P.$$typeof===e}function Z(P){var Q={"=":"=0",":":"=2"};return"$"+P.replace(/[=:]/g,function(ne){return Q[ne]})}var pe=/\/+/g;function fe(P,Q){return typeof P=="object"&&P!==null&&P.key!=null?Z(""+P.key):Q.toString(36)}function ce(P){switch(P.status){case"fulfilled":return P.value;case"rejected":throw P.reason;default:switch(typeof P.status=="string"?P.then(E,E):(P.status="pending",P.then(function(Q){P.status==="pending"&&(P.status="fulfilled",P.value=Q)},function(Q){P.status==="pending"&&(P.status="rejected",P.reason=Q)})),P.status){case"fulfilled":return P.value;case"rejected":throw P.reason}}throw P}function R(P,Q,ne,I,he){var be=typeof P;(be==="undefined"||be==="boolean")&&(P=null);var _e=!1;if(P===null)_e=!0;else switch(be){case"bigint":case"string":case"number":_e=!0;break;case"object":switch(P.$$typeof){case e:case t:_e=!0;break;case v:return _e=P._init,R(_e(P._payload),Q,ne,I,he)}}if(_e)return he=he(P),_e=I===""?"."+fe(P,0):I,D(he)?(ne="",_e!=null&&(ne=_e.replace(pe,"$&/")+"/"),R(he,Q,ne,"",function(ye){return ye})):he!=null&&(re(he)&&(he=T(he,ne+(he.key==null||P&&P.key===he.key?"":(""+he.key).replace(pe,"$&/")+"/")+_e)),Q.push(he)),1;_e=0;var W=I===""?".":I+":";if(D(P))for(var V=0;V<P.length;V++)I=P[V],be=W+fe(I,V),_e+=R(I,Q,ne,be,he);else if(V=w(P),typeof V=="function")for(P=V.call(P),V=0;!(I=P.next()).done;)I=I.value,be=W+fe(I,V++),_e+=R(I,Q,ne,be,he);else if(be==="object"){if(typeof P.then=="function")return R(ce(P),Q,ne,I,he);throw Q=String(P),Error("Objects are not valid as a React child (found: "+(Q==="[object Object]"?"object with keys {"+Object.keys(P).join(", ")+"}":Q)+"). If you meant to render a collection of children, use an array instead.")}return _e}function z(P,Q,ne){if(P==null)return P;var I=[],he=0;return R(P,I,"","",function(be){return Q.call(ne,be,he++)}),I}function G(P){if(P._status===-1){var Q=P._result;Q=Q(),Q.then(function(ne){(P._status===0||P._status===-1)&&(P._status=1,P._result=ne)},function(ne){(P._status===0||P._status===-1)&&(P._status=2,P._result=ne)}),P._status===-1&&(P._status=0,P._result=Q)}if(P._status===1)return P._result.default;throw P._result}var se=typeof reportError=="function"?reportError:function(P){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var Q=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof P=="object"&&P!==null&&typeof P.message=="string"?String(P.message):String(P),error:P});if(!window.dispatchEvent(Q))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",P);return}console.error(P)},ue={map:z,forEach:function(P,Q,ne){z(P,function(){Q.apply(this,arguments)},ne)},count:function(P){var Q=0;return z(P,function(){Q++}),Q},toArray:function(P){return z(P,function(Q){return Q})||[]},only:function(P){if(!re(P))throw Error("React.Children.only expected to receive a single React element child.");return P}};return ze.Activity=y,ze.Children=ue,ze.Component=A,ze.Fragment=n,ze.Profiler=l,ze.PureComponent=M,ze.StrictMode=r,ze.Suspense=m,ze.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=$,ze.__COMPILER_RUNTIME={__proto__:null,c:function(P){return $.H.useMemoCache(P)}},ze.cache=function(P){return function(){return P.apply(null,arguments)}},ze.cacheSignal=function(){return null},ze.cloneElement=function(P,Q,ne){if(P==null)thLine truncated
* @license React
* scheduler.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var rj;function OT(){return rj||(rj=1,(function(e){function t(R,z){var G=R.length;R.push(z);e:for(;0<G;){var se=G-1>>>1,ue=R[se];if(0<l(ue,z))R[se]=z,R[G]=ue,G=se;else break e}}function n(R){return R.length===0?null:R[0]}function r(R){if(R.length===0)return null;var z=R[0],G=R.pop();if(G!==z){R[0]=G;e:for(var se=0,ue=R.length,P=ue>>>1;se<P;){var Q=2*(se+1)-1,ne=R[Q],I=Q+1,he=R[I];if(0>l(ne,G))I<ue&&0>l(he,ne)?(R[se]=he,R[I]=G,se=I):(R[se]=ne,R[Q]=G,se=Q);else if(I<ue&&0>l(he,G))R[se]=he,R[I]=G,se=I;else break e}}return z}function l(R,z){var G=R.sortIndex-z.sortIndex;return G!==0?G:R.id-z.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var s=performance;e.unstable_now=function(){return s.now()}}else{var d=Date,f=d.now();e.unstable_now=function(){return d.now()-f}}var m=[],h=[],v=1,y=null,b=3,w=!1,j=!1,_=!1,S=!1,A=typeof setTimeout=="function"?setTimeout:null,C=typeof clearTimeout=="function"?clearTimeout:null,M=typeof setImmediate<"u"?setImmediate:null;function k(R){for(var z=n(h);z!==null;){if(z.callback===null)r(h);else if(z.startTime<=R)r(h),z.sortIndex=z.expirationTime,t(m,z);else break;z=n(h)}}function D(R){if(_=!1,k(R),!j)if(n(m)!==null)j=!0,E||(E=!0,Z());else{var z=n(h);z!==null&&ce(D,z.startTime-R)}}var E=!1,$=-1,U=5,K=-1;function T(){return S?!0:!(e.unstable_now()-K<U)}function re(){if(S=!1,E){var R=e.unstable_now();K=R;var z=!0;try{e:{j=!1,_&&(_=!1,C($),$=-1),w=!0;var G=b;try{t:{for(k(R),y=n(m);y!==null&&!(y.expirationTime>R&&T());){var se=y.callback;if(typeof se=="function"){y.callback=null,b=y.priorityLevel;var ue=se(y.expirationTime<=R);if(R=e.unstable_now(),typeof ue=="function"){y.callback=ue,k(R),z=!0;break t}y===n(m)&&r(m),k(R)}else r(m);y=n(m)}if(y!==null)z=!0;else{var P=n(h);P!==null&&ce(D,P.startTime-R),z=!1}}break e}finally{y=null,b=G,w=!1}z=void 0}}finally{z?Z():E=!1}}}var Z;if(typeof M=="function")Z=function(){M(re)};else if(typeof MessageChannel<"u"){var pe=new MessageChannel,fe=pe.port2;pe.port1.onmessage=re,Z=function(){fe.postMessage(null)}}else Z=function(){A(re,0)};function ce(R,z){$=A(function(){R(e.unstable_now())},z)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(R){R.callback=null},e.unstable_forceFrameRate=function(R){0>R||125<R?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):U=0<R?Math.floor(1e3/R):5},e.unstable_getCurrentPriorityLevel=function(){return b},e.unstable_next=function(R){switch(b){case 1:case 2:case 3:var z=3;break;default:z=b}var G=b;b=z;try{return R()}finally{b=G}},e.unstable_requestPaint=function(){S=!0},e.unstable_runWithPriority=function(R,z){switch(R){case 1:case 2:case 3:case 4:case 5:break;default:R=3}var G=b;b=R;try{return z()}finally{b=G}},e.unstable_scheduleCallback=function(R,z,G){var se=e.unstable_now();switch(typeof G=="object"&&G!==null?(G=G.delay,G=typeof G=="number"&&0<G?se+G:se):G=se,R){case 1:var ue=-1;break;case 2:ue=250;break;case 5:ue=1073741823;break;case 4:ue=1e4;break;default:ue=5e3}return ue=G+ue,R={id:v++,callback:z,priorityLevel:R,startTime:G,expirationTime:ue,sortIndex:-1},G>se?(R.sortIndex=G,t(h,R),n(m)===null&&R===n(h)&&(_?(C($),$=-1):_=!0,ce(D,G-se))):(R.sortIndex=ue,t(m,R),j||w||(j=!0,E||(E=!0,Z()))),R},e.unstable_shouldYield=T,e.unstable_wrapCallback=function(R){var z=b;return function(){var G=b;b=z;try{return R.apply(this,arguments)}finally{b=G}}}})(Xp)),Xp}var aj;function ET(){return aj||(aj=1,Fp.exports=OT()),Fp.exports}var Wp={exports:{}},vn={};/**
* @license React
* react-dom.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var ij;function kT(){if(ij)return vn;ij=1;var e=zs();function t(m){var h="https://react.dev/errors/"+m;if(1<arguments.length){h+="?args[]="+encodeURIComponent(arguments[1]);for(var v=2;v<arguments.length;v++)h+="&args[]="+encodeURIComponent(arguments[v])}return"Minified React error #"+m+"; visit "+h+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function n(){}var r={d:{f:n,r:function(){throw Error(t(522))},D:n,C:n,L:n,m:n,X:n,S:n,M:n},p:0,findDOMNode:null},l=Symbol.for("react.portal");function s(m,h,v){var y=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:l,key:y==null?null:""+y,children:m,containerInfo:h,implementation:v}}var d=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function f(m,h){if(m==="font")return"";if(typeof h=="string")return h==="use-credentials"?h:""}return vn.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,vn.createPortal=function(m,h){var v=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!h||h.nodeType!==1&&h.nodeType!==9&&h.nodeType!==11)throw Error(t(299));return s(m,h,null,v)},vn.flushSync=function(m){var h=d.T,v=r.p;try{if(d.T=null,r.p=2,m)return m()}finally{d.T=h,r.p=v,r.d.f()}},vn.preconnect=function(m,h){typeof m=="string"&&(h?(h=h.crossOrigin,h=typeof h=="string"?h==="use-credentials"?h:"":void 0):h=null,r.d.C(m,h))},vn.prefetchDNS=function(m){typeof m=="string"&&r.d.D(m)},vn.preinit=function(m,h){if(typeof m=="string"&&h&&typeof h.as=="string"){var v=h.as,y=f(v,h.crossOrigin),b=typeof h.integrity=="string"?h.integrity:void 0,w=typeof h.fetchPriority=="string"?h.fetchPriority:void 0;v==="style"?r.d.S(m,typeof h.precedence=="string"?h.precedence:void 0,{crossOrigin:y,integrity:b,fetchPriority:w}):v==="script"&&r.d.X(m,{crossOrigin:y,integrity:b,fetchPriority:w,nonce:typeof h.nonce=="string"?h.nonce:void 0})}},vn.preinitModule=function(m,h){if(typeof m=="string")if(typeof h=="object"&&h!==null){if(h.as==null||h.as==="script"){var v=f(h.as,h.crossOrigin);r.d.M(m,{crossOrigin:v,integrity:typeof h.integrity=="string"?h.integrity:void 0,nonce:typeof h.nonce=="string"?h.nonce:void 0})}}else h==null&&r.d.M(m)},vn.preload=function(m,h){if(typeof m=="string"&&typeof h=="object"&&h!==null&&typeof h.as=="string"){var v=h.as,y=f(v,h.crossOrigin);r.d.L(m,v,{crossOrigin:y,integrity:typeof h.integrity=="string"?h.integrity:void 0,nonce:typeof h.nonce=="string"?h.nonce:void 0,type:typeof h.type=="string"?h.type:void 0,fetchPriority:typeof h.fetchPriority=="string"?h.fetchPriority:void 0,referrerPolicy:typeof h.referrerPolicy=="string"?h.referrerPolicy:void 0,imageSrcSet:typeof h.imageSrcSet=="string"?h.imageSrcSet:void 0,imageSizes:typeof h.imageSizes=="string"?h.imageSizes:void 0,media:typeof h.media=="string"?h.media:void 0})}},vn.preloadModule=function(m,h){if(typeof m=="string")if(h){var v=f(h.as,h.crossOrigin);r.d.m(m,{as:typeof h.as=="string"&&h.as!=="script"?h.as:void 0,crossOrigin:v,integrity:typeof h.integrity=="string"?h.integrity:void 0})}else r.d.m(m)},vn.requestFormReset=function(m){r.d.r(m)},vn.unstable_batchedUpdates=function(m,h){return m(h)},vn.useFormState=function(m,h,v){return d.H.useFormState(m,h,v)},vn.useFormStatus=function(){return d.H.useHostTransitionStatus()},vn.version="19.2.7",vn}var lj;function iA(){if(lj)return Wp.exports;lj=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Wp.exports=kT(),Wp.exports}/**
* @license React
* react-dom-client.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var sj;function CT(){if(sj)return Uo;sj=1;var e=ET(),t=zs(),n=iA();function r(a){var i="https://react.dev/errors/"+a;if(1<arguments.length){i+="?args[]="+encodeURIComponent(arguments[1]);for(var o=2;o<arguments.length;o++)i+="&args[]="+encodeURIComponent(arguments[o])}return"Minified React error #"+a+"; visit "+i+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function l(a){return!(!a||a.nodeType!==1&&a.nodeType!==9&&a.nodeType!==11)}function s(a){var i=a,o=a;if(a.alternate)for(;i.return;)i=i.return;else{a=i;do i=a,(i.flags&4098)!==0&&(o=i.return),a=i.return;while(a)}return i.tag===3?o:null}function d(a){if(a.tag===13){var i=a.memoizedState;if(i===null&&(a=a.alternate,a!==null&&(i=a.memoizedState)),i!==null)return i.dehydrated}return null}function f(a){if(a.tag===31){var i=a.memoizedState;if(i===null&&(a=a.alternate,a!==null&&(i=a.memoizedState)),i!==null)return i.dehydrated}return null}function m(a){if(s(a)!==a)throw Error(r(188))}function h(a){var i=a.alternate;if(!i){if(i=s(a),i===null)throw Error(r(188));return i!==a?null:a}for(var o=a,u=i;;){var p=o.return;if(p===null)break;var g=p.alternate;if(g===null){if(u=p.return,u!==null){o=u;continue}break}if(p.child===g.child){for(g=p.child;g;){if(g===o)return m(p),a;if(g===u)return m(p),i;g=g.sibling}throw Error(r(188))}if(o.return!==u.return)o=p,u=g;else{for(var N=!1,O=p.child;O;){if(O===o){N=!0,o=p,u=g;break}if(O===u){N=!0,u=p,o=g;break}O=O.sibling}if(!N){for(O=g.child;O;){if(O===o){N=!0,o=g,u=p;break}if(O===u){N=!0,u=g,o=p;break}O=O.sibling}if(!N)throw Error(r(189))}}if(o.alternate!==u)throw Error(r(190))}if(o.tag!==3)throw Error(r(188));return o.stateNode.current===o?a:i}function v(a){var i=a.tag;if(i===5||i===26||i===27||i===6)return a;for(a=a.child;a!==null;){if(i=v(a),i!==null)return i;a=a.sibling}return null}var y=Object.assign,b=Symbol.for("react.element"),w=Symbol.for("react.transitional.element"),j=Symbol.for("react.portal"),_=Symbol.for("react.fragment"),S=Symbol.for("react.strict_mode"),A=Symbol.for("react.profiler"),C=Symbol.for("react.consumer"),M=Symbol.for("react.context"),k=Symbol.for("react.forward_ref"),D=Symbol.for("react.suspense"),E=Symbol.for("react.suspense_list"),$=Symbol.for("react.memo"),U=Symbol.for("react.lazy"),K=Symbol.for("react.activity"),T=Symbol.for("react.memo_cache_sentinel"),re=Symbol.iterator;function Z(a){return a===null||typeof a!="object"?null:(a=re&&a[re]||a["@@iterator"],typeof a=="function"?a:null)}var pe=Symbol.for("react.client.reference");function fe(a){if(a==null)return null;if(typeof a=="function")return a.$$typeof===pe?null:a.displayName||a.name||null;if(typeof a=="string")return a;switch(a){case _:return"Fragment";case A:return"Profiler";case S:return"StrictMode";case D:return"Suspense";case E:return"SuspenseList";case K:return"Activity"}if(typeof a=="object")switch(a.$$typeof){case j:return"Portal";case M:return a.displayName||"Context";case C:return(a._context.displayName||"Context")+".Consumer";case k:var i=a.render;return a=a.displayName,a||(a=i.displayName||i.name||"",a=a!==""?"ForwardRef("+a+")":"ForwardRef"),a;case $:return i=a.displayName||null,i!==null?i:fe(a.type)||"Memo";case U:i=a._payload,a=a._init;try{return fe(a(i))}catch{}}return null}var ce=Array.isArray,R=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,z=n.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,G={pending:!1,data:null,method:null,action:null},se=[],ue=-1;function P(a){return{current:a}}function Q(a){0>ue||(a.current=se[ue],se[ue]=null,ue--)}function ne(a,i){ue++,se[ue]=a.current,a.current=i}var I=P(null),he=P(null),be=P(null),_e=P(null);function W(a,i){switch(ne(be,i),ne(he,a),ne(I,null),i.nodeType){case 9:case 11:a=(a=i.documentElement)&&(a=a.namespaceURI)?jw(a):0;break;default:if(a=i.tagName,i=i.namespaceURI)i=jw(i),a=_w(i,a);else switch(a){case"svg":a=1;break;case"math":a=2;break;default:a=0}}Q(I),ne(I,a)}function V(){Q(I),Q(he),Q(be)}function ye(a){a.memoizedState!==null&&ne(_e,a);var i=I.current,o=_w(i,a.type);i!==o&&(ne(he,a),ne(I,o))}function xe(a){he.current===a&&(Q(I),Q(he)),_e.current===a&&(Q(_e),Io._currentValue=G)}var ae,Le;function Ce(a){if(ae===void 0)try{throw Error()}catch(o){var i=o.stack.trim().match(/\n( *(at )?)/);ae=i&&i[1]||"",Le=-1<o.stack.indexOf(`
at`)?" (<anonymous>)":-1<o.stack.indexOf("@")?"@unknown:0:0":""}return`
`+ae+a+Le}var Y=!1;function ge(a,i){if(!a||Y)return"";Y=!0;var o=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var u={DetermineComponentFrameRoot:function(){try{if(i){var me=function(){throw Error()};if(Object.defineProperty(me.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(me,[])}catch(le){var te=le}Reflect.construct(a,[],me)}else{try{me.call()}catch(le){te=le}a.call(me.prototype)}}else{try{throw Error()}catch(le){te=le}(me=a())&&typeof me.catch=="function"&&me.catch(function(){})}}catch(le){if(le&&te&&typeof le.stack=="string")return[le.stack,te.stack]}return[null,null]}};u.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var p=Object.getOwnPropertyDescriptor(u.DetermineComponentFrameRoot,"name");p&&p.configurable&&Object.defineProperty(u.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var g=u.DetermineComponentFrameRoot(),N=g[0],O=g[1];if(N&&O){var L=N.split(`
`),ee=O.split(`
`);for(p=u=0;u<L.length&&!L[u].includes("DetermineComponentFrameRoot");)u++;for(;p<ee.length&&!ee[p].includes("DetermineComponentFrameRoot");)p++;if(u===L.length||p===ee.length)for(u=L.length-1,p=ee.length-1;1<=u&&0<=p&&L[u]!==ee[p];)p--;for(;1<=u&&0<=p;u--,p--)if(L[u]!==ee[p]){if(u!==1||p!==1)do if(u--,p--,0>p||L[u]!==ee[p]){var oe=`
`+L[u].replace(" at new "," at ");return a.displayName&&oe.includes("<anonymous>")&&(oe=oe.replace("<anonymous>",a.displayName)),oe}while(1<=u&&0<=p);break}}}finally{Y=!1,Error.prepareStackTrace=o}return(o=a?a.displayName||a.name:"")?Ce(o):""}function Pe(a,i){switch(a.tag){case 26:case 27:case 5:return Ce(a.type);case 16:return Ce("Lazy");case 13:return a.child!==i&&i!==null?Ce("Suspense Fallback"):Ce("Suspense");case 19:return Ce("SuspenseList");case 0:case 15:return ge(a.type,!1);case 11:return ge(a.type.render,!1);case 1:return ge(a.type,!0);case 31:return Ce("Activity");default:return""}}function Be(a){try{var i="",o=null;do i+=Pe(a,o),o=a,a=a.return;while(a);return i}catch(u){return`
Error generating stack: `+u.message+`
`+u.stack}}var Ve=Object.prototype.hasOwnProperty,Dt=e.unstable_scheduleCallback,ie=e.unstable_cancelCallback,De=e.unstable_shouldYield,Ue=e.unstable_requestPaint,B=e.unstable_now,Te=e.unstable_getCurrentPriorityLevel,lt=e.unstable_ImmediatePriority,Zr=e.unstable_UserBlockingPriority,Qn=e.unstable_NormalPriority,$n=e.unstable_LowPriority,wi=e.unstable_IdlePriority,xl=e.log,q=e.unstable_setDisableYieldValue,ve=null,we=null;function $e(a){if(typeof xl=="function"&&q(a),we&&typeof we.setStrictMode=="function")try{we.setStrictMode(ve,a)}catch{}}var We=Math.clz32?Math.clz32:Cr,Jt=Math.log,jt=Math.LN2;function Cr(a){return a>>>=0,a===0?32:31-(Jt(a)/jt|0)|0}var _t=256,bl=262144,Vc=4194304;function ji(a){var i=a&42;if(i!==0)return i;switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return a&261888;case 262144:case 524288:case 1048576:case 2097152:return a&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return a&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return a}}function Fc(a,i,o){var u=a.pendingLanes;if(u===0)return 0;var p=0,g=a.suspendedLanes,N=a.pingedLanes;a=a.warmLanes;var O=u&134217727;return O!==0?(u=O&~g,u!==0?p=ji(u):(N&=O,N!==0?p=ji(N):o||(o=O&~a,o!==0&&(p=ji(o))))):(O=u&~g,O!==0?p=ji(O):N!==0?p=ji(N):o||(o=u&~a,o!==0&&(p=ji(o)))),p===0?0:i!==0&&i!==p&&(i&g)===0&&(g=p&-p,o=i&-i,g>=o||g===32&&(o&4194048)!==0)?i:p}function Fs(a,i){return(a.pendingLanes&~(a.suspendedLanes&~a.pingedLanes)&i)===0}function s5(a,i){switch(a){case 1:case 2:case 4:case 8:case 64:return i+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return i+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function rx(){var a=Vc;return Vc<<=1,(Vc&62914560)===0&&(Vc=4194304),a}function Dm(a){for(var i=[],o=0;31>o;o++)i.push(a);return i}function Xs(a,i){a.pendingLanes|=i,i!==268435456&&(a.suspendedLanes=0,a.pingedLanes=0,a.warmLanes=0)}function o5(a,i,o,u,p,g){var N=a.pendingLanes;a.pendingLanes=o,a.suspendedLanes=0,a.pingedLanes=0,a.warmLanes=0,a.expiredLanes&=o,a.entangledLanes&=o,a.errorRecoveryDisabledLanes&=o,a.shellSuspendCounter=0;var O=a.entanglements,L=a.expirationTimes,ee=a.hiddenUpdates;for(o=N&~o;0<o;){var oe=31-We(o),me=1<<oe;O[oe]=0,L[oe]=-1;var te=ee[oe];if(te!==null)for(ee[oe]=null,oe=0;oe<te.length;oe++){var le=te[oe];le!==null&&(le.lane&=-536870913)}o&=~me}u!==0&&ax(a,u,0),g!==0&&p===0&&a.tag!==0&&(a.suspendedLanes|=g&~(N&~i))}function ax(a,i,o){a.pendingLanes|=i,a.suspendedLanes&=~i;var u=31-We(i);a.entangledLanes|=i,a.entanglements[u]=a.entanglements[u]|1073741824|o&261930}function ix(a,i){var o=a.entangledLanes|=i;for(a=a.entanglements;o;){var u=31-We(o),p=1<<u;p&i|a[u]&i&&(a[u]|=i),o&=~p}}function lx(a,i){var o=i&-i;return o=(o&42)!==0?1:Pm(o),(o&(a.suspendedLanes|i))!==0?0:o}function Pm(a){switch(a){case 2:a=1;break;case 8:a=4;break;case 32:a=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:a=128;break;case 268435456:a=134217728;break;default:a=0}return a}function zm(a){return a&=-a,2<a?8<a?(a&134217727)!==0?32:268435456:8:2}function sx(){var a=z.p;return a!==0?a:(a=window.event,a===void 0?32:Gw(a.type))}function ox(a,i){var o=z.p;try{return z.p=a,i()}finally{z.p=o}}var Ia=Math.random().toString(36).slice(2),on="__reactFiber$"+Ia,An="__reactProps$"+Ia,wl="__reactContainer$"+Ia,Im="__reactEvents$"+Ia,c5="__reactListeners$"+Ia,u5="__reactHandles$"+Ia,cx="__reactResources$"+Ia,Ws="__reactMarker$"+Ia;function $m(a){delete a[on],delete a[An],delete a[Im],delete a[c5],delete a[u5]}function jl(a){var i=a[on];if(i)return i;for(var o=a.parentNode;o;){if(i=o[wl]||o[on]){if(o=i.alternate,i.child!==null||o!==null&&o.child!==null)for(a=Cw(a);a!==null;){if(o=a[on])return o;a=Cw(a)}return i}a=o,o=a.parentNode}return null}function _l(a){if(a=a[on]||a[wl]){var i=a.tag;if(i===5||i===6||i===13||i===31||i===26||i===27||i===3)return a}return null}function Zs(a){var i=a.tag;if(i===5||i===26||i===27||i===6)return a.stateNode;throw Error(r(33))}function Nl(a){var i=a[cx];return i||(i=a[cx]={hoistableStyles:new Map,hoistableScripts:new Map}),i}function en(a){a[Ws]=!0}var ux=new Set,dx={};function _i(a,i){Sl(a,i),Sl(a+"Capture",i)}function Sl(a,i){for(dx[a]=i,a=0;a<i.length;a++)ux.add(i[a])}var d5=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\ Line truncated
`).replace(H3,"")}function bw(a,i){return i=xw(i),xw(a)===i}function ot(a,i,o,u,p,g){switch(o){case"children":typeof u=="string"?i==="body"||i==="textarea"&&u===""||Ol(a,u):(typeof u=="number"||typeof u=="bigint")&&i!=="body"&&Ol(a,""+u);break;case"className":Wc(a,"class",u);break;case"tabIndex":Wc(a,"tabindex",u);break;case"dir":case"role":case"viewBox":case"width":case"height":Wc(a,o,u);break;case"style":bx(a,u,g);break;case"data":if(i!=="object"){Wc(a,"data",u);break}case"src":case"href":if(u===""&&(i!=="a"||o!=="href")){a.removeAttribute(o);break}if(u==null||typeof u=="function"||typeof u=="symbol"||typeof u=="boolean"){a.removeAttribute(o);break}u=Qc(""+u),a.setAttribute(o,u);break;case"action":case"formAction":if(typeof u=="function"){a.setAttribute(o,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof g=="function"&&(o==="formAction"?(i!=="input"&&ot(a,i,"name",p.name,p,null),ot(a,i,"formEncType",p.formEncType,p,null),ot(a,i,"formMethod",p.formMethod,p,null),ot(a,i,"formTarget",p.formTarget,p,null)):(ot(a,i,"encType",p.encType,p,null),ot(a,i,"method",p.method,p,null),ot(a,i,"target",p.target,p,null)));if(u==null||typeof u=="symbol"||typeof u=="boolean"){a.removeAttribute(o);break}u=Qc(""+u),a.setAttribute(o,u);break;case"onClick":u!=null&&(a.onclick=Jr);break;case"onScroll":u!=null&&Ke("scroll",a);break;case"onScrollEnd":u!=null&&Ke("scrollend",a);break;case"dangerouslySetInnerHTML":if(u!=null){if(typeof u!="object"||!("__html"in u))throw Error(r(61));if(o=u.__html,o!=null){if(p.children!=null)throw Error(r(60));a.innerHTML=o}}break;case"multiple":a.multiple=u&&typeof u!="function"&&typeof u!="symbol";break;case"muted":a.muted=u&&typeof u!="function"&&typeof u!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(u==null||typeof u=="function"||typeof u=="boolean"||typeof u=="symbol"){a.removeAttribute("xlink:href");break}o=Qc(""+u),a.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",o);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":u!=null&&typeof u!="function"&&typeof u!="symbol"?a.setAttribute(o,""+u):a.removeAttribute(o);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":u&&typeof u!="function"&&typeof u!="symbol"?a.setAttribute(o,""):a.removeAttribute(o);break;case"capture":case"download":u===!0?a.setAttribute(o,""):u!==!1&&u!=null&&typeof u!="function"&&typeof u!="symbol"?a.setAttribute(o,u):a.removeAttribute(o);break;case"cols":case"rows":case"size":case"span":u!=null&&typeof u!="function"&&typeof u!="symbol"&&!isNaN(u)&&1<=u?a.setAttribute(o,u):a.removeAttribute(o);break;case"rowSpan":case"start":u==null||typeof u=="function"||typeof u=="symbol"||isNaN(u)?a.removeAttribute(o):a.setAttribute(o,u);break;case"popover":Ke("beforetoggle",a),Ke("toggle",a),Xc(a,"popover",u);break;case"xlinkActuate":Qr(a,"http://www.w3.org/1999/xlink","xlink:actuate",u);break;case"xlinkArcrole":Qr(a,"http://www.w3.org/1999/xlink","xlink:arcrole",u);break;case"xlinkRole":Qr(a,"http://www.w3.org/1999/xlink","xlink:role",u);break;case"xlinkShow":Qr(a,"http://www.w3.org/1999/xlink","xlink:show",u);break;case"xlinkTitle":Qr(a,"http://www.w3.org/1999/xlink","xlink:title",u);break;case"xlinkType":Qr(a,"http://www.w3.org/1999/xlink","xlink:type",u);break;case"xmlBase":Qr(a,"http://www.w3.org/XML/1998/namespace","xml:base",u);break;case"xmlLang":Qr(a,"http://www.w3.org/XML/1998/namespace","xml:lang",u);break;case"xmlSpace":Qr(a,"http://www.w3.org/XML/1998/namespace","xml:space",u);break;case"is":Xc(a,"is",u);break;case"innerText":case"textContent":break;default:(!(2<o.length)||o[0]!=="o"&&o[0]!=="O"||o[1]!=="n"&&o[1]!=="N")&&(o=v5.get(o)||o,Xc(a,o,u))}}function Op(a,i,o,u,p,g){switch(o){case"style":bx(a,u,g);break;case"dangerouslySetInnerHTML":if(u!=null){if(typeof u!="object"||!("__html"in u))throw Error(r(61));if(o=u.__html,o!=null){if(p.children!=null)throw Error(r(60));a.innerHTML=o}}break;case"children":typeof u=="string"?Ol(a,u):(typeof u=="number"||typeof u=="bigint")&&Ol(a,""+u);break;case"onScroll":u!=null&&Ke("scroll",a);break;case"onScrollEnd":u!=null&&Ke("scrollend",a);break;case"onClick":u!=null&&(a.onclick=Jr);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"inne Line truncated
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const PT=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),zT=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),cj=e=>{const t=zT(e);return t.charAt(0).toUpperCase()+t.slice(1)},lA=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),IT=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/var $T={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const RT=x.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:l="",children:s,iconNode:d,...f},m)=>x.createElement("svg",{ref:m,...$T,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:lA("lucide",l),...!s&&!IT(f)&&{"aria-hidden":"true"},...f},[...d.map(([h,v])=>x.createElement(h,v)),...Array.isArray(s)?s:[s]]));/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Oe=(e,t)=>{const n=x.forwardRef(({className:r,...l},s)=>x.createElement(RT,{ref:s,iconNode:t,className:lA(`lucide-${PT(cj(e))}`,`lucide-${e}`,r),...l}));return n.displayName=cj(e),n};/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const LT=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],uj=Oe("activity",LT);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const BT=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Rv=Oe("arrow-right",BT);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const UT=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],gs=Oe("bell",UT);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const HT=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],ps=Oe("bot",HT);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const qT=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],sA=Oe("box",qT);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const KT=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],ci=Oe("check",KT);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const YT=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],GT=Oe("chevron-down",YT);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const VT=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],FT=Oe("chevron-left",VT);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const XT=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],WT=Oe("chevron-right",XT);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const ZT=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],$d=Oe("circle-alert",ZT);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const QT=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],oA=Oe("circle-check",QT);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const JT=[["path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0",key:"5ilxe3"}],["path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0",key:"11zvb9"}],["path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7",key:"1iw5b2"}],["path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8",key:"c0bmvh"}],["path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69",key:"1ruxm7"}],["path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8",key:"qkgqxc"}],["path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69",key:"1mcia2"}],["path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7",key:"1fvljs"}]],eM=Oe("circle-dashed",JT);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const tM=[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],cA=Oe("clock-3",tM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const nM=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],dj=Oe("clock",nM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const rM=[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]],od=Oe("cloud-upload",rM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const aM=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],fj=Oe("code",aM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const iM=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],lM=Oe("copy",iM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const sM=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],Lv=Oe("credit-card",sM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const oM=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],cM=Oe("database",oM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const uM=[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]],dM=Oe("dollar-sign",uM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const fM=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],uA=Oe("external-link",fM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const mM=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],ic=Oe("eye-off",mM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const hM=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],xs=Oe("eye",hM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const pM=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]],vM=Oe("file-down",pM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const yM=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],mj=Oe("file-text",yM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const gM=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]],xM=Oe("gift",gM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const bM=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],hj=Oe("image",bM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const wM=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],jM=Oe("key",wM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const _M=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],NM=Oe("layers",_M);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const SM=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],AM=Oe("layout-dashboard",SM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const OM=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],EM=Oe("link-2",OM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const kM=[["path",{d:"M16 5H3",key:"m91uny"}],["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 19H3",key:"zzsher"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]],CM=Oe("list-plus",kM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const TM=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Yn=Oe("loader-circle",TM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const MM=[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]],pj=Oe("lock-keyhole",MM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const DM=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],PM=Oe("lock",DM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const zM=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],IM=Oe("log-out",zM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const $M=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],dA=Oe("mail",$M);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const RM=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],Cd=Oe("message-circle",RM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const LM=[["path",{d:"m16 16 2 2 4-4",key:"gfu2re"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],uc=Oe("package-check",LM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const BM=[["path",{d:"M16 16h6",key:"100bgy"}],["path",{d:"M19 13v6",key:"85cyf1"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],Zp=Oe("package-plus",BM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const UM=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],fA=Oe("package",UM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const HM=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],mA=Oe("pen",HM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const qM=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],ja=Oe("plus",qM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const KM=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],YM=Oe("power",KM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const GM=[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]],Qp=Oe("qr-code",GM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const VM=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],pr=Oe("refresh-cw",VM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const FM=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],Sa=Oe("save",FM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const XM=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],WM=Oe("search",XM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const ZM=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],Yy=Oe("send",ZM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const QM=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Gy=Oe("settings",QM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const JM=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],hA=Oe("shield-check",JM);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const eD=[["path",{d:"M16 10a4 4 0 0 1-8 0",key:"1ltviw"}],["path",{d:"M3.103 6.034h17.794",key:"awc11p"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z",key:"o988cm"}]],pA=Oe("shopping-bag",eD);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const tD=[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]],vj=Oe("shopping-cart",tD);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const nD=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],vA=Oe("sparkles",nD);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const rD=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],bs=Oe("square-pen",rD);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const aD=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],xa=Oe("trash-2",aD);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const iD=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],lD=Oe("trending-up",iD);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const sD=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]],yj=Oe("truck",sD);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const oD=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],tc=Oe("upload",oD);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const cD=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],uD=Oe("user-round",cD);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const dD=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],Bv=Oe("user",dD);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const fD=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],yA=Oe("users",fD);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const mD=[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]],hD=Oe("webhook",mD);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const pD=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Xt=Oe("x",pD);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const vD=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],Uv=Oe("zap",vD),yD=({activeTab:e,onNavigate:t,onLogout:n})=>{const r=[{id:"dashboard",icon:AM,label:"仪表盘"},{id:"accounts",icon:yA,label:"账号管理"},{id:"orders",icon:pA,label:"订单管理"},{id:"cards",icon:Lv,label:"卡密库存"},{id:"items",icon:sA,label:"商品列表"},{id:"rules",icon:Uv,label:"自动化规则"},{id:"notifications",icon:gs,label:"通知设置"},{id:"settings",icon:Gy,label:"系统与AI"}];return c.jsxs("div",{className:"w-64 h-screen fixed left-0 top-0 bg-white border-r border-gray-100 flex flex-col justify-between z-20 shadow-[4px_0_24px_rgba(0,0,0,0.02)]",children:[c.jsxs("div",{className:"p-6",children:[c.jsxs("div",{className:"flex items-center gap-3 mb-12 px-2",children:[c.jsx("div",{className:"w-10 h-10 bg-[#0094f7] squircle flex items-center justify-center shrink-0 p-1.5",style:{filter:"drop-shadow(0 4px 12px rgba(0,148,247,0.25))"},children:c.jsx("img",{src:"/static/ydisks-logo.svg",alt:"Ydisks",className:"w-full h-full"})}),c.jsxs("h1",{className:"text-xl font-extrabold tracking-tight text-gray-900",children:["Ydisks闲鱼助手 ",c.jsx("span",{className:"text-xs bg-[#0094f7] text-white px-1.5 py-0.5 rounded ml-1",children:"PRO"})]})]}),c.jsx("nav",{className:"space-y-2",children:r.map(l=>{const s=l.icon,d=e===l.id;return c.jsxs("button",{onClick:()=>t(l.id),className:`w-full flex items-center gap-3 px-4 py-3.5 rounded-2xl transition-all duration-300 group relative overflow-hidden ${d?"bg-[#0094f7] text-white font-bold shadow-lg shadow-blue-100 transform scale-[1.02]":"text-gray-500 hover:bg-gray-50 hover:text-gray-900"}`,children:[c.jsx(s,{className:`w-5 h-5 transition-colors ${d?"text-white":"text-gray-400 group-hover:text-gray-600"}`}),c.jsx("span",{className:"text-sm tracking-wide",children:l.label}),d&&c.jsx(vA,{className:"w-4 h-4 absolute right-3 text-white/30 animate-pulse"})]},l.id)})})]}),c.jsx("div",{className:"p-6 border-t border-gray-50",children:c.jsxs("button",{onClick:n,className:"w-full flex items-center gap-3 px-4 py-3 text-gray-500 hover:text-red-500 hover:bg-red-50 rounded-2xl transition-all duration-200 font-medium",children:[c.jsx(IM,{className:"w-5 h-5"}),c.jsx("span",{className:"text-sm",children:"退出登录"})]})})]})},gD=e=>{if(!e)return"";const t=new URLSearchParams;for(const[r,l]of Object.entries(e))l!=null&&t.set(r,String(l));const n=t.toString();return n?`?${n}`:""},Rf=async(e,t,n={})=>{const r=gD(n.params),l=`${t}${r}`,s=await fetch(l,{method:e,credentials:"include",headers:{...n.body===void 0?{}:{"Content-Type":"application/json"}},body:n.body===void 0?void 0:JSON.stringify(n.body)}),f=(s.headers.get("content-type")||"").includes("application/json");if(!s.ok){const m=f?await s.json().catch(()=>{}):await s.text().catch(()=>{}),h=typeof m=="string"?m:(m==null?void 0:m.detail)||(m==null?void 0:m.message)||(m==null?void 0:m.msg);throw new Error(h||`请求失败: ${s.status}`)}return f?await s.json():await s.text()},Tt=async(e,t)=>Rf("GET",e,{params:t}),$t=async(e,t)=>Rf("POST",e,{body:t}),Sn=async(e,t)=>Rf("PUT",e,{body:t}),ml=async(e,t)=>Rf("DELETE",e,{params:t}),Vy=async(e,t)=>{const n=await fetch(e,{method:"POST",credentials:"include",body:t}),s=(n.headers.get("content-type")||"").includes("application/json")?await n.json().catch(()=>{}):await n.text().catch(()=>{});if(!n.ok){const d=typeof s=="string"?s:(s==null?void 0:s.detail)||(s==null?void 0:s.message)||(s==null?void 0:s.msg),f=new Error(d||"请求失败: "+n.status);throw f.payload=s,f}return s},xD=async e=>$t("/login",e),gA=async()=>Tt("/verify"),bD=async e=>Sn("/account/credentials",e),wD=async(e,t)=>$t("/cookies",{id:e,value:t}),jD=(e,t)=>{const n=e.avatar_url||"";if(!n)return"";try{const r=new URL(n,window.location.origin);return r.hostname.endsWith("alicdn.com")&&r.searchParams.set("_v",t),r.toString()}catch{return n}},Fy=async()=>{const e=await Tt("/cookies/details"),t=Date.now().toString();return e.map(n=>({id:n.id,value:"",cookie:"",enabled:n.enabled,auto_confirm:n.auto_confirm,remark:n.remark,note:n.remark,pause_duration:n.pause_duration,username:n.username||"",login_password:"",show_browser:n.show_browser,nickname:n.nickname||n.remark||`账号 ${n.id.substring(0,6)}`,avatar_url:jD(n,t),profile_error:n.profile_error||"",ai_enabled:!1}))},_D=async()=>Tt("/cookies/runtime-status"),ND=async()=>$t("/qr-login/generate"),SD=async e=>Tt(`/qr-login/check/${e}`),AD=async(e,t)=>Sn(`/cookies/${e}/status`,{enabled:t}),OD=async e=>ml(`/cookies/${e}`),ED=async(e,t)=>Sn(`/cookies/${e}/remark`,{remark:t}),kD=async(e,t)=>Sn(`/cookies/${e}/auto-confirm`,{auto_confirm:t}),CD=async(e,t)=>Sn(`/cookies/${e}/pause-duration`,{pause_duration:t}),gj=async(e,t)=>Sn(`/cookies/${e}`,{id:e,value:t}),TD=async e=>$t(`/cookies/${e}/refresh-profile`,{}),MD=async(e,t)=>Sn(`/cookies/${e}/login-info`,t),DD=asynLine truncated
A`).concat(s,",").concat(s,",0,1,1,").concat(2*d,",").concat(l,`
H`).concat(fr,"M").concat(2*d,",").concat(l,`
A`).concat(s,",").concat(s,",0,1,1,").concat(d,",").concat(l),className:"recharts-legend-icon"});if(m==="rect")return x.createElement("path",{stroke:"none",fill:f,d:"M0,".concat(fr/8,"h").concat(fr,"v").concat(fr*3/4,"h").concat(-fr,"z"),className:"recharts-legend-icon"});if(x.isValidElement(t.legendIcon)){var h=WA({},t);return delete h.legendIcon,x.cloneElement(t.legendIcon,h)}return x.createElement(FA,{fill:f,cx:l,cy:l,size:fr,sizeType:"diameter",type:m})}function D6(e){var t=e.payload,n=e.iconSize,r=e.layout,l=e.formatter,s=e.inactiveColor,d=e.iconType,f=e.labelStyle,m={x:0,y:0,width:fr,height:fr},h={display:r==="horizontal"?"inline-block":"block",marginRight:10},v={display:"inline-block",verticalAlign:"middle",marginRight:4};return t.map((y,b)=>{var w=y.formatter||l,j=nt({"recharts-legend-item":!0,["legend-item-".concat(b)]:!0,inactive:y.inactive});if(y.type==="none")return null;var _=typeof f=="object"?WA({},f):{};_.color=y.inactive?s:_.color||y.color;var S=w?w(y.value,y,b):y.value;return x.createElement("li",Kd({className:j,style:h,key:"legend-item-".concat(b)},Oc(e,y,b)),x.createElement(Wy,{width:n,height:n,viewBox:m,style:v,"aria-label":"".concat(y.value," legend icon")},x.createElement(M6,{data:y,iconType:d,inactiveColor:s})),x.createElement("span",{className:"recharts-legend-item-text",style:_},S))})}var P6=e=>{var t=an(e,C6),n=t.payload,r=t.layout,l=t.align;if(!n||!n.length)return null;var s={padding:0,margin:0,textAlign:r==="horizontal"?l:"left"};return x.createElement("ul",{className:"recharts-default-legend",style:s},x.createElement(D6,Kd({},t,{payload:n})))};function z6(e,t){const n=new Map;for(let r=0;r<e.length;r++){const l=e[r],s=t(l,r,e);n.has(s)||n.set(s,l)}return Array.from(n.values())}function I6(e,t){return function(...n){return e.apply(this,n.slice(0,t))}}function ZA(e){return e}function $6(e){return function(t){return Hr(t,e)}}function Wv(e){return e==null||typeof e!="object"&&typeof e!="function"}function R6(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function L6(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function r0(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const B6="[object RegExp]",QA="[object String]",JA="[object Number]",eO="[object Boolean]",tO="[object Arguments]",U6="[object Symbol]",H6="[object Date]",q6="[object Map]",K6="[object Set]",Y6="[object Array]",G6="[object ArrayBuffer]",V6="[object Object]",F6="[object DataView]",X6="[object Uint8Array]",W6="[object Uint8ClampedArray]",Z6="[object Uint16Array]",Q6="[object Uint32Array]",J6="[object Int8Array]",ez="[object Int16Array]",tz="[object Int32Array]",nz="[object Float32Array]",rz="[object Float64Array]",Dj=typeof globalThis=="object"&&globalThis||typeof window=="object"&&window||typeof self=="object"&&self||typeof global=="object"&&global||(function(){return this})();function az(e){return typeof Dj.Buffer<"u"&&Dj.Buffer.isBuffer(e)}function iz(e,t){return Fi(e,void 0,e,new Map,t)}function Fi(e,t,n,r=new Map,l=void 0){const s=l==null?void 0:l(e,t,n,r);if(s!==void 0)return s;if(Wv(e))return e;if(r.has(e))return r.get(e);if(Array.isArray(e)){const d=new Array(e.length);r.set(e,d);for(let f=0;f<e.length;f++)d[f]=Fi(e[f],f,n,r,l);return Object.hasOwn(e,"index")&&(d.index=e.index),Object.hasOwn(e,"input")&&(d.input=e.input),d}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){const d=new RegExp(e.source,e.flags);return d.lastIndex=e.lastIndex,d}if(e instanceof Map){const d=new Map;r.set(e,d);for(const[f,m]of e)d.set(f,Fi(m,f,n,r,l));return d}if(e instanceof Set){const d=new Set;r.set(e,d);for(const f of e)d.add(Fi(f,void 0,n,r,l));return d}if(az(e))return e.subarray();if(R6(e)){const d=new(Object.getPrototypeOf(e)).constructor(e.length);r.set(e,d);for(let f=0;f<e.length;f++)d[f]=Fi(e[f],f,n,r,l);return d}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){const d=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return r.set(e,d),jr(d,e,n,r,l),d}if(typeof File<"u"&&e instanceof File){const d=new File([e],e.name,{type:e.type});return r.set(e,d),jr(d,e,n,r,l),d}if(typeof Blob<"u"&&e instanceof Blob){const d=new Blob([e],{type:e.type});return r.set(e,d),jr(d,e,n,r,l),d}if(e instanceof Error){const d=structuredClone(e);return r.set(e,d),d.message=e.message,d.name=e.name,d.stack=e.stack,d.cause=e.cause,d.constructor=e.constructor,jr(d,e,n,r,l),d}if(e instanceof Boolean){const d=new Boolean(e.valueOf());return r.set(e,d),jr(d,e,n,r,l),d}if(e instanceof Number){const d=new Number(e.valueOf());return r.set(e,d),jr(d,e,n,r,l),d}if(e instanceof String){const d=new String(e.valueOf());return r.set(e,d),jr(d,e,n,r,l),d}if(typeof e=="object"&&lz(e)){const d=Object.create(Object.getPrototypeOf(e));return r.set(e,d),jr(d,e,n,r,l),d}return e}function jr(e,t,n=e,r,l){const s=[...Object.keys Line truncated
* @license React
* use-sync-external-store-shim.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var zj;function jz(){if(zj)return iv;zj=1;var e=zs();function t(y,b){return y===b&&(y!==0||1/y===1/b)||y!==y&&b!==b}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,l=e.useEffect,s=e.useLayoutEffect,d=e.useDebugValue;function f(y,b){var w=b(),j=r({inst:{value:w,getSnapshot:b}}),_=j[0].inst,S=j[1];return s(function(){_.value=w,_.getSnapshot=b,m(_)&&S({inst:_})},[y,w,b]),l(function(){return m(_)&&S({inst:_}),y(function(){m(_)&&S({inst:_})})},[y]),d(w),w}function m(y){var b=y.getSnapshot;y=y.value;try{var w=b();return!n(y,w)}catch{return!0}}function h(y,b){return b()}var v=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?h:f;return iv.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:v,iv}var Ij;function _z(){return Ij||(Ij=1,av.exports=jz()),av.exports}/**
* @license React
* use-sync-external-store-shim/with-selector.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var $j;function Nz(){if($j)return rv;$j=1;var e=zs(),t=_z();function n(h,v){return h===v&&(h!==0||1/h===1/v)||h!==h&&v!==v}var r=typeof Object.is=="function"?Object.is:n,l=t.useSyncExternalStore,s=e.useRef,d=e.useEffect,f=e.useMemo,m=e.useDebugValue;return rv.useSyncExternalStoreWithSelector=function(h,v,y,b,w){var j=s(null);if(j.current===null){var _={hasValue:!1,value:null};j.current=_}else _=j.current;j=f(function(){function A(E){if(!C){if(C=!0,M=E,E=b(E),w!==void 0&&_.hasValue){var $=_.value;if(w($,E))return k=$}return k=E}if($=k,r(M,E))return $;var U=b(E);return w!==void 0&&w($,U)?(M=E,$):(M=E,k=U)}var C=!1,M,k,D=y===void 0?null:y;return[function(){return A(v())},D===null?void 0:function(){return A(D())}]},[v,y,b,w]);var S=l(h,j[0],j[1]);return d(function(){_.hasValue=!0,_.value=S},[S]),m(S),S},rv}var Rj;function Sz(){return Rj||(Rj=1,nv.exports=Nz()),nv.exports}var Az=Sz(),a0=x.createContext(null),Oz=e=>e,dt=()=>{var e=x.useContext(a0);return e?e.store.dispatch:Oz},Md=()=>{},Ez=()=>Md,kz=(e,t)=>e===t;function Ne(e){var t=x.useContext(a0),n=x.useMemo(()=>t?r=>{if(r!=null)return e(r)}:Md,[t,e]);return Az.useSyncExternalStoreWithSelector(t?t.subscription.addNestedSub:Ez,t?t.store.getState:Md,t?t.store.getState:Md,n,kz)}function Cz(e,t=`expected a function, instead received ${typeof e}`){if(typeof e!="function")throw new TypeError(t)}function Tz(e,t="expected all items to be functions, instead received the following types: "){if(!e.every(n=>typeof n=="function")){const n=e.map(r=>typeof r=="function"?`function ${r.name||"unnamed"}()`:typeof r).join(", ");throw new TypeError(`${t}[${n}]`)}}var Lj=e=>Array.isArray(e)?e:[e];function Mz(e){const t=Array.isArray(e[0])?e[0]:e;return Tz(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}function Dz(e,t){const n=[],{length:r}=e;for(let l=0;l<r;l++)n.push(e[l].apply(null,t));return n}var Pz=class{constructor(e){this.value=e}deref(){return this.value}},zz=()=>typeof WeakRef>"u"?Pz:WeakRef,cO=zz(),Iz=0,Bj=1;function dd(){return{s:Iz,v:void 0,o:null,p:null}}function $z(e){return e instanceof cO?e.deref():e}function uO(e,t={}){let n=dd();const{resultEqualityCheck:r}=t;let l,s=0;function d(){let f=n;const{length:m}=arguments;for(let y=0,b=m;y<b;y++){const w=arguments[y];if(typeof w=="function"||typeof w=="object"&&w!==null){let j=f.o;j===null&&(f.o=j=new WeakMap);const _=j.get(w);_===void 0?(f=dd(),j.set(w,f)):f=_}else{let j=f.p;j===null&&(f.p=j=new Map);const _=j.get(w);_===void 0?(f=dd(),j.set(w,f)):f=_}}const h=f;let v;if(f.s===Bj)v=f.v;else if(v=e.apply(null,arguments),s++,r){const y=$z(l);y!=null&&r(y,v)&&(v=y,s!==0&&s--),l=typeof v=="object"&&v!==null||typeof v=="function"?new cO(v):v}return h.s=Bj,h.v=v,v}return d.clearCache=()=>{n=dd(),d.resetResultsCount()},d.resultsCount=()=>s,d.resetResultsCount=()=>{s=0},d}function Rz(e,...t){const n=typeof e=="function"?{memoize:e,memoizeOptions:t}:e,r=(...l)=>{let s=0,d=0,f,m={},h=l.pop();typeof h=="object"&&(m=h,h=l.pop()),Cz(h,`createSelector expects an output function after the inputs, but received: [${typeof h}]`);const v={...n,...m},{memoize:y,memoizeOptions:b=[],argsMemoize:w=uO,argsMemoizeOptions:j=[]}=v,_=Lj(b),S=Lj(j),A=Mz(l),C=y(function(){return s++,h.apply(null,arguments)},..._),M=w(function(){d++;const D=Dz(A,arguments);return f=C.apply(null,D),f},...S);return Object.assign(M,{resultFunc:h,memoizedResultFunc:C,dependencies:A,dependencyRecomputations:()=>d,resetDependencyRecomputations:()=>{d=0},lastResult:()=>f,recomputations:()=>s,resetRecomputations:()=>{s=0},memoize:y,argsMemoize:w})};return Object.assign(r,{withTypes:()=>r}),r}var X=Rz(uO);function Lz(e,t=1){const n=[],r=Math.floor(t),l=(s,d)=>{for(let f=0;f<s.length;f++){const m=s[f];Array.isArray(m)&&d<r?l(m,d+1):n.push(m)}};return l(e,0),n}function Qv(e,t,n){return nO(n)&&(typeof t=="number"&&sO(n)&&lO(t)&&t<n.length||typeof t=="string"&&t in n)?Td(n[t],e):!1}function Uj(e){return typeof e=="symbol"?1:e===null?2:e===void 0?3:e!==e?4:0}const Bz=(e,t,n)=>{if(e!==t){const r=Uj(e),l=Uj(t);if(r===l&&r===0){if(e<t)return n==="desc"?1:-1;if(e>t)return n==="desc"?-1:1}return n==="desc"?l-r:r-l}return 0};function dO(e){return typeof e=="symbol"||e instanceof Symbol}const Uz=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Hz=/^\w*$/;function qz(e,t){return Array.isArray(e)?!1:typeof e=="number"||typeof e=="boolean"||e==null||dO(e)?!0:typeof e=="string"&&(Hz.test(e)||!Uz.test(e))||t!=null}function Kz(e,t,n,r){if(e==null)return[];n=n,Array.isArray(e)||(e=Object.values(e)),Array.isArray(t)||(t=t==null?[null]:[t]),t.length===0&&(t=[null]),Array.isArray(n)||(n=n==null?[]:[n]),n=n.map(f=>String(f));const l=(f,m)=>{let h=f;for(let v=0;v<m.length&&h!=null;++v)h=h[m[v]];return h},s=(f,m)=>m==null||f==null?m:typeof f=="object"&&"key"in f?Object.hasOwn(m,f.key)?m[f.key]:l(m,f.path):typeof f=="function"?f(m):Array.isArray(f)?l(m,f):typeof m=="object"?m[f]:m,d=t.map(f=>(Array.isArray(f)&&f.length===1&&(f=f[0]),f==nullLine truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Zz(e,t){if(e){if(typeof e=="string")return Hj(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Hj(e,t):void 0}}function Hj(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Qz(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function Jz(e){if(Array.isArray(e))return e}var fd=1;function qj(e,t){return Math.abs(e.height-t.height)>fd||Math.abs(e.left-t.left)>fd||Math.abs(e.top-t.top)>fd||Math.abs(e.width-t.width)>fd}function Kj(e){var t=e.getBoundingClientRect();return{height:t.height,left:t.left,top:t.top,width:t.width}}function mO(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=x.useState({height:0,left:0,top:0,width:0}),n=Xz(t,2),r=n[0],l=n[1],s=x.useRef(null),d=x.useRef(r);d.current=r;var f=x.useCallback(m=>{if(s.current!=null&&(s.current.disconnect(),s.current=null),m!=null){var h=Kj(m);if(qj(h,d.current)&&l(h),typeof ResizeObserver<"u"){var v=new ResizeObserver(()=>{var y=Kj(m);qj(y,d.current)&&l(y)});v.observe(m),s.current=v}}},[...e]);return x.useEffect(()=>()=>{var m;(m=s.current)===null||m===void 0||m.disconnect()},[]),[r,f]}function mn(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var e8=typeof Symbol=="function"&&Symbol.observable||"@@observable",Yj=e8,lv=()=>Math.random().toString(36).substring(7).split("").join("."),t8={INIT:`@@redux/INIT${lv()}`,REPLACE:`@@redux/REPLACE${lv()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${lv()}`},Yd=t8;function i0(e){if(typeof e!="object"||e===null)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||Object.getPrototypeOf(e)===null}function hO(e,t,n){if(typeof e!="function")throw new Error(mn(2));if(typeof t=="function"&&typeof n=="function"||typeof n=="function"&&typeof arguments[3]=="function")throw new Error(mn(0));if(typeof t=="function"&&typeof n>"u"&&(n=t,t=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(mn(1));return n(hO)(e,t)}let r=e,l=t,s=new Map,d=s,f=0,m=!1;function h(){d===s&&(d=new Map,s.forEach((S,A)=>{d.set(A,S)}))}function v(){if(m)throw new Error(mn(3));return l}function y(S){if(typeof S!="function")throw new Error(mn(4));if(m)throw new Error(mn(5));let A=!0;h();const C=f++;return d.set(C,S),function(){if(A){if(m)throw new Error(mn(6));A=!1,h(),d.delete(C),s=null}}}function b(S){if(!i0(S))throw new Error(mn(7));if(typeof S.type>"u")throw new Error(mn(8));if(typeof S.type!="string")throw new Error(mn(17));if(m)throw new Error(mn(9));try{m=!0,l=r(l,S)}finally{m=!1}return(s=d).forEach(C=>{C()}),S}function w(S){if(typeof S!="function")throw new Error(mn(10));r=S,b({type:Yd.REPLACE})}function j(){const S=y;return{subscribe(A){if(typeof A!="object"||A===null)throw new Error(mn(11));function C(){const k=A;k.next&&k.next(v())}return C(),{unsubscribe:S(C)}},[Yj](){return this}}}return b({type:Yd.INIT}),{dispatch:b,subscribe:y,getState:v,replaceReducer:w,[Yj]:j}}function n8(e){Object.keys(e).forEach(t=>{const n=e[t];if(typeof n(void 0,{type:Yd.INIT})>"u")throw new Error(mn(12));if(typeof n(void 0,{type:Yd.PROBE_UNKNOWN_ACTION()})>"u")throw new Error(mn(13))})}function pO(e){const t=Object.keys(e),n={};for(let s=0;s<t.length;s++){const d=t[s];typeof e[d]=="function"&&(n[d]=e[d])}const r=Object.keys(n);let l;try{n8(n)}catch(s){l=s}return function(d={},f){if(l)throw l;let m=!1;const h={};for(let v=0;v<r.length;v++){const y=r[v],b=n[y],w=d[y],j=b(w,f);if(typeof j>"u")throw f&&f.type,new Error(mn(14));h[y]=j,m=m||j!==w}return m=m||r.length!==Object.keys(d).length,m?h:d}}function Gd(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,n)=>(...r)=>t(n(...r)))}function r8(...e){return t=>(n,r)=>{const l=t(n,r);let s=()=>{throw new Error(mn(15))};const d={getState:l.getState,dispatch:(m,...h)=>s(m,...h)},f=e.map(m=>m(d));return s=Gd(...f)(l.dispatch),{...l,dispatch:s}}}function vO(e){return i0(e)&&"type"in e&&typeof e.type=="string"}var yO=Symbol.for("immer-nothing"),Gj=Symbol.for("immer-draftable"),Nn=Symbol.for("immer-state");function _r(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Vn=Object,Ss=Vn.getPrototypeOf,Vd="constructor",qf="prototype",Jv="configurable",Fd="enumerable",Dd="writable",fc="value",Aa=e=>!!e&&!!e[Nn];function Or(e){var t;return e?gO(e)||Yf(e)||!!e[Gj]||!!((t=e[Vd])!=null&&t Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function HI(e,t){if(e){if(typeof e=="string")return p_(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?p_(e,t):void 0}}function p_(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function qI(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function KI(e){if(Array.isArray(e))return e}function YI(e,t){if(e==null)return{};var n,r,l=GI(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(r=0;r<s.length;r++)n=s[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(l[n]=e[n])}return l}function GI(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var ZO=x.createContext(Rr.initialDimension);function VI(e){return Kr(e.width)&&Kr(e.height)}function QO(e){var t=e.children,n=e.width,r=e.height,l=x.useMemo(()=>({width:n,height:r}),[n,r]);return VI(l)?x.createElement(ZO.Provider,{value:l},t):null}var f0=()=>x.useContext(ZO),FI=x.forwardRef((e,t)=>{var n=e.aspect,r=e.initialDimension,l=r===void 0?Rr.initialDimension:r,s=e.width,d=e.height,f=e.minWidth,m=f===void 0?Rr.minWidth:f,h=e.minHeight,v=e.maxHeight,y=e.children,b=e.debounce,w=b===void 0?Rr.debounce:b,j=e.id,_=e.className,S=e.onResize,A=e.style,C=A===void 0?{}:A,M=YI(e,II),k=x.useRef(null),D=x.useRef();D.current=S,x.useImperativeHandle(t,()=>k.current);var E=x.useState({containerWidth:l.width,containerHeight:l.height}),$=BI(E,2),U=$[0],K=$[1],T=x.useCallback((R,z)=>{K(G=>{var se=Math.round(R),ue=Math.round(z);return G.containerWidth===se&&G.containerHeight===ue?G:{containerWidth:se,containerHeight:ue}})},[]);x.useEffect(()=>{if(k.current==null||typeof ResizeObserver>"u")return hl;var R=P=>{var Q,ne=P[0];if(ne!=null){var I=ne.contentRect,he=I.width,be=I.height;T(he,be),(Q=D.current)===null||Q===void 0||Q.call(D,he,be)}};w>0&&(R=kI(R,w,{trailing:!0,leading:!1}));var z=new ResizeObserver(R),G=k.current.getBoundingClientRect(),se=G.width,ue=G.height;return T(se,ue),z.observe(k.current),()=>{z.disconnect()}},[T,w]);var re=U.containerWidth,Z=U.containerHeight;tf(!n||n>0,"The aspect(%s) must be greater than zero.",n);var pe=WO(re,Z,{width:s,height:d,aspect:n,maxHeight:v}),fe=pe.calculatedWidth,ce=pe.calculatedHeight;return tf(re<0||Z<0||fe!=null&&fe>0||ce!=null&&ce>0,`The width(%s) and height(%s) of chart should be greater than 0,
please check the style of container, or the props width(%s) and height(%s),
or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the
height and width.`,fe,ce,s,d,m,h,n),x.createElement("div",nf({id:j?"".concat(j):void 0,className:nt("recharts-responsive-container",_),style:h_(h_({},C),{},{width:s,height:d,minWidth:m,minHeight:h,maxHeight:v}),ref:k},M),x.createElement("div",{style:PI({width:s,height:d})},x.createElement(QO,{width:fe,height:ce},y)))}),yd=x.forwardRef((e,t)=>{var n=f0();if(Kr(n.width)&&Kr(n.height))return e.children;var r=zI({width:e.width,height:e.height,aspect:e.aspect}),l=r.width,s=r.height,d=WO(void 0,void 0,{width:l,height:s,aspect:e.aspect,maxHeight:e.maxHeight}),f=d.calculatedWidth,m=d.calculatedHeight;return je(f)&&je(m)?x.createElement(QO,{width:f,height:m},e.children):x.createElement(FI,nf({},e,{width:l,height:s,ref:t}))});function m0(e){if(e)return{x:e.x,y:e.y,upperWidth:"upperWidth"in e?e.upperWidth:e.width,lowerWidth:"lowerWidth"in e?e.lowerWidth:e.width,width:e.width,height:e.height}}var rm=()=>{var e,t=wn(),n=Ne(SI),r=Ne(nm),l=(e=Ne(tm))===null||e===void 0?void 0:e.padding;return!t||!r||!l?n:{width:r.width-l.left-l.right,height:r.height-l.top-l.bottom,x:l.left,y:l.top}},XI={top:0,bottom:0,left:0,right:0,width:0,height:0,brushBottom:0},JO=()=>{var e;return(e=Ne(Wt))!==null&&e!==void 0?e:XI},h0=()=>Ne(Ca),p0=()=>Ne(Ta),WI=()=>Ne(e=>e.layout.margin),Ze=e=>e.layout.layoutType,pl=()=>Ne(Ze),v0=()=>{var e=pl();if(e==="horizontal"||e==="vertical")return e},y0=e=>{var t=e.layout.layoutType;if(t==="centric"||t==="radial")return t},ZI=()=>Ne(y0),QI=()=>{var e=pl();return e!==void 0},Tc=e=>{var t=dt(),n=wn(),r=e.width,l=e.height,s=f0(),d=r,f=l;return s&&(d=s.width>0?s.width:r,f=s.height>0?s.height:l),x.useEffect(()=>{!n&&Kr(d)&&Kr(f)&&t(Q8({width:d,height:f}))},[t,n,d,f]),null},eE=Symbol.for("immer-nothing"),v_=Symbol.for("immer-draftable"),Zn=Symbol.for("immer-state");function Nr(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var pc=Object.getPrototypeOf;function Os(e){return!!e&&!!e[Zn]}function sl(e){var t;return e?tE(e)||Array.isArray(e)||!!e[v_]||!!((t=e.constructor)!=null&&t[v_])||Mc(e)||im(e):!1}var JI=Object.prototype.constructor.toString(),y_=new WeakMap;function tE(e){if(!e||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);if(t===null||t===Object.prototype)return!0;const n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;if(n===Object)return!0;if(typeof n!="function")return!1;let r=y_.get(n);return r===void 0&&(r=Function.toString.call(n),y_.set(n,r)),r===JI}function rf(e,t,n=!0){am(e)===0?(n?Reflect.ownKeys(e):Object.keys(e)).forEach(l=>{t(l,e[l],e)}):e.forEach((r,l)=>t(l,r,e))}function am(e){const t=e[Zn];return t?t.type_:Array.isArray(e)?1:Mc(e)?2:im(e)?3:0}function cy(e,t){return am(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function nE(e,t,n){const r=am(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function e$(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Mc(e){return e instanceof Map}function im(e){return e instanceof Set}function Yi(e){return e.copy_||e.base_}function uy(e,t){if(Mc(e))return new Map(e);if(im(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const n=tE(e);if(t===!0||t==="class_only"&&!n){const r=Object.getOwnPropertyDescriptors(e);delete r[Zn];let l=Reflect.ownKeys(r);for(let s=0;s<l.length;s++){const d=l[s],f=r[d];f.writable===!1&&(f.writable=!0,f.configurable=!0),(f.get||f.set)&&(r[d]={configurable:!0,writable:!0,enumerable:f.enumerable,value:e[d]})}return Object.create(pc(e),r)}else{const r=pc(e);if(r!==null&&n)return{...e};const l=Object.create(r);return Object.assign(l,e)}}function g0(e,t=!1){return lm(e)||Os(e)||!sl(e)||(am(e)>1&&Object.defineProperties(e,{set:gd,add:gd,clear:gd,delete:gd}),Object.freeze(e),t&&Object.values(e).forEach(n=>g0(n,!0))),e}function t$(){Nr(2)}var gd={value:t$};function lm(e){return e===null||typeof e!="object"?!0:Object.isFrozen(e)}var n$={};function ol(e){const t=n$[e];return t||Nr(0,e),t}var vc;function rE(){return vc}function r$(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function g_(e,t){t&&(ol("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function dy(e){fy(e),e.drafts_.forEach(a$),e.drafts_=null}function fy(e){e===vc&&(vc=e.parent_)}function x_(e){return vc=r$(vc,e)}function a$(e){const t=e[Zn];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function b_(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[Zn].modified_&&(dy(t),Nr(4)),sl(e)&&(e=af(t,e),t.parent_||lf(t,e)),t.patches_&&ol("Patches").generateReplacementPatches_(n[Zn].base_,e,t.patches_,t.inversePatches_)):e=af(t,n,[]),dy(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==eE?e:void 0}function af(e,t,n){if(lm(t))return t;const r=e.immer_.shouldUseStrictIteration(),l=t[Zn];if(!l)return rf(t,(s,d)=>w_(e,l,t,s,d,n),r),t;if(l.scope_!==e)return t;if(!l.modified_)return lf(e,l.base_,!0),l.base_;if(!l.finalized_){l.finalized_=!0,l.scope_.unfinalizedDraft Line truncated
* @license React
* use-sync-external-store-with-selector.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var __;function m$(){if(__)return fv;__=1;var e=zs();function t(m,h){return m===h&&(m!==0||1/m===1/h)||m!==m&&h!==h}var n=typeof Object.is=="function"?Object.is:t,r=e.useSyncExternalStore,l=e.useRef,s=e.useEffect,d=e.useMemo,f=e.useDebugValue;return fv.useSyncExternalStoreWithSelector=function(m,h,v,y,b){var w=l(null);if(w.current===null){var j={hasValue:!1,value:null};w.current=j}else j=w.current;w=d(function(){function S(D){if(!A){if(A=!0,C=D,D=y(D),b!==void 0&&j.hasValue){var E=j.value;if(b(E,D))return M=E}return M=D}if(E=M,n(C,D))return E;var $=y(D);return b!==void 0&&b(E,$)?(C=D,E):(C=D,M=$)}var A=!1,C,M,k=v===void 0?null:v;return[function(){return S(h())},k===null?void 0:function(){return S(k())}]},[h,v,y,b]);var _=r(m,w[0],w[1]);return s(function(){j.hasValue=!0,j.value=_},[_]),f(_),_},fv}var N_;function h$(){return N_||(N_=1,dv.exports=m$()),dv.exports}h$();function p$(e){e()}function v$(){let e=null,t=null;return{clear(){e=null,t=null},notify(){p$(()=>{let n=e;for(;n;)n.callback(),n=n.next})},get(){const n=[];let r=e;for(;r;)n.push(r),r=r.next;return n},subscribe(n){let r=!0;const l=t={callback:n,next:null,prev:t};return l.prev?l.prev.next=l:e=l,function(){!r||e===null||(r=!1,l.next?l.next.prev=l.prev:t=l.prev,l.prev?l.prev.next=l.next:e=l.next)}}}}var S_={notify(){},get:()=>[]};function y$(e,t){let n,r=S_,l=0,s=!1;function d(_){v();const S=r.subscribe(_);let A=!1;return()=>{A||(A=!0,S(),y())}}function f(){r.notify()}function m(){j.onStateChange&&j.onStateChange()}function h(){return s}function v(){l++,n||(n=e.subscribe(m),r=v$())}function y(){l--,n&&l===0&&(n(),n=void 0,r.clear(),r=S_)}function b(){s||(s=!0,v())}function w(){s&&(s=!1,y())}const j={addNestedSub:d,notifyNestedSubs:f,handleChangeWrapper:m,isSubscribed:h,trySubscribe:b,tryUnsubscribe:w,getListeners:()=>r};return j}var g$=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",x$=g$(),b$=()=>typeof navigator<"u"&&navigator.product==="ReactNative",w$=b$(),j$=()=>x$||w$?x.useLayoutEffect:x.useEffect,_$=j$();function A_(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function N$(e,t){if(A_(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let l=0;l<n.length;l++)if(!Object.prototype.hasOwnProperty.call(t,n[l])||!A_(e[n[l]],t[n[l]]))return!1;return!0}var mv=Symbol.for("react-redux-context"),hv=typeof globalThis<"u"?globalThis:{};function S$(){if(!x.createContext)return{};const e=hv[mv]??(hv[mv]=new Map);let t=e.get(x.createContext);return t||(t=x.createContext(null),e.set(x.createContext,t)),t}var A$=S$();function O$(e){const{children:t,context:n,serverState:r,store:l}=e,s=x.useMemo(()=>{const m=y$(l);return{store:l,subscription:m,getServerState:r?()=>r:void 0}},[l,r]),d=x.useMemo(()=>l.getState(),[l]);_$(()=>{const{subscription:m}=s;return m.onStateChange=m.notifyNestedSubs,m.trySubscribe(),d!==l.getState()&&m.notifyNestedSubs(),()=>{m.tryUnsubscribe(),m.onStateChange=void 0}},[s,d]);const f=n||A$;return x.createElement(f.Provider,{value:s},t)}var E$=O$,k$=new Set(["axisLine","tickLine","activeBar","activeDot","activeLabel","activeShape","allowEscapeViewBox","background","cursor","dot","label","line","margin","padding","position","shape","style","tick","wrapperStyle","radius","throttledEvents"]);function C$(e,t){return e==null&&t==null?!0:typeof e=="number"&&typeof t=="number"?e===t||e!==e&&t!==t:e===t}function $s(e,t){var n=new Set([...Object.keys(e),...Object.keys(t)]);for(var r of n)if(k$.has(r)){if(e[r]==null&&t[r]==null)continue;if(!N$(e[r],t[r]))return!1}else if(!C$(e[r],t[r]))return!1;return!0}var T$=["contextPayload"];function py(){return py=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},py.apply(null,arguments)}function M$(e,t){return I$(e)||z$(e,t)||P$(e,t)||D$()}function D$(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function P$(e,t){if(e){if(typeof e=="string")return O_(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?O_(e,t):void 0}}function O_(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function z$(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function I$(e){if(Array.isArray(e))return e}function E_(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),n.push.apply(n,r)}return n}function Es(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?E_(Object(n),!0).forEach(function(r){$$(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):E_(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function $$(e,t,n){return(t=R$(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function R$(e){var t=L$(e,"string");return typeof t=="symbol"?t:t+""}function L$(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function B$(e,t){if(e==null)return{};var n,r,l=U$(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(r=0;r<s.length;r++)n=s[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(l[n]=e[n])}return l}function U$(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function H$(e){return e.value}function q$(e){var t=e.contextPayload,n=B$(e,T$),r=oO(t,e.payloadUniqBy,H$),l=Es(Es({},n),{},{payload:r});return x.isValidElement(e.content)?x.cloneElement(e.content,l):typeof e.content=="function"?x.createElement(e.content,l):x.createElement(P6,l)}function K$(e,t,n,r,l,s){var d=t.layout,f=t.align,m=t.verticalAlign,h,v;return(!e||(e.left===void 0||e.left===null)&&(e.right===void 0||e.right===null))&&(f==="center"&&d==="vertical"?h={left:((r||0)-s.width)/2}:h=f==="right"?{right:n&&n.right||0}:{left:n&&n.left||0}),(!e||(e.top===void 0||e.top===null)&&(e.bottom===void 0||e.bottom===null))&&(m==="middle"?v={top:((l||0)-s.height)/2}:v=m==="bottom"?{bottom:n&&n.bottom||0}:{top:n&&n.top||0}),Es(Es({},h),v)}function Y$(e){var t=e.align,n=e.layout,r=e.verticalAlign,l=e.itemSorter,s=dt();return x.useLayoutEffect(()=>{s(d$({align:t,layout:n,verticalAlign:r,itemSorter:l}))},[s,t,n,r,l]),null}function G$(e){var t=e.width,n=e.height,r=dt();return x.useLayoutEffect(()=>{r(j_({width:t,height:n}))},[r,t,n]),x.useLayoutEffect(()=>()=>{r(j_({width:0,height:0}))},[r]),null}function V$(e,t,n,r){return e==="vertical"&&t!=null?{height:t}:e==="horizontal"?{width:n||r}:null}var F$={align:"center",iconSize:14,inactiveColor:"#ccc",itemSorter:"value",labelStyle:{},layout:"horizontal",verticalAlign:"bottom"};function X$(e){var t=an(e,F$),n=Fz(),r=kP(),l=WI(),s=t.width,d=t.height,f=t.wrapperStyle,m=t.portal,h=mO([n]),v=M$(h,2),y=v[0],b=v[1],w=h0(),j=p0();if(w==null||j==null)return null;var _=w-((l==null?void 0:l.left)||0)-((l==null?void 0:l.right)||0),S=V$(t.layout,d,s,_),A=m?f:Es(Es({position:"absolute",width:(S==null?void 0:S.width)||s||"auto",height:(S==null?void 0:S.height)||d||"auto"},K$(f,t,l,w,j,y)),f),C=m??r;if(C==null||n==null)return null;var M=x.createElement("div",{className:"recharts-legend-wrapper",style:A,ref:b},x.createElement(Y$,{layout:t.layout,align:t.align,verticalAlign:t.verticalAlign,itemSorter:t.itemSorter}),!m&&x.createElement(G$,{width:y.width,height:y.height}),x.createElement(q$,py({},t,S,{margin:l,chartWidth:w,chartHeight:j,contextPayload:n})));return It.createPortal(M,C)}var uE=x.memo(X$,$s);uE.displayName="Legend";function vy(){return vy=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},vy.apply(null,arguments)}function k_(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),n.push.apply(n,r)}return n}function Ho(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?k_(Object(n),!0).forEach(func Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function tR(e,t){if(e){if(typeof e=="string")return C_(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?C_(e,t):void 0}}function C_(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function nR(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function rR(e){if(Array.isArray(e))return e}function aR(e){return Array.isArray(e)&&qr(e[0])&&qr(e[1])?e.join(" ~ "):e}var is={separator:" : ",contentStyle:{margin:0,padding:10,backgroundColor:"#fff",border:"1px solid #ccc",whiteSpace:"nowrap"},itemStyle:{display:"block",paddingTop:4,paddingBottom:4,color:"#000"},labelStyle:{},accessibilityLayer:!1};function iR(e,t){return t==null?e:Hf(e,t)}var lR=e=>{var t=e.separator,n=t===void 0?is.separator:t,r=e.contentStyle,l=e.itemStyle,s=e.labelStyle,d=s===void 0?is.labelStyle:s,f=e.payload,m=e.formatter,h=e.itemSorter,v=e.wrapperClassName,y=e.labelClassName,b=e.label,w=e.labelFormatter,j=e.accessibilityLayer,_=j===void 0?is.accessibilityLayer:j,S=()=>{if(f&&f.length){var U={padding:0,margin:0},K=iR(f,h),T=K.map((re,Z)=>{if(!re||re.type==="none")return null;var pe=re.formatter||m||aR,fe=re.value,ce=re.name,R=fe,z=ce;if(pe){var G=pe(fe,ce,re,Z,f);if(Array.isArray(G)){var se=J$(G,2);R=se[0],z=se[1]}else if(G!=null)R=G;else return null}var ue=Ho(Ho({},is.itemStyle),{},{color:re.color||is.itemStyle.color},l);return x.createElement("li",{className:"recharts-tooltip-item",key:"tooltip-item-".concat(Z),style:ue},qr(z)?x.createElement("span",{className:"recharts-tooltip-item-name"},z):null,qr(z)?x.createElement("span",{className:"recharts-tooltip-item-separator"},n):null,x.createElement("span",{className:"recharts-tooltip-item-value"},R),x.createElement("span",{className:"recharts-tooltip-item-unit"},re.unit||""))});return x.createElement("ul",{className:"recharts-tooltip-item-list",style:U},T)}return null},A=Ho(Ho({},is.contentStyle),r),C=Ho({margin:0},d),M=!Nt(b),k=M?b:"",D=nt("recharts-default-tooltip",v),E=nt("recharts-tooltip-label",y);M&&w&&f!==void 0&&f!==null&&(k=w(b,f));var $=_?{role:"status","aria-live":"assertive"}:{};return x.createElement("div",vy({className:D,style:A},$),x.createElement("p",{className:E,style:C},x.isValidElement(k)?k:"".concat(k)),S())},qo="recharts-tooltip-wrapper",sR={visibility:"hidden"};function oR(e){var t=e.coordinate,n=e.translateX,r=e.translateY;return nt(qo,{["".concat(qo,"-right")]:je(n)&&t&&je(t.x)&&n>=t.x,["".concat(qo,"-left")]:je(n)&&t&&je(t.x)&&n<t.x,["".concat(qo,"-bottom")]:je(r)&&t&&je(t.y)&&r>=t.y,["".concat(qo,"-top")]:je(r)&&t&&je(t.y)&&r<t.y})}function T_(e){var t=e.allowEscapeViewBox,n=e.coordinate,r=e.key,l=e.offset,s=e.position,d=e.reverseDirection,f=e.tooltipDimension,m=e.viewBox,h=e.viewBoxDimension;if(s&&je(s[r]))return s[r];var v=n[r]-f-(l>0?l:0),y=n[r]+l;if(t[r])return d[r]?v:y;var b=m[r];if(b==null)return 0;if(d[r]){var w=v,j=b;return w<j?Math.max(y,b):Math.max(v,b)}if(h==null)return 0;var _=y+f,S=b+h;return _>S?Math.max(v,b):Math.max(y,b)}function cR(e){var t=e.translateX,n=e.translateY,r=e.useTranslate3d;return{transform:r?"translate3d(".concat(t,"px, ").concat(n,"px, 0)"):"translate(".concat(t,"px, ").concat(n,"px)")}}function uR(e){var t=e.allowEscapeViewBox,n=e.coordinate,r=e.offsetTop,l=e.offsetLeft,s=e.position,d=e.reverseDirection,f=e.tooltipBox,m=e.useTranslate3d,h=e.viewBox,v,y,b;return f.height>0&&f.width>0&&n?(y=T_({allowEscapeViewBox:t,coordinate:n,key:"x",offset:l,position:s,reverseDirection:d,tooltipDimension:f.width,viewBox:h,viewBoxDimension:h.width}),b=T_({allowEscapeViewBox:t,coordinate:n,key:"y",offset:r,position:s,reverseDirection:d,tooltipDimension:f.height,viewBox:h,viewBoxDimension:h.height}),v=cR({translateX:y,translateY:b,useTranslate3d:m})):v=sR,{cssProperties:v,cssClasses:oR({translateX:y,translateY:b,coordinate:n})}}var dR=()=>!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout),Pc={isSsr:dR()};function fR(e,t){return vR(e)||pR(e,t)||hR(e,t)||mR()}function mR(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function hR(e,t){if(e){if(typeof e=="string")return M_(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?M_(e,t):void 0}}function M_(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function pR(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function vR(e){if(Array.isArray(e))return e}function dE(){var e=x.useState(()=>Pc.isSsr||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches),t=fR(e,2),n=t[0],r=t[1];return x.useEffect(()=>{if(window.matchMedia){var l=window.matchMedia("(prefers-reduced-motion: reduce)"),s=()=>{r(l.matches)};return l.addEventListener("change",s),()=>{l.removeEventListener("change",s)}}},[]),n}function D_(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),n.push.apply(n,r)}return n}function ls(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?D_(Object(n),!0).forEach(function(r){yR(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):D_(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function yR(e,t,n){return(t=gR(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function gR(e){var t=xR(e,"string");return typeof t=="symbol"?t:t+""}function xR(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function bR(e,t){return NR(e)||_R(e,t)||jR(e,t)||wR()}function wR(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function jR(e,t){if(e){if(typeof e=="string")return P_(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?P_(e,t):void 0}}function P_(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function _R(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function NR(e){if(Array.isArray(e))return e}function SR(e){if(!(e.prefersReducedMotion&&e.isAnimationActive==="auto")&&e.isAnimationActive&&e.active){var t=typeof e.animationEasing=="string"?e.animationEasing:"ease";return"transform ".concat(e.animationDuration,"ms ").concat(t)}}function AR(e){var t,n,r,l,s,d,f=dE(),m=x.useState(()=>({dismissed:!1,dismissedAtCoordinate:{x:0,y:0}})),h=bR(m,2),v=h[0],y=h[1];x.useEffect(()=>{var A=C=>{if(C.key==="Escape"){var M,k,D,E;y({dismissed:!0,dismissedAtCoordinate:{x:(M=(k=e.coordinate)===null||k===void 0?void 0:k.x)!==null&&M!==void 0?M:0,y:(D=(E=e.coordinate)===null||E===void 0?void 0:E.y)!==null&&D!==void 0?D:0}})}};return document.addEventListener("keydown",A),()=>{document.removeEventListener("keydown",A)}},[(t=e.coordinate)===null||t===void 0?void 0:t.x,(n=e.coordinate)===null||n===void 0?void 0:n.y]),v.dismissed&&(((r=(l=e.coordinate)===null||l===void 0?void 0:l.x)!==null&&r!==void 0?r:0)!==v.dismissedAtCoordinate.x||((s=(d=e.coordinate)===null||d===void 0?void 0:d.y)!==null&&s!==void 0?s:0)!==v.dismissedAtCoordinate.y)&&y(ls(ls({},v),{},{dismissed:!1}));var b=uR({allowEscapeViewBox:e.allowEscapeViewBox,coordinate:e.coordinate,offsetLeft:typeof e.offset=="number"?e.offset:e.offset.x,offsetTop:typeof e.offset=="number"?e.offset:e.offset.y,position:e.position,reverseDirection:e.reverseDirection,tooltipBox:{height:e.lastBoundingBox.height,width:e.lastBoundingBox.width},useTranslate3d:e.useTranslate3d,viewBox:e.viewBox}),w=b.cssClasses,j=b.cssProperties,_=e.hasPortalFromProps?{}:ls(ls({transition:SR({prefersReducedMotion:f,isAnimationActive:e.isAnimationActive,active:e.active,animationDuration:e.animationDuration,animationEasing:e.animationEasing})},j),{},{pointerEvents:"none",position:"absolute",top:0,left:0}),S=ls(ls({},_),{},{visibility:!v.dismissed&&e.active&&e.hasPayload?"visible":"hidden"},e.wrapperStyle);return x.createElement("div",{xmlns:"http://www.w3.org/1999/xhtml",tabIndex:-1,className:w,style:S,ref:e.innerRef},e.children)}var OR=x.memo(AR),fE=()=>{var e;return(e=Ne(t=>t.rootProps.accessibilityLayer))!==null&&e!==void 0?e:!0};function yy(){return yy=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},yy.apply(null,arguments)}function z_(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),n.push.apply(n,r)}return n}function I_(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?z_(Object(n),!0).forEach(function(r){ER(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):z_(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function ER(e,t,n){return(t=kR(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function kR(e){var t=CR(e,"string");return typeof t=="symbol"?t:t+""}function CR(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var $_={curveBasisClosed:FP,curveBasisOpen:XP,curveBasis:VP,curveBumpX:DP,curveBumpY:PP,curveLinearClosed:WP,curveLinear:Bf,curveMonotoneX:ZP,curveMonotoneY:QP,curveNatural:JP,curveStep:e6,curveStepAfter:n6,curveStepBefore:t6},sf=e=>He(e.x)&&He(e.y),R_=e=>e.base!=null&&sf(e.base)&&sf(e),Ko=e=>e.x,Yo=e=>e.y,TR=(e,t)=>{if(typeof e=="function")return e;var n="curve".concat(Ac(e));if((n==="curveMonotone"||n==="curveBump")&&t){var r=$_["".concat(n).concat(t==="vertical"?"Y":"X")];if(r)return r}return $_[n]||Bf},L_={connectNulls:!1,type:"linear"},MR=e=>{var t=e.type,n=t===void 0?L_.type:t,r=e.points,l=r===void 0?[]:r,s=e.baseLine,d=e.layout,f=e.connectNulls,m=f===void 0?L_.connectNulls:f,h=TR(n,d),v=m?l.filter(sf):l;if(Array.isArray(s)){var y,b=l.map((A,C)=>I_(I_({},A),{},{base:s[C]}));d==="vertical"?y=ud().y(Yo).x1(Ko).x Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function l7(e,t){if(e){if(typeof e=="string")return G_(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?G_(e,t):void 0}}function G_(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function s7(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function o7(e){if(Array.isArray(e))return e}var c7={begin:0,duration:1e3,easing:"ease",isActive:!0,canBegin:!0,onAnimationEnd:()=>{},onAnimationStart:()=>{}},V_=0,vv=1;function vE(e){var t=an(e,c7),n=t.animationId,r=t.isActive,l=t.canBegin,s=t.duration,d=t.easing,f=t.begin,m=t.onAnimationEnd,h=t.onAnimationStart,v=t.children,y=dE(),b=r==="auto"?!Pc.isSsr&&!y:r,w=WR(t.animationController),j=x.useState(b?V_:vv),_=a7(j,2),S=_[0],A=_[1];return x.useEffect(()=>{b||A(vv)},[b]),x.useEffect(()=>{var C=FR(d);if(!b||!l||C==null)return hl;var M=new r7,k=new n7({animationId:n,easing:C,animationDuration:s,animationBegin:f,onAnimationStart:h,onAnimationEnd:m,from:V_,to:vv});return w(M,k,A)},[w,n,b,l,s,d,f,h,m]),v(Number(S))}function yE(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"animation-",n=x.useRef(dc(t)),r=x.useRef(e);return r.current!==e&&(n.current=dc(t),r.current=e),n.current}var u7=e=>e.replace(/([A-Z])/g,t=>"-".concat(t.toLowerCase())),d7=(e,t,n)=>e.map(r=>"".concat(u7(r)," ").concat(t,"ms ").concat(n)).join(","),f7=["radius"],m7=["radius"],F_,X_,W_,Z_,Q_,J_,e2,t2,n2,r2;function a2(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),n.push.apply(n,r)}return n}function i2(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?a2(Object(n),!0).forEach(function(r){h7(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):a2(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function h7(e,t,n){return(t=p7(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function p7(e){var t=v7(e,"string");return typeof t=="symbol"?t:t+""}function v7(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function cf(){return cf=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},cf.apply(null,arguments)}function l2(e,t){if(e==null)return{};var n,r,l=y7(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(r=0;r<s.length;r++)n=s[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(l[n]=e[n])}return l}function y7(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function g7(e,t){return j7(e)||w7(e,t)||b7(e,t)||x7()}function x7(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function b7(e,t){if(e){if(typeof e=="string")return s2(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?s2(e,t):void 0}}function s2(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function w7(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function j7(e){if(Array.isArray(e))return e}function zr(e,t){return t||(t=e.slice(0)),Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}}))}var o2=(e,t,n,r,l)=>{var s=di(n),d=di(r),f=Math.min(Math.abs(s)/2,Math.abs(d)/2),m=d>=0?1:-1,h=s>=0?1:-1,v=d>=0&&s>=0||d<0&&s<0?1:0,y;if(f>0&&Array.isArray(l)){for(var b=[0,0,0,0],w=0,j=4;w<j;w++){var _,S=(_=l[w])!==null&&_!==void 0?_:0;b[w]=S>f?f:S}y=hn(F_||(F_=zr(["M",",",""])),e,t+m*b[0]),b[0]>0&&(y+=hn(X_||(X_=zr(["A ",",",",0,0,",",",",",""])),b[0],b[0],v,e+h*b[0],t)),y+=hn(W_||(W_=zr(["L ",",",""])),e+n-h*b[1],t),b[1]>0&&(y+=hn(Z_||(Z_=zr(["A ",",",",0,0,",`,
`,",",""])),b[1],b[1],v,e+n,t+m*b[1])),y+=hn(Q_||(Q_=zr(["L ",",",""])),e+n,t+r-m*b[2]),b[2]>0&&(y+=hn(J_||(J_=zr(["A ",",",",0,0,",`,
`,",",""])),b[2],b[2],v,e+n-h*b[2],t+r)),y+=hn(e2||(e2=zr(["L ",",",""])),e+h*b[3],t+r),b[3]>0&&(y+=hn(t2||(t2=zr(["A ",",",",0,0,",`,
`,",",""])),b[3],b[3],v,e,t+r-m*b[3])),y+="Z"}else if(f>0&&l===+l&&l>0){var A=Math.min(f,l);y=hn(n2||(n2=zr(["M ",",",`
A `,",",",0,0,",",",",",`
L `,",",`
A `,",",",0,0,",",",",",`
L `,",",`
A `,",",",0,0,",",",",",`
L `,",",`
A `,",",",0,0,",",",","," Z"])),e,t+m*A,A,A,v,e+h*A,t,e+n-h*A,t,A,A,v,e+n,t+m*A,e+n,t+r-m*A,A,A,v,e+n-h*A,t+r,e+h*A,t+r,A,A,v,e,t+r-m*A)}else y=hn(r2||(r2=zr(["M ",","," h "," v "," h "," Z"])),e,t,n,r,-n);return y},c2={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},gE=e=>{var t=an(e,c2),n=x.useRef(null),r=x.useState(-1),l=g7(r,2),s=l[0],d=l[1];x.useEffect(()=>{if(n.current&&n.current.getTotalLength)try{var G=n.current.getTotalLength();G&&d(G)}catch{}},[]);var f=t.x,m=t.y,h=t.width,v=t.height,y=t.radius,b=t.className,w=t.animationEasing,j=t.animationDuration,_=t.animationBegin,S=t.isAnimationActive,A=t.isUpdateAnimationActive,C=x.useRef(h),M=x.useRef(v),k=x.useRef(f),D=x.useRef(m),E=x.useMemo(()=>({x:f,y:m,width:h,height:v,radius:y}),[f,m,h,v,y]),$=yE(E,"rectangle-");if(f!==+f||m!==+m||h!==+h||v!==+v||h===0||v===0)return null;var U=nt("recharts-rectangle",b);if(!A){var K=Xn(t);K.radius;var T=l2(K,f7);return x.createElement("path",cf({},T,{x:di(f),y:di(m),width:di(h),height:di(v),radius:typeof y=="number"?y:void 0,className:U,d:o2(f,m,h,v,y)}))}var re=C.current,Z=M.current,pe=k.current,fe=D.current,ce="0px ".concat(s===-1?1:s,"px"),R="".concat(s,"px ").concat(s,"px"),z=d7(["strokeDasharray"],j,typeof w=="string"?w:c2.animationEasing);return x.createElement(vE,{animationId:$,key:$,canBegin:s>0,duration:j,easing:w,isActive:A,begin:_},G=>{var se=Et(re,h,G),ue=Et(Z,v,G),P=Et(pe,f,G),Q=Et(fe,m,G);n.current&&(C.current=se,M.current=ue,k.current=P,D.current=Q);var ne;S?G>0?ne={transition:z,strokeDasharray:R}:ne={strokeDasharray:ce}:ne={strokeDasharray:R};var I=Xn(t);I.radius;var he=l2(I,m7);return x.createElement("path",cf({},he,{radius:typeof y=="number"?y:void 0,className:U,d:o2(P,Q,se,ue,y),ref:n,style:i2(i2({},ne),t.style)}))})};function u2(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),n.push.apply(n,r)}return n}function d2(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?u2(Object(n),!0).forEach(function(r){_7(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):u2(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function _7(e,t,n){return(t=N7(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function N7(e){var t=S7(e,"string");return typeof t=="symbol"?t:t+""}function S7(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var uf=Math.PI/180,A7=e=>e*180/Math.PI,Ht=(e,t,n,r)=>({x:e+Math.cos(-uf*r)*n,y:t+Math.sin(-uf*r)*n}),xE=function(t,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(t-(r.left||0)-(r.right||0)),Math.abs(n-(r.top||0)-(r.bottom||0)))/2},O7=(e,t)=>{var n=e.x,r=e.y,l=t.x,s=t.y;return Math.sqrt((n-l)**2+(r-s)**2)},E7=(e,t)=>{var n=e.x,r=e.y,l=t.cx,s=t.cy,d=O7({x:n,y:r},{x:l,y:s});if(d<=0)return{radius:d,angle:0};var f=(n-l)/d,m=Math.acos(f);return r>s&&(m=2*Math.PI-m),{radius:d,angle:A7(m),angleInRadian:m}},k7=e=>{var t=e.startAngle,n=e.endAngle,r=Math.floor(t/360),l=Math.floor(n/360),s=Math.min(r,l);return{startAngle:t-s*360,endAngle:n-s*360}},C7=(e,t)=>{var n=t.startAngle,r=t.endAngle,l=Math.floor(n/360),s=Math.floor(r/360),d=Math.min(l,s);return e+d*360},T7=(e,t)=>{var n=e.relativeX,r=e.relativeY,l=E7({x:n,y:r},t),s=l.radius,d=l.angle,f=t.innerRadius,m=t.outerRadius;if(s<f||s>m||s===0)return null;var h=k7(t),v=h.startAngle,y=h.endAngle,b=d,w;if(v<=y){for(;b>y;)b-=360;for(;b<v;)b+=360;w=b>=v&&b<=y}else{for(;b>v;)b-=360;for(;b<y;)b+=360;w=b>=y&&b<=v}return w?d2(d2({},t),{},{radius:s,angle:C7(b,t)}):null};function bE(e){var t=e.cx,n=e.cy,r=e.radius,l=e.startAngle,s=e.endAngle,d=Ht(t,n,r,l),f=Ht(t,n,r,s);return{points:[d,f],cx:t,cy:n,radius:r,startAngle:l,endAngle:s}}var f2,m2,h2,p2,v2,y2,g2;function xy(){return xy=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},xy.apply(null,arguments)}function Xi(e,t){return t||(t=e.slice(0)),Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}}))}var M7=(e,t)=>{var n=rn(t-e),r=Math.min(Math.abs(t-e),359.999);return n*r},xd=e=>{var t=e.cx,n=e.cy,r=e.radius,l=e.angle,s=e.sign,d=e.isExternal,f=e.cornerRadius,m=e.cornerIsExternal,h=f*(d?1:-1)+r,v=Math.asin(f/h)/uf,y=m?l:l+s*v,b=Ht(t,n,h,y),w=Ht(t,n,r,y),j=m?l-s*v:l,_=Ht(t,n,h*Math.cos(v*uf),j);return{center:b,circleTangency:w,lineTangency:_,theta:v}},wE=e=>{var t=e.cx,n=e.cy,r=e.innerRadius,l=e. Line truncated
A `,",",`,0,
`,",",`,
`,",",`
`])),h.x,h.y,l,l,+(Math.abs(f)>180),+(s>m),v.x,v.y);if(r>0){var b=Ht(t,n,r,s),w=Ht(t,n,r,m);y+=hn(m2||(m2=Xi(["L ",",",`
A `,",",`,0,
`,",",`,
`,","," Z"])),w.x,w.y,r,r,+(Math.abs(f)>180),+(s<=m),b.x,b.y)}else y+=hn(h2||(h2=Xi(["L ",","," Z"])),t,n);return y},D7=e=>{var t=e.cx,n=e.cy,r=e.innerRadius,l=e.outerRadius,s=e.cornerRadius,d=e.forceCornerRadius,f=e.cornerIsExternal,m=e.startAngle,h=e.endAngle,v=rn(h-m),y=xd({cx:t,cy:n,radius:l,angle:m,sign:v,cornerRadius:s,cornerIsExternal:f}),b=y.circleTangency,w=y.lineTangency,j=y.theta,_=xd({cx:t,cy:n,radius:l,angle:h,sign:-v,cornerRadius:s,cornerIsExternal:f}),S=_.circleTangency,A=_.lineTangency,C=_.theta,M=f?Math.abs(m-h):Math.abs(m-h)-j-C;if(M<0)return d?hn(p2||(p2=Xi(["M ",",",`
a`,",",",0,0,1,",`,0
a`,",",",0,0,1,",`,0
`])),w.x,w.y,s,s,s*2,s,s,-s*2):wE({cx:t,cy:n,innerRadius:r,outerRadius:l,startAngle:m,endAngle:h});var k=hn(v2||(v2=Xi(["M ",",",`
A`,",",",0,0,",",",",",`
A`,",",",0,",",",",",",",`
A`,",",",0,0,",",",",",`
`])),w.x,w.y,s,s,+(v<0),b.x,b.y,l,l,+(M>180),+(v<0),S.x,S.y,s,s,+(v<0),A.x,A.y);if(r>0){var D=xd({cx:t,cy:n,radius:r,angle:m,sign:v,isExternal:!0,cornerRadius:s,cornerIsExternal:f}),E=D.circleTangency,$=D.lineTangency,U=D.theta,K=xd({cx:t,cy:n,radius:r,angle:h,sign:-v,isExternal:!0,cornerRadius:s,cornerIsExternal:f}),T=K.circleTangency,re=K.lineTangency,Z=K.theta,pe=f?Math.abs(m-h):Math.abs(m-h)-U-Z;if(pe<0&&s===0)return"".concat(k,"L").concat(t,",").concat(n,"Z");k+=hn(y2||(y2=Xi(["L",",",`
A`,",",",0,0,",",",",",`
A`,",",",0,",",",",",",",`
A`,",",",0,0,",",",",","Z"])),re.x,re.y,s,s,+(v<0),T.x,T.y,r,r,+(pe>180),+(v>0),E.x,E.y,s,s,+(v<0),$.x,$.y)}else k+=hn(g2||(g2=Xi(["L",",","Z"])),t,n);return k},P7={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},jE=e=>{var t=an(e,P7),n=t.cx,r=t.cy,l=t.innerRadius,s=t.outerRadius,d=t.cornerRadius,f=t.forceCornerRadius,m=t.cornerIsExternal,h=t.startAngle,v=t.endAngle,y=t.className;if(s<l||h===v)return null;var b=nt("recharts-sector",y),w=s-l,j=xn(d,w,0,!0),_;return j>0&&Math.abs(h-v)<360?_=D7({cx:n,cy:r,innerRadius:l,outerRadius:s,cornerRadius:Math.min(j,w/2),forceCornerRadius:f,cornerIsExternal:m,startAngle:h,endAngle:v}):_=wE({cx:n,cy:r,innerRadius:l,outerRadius:s,startAngle:h,endAngle:v}),x.createElement("path",xy({},Xn(t),{className:b,d:_}))};function z7(e,t,n){if(e==="horizontal")return[{x:t.x,y:n.top},{x:t.x,y:n.top+n.height}];if(e==="vertical")return[{x:n.left,y:t.y},{x:n.left+n.width,y:t.y}];if(XA(t)){if(e==="centric"){var r=t.cx,l=t.cy,s=t.innerRadius,d=t.outerRadius,f=t.angle,m=Ht(r,l,s,f),h=Ht(r,l,d,f);return[{x:m.x,y:m.y},{x:h.x,y:h.y}]}return bE(t)}}function I7(e){return dO(e)?NaN:Number(e)}function yv(e){return e?(e=I7(e),e===1/0||e===-1/0?(e<0?-1:1)*Number.MAX_VALUE:e===e?e:0):e===0?e:0}function _E(e,t,n){n&&typeof n!="number"&&Qv(e,t,n)&&(t=n=void 0),e=yv(e),t===void 0?(t=e,e=0):t=yv(t),n=n===void 0?e<t?1:-1:yv(n);const r=Math.max(Math.ceil((t-e)/(n||1)),0),l=new Array(r);for(let s=0;s<r;s++)l[s]=e,e+=n;return l}var kr=e=>e.chartData,zc=X([kr],e=>{var t=e.chartData!=null?e.chartData.length-1:0;return{chartData:e.chartData,computedData:e.computedData,dataEndIndex:t,dataStartIndex:0}}),sm=(e,t,n,r)=>r?zc(e):kr(e),NE=(e,t,n)=>n?zc(e):kr(e),$7=X([sm],e=>{var t=e.chartData,n=e.dataStartIndex,r=e.dataEndIndex;return t!=null?t.slice(n,r+1):[]}),R7=X([zc],e=>{var t=e.chartData,n=e.dataStartIndex,r=e.dataEndIndex;return t!=null?t.slice(n,r+1):[]}),L7=X([kr],e=>{var t=e.chartData,n=e.dataStartIndex,r=e.dataEndIndex;return t!=null?t.slice(n,r+1):[]});function b0(e,t){return q7(e)||H7(e,t)||U7(e,t)||B7()}function B7(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function U7(e,t){if(e){if(typeof e=="string")return x2(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?x2(e,t):void 0}}function x2(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function H7(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function q7(e){if(Array.isArray(e))return e}function Br(e){if(Array.isArray(e)&&e.length===2){var t=b0(e,2),n=t[0],r=t[1];if(He(n)&&He(r))return!0}return!1}function b2(e,t,n){return n?e:[Math.min(e[0],t[0]),Math.max(e[1],t[1])]}function SE(e,t){if(t&&typeof e!="function"&&Array.isArray(e)&&e.length===2){var n=b0(e,2),r=n[0],l=n[1],s,d;if(He(r))s=r;else if(typeof r=="function")return;if(He(l))d=l;else if(typeof l=="function")return;var f=[s,d];if(Br(f))return f}}function K7(e,t,n){if(!(!n&&t==null)){if(typeof e=="function"&&t!=null)try{var r=e(t,n);if(Br(r))return b2(r,t,n)}catch{}if(Array.isArray(e)&&e.length===2){var l=b0(e,2),s=l[0],d=l[1],f,m;if(s==="auto")t!=null&&(f=Math.min(...t));else if(je(s))f=s;else if(typeof s=="function")try{t!=null&&(f=s(t==null?void 0:t[0]))}catch{}else if(typeof s=="string"&&c_.test(s)){var h=c_.exec(s);if(h==null||h[1]==null||t==null)f=void 0;else{var v=+h[1];f=t[0]-v}}else f=t==null?void 0:t[0];if(d==="auto")t!=null&&(m=Math.max(...t));else if(je(d))m=d;else if(typeof d=="function")try{t!=null&&(m=d(t==null?void 0:t[1]))}catch{}else if(typeof d=="string"&&u_.test(d)){var y=u_.exec(d);if(y==null||y[1]==null||t==null)m=void 0;else{var b=+y[1];m=t[1]+b}}else m=t==null?void 0:t[1];var w=[f,m];if(Br(w))return t==null?w:b2(w,t,n)}}}var Rs=1e9,Y7={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:"2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"},j0,wt=!0,vr="[DecimalError] ",el=vr+"Invalid argument: ",w0=vr+"Exponent out of range: ",Ls=Math.floor,Gi=Math.pow,G7=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Gn,nn=1e7,gt=7,AE=9007199254740991,df=Ls(AE/gt),Se={};Se.absoluteValue=Se.abs=function(){var e=new this.constructor(this);return e.s&&(e.s=1),e};Se.comparedTo=Se.cmp=function(e){var t,n,r,l,s=this;if(e=new s.constructor(e),s.s!==e.s)return s.s||-e.s;if(s.e!==e.e)return s.e>e.e^s.s<0?1:-1;for(r=s.d.length,l=e.d.length,t=0,n=r<l?r:l;t<n;++t)if(s.d[t]!==e.d[t])return s.d[t]>e.d[t]^s.s<0?1:-1;return r===l?0:r>l^s.s<0?1:-1};Se.decimalPlaces=Se.dp=function(){var e=this,t=e.d.length-1,n=(t-e.e)*gt;if(t=e.d[t],t)for(;t%10==0;t/=10)n--;return n<0?0:n};Se.dividedBy=Se.div=function(e){return _a(this,new this.constructor(e))};Se.dividedToIntegerBy=Se.idiv=function(e){var t=this,n=t.constructor;return mt(_a(t,new n(e),0,1),n.precision)};Se.equals=Se.eq=function(e){return!this.cmp(e)};Se.exponent=function(){return Kt(this)};Se.greaterThan=Se.gt=function(e){return this.cmp(e)>0};Se.greaterThanOrEqualTo=Se.gte=function(e){return this.cmp(e)>=0};Se.isInteger=Se.isint=function(){return this.e>this.d.length-2};Se.isNegative=Se.isneg=function(){return this.s<0};Se.isPositive=Se.ispos=function(){return this.s>0};Se.isZero=function(){return this.s===0};Se.lessThan=Se.lt=function(e){return this.cmp(e)<0};Se.lessThanOrEqualTo=Se.lte=function(e){return this.cmp(e)<1};Se.logarithm=Se.log=function(e){var t,n=this,r=n.constructor,l=r.precision,s=l+5;if(e===void 0)e=new r(10);else if(e=new r(e),e.s<1||e.eq(Gn))throw Error(vr+"NaN");if(n.s<1)throw Error(vr+(n.s?"NaN":"-Infinity"));return n.eq(Gn)?new r(0):(wt=!1,t=_a(gc(n,s),gc(e,s),s),wt=!0,mt(t,l))};Se.minus=Se.sub=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?kE(t,e):OE(t,(e.s=-e.s,e))};Se.modulo=Se.mod=function(e){var t,n=this,r=n.constructor,l=r.precision;if(e=new r(e),!e.s)throw Error(vr+"NaN");return n.s?(wt=!1,t=_a(n,e,0,1).times(e),wt=!0,n.minus(t)):mt(new r(n),l)};Se.naturalExponential=Se.exp=function(){return EE(this)};Se.naturalLogarithm=Se.ln=function(){return gc(this)};Se.negated=Se.neg=function(){var e=new this.constructor(this);return e.s=-e.s||0,e};Se.plus=Se.add=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?OE(t,e):kE(t,(e.s=-e.s,e))};Se.precision=Se.sd=function(e){var t,n,r,l=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(el+e);if(t=Kt(l)+1,r=l.d.length-1,n=r*gt+1,r=l.d[r],r){for(;r%10==0;r/=10)n--;for(r=l.d[0];r>=10;r/=10)n++}return e&&t>n?t:n};Se.squareRoot=Se.sqrt=function(){var e,t,n,r,l,s,d,f=this,m=f.constructor;if(f.s<1){if(!f.s)return new m(0);throw Error(vr+"NaN")}for(e=Kt(f),wt=!1,l=Math.sqrt(+f),l==0||l==1/0?(t=Lr(f.d),(t.len Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function X7(e,t){if(e){if(typeof e=="string")return _2(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_2(e,t):void 0}}function _2(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function W7(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function Z7(e){if(Array.isArray(e))return e}var DE=e=>{var t=xc(e,2),n=t[0],r=t[1],l=n,s=r;return n>r&&(l=r,s=n),[l,s]},_0=(e,t,n)=>{if(e.lte(0))return new Xe(0);var r=TE(e.toNumber()),l=new Xe(10).pow(r),s=e.div(l),d=r!==1?.05:.1,f=new Xe(Math.ceil(s.div(d).toNumber())).add(n).mul(d),m=f.mul(l);return t?new Xe(m.toNumber()):new Xe(Math.ceil(m.toNumber()))},PE=(e,t,n)=>{var r;if(e.lte(0))return new Xe(0);var l=[1,2,2.5,5],s=e.toNumber(),d=Math.floor(new Xe(s).abs().log(10).toNumber()),f=new Xe(10).pow(d),m=e.div(f).toNumber(),h=l.findIndex(w=>w>=m-1e-10);if(h===-1&&(f=f.mul(10),h=0),h+=n,h>=l.length){var v=Math.floor(h/l.length);h%=l.length,f=f.mul(new Xe(10).pow(v))}var y=(r=l[h])!==null&&r!==void 0?r:1,b=new Xe(y).mul(f);return t?b:new Xe(Math.ceil(b.toNumber()))},Q7=(e,t,n)=>{var r=new Xe(1),l=new Xe(e);if(!l.isint()&&n){var s=Math.abs(e);s<1?(r=new Xe(10).pow(TE(e)-1),l=new Xe(Math.floor(l.div(r).toNumber())).mul(r)):s>1&&(l=new Xe(Math.floor(e)))}else e===0?l=new Xe(Math.floor((t-1)/2)):n||(l=new Xe(Math.floor(e)));for(var d=Math.floor((t-1)/2),f=[],m=0;m<t;m++)f.push(l.add(new Xe(m-d).mul(r)).toNumber());return f},zE=function(t,n,r,l){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0,d=arguments.length>5&&arguments[5]!==void 0?arguments[5]:_0;if(!Number.isFinite((n-t)/(r-1)))return{step:new Xe(0),tickMin:new Xe(0),tickMax:new Xe(0)};var f=d(new Xe(n).sub(t).div(r-1),l,s),m;t<=0&&n>=0?m=new Xe(0):(m=new Xe(t).add(n).div(2),m=m.sub(new Xe(m).mod(f)));var h=Math.ceil(m.sub(t).div(f).toNumber()),v=Math.ceil(new Xe(n).sub(m).div(f).toNumber()),y=h+v+1;return y>r?zE(t,n,r,l,s+1,d):(y<r&&(v=n>0?v+(r-y):v,h=n>0?h:h+(r-y)),{step:f,tickMin:m.sub(new Xe(h).mul(f)),tickMax:m.add(new Xe(v).mul(f))})},N2=function(t){var n=xc(t,2),r=n[0],l=n[1],s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,d=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,f=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"auto",m=Math.max(s,2),h=DE([r,l]),v=xc(h,2),y=v[0],b=v[1];if(y===-1/0||b===1/0){var w=b===1/0?[y,...Array(s-1).fill(1/0)]:[...Array(s-1).fill(-1/0),b];return r>l?w.reverse():w}if(y===b)return Q7(y,s,d);var j=f==="snap125"?PE:_0,_=zE(y,b,m,d,0,j),S=_.step,A=_.tickMin,C=_.tickMax,M=ME(A,C.add(new Xe(.1).mul(S)),S);return r>l?M.reverse():M},S2=function(t,n){var r=xc(t,2),l=r[0],s=r[1],d=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,f=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"auto",m=DE([l,s]),h=xc(m,2),v=h[0],y=h[1];if(v===-1/0||y===1/0)return[l,s];if(v===y)return[v];var b=f==="snap125"?PE:_0,w=Math.max(n,2),j=b(new Xe(y).sub(v).div(w-1),d,0),_=[...ME(new Xe(v),new Xe(y),j),y];return d===!1&&(_=_.map(S=>Math.round(S))),l>s?_.reverse():_},IE=e=>e.rootProps.maxBarSize,J7=e=>e.rootProps.barGap,$E=e=>e.rootProps.barCategoryGap,e9=e=>e.rootProps.barSize,Ic=e=>e.rootProps.stackOffset,RE=e=>e.rootProps.reverseStackOrder,N0=e=>e.options.chartName,S0=e=>e.rootProps.syncId,LE=e=>e.rootProps.syncMethod,A0=e=>e.options.eventEmitter,t9=e=>e.rootProps.baseValue,qt={grid:-100,barBackground:-50,area:100,cursorRectangle:200,bar:300,line:400,axis:500,scatter:600,activeBar:1e3,cursorLine:1100,activeDot:1200,label:2e3},Bi={allowDecimals:!1,allowDataOverflow:!1,angleAxisId:0,reversed:!1,scale:"auto",tick:!0,type:"auto"},Ir={allowDataOverflow:!1,allowDecimals:!1,allowDuplicatedCategory:!0,includeHidden:!1,radiusAxisId:0,reversed:!1,scale:"auto",tick:!0,tickCount:5,type:"auto"},om=(e,t)=>{if(!(!e||!t))return e!=null&&e.reversed?[t[1],t[0]]:t};function cm(e,t,n){if(n!=="auto")return n;if(e!=null)return Vr(e,t)?"category":"number"}function A2(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),n.push.apply(n,r)}return n}function ff(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?A2(Object(n),!0).forEach(function(r){n9(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):A2(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}retu Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function GB(e,t){if(e){if(typeof e=="string")return hN(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?hN(e,t):void 0}}function hN(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function VB(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function FB(e){if(Array.isArray(e))return e}var Oy=[0,"auto"],Gt={allowDataOverflow:!1,allowDecimals:!0,allowDuplicatedCategory:!0,angle:0,dataKey:void 0,domain:void 0,height:30,hide:!0,id:0,includeHidden:!1,interval:"preserveEnd",minTickGap:5,mirror:!1,name:void 0,orientation:"bottom",padding:{left:0,right:0},reversed:!1,scale:"auto",tick:!0,tickCount:5,tickFormatter:void 0,ticks:void 0,type:"category",unit:void 0,niceTicks:"auto"},Ck=(e,t)=>e.cartesianAxis.xAxis[t],Da=(e,t)=>{var n=Ck(e,t);return n??Gt},Vt={allowDataOverflow:!1,allowDecimals:!0,allowDuplicatedCategory:!0,angle:0,dataKey:void 0,domain:Oy,hide:!0,id:0,includeHidden:!1,interval:"preserveEnd",minTickGap:5,mirror:!1,name:void 0,orientation:"left",padding:{top:0,bottom:0},reversed:!1,scale:"auto",tick:!0,tickCount:5,tickFormatter:void 0,ticks:void 0,type:"number",unit:void 0,niceTicks:"auto",width:Cc},Tk=(e,t)=>e.cartesianAxis.yAxis[t],Pa=(e,t)=>{var n=Tk(e,t);return n??Vt},XB={domain:[0,"auto"],includeHidden:!1,reversed:!1,allowDataOverflow:!1,allowDuplicatedCategory:!1,dataKey:void 0,id:0,name:"",range:[64,64],scale:"auto",type:"number",unit:""},tg=(e,t)=>{var n=e.cartesianAxis.zAxis[t];return n??XB},Mt=(e,t,n)=>{switch(t){case"xAxis":return Da(e,n);case"yAxis":return Pa(e,n);case"zAxis":return tg(e,n);case"angleAxis":return O0(e,n);case"radiusAxis":return E0(e,n);default:throw new Error("Unexpected axis type: ".concat(t))}},WB=(e,t,n)=>{switch(t){case"xAxis":return Da(e,n);case"yAxis":return Pa(e,n);default:throw new Error("Unexpected axis type: ".concat(t))}},Hs=(e,t,n)=>{switch(t){case"xAxis":return Da(e,n);case"yAxis":return Pa(e,n);case"angleAxis":return O0(e,n);case"radiusAxis":return E0(e,n);default:throw new Error("Unexpected axis type: ".concat(t))}},Mk=e=>e.graphicalItems.cartesianItems.some(t=>t.type==="bar")||e.graphicalItems.polarItems.some(t=>t.type==="radialBar");function ng(e,t){return n=>{switch(e){case"xAxis":return"xAxisId"in n&&n.xAxisId===t;case"yAxis":return"yAxisId"in n&&n.yAxisId===t;case"zAxis":return"zAxisId"in n&&n.zAxisId===t;case"angleAxis":return"angleAxisId"in n&&n.angleAxisId===t;case"radiusAxis":return"radiusAxisId"in n&&n.radiusAxisId===t;default:return!1}}}var wm=e=>e.graphicalItems.cartesianItems,ZB=X([St,$c],ng),rg=(e,t,n)=>e.filter(n).filter(r=>(t==null?void 0:t.includeHidden)===!0?!0:!r.hide),qs=X([wm,Mt,ZB],rg,{memoizeOptions:{resultEqualityCheck:hm}}),Dk=X([qs],e=>e.filter(t=>t.type==="area"||t.type==="bar").filter(fm)),Pk=e=>e.filter(t=>!("stackId"in t)||t.stackId===void 0),QB=X([qs],Pk),ag=e=>e.map(t=>t.data).filter(Boolean).flat(1),JB=X([qs],e=>e.some(t=>!t.data)),zk=X([qs],ag,{memoizeOptions:{resultEqualityCheck:hm}}),ig=(e,t)=>{var n=t.chartData,r=n===void 0?[]:n,l=t.dataStartIndex,s=t.dataEndIndex;return e.length>0?e:r.slice(l,s+1)},lg=X([zk,sm],ig),Ik=(e,t,n)=>(t==null?void 0:t.dataKey)!=null?e.map(r=>({value:rt(r,t.dataKey)})):n.length>0?n.map(r=>r.dataKey).flatMap(r=>e.map(l=>({value:rt(l,r)}))):e.map(r=>({value:r})),$k=(e,t,n,r,l,s)=>{var d=r.chartData,f=d===void 0?[]:d,m=r.dataStartIndex,h=r.dataEndIndex,v=Ik(e,t,n);if(l&&(t==null?void 0:t.dataKey)!=null&&s.length>0){var y=f.slice(m,h+1),b=y.map(w=>({value:rt(w,t.dataKey)})).filter(w=>w.value!=null);return[...b,...v]}return v},Hc=X([lg,Mt,qs,sm,JB,zk],$k);function _s(e){if(qr(e)||e instanceof Date){var t=Number(e);if(He(t))return t}}function pN(e){if(Array.isArray(e)){var t=[_s(e[0]),_s(e[1])];return Br(t)?t:void 0}var n=_s(e);if(n!=null)return[n,n]}function Gr(e){return e.map(_s).filter(Dn)}function eU(e,t){var n=_s(e),r=_s(t);return n==null&&r==null?0:n==null?-1:r==null?1:n-r}var tU=X([Hc],e=>e==null?void 0:e.map(t=>t.value).sort(eU));function Rk(e,t){switch(e){case"xAxis":return t.direction==="x";case"yAxis":return t.direction==="y";default:return!1}}function nU(e,t,n){if(!n)return[];if(!n.length)return[];var r;if(typeof t=="number"&&!Ar(t))r=t;else if(Array.isArray(t)){var l=Gr(t);l.length>0&&(r=Math.max(...l))}return r==null?[]:Gr(n.flatMap(s=>{var d=rt(e,s.dataKey),f,m;if(Array.isArray(d)){var h=kk(d,2);f=h[0],m=h[1]}else f=m=d;if(!(!He(f)||!He(m)))return[r-f,r+m]}))}var Qt=e=>{var t=ln(e),n=Bs(e);return Hs(e,t,n)},Ms=X([Qt],e=>e==nu Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function aK(e,t){if(e){if(typeof e=="string")return PN(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?PN(e,t):void 0}}function PN(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function iK(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function lK(e){if(Array.isArray(e))return e}function sK(e){return e.dataKey}function oK(e,t){return x.isValidElement(e)?x.cloneElement(e,t):typeof e=="function"?x.createElement(e,t):x.createElement(lR,t)}var zN=[],cK={allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",axisId:0,contentStyle:{},cursor:!0,filterNull:!0,includeHidden:!1,isAnimationActive:"auto",itemSorter:"name",itemStyle:{},labelStyle:{},offset:10,reverseDirection:{x:!1,y:!1},separator:" : ",trigger:"hover",useTranslate3d:!1,wrapperStyle:{}};function Ev(e){var t,n,r=an(e,cK),l=r.active,s=r.allowEscapeViewBox,d=r.animationDuration,f=r.animationEasing,m=r.content,h=r.filterNull,v=r.isAnimationActive,y=r.offset,b=r.payloadUniqBy,w=r.position,j=r.reverseDirection,_=r.useTranslate3d,S=r.wrapperStyle,A=r.cursor,C=r.shared,M=r.trigger,k=r.defaultIndex,D=r.portal,E=r.axisId,$=dt(),U=typeof k=="number"?String(k):k;x.useEffect(()=>{$(ZU({shared:C,trigger:M,axisId:E,active:l,defaultIndex:U}))},[$,C,M,E,l,U]);var K=rm(),T=fE(),re=YU(C),Z=(t=Ne(xe=>cq(xe,re,M,U)))!==null&&t!==void 0?t:{},pe=Z.activeIndex,fe=Z.isActive,ce=Ne(xe=>oq(xe,re,M,U)),R=Ne(xe=>TC(xe,re,M,U)),z=Ne(xe=>sq(xe,re,M,U)),G=ce,se=Mq(),ue=(n=l??fe)!==null&&n!==void 0?n:!1,P=mO([G,ue]),Q=nK(P,2),ne=Q[0],I=Q[1],he=re==="axis"?R:void 0;Qq(re,M,z,he,pe,ue);var be=D??se;if(be==null||K==null||re==null)return null;var _e=G??zN;ue||(_e=zN),h&&_e.length&&(_e=oO(_e.filter(xe=>xe.value!=null&&(xe.hide!==!0||r.includeHidden)),b,sK));var W=_e.length>0,V=DN(DN({},r),{},{payload:_e,label:he,active:ue,activeIndex:pe,coordinate:z,accessibilityLayer:T}),ye=x.createElement(OR,{allowEscapeViewBox:s,animationDuration:d,animationEasing:f,isAnimationActive:v,active:ue,coordinate:z,hasPayload:W,offset:y,position:w,reverseDirection:j,useTranslate3d:_,viewBox:K,wrapperStyle:S,lastBoundingBox:ne,innerRef:I,hasPortalFromProps:!!D},oK(m,V));return x.createElement(x.Fragment,null,It.createPortal(ye,be),ue&&x.createElement(Tq,{cursor:A,tooltipEventType:re,coordinate:z,payload:_e,index:pe}))}var nl=e=>null;nl.displayName="Cell";function uK(e,t,n){return(t=dK(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function dK(e){var t=fK(e,"string");return typeof t=="symbol"?t:t+""}function fK(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}class mK{constructor(t){uK(this,"cache",new Map),this.maxSize=t}get(t){var n=this.cache.get(t);return n!==void 0&&(this.cache.delete(t),this.cache.set(t,n)),n}set(t,n){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.maxSize){var r=this.cache.keys().next().value;r!=null&&this.cache.delete(r)}this.cache.set(t,n)}clear(){this.cache.clear()}size(){return this.cache.size}}function IN(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),n.push.apply(n,r)}return n}function hK(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?IN(Object(n),!0).forEach(function(r){pK(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):IN(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function pK(e,t,n){return(t=vK(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function vK(e){var t=yK(e,"string");return typeof t=="symbol"?t:t+""}function yK(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var gK={cacheSize:2e3,enableCache:!0},IC=hK({},gK),$N=new mK(IC.cacheSize),xK={position:"absolute",top:"-20000px",left:0,padding:0,margin:0,border:"none",whiteSpace:"pre"},RN="recharts_measurement_span";function bK(e,t){var n=t.fontSize||"",r=t.fo Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function jK(e,t){if(e){if(typeof e=="string")return BN(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?BN(e,t):void 0}}function BN(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function _K(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;m=!1}else for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function NK(e){if(Array.isArray(e))return e}function SK(e,t,n){return(t=AK(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function AK(e){var t=OK(e,"string");return typeof t=="symbol"?t:t+""}function OK(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var UN=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([*/])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,HN=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([+-])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,EK=/^(px|cm|vh|vw|em|rem|%|mm|in|pt|pc|ex|ch|vmin|vmax|Q)$/,kK=/(-?\d+(?:\.\d+)?)([a-zA-Z%]+)?/,CK={cm:96/2.54,mm:96/25.4,pt:96/72,pc:96/6,in:96,Q:96/(2.54*40),px:1},TK=["cm","mm","pt","pc","in","Q","px"];function MK(e){return TK.includes(e)}var ys="NaN";function DK(e,t){return e*CK[t]}class pn{static parse(t){var n,r=(n=kK.exec(t))!==null&&n!==void 0?n:[],l=Ef(r,3),s=l[1],d=l[2];return s==null?pn.NaN:new pn(parseFloat(s),d??"")}constructor(t,n){this.num=t,this.unit=n,this.num=t,this.unit=n,Ar(t)&&(this.unit=""),n!==""&&!EK.test(n)&&(this.num=NaN,this.unit=""),MK(n)&&(this.num=DK(t,n),this.unit="px")}add(t){return this.unit!==t.unit?new pn(NaN,""):new pn(this.num+t.num,this.unit)}subtract(t){return this.unit!==t.unit?new pn(NaN,""):new pn(this.num-t.num,this.unit)}multiply(t){return this.unit!==""&&t.unit!==""&&this.unit!==t.unit?new pn(NaN,""):new pn(this.num*t.num,this.unit||t.unit)}divide(t){return this.unit!==""&&t.unit!==""&&this.unit!==t.unit?new pn(NaN,""):new pn(this.num/t.num,this.unit||t.unit)}toString(){return"".concat(this.num).concat(this.unit)}isNaN(){return Ar(this.num)}}$C=pn;SK(pn,"NaN",new $C(NaN,""));function RC(e){if(e==null||e.includes(ys))return ys;for(var t=e;t.includes("*")||t.includes("/");){var n,r=(n=UN.exec(t))!==null&&n!==void 0?n:[],l=Ef(r,4),s=l[1],d=l[2],f=l[3],m=pn.parse(s??""),h=pn.parse(f??""),v=d==="*"?m.multiply(h):m.divide(h);if(v.isNaN())return ys;t=t.replace(UN,v.toString())}for(;t.includes("+")||/.-\d+(?:\.\d+)?/.test(t);){var y,b=(y=HN.exec(t))!==null&&y!==void 0?y:[],w=Ef(b,4),j=w[1],_=w[2],S=w[3],A=pn.parse(j??""),C=pn.parse(S??""),M=_==="+"?A.add(C):A.subtract(C);if(M.isNaN())return ys;t=t.replace(HN,M.toString())}return t}var qN=/\(([^()]*)\)/;function PK(e){for(var t=e,n;(n=qN.exec(t))!=null;){var r=n,l=Ef(r,2),s=l[1];t=t.replace(qN,RC(s))}return t}function zK(e){var t=e.replace(/\s+/g,"");return t=PK(t),t=RC(t),t}function IK(e){try{return zK(e)}catch{return ys}}function kv(e){var t=IK(e.slice(5,-1));return t===ys?"":t}var $K=["x","y","lineHeight","capHeight","fill","scaleToFit","textAnchor","verticalAnchor"],RK=["dx","dy","angle","className","breakAll"];function Cy(){return Cy=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Cy.apply(null,arguments)}function KN(e,t){if(e==null)return{};var n,r,l=LK(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(r=0;r<s.length;r++)n=s[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(l[n]=e[n])}return l}function LK(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function YN(e,t){return qK(e)||HK(e,t)||UK(e,t)||BK()}function BK(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function UK(e,t){if(e){if(typeof e=="string")return GN(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?GN(e,t):void 0}}function GN(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function HK(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;m=!1}else for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function qK(e){if(Array.isArray(e))return e}var LC=/[ \f\n\r\t\v\u2028\u2029]+/,BC=e=>{var t=e.children,n=e.breakAll,r=e.style;try{var l=[];Nt(t)||(n?l=t.toString().split(""):l=t.toString().split(LC));var s=l.map(f=>({word:f,width:oc(f,r).width})),d=n?0:oc(" ",r).width;return{wordsWithComputedWidth:s,spaceWidth:d}}catch{return null}};function UC(e){return e==="start"||e==="middle"||e==="end"||e==="inherit"}function KK(e){return Nt(e)||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}var HC=(e,t,n,r)=>e.reduce((l,s)=>{var d=s.word,f=s.width,m=l[l.length-1];if(m&&f!=null&&(t==null||r||m.width+f+n<Number(t)))m.words.push(d),m.width+=f+n;else{var h={words:[d],width:f};l.push(h)}return l},[]),qC=e=>e.reduce((t,n)=>t.width>n.width?t:n),YK="…",VN=(e,t,n,r,l,s,d,f)=>{var m=e.slice(0,t),h=BC({breakAll:n,style:r,children:m+YK});if(!h)return[!1,[]];var v=HC(h.wordsWithComputedWidth,s,d,f),y=v.length>l||qC(v).width>Number(s);return[y,v]},GK=(e,t,n,r,l)=>{var s=e.maxLines,d=e.children,f=e.style,m=e.breakAll,h=je(s),v=String(d),y=HC(t,r,n,l);if(!h||l)return y;var b=y.length>s||qC(y).width>Number(r);if(!b)return y;for(var w=0,j=v.length-1,_=0,S;w<=j&&_<=v.length-1;){var A=Math.floor((w+j)/2),C=A-1,M=VN(v,C,m,f,s,r,n,l),k=YN(M,2),D=k[0],E=k[1],$=VN(v,A,m,f,s,r,n,l),U=YN($,1),K=U[0];if(!D&&!K&&(w=A+1),D&&K&&(j=A-1),!D&&K){S=E;break}_++}return S||y},FN=e=>{var t=Nt(e)?[]:e.toString().split(LC);return[{words:t,width:void 0}]},VK=e=>{var t=e.width,n=e.scaleToFit,r=e.children,l=e.style,s=e.breakAll,d=e.maxLines;if((t||n)&&!Pc.isSsr){var f,m,h=BC({breakAll:s,children:r,style:l});if(h){var v=h.wordsWithComputedWidth,y=h.spaceWidth;f=v,m=y}else return FN(r);return GK({breakAll:s,children:r,maxLines:d,style:l},f,m,t,!!n)}return FN(r)},KC="#808080",FK={angle:0,breakAll:!1,capHeight:"0.71em",fill:KC,lineHeight:"1em",scaleToFit:!1,textAnchor:"start",verticalAnchor:"end",x:0,y:0},Om=x.forwardRef((e,t)=>{var n=an(e,FK),r=n.x,l=n.y,s=n.lineHeight,d=n.capHeight,f=n.fill,m=n.scaleToFit,h=n.textAnchor,v=n.verticalAnchor,y=KN(n,$K),b=x.useMemo(()=>VK({breakAll:y.breakAll,children:y.children,maxLines:y.maxLines,scaleToFit:m,style:y.style,width:y.width}),[y.breakAll,y.children,y.maxLines,m,y.style,y.width]),w=y.dx,j=y.dy,_=y.angle,S=y.className,A=y.breakAll,C=KN(y,RK);if(!qr(r)||!qr(l)||b.length===0)return null;var M=Number(r)+(je(w)?w:0),k=Number(l)+(je(j)?j:0);if(!He(M)||!He(k))return null;var D;switch(v){case"start":D=kv("calc(".concat(d,")"));break;case"middle":D=kv("calc(".concat((b.length-1)/2," * -").concat(s," + (").concat(d," / 2))"));break;default:D=kv("calc(".concat(b.length-1," * -").concat(s,")"));break}var E=[],$=b[0];if(m&&$!=null){var U=$.width,K=y.width;E.push("scale(".concat(je(K)&&je(U)?K/U:1,")"))}return _&&E.push("rotate(".concat(_,", ").concat(M,", ").concat(k,")")),E.length&&(C.transform=E.join(" ")),x.createElement("text",Cy({},Xn(C),{ref:t,x:M,y:k,className:nt("recharts-text",S),textAnchor:h,fill:f.includes("url")?KC:f}),b.map((T,re)=>{var Z=T.words.join(A?"":" ");return x.createElement("tspan",{x:M,dy:re===0?D:s,key:"".concat(Z,"-").concat(re)},Z)}))});Om.displayName="Text";function XN(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),n.push.apply(n,r)}return n}function $r(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?XN(Object(n),!0).forEach(function(r){XK(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):XN(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function XK(e,t,n){return(t=WK(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function WK(e){var t=ZK(e,"string");return typeof t=="symbol"?t:t+""}function ZK(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Numb Line truncated
A`).concat(j,",").concat(j,",0,1,").concat(C?0:1,`,
`).concat(k.x,",").concat(k.y),E=Nt(e.id)?dc("recharts-radial-line-"):e.id;return x.createElement("text",ga({},r,{dominantBaseline:"central",className:nt("recharts-radial-bar-label",d)}),x.createElement("defs",null,x.createElement("path",{id:E,d:D})),x.createElement("textPath",{xlinkHref:"#".concat(E)},n))},dY=(e,t,n)=>{var r=e.cx,l=e.cy,s=e.innerRadius,d=e.outerRadius,f=e.startAngle,m=e.endAngle,h=(f+m)/2;if(n==="outside"){var v=Ht(r,l,d+t,h),y=v.x,b=v.y;return{x:y,y:b,textAnchor:y>=r?"start":"end",verticalAnchor:"middle"}}if(n==="center")return{x:r,y:l,textAnchor:"middle",verticalAnchor:"middle"};if(n==="centerTop")return{x:r,y:l,textAnchor:"middle",verticalAnchor:"start"};if(n==="centerBottom")return{x:r,y:l,textAnchor:"middle",verticalAnchor:"end"};var w=(s+d)/2,j=Ht(r,l,w,h),_=j.x,S=j.y;return{x:_,y:S,textAnchor:"middle",verticalAnchor:"middle"}},zd=e=>e!=null&&"cx"in e&&je(e.cx),fY={angle:0,offset:5,zIndex:qt.label,position:"middle",textBreakAll:!1};function mY(e){if(!zd(e))return e;var t=e.cx,n=e.cy,r=e.outerRadius,l=r*2;return{x:t-r,y:n-r,width:l,upperWidth:l,lowerWidth:l,height:l}}function oi(e){var t=an(e,fY),n=t.viewBox,r=t.parentViewBox,l=t.position,s=t.value,d=t.children,f=t.content,m=t.className,h=m===void 0?"":m,v=t.textBreakAll,y=t.labelRef,b=sY(),w=GC(),j=l==="center"?w:b??w,_,S,A;n==null?_=j:zd(n)?_=n:_=m0(n);var C=mY(_);if(!_||Nt(s)&&Nt(d)&&!x.isValidElement(f)&&typeof f!="function")return null;var M=ac(ac({},t),{},{viewBox:_});if(x.isValidElement(f)){M.labelRef;var k=WN(M,JK);return x.cloneElement(f,k)}if(typeof f=="function"){M.content;var D=WN(M,eY);if(S=x.createElement(f,D),x.isValidElement(S))return S}else S=oY(t);var E=Xn(t);if(zd(_)){if(l==="insideStart"||l==="insideEnd"||l==="end")return uY(t,l,S,E,_);A=dY(_,t.offset,t.position)}else{if(!C)return null;var $=QK({viewBox:C,position:l,offset:t.offset,parentViewBox:zd(r)?void 0:r});A=ac(ac({x:$.x,y:$.y,textAnchor:$.horizontalAnchor,verticalAnchor:$.verticalAnchor},$.width!==void 0?{width:$.width}:{}),$.height!==void 0?{height:$.height}:{})}return x.createElement(In,{zIndex:t.zIndex},x.createElement(Om,ga({ref:y,className:nt("recharts-label",h)},E,A,{textAnchor:UC(E.textAnchor)?E.textAnchor:A.textAnchor,breakAll:v}),S))}oi.displayName="Label";var hY=(e,t,n)=>{if(!e)return null;var r={viewBox:t,labelRef:n};return e===!0?x.createElement(oi,ga({key:"label-implicit"},r)):qr(e)?x.createElement(oi,ga({key:"label-implicit",value:e},r)):x.isValidElement(e)?e.type===oi?x.cloneElement(e,ac({key:"label-implicit"},r)):x.createElement(oi,ga({key:"label-implicit",content:e},r)):Tg(e)?x.createElement(oi,ga({key:"label-implicit",content:e},r)):e&&typeof e=="object"?x.createElement(oi,ga({},e,{key:"label-implicit"},r)):null};function pY(e){var t=e.label,n=e.labelRef,r=GC();return hY(t,r,n)||null}var vY=["valueAccessor"],yY=["dataKey","clockWise","id","textBreakAll","zIndex"];function kf(){return kf=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},kf.apply(null,arguments)}function QN(e,t){if(e==null)return{};var n,r,l=gY(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(r=0;r<s.length;r++)n=s[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(l[n]=e[n])}return l}function gY(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var xY=e=>{var t=Array.isArray(e.value)?e.value[e.value.length-1]:e.value;if(KK(t))return t},VC=x.createContext(void 0),FC=VC.Provider,XC=x.createContext(void 0),bY=XC.Provider;function wY(){return x.useContext(VC)}function jY(){return x.useContext(XC)}function Id(e){var t=e.valueAccessor,n=t===void 0?xY:t,r=QN(e,vY),l=r.dataKey;r.clockWise;var s=r.id,d=r.textBreakAll,f=r.zIndex,m=QN(r,yY),h=wY(),v=jY(),y=h||v;return!y||!y.length?null:x.createElement(In,{zIndex:f??qt.label},x.createElement(Ct,{className:"recharts-label-list"},y.map((b,w)=>{var j,_=Nt(l)?n(b,w):rt(b.payload,l),S=Nt(s)?{}:{id:"".concat(s,"-").concat(w)};return x.createElement(oi,kf({key:"label-".concat(w)},Xn(b),m,S,{fill:(j=r.fill)!==null&&j!==void 0?j:b.fill,parentViewBox:b.parentViewBox,value:_,textBreakAll:d,viewBox:b.viewBox,index:w,zIndex:0}))})))}Id.displayName="LabelList";function Mg(e){var t=e.label;return t?t===!0?x.createElement(Id,{key:"labelList-implicit"}):x.isValidElement(t)||Tg(t)?x.createElement(Id,{key:"labelList-implicit",content:t}):typeof t=="object"?x.createElement(Id,kf({key:"labelList-implicit"},t,{type:String(t.type)})):null:null}function Ty(){return Ty=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Ty.apply(null,arguments)}var WC=e=>{var t=e.cx,n=e.cy,r=e.r,l=e.className,s=nt("recharts-dot",l);return je(t)&&je(n)&&je(r)?x.createElement("circle",Ty({},zn(e),n0(e),{className:s,cx:t,cy:n, Line truncated
* @license React
* react-is.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var nS;function LY(){if(nS)return ut;nS=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),l=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),d=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),h=Symbol.for("react.suspense_list"),v=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),b=Symbol.for("react.view_transition"),w=Symbol.for("react.client.reference");function j(_){if(typeof _=="object"&&_!==null){var S=_.$$typeof;switch(S){case e:switch(_=_.type,_){case n:case l:case r:case m:case h:case b:return _;default:switch(_=_&&_.$$typeof,_){case d:case f:case y:case v:return _;case s:return _;default:return S}}case t:return S}}}return ut.ContextConsumer=s,ut.ContextProvider=d,ut.Element=e,ut.ForwardRef=f,ut.Fragment=n,ut.Lazy=y,ut.Memo=v,ut.Portal=t,ut.Profiler=l,ut.StrictMode=r,ut.Suspense=m,ut.SuspenseList=h,ut.isContextConsumer=function(_){return j(_)===s},ut.isContextProvider=function(_){return j(_)===d},ut.isElement=function(_){return typeof _=="object"&&_!==null&&_.$$typeof===e},ut.isForwardRef=function(_){return j(_)===f},ut.isFragment=function(_){return j(_)===n},ut.isLazy=function(_){return j(_)===y},ut.isMemo=function(_){return j(_)===v},ut.isPortal=function(_){return j(_)===t},ut.isProfiler=function(_){return j(_)===l},ut.isStrictMode=function(_){return j(_)===r},ut.isSuspense=function(_){return j(_)===m},ut.isSuspenseList=function(_){return j(_)===h},ut.isValidElementType=function(_){return typeof _=="string"||typeof _=="function"||_===n||_===l||_===r||_===m||_===h||typeof _=="object"&&_!==null&&(_.$$typeof===y||_.$$typeof===v||_.$$typeof===d||_.$$typeof===s||_.$$typeof===f||_.$$typeof===w||_.getModuleId!==void 0)},ut.typeOf=j,ut}var rS;function BY(){return rS||(rS=1,Cv.exports=LY()),Cv.exports}var UY=BY(),aS=e=>typeof e=="string"?e:e?e.displayName||e.name||"Component":"",iS=null,Tv=null,n4=e=>{if(e===iS&&Array.isArray(Tv))return Tv;var t=[];return x.Children.forEach(e,n=>{Nt(n)||(UY.isFragment(n)?t=t.concat(n4(n.props.children)):t.push(n))}),Tv=t,iS=e,t};function zg(e,t){var n=[],r=[];return Array.isArray(t)?r=t.map(l=>aS(l)):r=[aS(t)],n4(e).forEach(l=>{var s=Hr(l,"type.displayName")||Hr(l,"type.name");s&&r.indexOf(s)!==-1&&n.push(l)}),n}var r4=e=>e&&typeof e=="object"&&"clipDot"in e?!!e.clipDot:!0;function lS(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),n.push.apply(n,r)}return n}function sS(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?lS(Object(n),!0).forEach(function(r){HY(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):lS(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function HY(e,t,n){return(t=qY(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function qY(e){var t=KY(e,"string");return typeof t=="symbol"?t:t+""}function KY(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function a4(e,t){return sS(sS({},t),e)}function YY(e){return x.isValidElement(e)?e.props:e}function GY(e,t){return x.cloneElement(e,a4(YY(e),t))}function VY(e){if("index"in e){var t=e.index;return typeof t=="number"||typeof t=="string"?t:void 0}}function FY(e){return"isActive"in e&&e.isActive===!0}function Ig(e){var t=e.option,n=e.DefaultShape,r=e.shapeProps,l=e.activeClassName,s=l===void 0?"recharts-active-shape":l,d=e.inActiveClassName,f=d===void 0?"recharts-shape":d,m=VY(r),h;return x.isValidElement(t)?h=GY(t,r):t===n?h=x.createElement(n,r):typeof t=="function"?h=t(r,m):typeof t=="object"?h=x.createElement(n,a4(t,r)):h=x.createElement(n,r),FY(r)?x.createElement(Ct,{className:s},h):x.createElement(Ct,{className:f},h)}var $g=(e,t,n)=>{var r=dt();return(l,s)=>d=>{e==null||e(l,s,d),r(cC({activeIndex:String(s),activeDataKey:t,activeCoordinate:l.tooltipPosition,activeGraphicalItemId:n}))}},Rg=e=>{var t=dt();return(n,r)=>l=>{e==null||e(n,r,l),t(QU())}},Lg=(e,t,n)=>{var r=dt();return(l,s)=>d=>{e==null||e(l,s,d),r(JU({activeIndex:String(s),activeDataKey:t,activeCoordinate:l.tooltipPosition,activeGraphicalItemId:n}))}};function Bg(e){var t=e.tooltipEntrySettings,n=dt(),r=wn(),l=x.useRef(null);return x.useLayoutEffect(()=>{r||(l.current===null?n(FU(t)):l.current!==t&&n(XU({prev:l.current,next:t})),l.current=t)},[t,n,r]),x.useLayoutEffect(()=>()=>{l.current&&(n(WU(l.current)),l.current=null)},[n]),null}function i4(e){var t=e.legendPayload,n=dt(),r=wn(),l=x.useRef(null);return x.useLayoutEffect(()=>{r||(l.current===null?n(sE(t)):l.current!==t&&n(oE({prev:l.currentLine truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function QY(e,t){if(e){if(typeof e=="string")return oS(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?oS(e,t):void 0}}function oS(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function JY(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function eG(e){if(Array.isArray(e))return e}var Ug="index",Hg="append";function qg(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[],r=[];for(var l of n)r.push({status:"removed",prev:l});for(var s=0;s<t.length;s++){var d=e[s],f=t[s];d!=null?r.push({status:"matched",prev:d,next:f}):r.push({status:"added",next:f})}return r}function tG(e,t){var n=e.length/t.length,r=t.map((l,s)=>e[Math.floor(s*n)]);return qg(r,t)}function nG(e,t){var n=t.map((r,l)=>e[l]);return qg(n,t)}function rG(e,t){for(var n=new Map,r=0;r<e.length;r++){var l=e[r];if(l!=null){var s=t(l,r);s!=null&&!n.has(s)&&n.set(s,l)}}return n}function aG(e,t,n){var r=rG(e,n),l=new Set,s=t.map((y,b)=>{var w=n(y,b);if(w!=null){var j=r.get(w);if(j!==void 0)return l.add(w),j}}),d=[];for(var f of r){var m=WY(f,2),h=m[0],v=m[1];l.has(h)||d.push(v)}return qg(s,t,d)}function My(e,t,n){return t==null?null:e==null?t.map(r=>({status:"added",next:r})):n===Ug?tG(e,t):n===Hg?nG(e,t):aG(e,t,n)}function l4(e,t){var n=x.useRef(e),r=x.useRef(t.current),l=x.useRef(!0);n.current!==e&&(n.current=e,r.current=t.current,l.current=!1);var s=x.useCallback(function(d,f){var m=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(f===0){l.current=!0;return}f===1&&(r.current=d),f>0&&l.current&&m&&(t.current=d)},[t]);return{startValue:r.current,syncStepValue:s}}function iG(e,t){return cG(e)||oG(e,t)||sG(e,t)||lG()}function lG(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function sG(e,t){if(e){if(typeof e=="string")return cS(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?cS(e,t):void 0}}function cS(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function oG(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function cG(e){if(Array.isArray(e))return e}function Kg(e,t){var n=x.useState(!1),r=iG(n,2),l=r[0],s=r[1],d=x.useCallback(()=>{typeof e=="function"&&e(),s(!0)},[e]),f=x.useCallback(()=>{typeof t=="function"&&t(),s(!1)},[t]);return{isAnimating:l,handleAnimationStart:d,handleAnimationEnd:f}}function Yg(e){var t,n=e.animationInput,r=e.animationIdPrefix,l=e.items,s=e.previousItemsRef,d=e.isAnimationActive,f=e.animationBegin,m=e.animationDuration,h=e.animationEasing,v=e.onAnimationStart,y=e.onAnimationEnd,b=e.animationInterpolateFn,w=e.animationMatchBy,j=e.shouldUpdatePreviousRef,_=e.children,S=e.layout,A=yE(n,r),C=l4(A,s),M=(t=C.startValue)!==null&&t!==void 0?t:null,k=My(M,l,w??Ug);return x.createElement(vE,{animationId:A,begin:f,duration:m,isActive:d,easing:h,onAnimationEnd:y,onAnimationStart:v,key:A},D=>{var E=M==null,$=l==null?l:b(k,D,S),U=j?j(D):D>0;return C.syncStepValue($,D,U),$==null?null:_($,D,E)})}var Mv;function uG(e,t){return hG(e)||mG(e,t)||fG(e,t)||dG()}function dG(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function fG(e,t){if(e){if(typeof e=="string")return uS(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?uS(e,t):void 0}}function uS(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function mG(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function hG(e){if(Array.isArray(e))return e}var pG=()=>{var e=x.useState(()=>dc("uid-")),t=uG(e,1),n=t[0];return n},s4=(Mv=AT.useId)!==null&&Mv!==void 0?Mv:pG;function vG(e,t){var n=s4();return t||(e?"".concat(e,"-").concat(n):n)}var yG=x.createContext(void 0),Gg=e=>{var t=e.id,n=e.type,r=e.children,l=vG("recharts-".concat(n),t);return x.createElement(yG.Provider,{value:l},r(l))},gG={cartesianItems:[],polarItems:[]},o4=bn({name:"graphicalItems",initialState:gG,reducers:{addCartesianGraphicalItem:{reducer(e,t){e.cartesianItems.push(t.payload)},prepare:yt()},replaceCartesianGraphicalItem:{reducer(e,t){var n=t.payload,r=n.prev,l=n.next,s=mr(e).cartesianItems.indexOf(r);s>-1&&(e.cartesianItems[s]=l)},prepare:yt()},removeCartesianGraphicalItem:{reducer(e,t){var n=mr(e).cartesianItems.indexOf(t.payload);n>-1&&e.cartesianItems.splice(n,1)},prepare:yt()},addPolarGraphicalItem:{reducer(e,t){e.polarItems.push(t.payload)},prepare:yt()},removePolarGraphicalItem:{reducer(e,t){var n=mr(e).polarItems.indexOf(t.payload);n>-1&&e.polarItems.splice(n,1)},prepare:yt()},replacePolarGraphicalItem:{reducer(e,t){var n=t.payload,r=n.prev,l=n.next,s=mr(e).polarItems.indexOf(r);s>-1&&(e.polarItems[s]=l)},prepare:yt()}}}),Gs=o4.actions,xG=Gs.addCartesianGraphicalItem,bG=Gs.replaceCartesianGraphicalItem,wG=Gs.removeCartesianGraphicalItem,jG=Gs.addPolarGraphicalItem,_G=Gs.removePolarGraphicalItem,NG=Gs.replacePolarGraphicalItem,SG=o4.reducer,AG=e=>{var t=dt(),n=x.useRef(null);return x.useLayoutEffect(()=>{n.current===null?t(xG(e)):n.current!==e&&t(bG({prev:n.current,next:e})),n.current=e},[t,e]),x.useLayoutEffect(()=>()=>{n.current&&(t(wG(n.current)),n.current=null)},[t]),null},c4=x.memo(AG),OG=e=>{var t=dt(),n=x.useRef(null);return x.useLayoutEffect(()=>{n.current===null?t(jG(e)):n.current!==e&&t(NG({prev:n.current,next:e})),n.current=e},[t,e]),x.useLayoutEffect(()=>()=>{n.current&&(t(_G(n.current)),n.current=null)},[t]),null},EG=x.memo(OG),kG=["key"],CG=["onMouseEnter","onClick","onMouseLeave"],TG=["id"],MG=["id"];function dl(){return dl=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},dl.apply(null,arguments)}function Tm(e,t){if(e==null)return{};var n,r,l=DG(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(r=0;r<s.length;r++)n=s[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(l[n]=e[n])}return l}function DG(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function dS(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),n.push.apply(n,r)}return n}function bt(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?dS(Object(n),!0).forEach(function(r){PG(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):dS(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function PG(e,t,n){return(t=zG(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function zG(e){var t=IG(e,"string");return typeof t=="symbol"?t:t+""}function IG(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var u4=jE;function $G(e){var t=x.useMemo(()=>zg(e.children,nl),[e.children]),n=Ne(r=>$Y(r,e.id,t));return n==null?null:x.createElement(XY,{legendPayload:n})}function RG(e){if(!(e==null||typeof e=="boolean"||typeof e=="function")){if(x.isValidElement(e)){var t,n=(t=e.props)===null||t===void 0?void 0:t.fill;return typeof n=="string"?n:void 0}var r=e.fill;return typeof r=="string"?r:void 0}}var LG=x.memo(e=>{var t=e.dataKey,n=e.nameKey,r=e.sectors,l=e.stroke,s=e.strokeWidth,d=e.fill,f=e.name,m=e.hide,h=e.tooltipType,v=e.id,y=e.activeShape,b=RG(y Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function MV(e,t){if(e){if(typeof e=="string")return yS(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?yS(e,t):void 0}}function yS(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function DV(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function PV(e){if(Array.isArray(e))return e}var gS=(e,t,n)=>{var r=n??e;if(!Nt(r))return xn(r,t,0)},zV=(e,t,n)=>{var r={},l=e.filter(fm),s=e.filter(h=>h.stackId==null),d=l.reduce((h,v)=>{var y=h[v.stackId];return y==null&&(y=[]),y.push(v),h[v.stackId]=y,h},r),f=Object.entries(d).map(h=>{var v,y=CV(h,2),b=y[0],w=y[1],j=w.map(S=>S.dataKey),_=gS(t,n,(v=w[0])===null||v===void 0?void 0:v.barSize);return{stackId:b,dataKeys:j,barSize:_}}),m=s.map(h=>{var v=[h.dataKey].filter(b=>b!=null),y=gS(t,n,h.barSize);return{stackId:void 0,dataKeys:v,barSize:y}});return[...f,...m]};function xS(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),n.push.apply(n,r)}return n}function Sd(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?xS(Object(n),!0).forEach(function(r){IV(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):xS(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function IV(e,t,n){return(t=$V(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function $V(e){var t=RV(e,"string");return typeof t=="symbol"?t:t+""}function RV(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function LV(e,t,n,r,l){var s,d=r.length;if(!(d<1)){var f=xn(e,n,0,!0),m,h=[];if(He((s=r[0])===null||s===void 0?void 0:s.barSize)){var v=!1,y=n/d,b=r.reduce((C,M)=>C+(M.barSize||0),0);b+=(d-1)*f,b>=n&&(b-=(d-1)*f,f=0),b>=n&&y>0&&(v=!0,y*=.9,b=d*y);var w=Math.round((n-b)/2),j={offset:w-f,size:0};m=r.reduce((C,M)=>{var k,D={stackId:M.stackId,dataKeys:M.dataKeys,position:{offset:j.offset+j.size+f,size:v?y:(k=M.barSize)!==null&&k!==void 0?k:0}},E=[...C,D];return j=D.position,E},h)}else{var _=xn(t,n,0,!0);n-2*_-(d-1)*f<=0&&(f=0);var S=(n-2*_-(d-1)*f)/d;S>1&&(S=Math.round(S));var A=He(l)?Math.min(S,l):S;m=r.reduce((C,M,k)=>[...C,{stackId:M.stackId,dataKeys:M.dataKeys,position:{offset:_+(S+f)*k+(S-A)/2,size:A}}],h)}return m}}var BV=(e,t,n,r,l,s,d)=>{var f=Nt(d)?t:d,m=LV(n,r,l!==s?l:s,e,f);return l!==s&&m!=null&&(m=m.map(h=>Sd(Sd({},h),{},{position:Sd(Sd({},h.position),{},{offset:h.position.offset-l/2})}))),m},UV=(e,t)=>{var n=dm(t);if(!(!e||n==null||t==null)){var r=t.stackId;if(r!=null){var l=e[r];if(l){var s=l.stackedData;if(s)return s.find(d=>d.key===n)}}}},HV=(e,t)=>{if(!(e==null||t==null)){var n=e.find(r=>r.stackId===t.stackId&&t.dataKey!=null&&r.dataKeys.includes(t.dataKey));if(n!=null)return n.position}};function qV(e,t){return e&&typeof e=="object"&&"zIndex"in e&&typeof e.zIndex=="number"&&He(e.zIndex)?e.zIndex:t}var m4=e=>{var t=e.chartData,n=dt(),r=wn();return x.useEffect(()=>r?()=>{}:(n(CN(t)),()=>{n(CN(void 0))}),[t,n,r]),null},bS={x:0,y:0,width:0,height:0,padding:{top:0,right:0,bottom:0,left:0}},h4=bn({name:"brush",initialState:bS,reducers:{setBrushSettings(e,t){return t.payload==null?bS:t.payload}}});h4.actions.setBrushSettings;var KV=h4.reducer;function YV(e){return(e%180+180)%180}var GV=function(t){var n=t.width,r=t.height,l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,s=YV(l),d=s*Math.PI/180,f=Math.atan(r/n),m=d>f&&d<Math.PI-f?r/Math.sin(d):n/Math.cos(d);return Math.abs(m)},VV={dots:[],areas:[],lines:[]},p4=bn({name:"referenceElements",initialState:VV,reducers:{addDot:(e,t)=>{e.dots.push(t.payload)},removeDot:(e,t)=>{var n=mr(e).dots.findIndex(r=>r===t.payload);n!==-1&&e.dots.splice(n,1)},addArea:(e,t)=>{e.areas.push(t.payload)},removeArea:(e,t)=>{var n=mr(e).areas.findIndex(r=>r===t.payload);n!==-1&&e.areas.splice(n,1)},addLine:(e,t)=>{e.lines.push(t.payload)},removeLine:(e,t)=>{var n=mr(e).lines.findIndex(r=>r===t.payload);n!==-1&&e.lines.splice(n,1)}}}),Vs=p4.actions;Vs.addDot;Vs.removeDot;Vs.addArea;Vs.removeArea;Vs.addLine;Vs.removeLine;var FV=p4.reducer;function XV(e,t){return JV(e)||QV(e,t)||ZV(e,t)||WV()}function WV(){ Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ZV(e,t){if(e){if(typeof e=="string")return wS(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?wS(e,t):void 0}}function wS(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function QV(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function JV(e){if(Array.isArray(e))return e}var eF=x.createContext(void 0),tF=e=>{var t=e.children,n=x.useState("".concat(dc("recharts"),"-clip")),r=XV(n,1),l=r[0],s=Vg();if(s==null)return null;var d=s.x,f=s.y,m=s.width,h=s.height;return x.createElement(eF.Provider,{value:l},x.createElement("defs",null,x.createElement("clipPath",{id:l},x.createElement("rect",{x:d,y:f,height:h,width:m}))),t)};function v4(e,t){if(t<1)return[];if(t===1)return e;for(var n=[],r=0;r<e.length;r+=t){var l=e[r];l!==void 0&&n.push(l)}return n}function nF(e,t,n){var r={width:e.width+t.width,height:e.height+t.height};return GV(r,n)}function rF(e,t,n){var r=n==="width",l=e.x,s=e.y,d=e.width,f=e.height;return t===1?{start:r?l:s,end:r?l+d:s+f}:{start:r?l+d:s+f,end:r?l:s}}function Sc(e,t,n,r,l){if(e*t<e*r||e*t>e*l)return!1;var s=n();return e*(t-e*s/2-r)>=0&&e*(t+e*s/2-l)<=0}function aF(e,t){return v4(e,t+1)}function iF(e,t,n,r,l){for(var s=(r||[]).slice(),d=t.start,f=t.end,m=0,h=1,v=d,y=function(){var j=r==null?void 0:r[m];if(j===void 0)return{v:v4(r,h)};var _=m,S,A=()=>(S===void 0&&(S=n(j,_)),S),C=j.coordinate,M=m===0||Sc(e,C,A,v,f);M||(m=0,v=d,h+=1),M&&(v=C+e*(A()/2+l),m+=h)},b;h<=s.length;)if(b=y(),b)return b.v;return[]}function lF(e,t,n,r,l){var s=(r||[]).slice(),d=s.length;if(d===0)return[];for(var f=t.start,m=t.end,h=1;h<=d;h++){for(var v=(d-1)%h,y=f,b=!0,w=function(){var k=r[_];if(k==null)return 0;var D=_,E,$=()=>(E===void 0&&(E=n(k,D)),E),U=k.coordinate,K=_===v||Sc(e,U,$,y,m);if(!K)return b=!1,1;K&&(y=U+e*($()/2+l))},j,_=v;_<d&&(j=w(),!(j!==0&&j===1));_+=h);if(b){for(var S=[],A=v;A<d;A+=h){var C=r[A];C!=null&&S.push(C)}return S}}return[]}function jS(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),n.push.apply(n,r)}return n}function yn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?jS(Object(n),!0).forEach(function(r){sF(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):jS(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function sF(e,t,n){return(t=oF(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function oF(e){var t=cF(e,"string");return typeof t=="symbol"?t:t+""}function cF(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function uF(e,t,n,r,l){for(var s=(r||[]).slice(),d=s.length,f=t.start,m=t.end,h=function(b){var w=s[b];if(w==null)return 1;var j=w,_,S=()=>(_===void 0&&(_=n(w,b)),_);if(b===d-1){var A=e*(j.coordinate+e*S()/2-m);s[b]=j=yn(yn({},j),{},{tickCoord:A>0?j.coordinate-A*e:j.coordinate})}else s[b]=j=yn(yn({},j),{},{tickCoord:j.coordinate});if(j.tickCoord!=null){var C=Sc(e,j.tickCoord,S,f,m);C&&(m=j.tickCoord-e*(S()/2+l),s[b]=yn(yn({},j),{},{isShow:!0}))}},v=d-1;v>=0;v--)h(v);return s}function dF(e,t,n,r,l,s){var d=(r||[]).slice(),f=d.length,m=t.start,h=t.end;if(s){var v=r[f-1];if(v!=null){var y=n(v,f-1),b=e*(v.coordinate+e*y/2-h);if(d[f-1]=v=yn(yn({},v),{},{tickCoord:b>0?v.coordinate-b*e:v.coordinate}),v.tickCoord!=null){var w=Sc(e,v.tickCoord,()=>y,m,h);w&&(h=v.tickCoord-e*(y/2+l),d[f-1]=yn(yn({},v),{},{isShow:!0}))}}}for(var j=s?f-1:f,_=function(C){var M=d[C];if(M==null)return 1;var k=M,D,E=()=>(D===void 0&&(D=n(M,C)),D);if(C===0){var $=e*(k.coordinate-e*E()/2-m);d[C]=k=yn(yn({},k),{},{tickCoord:$<0?k.coordinate-$*e:k.coordinate})}else d[C]=k=yn(yn({},k),{},{tickCoord:k.coordinate});if(k.tickCoord!=null){var U=Sc(e,k.tickCoord,E,m,h);U&&(m=k.tickCoord+e*(E()/2+l),d[C]=yn(yn({},k),{},{isShow:!0}))}},S=0;S<j;S++)_(S);return d}function Fg(e,t,n){var r=e.tick,l=e.ticks,s=e.viewBox,d=e.minTickGap,f=e.orientation,m=e.interval,h=e.tickFormatter,v=e.unit,y=e.angle;if(!l||!l.length||!r)return[];if(je(m)||Pc.isSsr){var b;return(b=aF(l,je(m)?m:0))!==null&&b!==void 0?b:[]}var w=[],j=f==="top"||f==="bottom"?"width": Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function xF(e,t){if(e){if(typeof e=="string")return NS(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?NS(e,t):void 0}}function NS(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function bF(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function wF(e){if(Array.isArray(e))return e}function jF(e,t){if(e==null)return{};var n,r,l=_F(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(r=0;r<s.length;r++)n=s[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(l[n]=e[n])}return l}function _F(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function fl(){return fl=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},fl.apply(null,arguments)}function SS(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),n.push.apply(n,r)}return n}function kt(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?SS(Object(n),!0).forEach(function(r){NF(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):SS(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function NF(e,t,n){return(t=SF(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function SF(e){var t=AF(e,"string");return typeof t=="symbol"?t:t+""}function AF(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Na={x:0,y:0,width:0,height:0,viewBox:{x:0,y:0,width:0,height:0},orientation:"bottom",ticks:[],stroke:"#666",tickLine:!0,axisLine:!0,tick:!0,mirror:!1,minTickGap:5,tickSize:6,tickMargin:2,interval:"preserveEnd",zIndex:qt.axis};function OF(e){var t=e.x,n=e.y,r=e.width,l=e.height,s=e.orientation,d=e.mirror,f=e.axisLine,m=e.otherSvgProps;if(!f)return null;var h=kt(kt(kt({},m),zn(f)),{},{fill:"none"});if(s==="top"||s==="bottom"){var v=+(s==="top"&&!d||s==="bottom"&&d);h=kt(kt({},h),{},{x1:t,y1:n+v*l,x2:t+r,y2:n+v*l})}else{var y=+(s==="left"&&!d||s==="right"&&d);h=kt(kt({},h),{},{x1:t+y*r,y1:n,x2:t+y*r,y2:n+l})}return x.createElement("line",fl({},h,{className:nt("recharts-cartesian-axis-line",Hr(f,"className"))}))}function EF(e,t,n,r,l,s,d,f,m){var h,v,y,b,w,j,_=f?-1:1,S=e.tickSize||d,A=je(e.tickCoord)?e.tickCoord:e.coordinate;switch(s){case"top":h=v=e.coordinate,b=n+ +!f*l,y=b-_*S,j=y-_*m,w=A;break;case"left":y=b=e.coordinate,v=t+ +!f*r,h=v-_*S,w=h-_*m,j=A;break;case"right":y=b=e.coordinate,v=t+ +f*r,h=v+_*S,w=h+_*m,j=A;break;default:h=v=e.coordinate,b=n+ +f*l,y=b+_*S,j=y+_*m,w=A;break}return{line:{x1:h,y1:y,x2:v,y2:b},tick:{x:w,y:j}}}function kF(e,t){switch(e){case"left":return t?"start":"end";case"right":return t?"end":"start";default:return"middle"}}function CF(e,t){switch(e){case"left":case"right":return"middle";case"top":return t?"start":"end";default:return t?"end":"start"}}function TF(e){var t=e.option,n=e.tickProps,r=e.value,l,s=nt(n.className,"recharts-cartesian-axis-tick-value");if(x.isValidElement(t))l=x.cloneElement(t,kt(kt({},n),{},{className:s}));else if(typeof t=="function")l=t(kt(kt({},n),{},{className:s}));else{var d="recharts-cartesian-axis-tick-value";typeof t!="boolean"&&(d=nt(d,e4(t))),l=x.createElement(Om,fl({},n,{className:d}),r)}return l}function MF(e){var t=e.ticks,n=e.axisType,r=e.axisId,l=dt();return x.useEffect(()=>{if(r==null||n==null)return hl;var s=t.map(d=>({value:d.value,coordinate:d.coordinate,offset:d.offset,index:d.index}));return l(hF({ticks:s,axisId:r,axisType:n})),()=>{l(pF({axisId:r,axisType:n}))}},[l,t,r,n]),null}var DF=x.forwardRef((e,t)=>{var n=e.ticks,r=n===void 0?[]:n,l=e.tick,s=e.tickLine,d=e.stroke,f=e.tickFormatter,m=e.unit,h=e.padding,v=e.tickTextProps,y=e.orientation,b=e.mirror,w=e.x,j=e.y,_=e.width,S=e.height,A=e.tickSize,C=e.tickMargin,M=e.fontSize,k=e.letterSpacing,D=e.getTicksConfig,E=e.events,$=e.axisType,U=e.axisId,K=Fg(kt(kt({},D),{},{ticks:r}),M,k),T=zn(D),re=rl(l),Z=UC(T.textAnchor)?T.textAnchor:kF(y,b),pe=CF(y,b),fe={};type Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function xW(e,t){if(e){if(typeof e=="string")return CS(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?CS(e,t):void 0}}function CS(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function bW(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function wW(e){if(Array.isArray(e))return e}function yi(){return yi=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},yi.apply(null,arguments)}function TS(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),n.push.apply(n,r)}return n}function Ft(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?TS(Object(n),!0).forEach(function(r){jW(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):TS(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function jW(e,t,n){return(t=_W(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _W(e){var t=NW(e,"string");return typeof t=="symbol"?t:t+""}function NW(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Pf(e,t){if(e==null)return{};var n,r,l=SW(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(r=0;r<s.length;r++)n=s[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(l[n]=e[n])}return l}function SW(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var AW=e=>{var t=e.dataKey,n=e.name,r=e.fill,l=e.legendType,s=e.hide;return[{inactive:s,dataKey:t,type:l,color:r,value:Is(n,t),payload:e}]},OW=x.memo(e=>{var t=e.dataKey,n=e.stroke,r=e.strokeWidth,l=e.fill,s=e.name,d=e.hide,f=e.unit,m=e.tooltipType,h=e.id,v={dataDefinedOnItem:void 0,getPosition:hl,settings:{stroke:n,strokeWidth:r,fill:l,dataKey:t,nameKey:void 0,name:Is(s,t),hide:d,type:m,color:l,unit:f,graphicalItemId:h}};return x.createElement(Bg,{tooltipEntrySettings:v})});function EW(e){var t=Ne(vi),n=e.data,r=e.dataKey,l=e.background,s=e.allOtherBarProps,d=s.onMouseEnter,f=s.onMouseLeave,m=s.onClick,h=Pf(s,hW),v=$g(d,r,s.id),y=Rg(f),b=Lg(m,r,s.id);if(!l||n==null)return null;var w=rl(l);return x.createElement(In,{zIndex:qV(l,qt.barBackground)},n.map((j,_)=>{j.value;var S=j.background;j.tooltipPosition;var A=Pf(j,pW);if(!S)return null;var C=v(j,j.originalDataIndex),M=y(j,j.originalDataIndex),k=b(j,j.originalDataIndex),D=Ft(Ft(Ft(Ft(Ft({option:l,isActive:String(j.originalDataIndex)===t},A),{},{fill:"#eee"},S),w),Oc(h,j,_)),{},{onMouseEnter:C,onMouseLeave:M,onClick:k,dataKey:r,index:_,className:"recharts-bar-background-rectangle"});return x.createElement(Jg,yi({key:"background-bar-".concat(_)},D))}))}function kW(e){var t=e.showLabels,n=e.children,r=e.rects,l=r==null?void 0:r.map(s=>{var d={x:s.x,y:s.y,width:s.width,lowerWidth:s.width,upperWidth:s.width,height:s.height};return Ft(Ft({},d),{},{value:s.value,payload:s.payload,parentViewBox:s.parentViewBox,viewBox:d,fill:s.fill})});return x.createElement(FC,{value:t?l:void 0},n)}function CW(e){var t=e.shape,n=e.activeBar,r=e.baseProps,l=e.entry,s=e.index,d=e.dataKey,f=Ne(vi),m=Ne(Ng),h=n&&String(l.originalDataIndex)===f&&(m==null||d===m),v=x.useState(!1),y=kS(v,2),b=y[0],w=y[1],j=x.useState(!1),_=kS(j,2),S=_[0],A=_[1];x.useEffect(()=>{var $;return h?(w(!0),$=requestAnimationFrame(()=>{A(!0)})):A(!1),()=>{cancelAnimationFrame($)}},[h]);var C=x.useCallback(()=>{h||w(!1)},[h]),M=h&&S,k=h||b,D;h?n===!0?D=t:D=n:D=t;var E=x.createElement(Jg,yi({},r,{name:String(r.name)},l,{isActive:M,option:D,index:s,dataKey:d,animationElapsedTime:e.animationElapsedTime,isAnimating:e.isAnimating,isEntrance:e.isEntrance,onTransitionEnd:C}));return k?x.createElement(In,{zIndex:qt.activeBar},x.createElement(P4,{index:l.originalDataIndex},E)):E}function TW(e){var t=e.shape,n=e.baseProps,r=e.entry,l=e.index,s=e.dataKey;return x.createElement(Jg,yi({},n,{name:String(n.name)},r,{isActive:!1,option:t,index:l,dataKey:s,animationElapsedTime:e.animationElapsedTime,isAn Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function RZ(e,t){if(e){if(typeof e=="string")return qS(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?qS(e,t):void 0}}function qS(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function LZ(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function BZ(e){if(Array.isArray(e))return e}function UZ(){var e=dt(),t=x.useState(null),n=IZ(t,2),r=n[0],l=n[1],s=Ne(vI);return x.useEffect(()=>{if(r!=null){var d=r.getBoundingClientRect(),f=d.width/r.offsetWidth;He(f)&&f!==s&&e(J8(f))}},[r,e,s]),l}function KS(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),n.push.apply(n,r)}return n}function HZ(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?KS(Object(n),!0).forEach(function(r){qZ(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):KS(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function qZ(e,t,n){return(t=KZ(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function KZ(e){var t=YZ(e,"string");return typeof t=="symbol"?t:t+""}function YZ(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function mi(){return mi=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},mi.apply(null,arguments)}function If(e,t){return XZ(e)||FZ(e,t)||VZ(e,t)||GZ()}function GZ(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function VZ(e,t){if(e){if(typeof e=="string")return YS(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?YS(e,t):void 0}}function YS(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function FZ(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,l,s,d,f=[],m=!0,h=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(m=(r=s.call(n)).done)&&(f.push(r.value),f.length!==t);m=!0);}catch(v){h=!0,l=v}finally{try{if(!m&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(h)throw l}}return f}}function XZ(e){if(Array.isArray(e))return e}var WZ=()=>(Zq(),null);function $f(e){if(typeof e=="number")return e;if(typeof e=="string"){var t=parseFloat(e);if(!Number.isNaN(t))return t}return 0}var ZZ=x.forwardRef((e,t)=>{var n,r,l=x.useRef(null),s=x.useState({containerWidth:$f((n=e.style)===null||n===void 0?void 0:n.width),containerHeight:$f((r=e.style)===null||r===void 0?void 0:r.height)}),d=If(s,2),f=d[0],m=d[1],h=x.useCallback((y,b)=>{m(w=>{var j=Math.round(y),_=Math.round(b);return w.containerWidth===j&&w.containerHeight===_?w:{containerWidth:j,containerHeight:_}})},[]),v=x.useCallback(y=>{if(typeof t=="function"&&t(y),l.current!=null&&(l.current.disconnect(),l.current=null),y!=null&&typeof ResizeObserver<"u"){var b=y.getBoundingClientRect(),w=b.width,j=b.height;h(w,j);var _=A=>{var C=A[0];if(C!=null){var M=C.contentRect,k=M.width,D=M.height;h(k,D)}},S=new ResizeObserver(_);S.observe(y),l.current=S}},[t,h]);return x.useEffect(()=>()=>{var y=l.current;y!=null&&y.disconnect()},[h]),x.createElement(x.Fragment,null,x.createElement(Tc,{width:f.containerWidth,height:f.containerHeight}),x.createElement("div",mi({ref:v},e)))}),QZ=x.forwardRef((e,t)=>{var n=e.width,r=e.height,l=x.useState({containerWidth:$f(n),containerHeight:$f(r)}),s=If(l,2),d=s[0],f=s[1],m=x.useCallback((v,y)=>{f(b=>{var w=Math.round(v),j=Math.round(y);return b.containerWidth===w&&b.containerHeight===j?b:{containerWidth:w,containerHeight:j}})},[]),h=x.useCallback(v=>{if(typeof t=="function"&&t(v),v!=null){var y=v.getBoundingClientRect(),b=y.width,w=y.height;m(b,w)}},[t,m]);return x.createElement(x.Fragment,null,x.createElement(Tc,{width:d.containerWidth,height:d.containerHeight}),x.createElement("div",mi({ref:h},e)))}),JZ=x.forwardRef((e,t)=>{var n=e.width,r=e.height;return x.createElement(x.Fragment,null,x.createElement(Tc,{width:n,height:r}),x.createElement("div",mi({ref:t},e)))}),eQ=x.forwardRef((e,t)=>{var n=e.width,r=e.height;return typeof n=="string"||typeof r=="string"?x.createElement(QZ,mi({},e,{ref:t})):typeof n=="number"&&typeof r=="number"?x.createElement(JZ,mi({},e,{width:n,height:r,ref:t})):x.createElement(x.Fragment,null,x.createElement(Tc,{width:n,height:r}),x.createElement("div",mi({ref:t},e)))});function tQ(e){return e?ZZ:eQ}var nQ=x.forwardRef((e,t)=>{var n=e.children,r=e.className,l=e.height,s=e.onClick,d=e.onContextMenu,f=e.onDoubleClick,m=e.onMouseDown,h=e.onMouseEnter,v=e.onMouseLeave,y=e.onMouseMove,b=e.onMouseUp,w=e.onTouchEnd,j=e.onTouchMove,_=e.onTouchStart,S=e.style,A=e.width,C=e.responsive,M=e.dispatchTouchEvents,k=M===void 0?!0:M,D=x.useRef(null),E=dt(),$=x.useState(null),U=If($,2),K=U[0],T=U[1],re=x.useState(null),Z=If(re,2),pe=Z[0],fe=Z[1],ce=UZ(),R=f0(),z=(R==null?void 0:R.width)>0?R.width:A,G=(R==null?void 0:R.height)>0?R.height:l,se=x.useCallback(Y=>{ce(Y),typeof t=="function"&&t(Y),T(Y),fe(Y),Y!=null&&(D.current=Y)},[ce,t,T,fe]),ue=x.useCallback(Y=>{E(R4(Y)),E(dr({handler:s,reactEvent:Y}))},[E,s]),P=x.useCallback(Y=>{E(Uy(Y)),E(dr({handler:h,reactEvent:Y}))},[E,h]),Q=x.useCallback(Y=>{E(uC()),E(dr({handler:v,reactEvent:Y}))},[E,v]),ne=x.useCallback(Y=>{E(Uy(Y)),E(dr({handler:y,reactEvent:Y}))},[E,y]),I=x.useCallback(()=>{E(K4())},[E]),he=x.useCallback(()=>{E(Y4())},[E]),be=x.useCallback(Y=>{E(q4(Y.key))},[E]),_e=x.useCallback(Y=>{E(dr({handler:d,reactEvent:Y}))},[E,d]),W=x.useCallback(Y=>{E(dr({handler:f,reactEvent:Y}))},[E,f]),V=x.useCallback(Y=>{E(dr({handler:m,reactEvent:Y}))},[E,m]),ye=x.useCallback(Y=>{E(dr({handler:b,reactEvent:Y}))},[E,b]),xe=x.useCallback(Y=>{E(dr({handler:_,reactEvent:Y}))},[E,_]),ae=x.useCallback(Y=>{k&&E(F4(Y)),E(dr({handler:j,reactEvent:Y}))},[E,k,j]),Le=x.useCallback(Y=>{E(dr({handler:w,reactEvent:Y}))},[E,w]),Ce=tQ(C);return x.createElement(DC.Provider,{value:K},x.createElement(AA.Provider,{value:pe},x.createElement(Ce,{width:z??(S==null?void 0:S.width),height:G??(S==null?void 0:S.height),className:nt("recharts-wrapper",r),style:HZ({position:"relative",cursor:"default",width:z,height:G},S),onClick:ue,onContextMenu:_e,onDoubleClick:W,onFocus:I,onBlur:he,onKeyDown:be,onMouseDown:V,onMouseEnter:P,onMouseLeave:Q,onMouseMove:ne,onMouseUp:ye,onTouchEnd:Le,onTouchMove:ae,onTouchSta Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),c.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[c.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[c.jsx(Gy,{className:"w-4 h-4"}),"AI如何工作"]}),c.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[c.jsx("li",{children:"• 自动识别买家的砍价请求"}),c.jsx("li",{children:"• 根据设定的策略智能回复"}),c.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),c.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),c.jsx("div",{className:"modal-footer",children:c.jsxs("div",{className:"flex gap-3 w-full",children:[c.jsx("button",{onClick:()=>K(null),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:ue,children:"取消"}),c.jsxs("button",{onClick:xe,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:ue,children:[ue?c.jsx(Yn,{className:"w-4 h-4 animate-spin"}):c.jsx(Sa,{className:"w-4 h-4"}),ue?"保存中...":"保存"]})]})})]})}),document.body)]})},QS=({status:e})=>{const t={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-[#0094f7] text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600"},n={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中"};return c.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[e]||t.cancelled}`,children:n[e]||e})},DQ=()=>{const[e,t]=x.useState([]),[n,r]=x.useState([]),[l,s]=x.useState([]),[d,f]=x.useState({}),[m,h]=x.useState("all"),[v,y]=x.useState(""),[b,w]=x.useState(1),[j,_]=x.useState(1),[S,A]=x.useState(!1),[C,M]=x.useState(!1),[k,D]=x.useState(!1),[E,$]=x.useState(!1),[U,K]=x.useState(null),[T,re]=x.useState(null),[Z,pe]=x.useState({}),[fe,ce]=x.useState(!1),[R,z]=x.useState(""),[G,se]=x.useState(!1),[ue,P]=x.useState(null),[Q,ne]=x.useState(null),[I,he]=x.useState(null),[be,_e]=x.useState(null),W=ie=>{if(!v.trim())return ie;const De=v.toLowerCase().trim();return ie.filter(Ue=>{var B,Te,lt,Zr,Qn,$n;return((B=Ue.order_id)==null?void 0:B.toLowerCase().includes(De))||((Te=Ue.item_id)==null?void 0:Te.toLowerCase().includes(De))||((lt=Ue.buyer_id)==null?void 0:lt.toLowerCase().includes(De))||((Zr=Ue.item_title)==null?void 0:Zr.toLowerCase().includes(De))||((Qn=Ue.receiver_name)==null?void 0:Qn.toLowerCase().includes(De))||(($n=Ue.receiver_phone)==null?void 0:$n.toLowerCase().includes(De))})},V=async()=>{A(!0);try{if(v.trim()){let ie=[],De=1,Ue=!0;for(;Ue;){const B=await xj(void 0,m,De,100);ie=[...ie,...B.data],Ue=De<B.total_pages,De++}r(ie),t(W(ie)),_(1)}else{const ie=await xj(void 0,m,b,20);r(ie.data),t(W(ie.data)),_(ie.total_pages)}}catch(ie){console.error("加载订单失败:",ie)}finally{A(!1)}};x.useEffect(()=>{t(W(n))},[n,v]);const ye=(ie,De)=>{if(De&&De.trim())return De;if(d[ie])return d[ie];const Ue=l.find(B=>{if(De&&B.item_title){const Te=De.toLowerCase(),lt=B.item_title.toLowerCase();return lt.includes(Te)||Te.includes(lt)}return!1});return Ue!=null&&Ue.item_title?Ue.item_title:"未知商品"},xe=ie=>{const De={};ie.forEach(Ue=>{Ue.item_id&&(De[Ue.item_id]=Ue.item_title||Ue.item_id)}),f(De)};x.useEffect(()=>{V(),Ns().then(ie=>{s(ie),xe(ie)}).catch(ie=>{console.error("加载商品列表失败:",ie)})},[m,b,v]);const ae=async()=>{A(!0);try{const ie=await ID();await V(),ie!=null&&ie.message&&alert(ie.message)}catch(ie){console.error("同步订单失败:",ie),alert((ie==null?void 0:ie.message)||"同步失败,请重试")}finally{A(!1)}},Le=ie=>{z(ie),P(null),ce(!0)},Ce=async ie=>{var De;se(!0),P(null);try{const Ue=await RD([R],ie),B=(De=Ue==null?void 0:Ue.results)==null?void 0:De[0];B!=null&&B.success?(P({success:!0,message:B.message}),V()):P({success:!1,message:(B==null?void 0:B.message)||"发货失败"})}catch(Ue){P({success:!1,message:(Ue==null?void 0:Ue.message)||"请求失败"})}finally{se(!1)}},Y=ie=>{K(ie),M(!0)},ge=ie=>{re({...ie}),D(!0)},Pe=async()=>{if(!(!T||!T.order_id))try{const ie={};T.status!==void 0&&(ie.order_status=T.status),T.buyer_id!==void 0&&(ie.buyer_id=T.buyer_id),T.amount!==void 0&&(ie.amount=T.amount),T.receiver_name!==void 0&&(ie.receiver_name=T.receiver_name),T.receiver_phone!==void 0&&(ie.receiver_phone=T.receiver_phone),T.receiver_address!==void 0&&(ie.receiver_address=T.receiver_address),T.item_id!==void 0&&(ie.item_id=T.item_id),T.quantity!==void 0&&(ie.quantity=T.quantity),await PD(T.order_id,ie),D(!1),re(null),V()}catch(ie){console.error("更新订单失败:",ie),alert("更新失败,请重试")}},Be=async()=>{if(Q)try{const ie=new FormData;ie.append("file",Q),await LD(ie),$(!1),ne(null),V(),alert("订 Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(ye=>ye.map(xe=>`"${String(xe).replace(/"/g,'""')}"`).join(",")).join(`
`),_e=new Blob(["\uFEFF"+be],{type:"text/csv;charset=utf-8"}),W=URL.createObjectURL(_e),V=document.createElement("a");V.href=W,V.download="卡密组批量导入模板.csv",document.body.appendChild(V),V.click(),V.remove(),URL.revokeObjectURL(W)},P=async()=>{if(S){D(!0),M(null);try{const I=await YD(S);if(M(I),I.created>0){const he=await va();t(he)}}catch(I){M({error:(I==null?void 0:I.message)||"上传失败"})}finally{D(!1)}}},Q=async()=>{if(!(!E||!U.trim())){D(!0),re(null);try{const I=await GD(E,U);re({added:I.added}),K("");const he=await va();t(he)}catch(I){alert("追加失败:"+((I==null?void 0:I.message)||"未知错误"))}finally{D(!1)}}},ne=()=>{var I;_("create"),A(null),M(null),$((I=se[0])!=null&&I.id?String(se[0].id):""),K(""),re(null),w(!0)};return c.jsxs("div",{className:"space-y-6 animate-fade-in",children:[c.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[c.jsxs("div",{children:[c.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),c.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsxs("button",{onClick:ne,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[c.jsx(tc,{className:"w-5 h-5"}),"批量导入"]}),c.jsxs("button",{onClick:()=>s(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[c.jsx(ja,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),c.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[c.jsx("div",{className:"overflow-x-auto",children:c.jsxs("table",{className:"w-full text-left border-collapse",children:[c.jsx("thead",{children:c.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[c.jsx("th",{className:"px-8 py-5 w-[18%]",children:"卡密名称"}),c.jsx("th",{className:"px-6 py-5 w-[12%]",children:"卡密组ID"}),c.jsx("th",{className:"px-6 py-5 w-[10%]",children:"类型"}),c.jsx("th",{className:"px-6 py-5 w-[22%]",children:"内容/库存"}),c.jsx("th",{className:"px-6 py-5 w-[18%]",children:"描述"}),c.jsx("th",{className:"px-6 py-5 w-[10%]",children:"状态"}),c.jsx("th",{className:"px-6 py-5 w-[10%] text-right",children:"操作"})]})}),c.jsx("tbody",{className:"divide-y divide-gray-50",children:e.map(I=>{let he="";return I.type==="data"&&I.data_content?he=`库存: ${I.data_content.split(`
`).filter(_e=>_e.trim()).length} 条`:I.type==="text"&&I.text_content?he=I.text_content.substring(0,20)+(I.text_content.length>20?"...":""):I.type==="api"&&I.api_config?he=I.api_config.url:I.type==="image"&&I.image_url&&(he="图片链接"),c.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[c.jsx("td",{className:"px-8 py-5",children:c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"p-2 bg-gray-50 rounded-xl group-hover:bg-white transition-colors",children:c.jsx(Z,{type:I.type})}),c.jsx("span",{className:"font-bold text-gray-900",children:I.name})]})}),c.jsx("td",{className:"px-6 py-5",children:c.jsxs("button",{onClick:()=>G(I.id),className:"inline-flex items-center gap-2 rounded-xl bg-gray-100 px-3 py-2 font-mono text-xs font-extrabold text-gray-700 hover:bg-gray-200 transition-colors",title:"复制卡密组ID,用于批量铺货表格",children:[I.id,c.jsx(lM,{className:"w-3.5 h-3.5"})]})}),c.jsx("td",{className:"px-6 py-5",children:c.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${I.type==="text"?"bg-blue-50 text-blue-600":I.type==="data"?"bg-purple-50 text-purple-600":I.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:I.type==="text"?"文本":I.type==="data"?"批量":I.type==="api"?"API":"图片"})}),c.jsx("td",{className:"px-6 py-5",children:c.jsx("span",{className:"text-sm text-gray-600 font-mono block truncate",title:he,children:he})}),c.jsx("td",{className:"px-6 py-5",children:c.jsx("span",{className:"text-sm text-gray-500 block max-w-[200px] truncate",title:I.description||"-",children:I.description||"-"})}),c.jsx("td",{className:"px-6 py-5",children:c.jsx("button",{onClick:()=>z(I),className:`w-12 h-8 rounded-full relative transition-colors ${I.enabled?"bg-green-500":"bg-gray-300"}`,children:c.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${I.enabled?"left-5":"left-1"}`})})}),c.jsx("td",{className:"px-6 py-5",children:c.jsxs("div",{className:"flex items-center justify-end gap-2",children:[c.jsx("button",{onClick:()=>pe(I),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:c.jsx(bs,{className:"w-4 h-4"})}),c.jsx("button",{onClick:()=>ce(I.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",children:c.jsx(xa,{className:"w-5 h-5"})})]})})]},I.id)})})]})}),e.length===0&&c.jsxs("div",{className:"py-20 text-center text-gray-400",children:[c.jsx(fA,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),c.jsx("p",{children:"暂无卡密配置,请点击右上角添加。"})]})]}),n&&d&&It.createPortal(c.jsx("div",{className:"modal-overlay-centered",children:c.jsxs("div",{className:"modal-container",children:[c.jsxs("div",{className:"modal-header",children:[c.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),c.jsx("button",{onClick:()=>r(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:c.jsx(Xt,{className:"w-5 h-5 text-gray-500"})})]}),c.jsx("div",{className:"modal-body",children:c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[c.jsxs("div",{children:[c.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",c.jsx("span",{className:"text-red-500",children:"*"})]}),c.jsx("input",{type:"text",value:m.name||"",onChange:I=>h({...m,name:I.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),c.jsxs("div",{children:[c.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),c.jsxs("select",{value:m.type||"text",onChange:I=>h({...m,type:I.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[c.jsx("option",{value:"",children:"请选择类型"}),c.jsx("option",{value:"text",children:"固定文字"}),c.jsx("option",{value:"data",children:"批量数据"}),c.jsx("option",{value:"api",children:"API接口"}),c.jsx("option",{value:"image",children:"图片"})]})]})]}),m.type==="api"&&c.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[c.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),c.jsxs("div",{children:[c.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),c.jsx("input",{type:"url",value:m.api_url||"",onChange:I=>h({...m,api_url:I.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{children:[c.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求方法"}),c.jsxs("select",{value:m.api_method||"GET",onChange:I=>h({...m,api_method:I.target.value}),className:"w-full ios-input pLine truncated
卡号1:密码1
卡号2:密码2
或者
兑换码1
兑换码2`}),c.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),c.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",c.jsx("span",{className:"font-bold text-blue-600",children:m.data_content?m.data_content.split(`
`).filter(I=>I.trim()).length:0})," 条"]})]})]}),m.type==="image"&&c.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[c.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),c.jsxs("div",{children:[c.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),c.jsx("input",{type:"url",value:m.image_url||"",onChange:I=>h({...m,image_url:I.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),c.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),m.image_url&&c.jsxs("div",{className:"mt-3",children:[c.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),c.jsx("img",{src:m.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:I=>{I.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),c.jsxs("div",{children:[c.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("input",{type:"number",value:m.delay_seconds||0,onChange:I=>h({...m,delay_seconds:parseInt(I.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),c.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),c.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),c.jsxs("div",{children:[c.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),c.jsx("textarea",{value:m.description||"",onChange:I=>h({...m,description:I.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),c.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[c.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),c.jsx("button",{type:"button",onClick:()=>h({...m,enabled:!m.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${m.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:c.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${m.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),c.jsx("div",{className:"modal-footer",children:c.jsxs("div",{className:"flex gap-3 w-full",children:[c.jsx("button",{onClick:()=>r(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),c.jsxs("button",{onClick:fe,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[c.jsx(Sa,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),l&&It.createPortal(c.jsx("div",{className:"modal-overlay-centered",children:c.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[c.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[c.jsxs("div",{children:[c.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),c.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),c.jsx("button",{onClick:()=>s(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:c.jsx(Xt,{className:"w-5 h-5 text-gray-500"})})]}),c.jsx("div",{className:"modal-body",children:c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),c.jsx("input",{type:"text",value:v.name,onChange:I=>y({...v,name:I.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),c.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:[c.jsxs("button",{type:"button",onClick:()=>y({...v,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${v.type==="data"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[c.jsx(Lv,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),c.jsxs("button",{type:"button",onClick:()=>y({...v,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${v.type==="text"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[c.jsx(mj,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),c.jsxs("button",{type:"button",onClick:()=>y({...v,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${v.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-grayLine truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),v.type==="data"&&c.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",c.jsx("span",{className:"font-bold text-[#0094f7]",children:v.content.split(`
`).filter(I=>I.trim()).length})," 条"]})]}),v.type==="api"&&c.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[c.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),c.jsxs("select",{value:v.api_method,onChange:I=>y({...v,api_method:I.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[c.jsx("option",{value:"GET",children:"GET"}),c.jsx("option",{value:"POST",children:"POST"})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),c.jsx("input",{type:"number",min:"1",max:"60",value:v.api_timeout,onChange:I=>y({...v,api_timeout:parseInt(I.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),c.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),c.jsx("textarea",{value:v.api_headers,onChange:I=>y({...v,api_headers:I.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),c.jsx("textarea",{value:v.api_params,onChange:I=>y({...v,api_params:I.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),c.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),c.jsx("input",{value:v.description,onChange:I=>y({...v,description:I.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),c.jsx("input",{type:"number",value:v.delay_seconds,onChange:I=>y({...v,delay_seconds:parseInt(I.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),c.jsx("div",{className:"modal-footer",children:c.jsxs("div",{className:"flex gap-3 w-full",children:[c.jsx("button",{onClick:()=>s(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),c.jsxs("button",{onClick:R,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[c.jsx(ja,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),b&&It.createPortal(c.jsx("div",{className:"modal-overlay",children:c.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[c.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[c.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),c.jsx("button",{onClick:()=>w(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:c.jsx(Xt,{className:"w-5 h-5 text-gray-600"})})]}),c.jsxs("div",{className:"px-6 py-5 space-y-5",children:[c.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[c.jsxs("button",{onClick:()=>_("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${j==="create"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[c.jsx(CM,{className:"w-4 h-4"}),"批量创建卡密组"]}),c.jsxs("button",{onClick:()=>_("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${j==="append"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[c.jsx(tc,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),j==="create"?c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",c.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image/api;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsxs("button",{onClick:ue,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),c.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),T&&c.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",T.added," 个卡密"]})]})})]}),c.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[c.jsx("button",{onClick:()=>w(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),j==="create"?c.jsxs("button",{onClick:P,disabled:!S||k,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[k?c.jsx(Yn,{className:"w-4 h-4 animate-spin"}):c.jsx(tc,{className:"w-4 h-4"}),k?"处理中...":"上传创建"]}):c.jsxs("button",{onClick:Q,disabled:!E||!U.trim()||k||se.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[k?c.jsx(Yn,{className:"w-4 h-4 animate-spin"}):c.jsx(ja,{className:"w-4 h-4"}),k?"处理中...":"追加卡密"]})]})]})}),document.body)]})},zQ=e=>{const t=String(e||"").trim();return t?/^[¥¥]/.test(t)?t:`¥${t}`:"-"},IQ=({onConfigureDelivery:e})=>{const[t,n]=x.useState([]),[r,l]=x.useState([]),[s,d]=x.useState([]),[f,m]=x.useState(""),[h,v]=x.useState(!1),[y,b]=x.useState(!1),[w,j]=x.useState(!1),[_,S]=x.useState(!1),[A,C]=x.useState(!1),[M,k]=x.useState(!1),[D,E]=x.useState(!1),[$,U]=x.useState("upload"),[K,T]=x.useState(null),[re,Z]=x.useState(null),[pe,fe]=x.useState(null),[ce,R]=x.useState(null),[z,G]=x.useState(null),[se,ue]=x.useState({}),[P,Q]=x.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[ne,I]=x.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),he=async()=>{const B=await Ns();n(B)},be=async()=>{l(await Rd())};x.useEffect(()=>{Promise.all([Fy(),Ns(),Rd()]).then(([B,Te,lt])=>{d(B),n(Te),l(lt)}).catch(B=>console.error("加载商品配置失败:",B))},[]),x.useEffect(()=>{if(!D||!(ce!=null&&ce.id)||ce.status!=="running")return;const B=window.setInterval(async()=>{try{const Te=await cd(ce.id);R(Te),Te.status!=="running"&&(U("done"),await he(),await be())}catch(Te){console.error("刷新批量铺货进度失败:",Te)}},3e3);return()=>window.clearInterval(B)},[D,ce==null?void 0:ce.id,ce==null?void 0:ce.status]);const _e=async()=>{if(!f)return alert("请先选择账号");v(!0);try{const B=await VD(f);await he(),alert((B==null?void 0:B.message)||"商品同步完成")}catch(B){console.error("同步商品失败:",B),alert((B==null?void 0:B.message)||"同步失败,请重试")}finally{v(!1)}},W=B=>{G(B),ue({...B}),S(!0)},V=async()=>{if(z)try{await tP(z.cookie_id,z.item_id,{item_title:se.item_title||"",item_description:se.item_description||"",item_category:se.item_category||"",item_price:se.item_price||"",item_detail:se.item_detail||z.item_detail||""}),await he(),await be(),S(!1),G(null)}catch(B){console.error("更新商品失败:",B),alert("更新失败,请重试")}},ye=async B=>{if(confirm(`确认删除商品"${B.item_title}"吗?`))try{await FD(B.cookie_id,B.item_id),n(Te=>Te.filter(lt=>!(lt.cookie_id===B.cookie_id&&lt.item_id===B.item_id)))}catch(Te){console.error("删除商品失败:",Te),alert("删除失败,请重试")}},xe=async()=>{try{if(!P.cookie_id||!P.item_id){alert("请选择账号并填写商品ID");return}await XD(P.cookie_id,{item_id:P.item_id,item_title:P.item_title,item_price:P.item_price,item_detail:P.item_image?JSON.stringify({item_image:P.item_image}):""}),await he(),C(!1),Q({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(B){console.error("添加商品失败:",B),alert("添加失败,请重试")}},ae=async()=>{if(!ne.cookie_id)return alert("请选择发布账号");if(!ne.title.trim())return alert("请填写商品标题");if(!ne.price.trim())return alert("请填写商品价格");if(!ne.quantity||Number(ne.quantity)<=0)return alert("库存数量必须大于 0");if(ne.images.length===0)return alert("至少上传 1 张商品图片");if(ne.postage_mode==="fixed"&&!ne.postage.trim())return alert("请填写一口价邮费");b(!0);try{const B=await WD(ne);if(await he(),k(!1),I({cookie_id:f||"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),B!=null&&B.item_id){const Te={id:B.item_id,cookie_id:ne.cookie_id,item_id:B.item_id,item_title:B.item_title||ne.title,item_price:B.item_price||ne.price,item_image:B.item_image};e(Te),alert("商品发布成功,ID: "+B.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(B){console.error("发布商品失败:",B);const Te=B==null?void 0:B.payload;if((Te==null?void 0:Te.code)==="stock_permission_missing" Line truncated
`),Zr=new Blob(["\uFEFF"+lt],{type:"text/csv;charset=utf-8"}),Qn=URL.createObjectURL(Zr),$n=document.createElement("a");$n.href=Qn,$n.download="批量铺货模板.csv",document.body.appendChild($n),$n.click(),$n.remove(),URL.revokeObjectURL(Qn)},Ve=()=>{Q(B=>({...B,cookie_id:f||B.cookie_id})),C(!0)},Dt=()=>{I(B=>({...B,cookie_id:f||B.cookie_id})),k(!0)},ie=B=>r.filter(Te=>Te.cookie_id===B.cookie_id&&Te.item_id===B.item_id),De=B=>{switch(B){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"canceled":return"已取消";default:return B||"-"}},Ue=B=>{switch(B){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}};return c.jsxs("div",{className:"space-y-6 animate-fade-in",children:[c.jsxs("div",{className:"flex justify-between items-center",children:[c.jsxs("div",{children:[c.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),c.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),c.jsxs("div",{className:"flex gap-3",children:[c.jsxs("select",{className:"ios-input px-4 py-3 rounded-xl text-sm",value:f,onChange:B=>m(B.target.value),children:[c.jsx("option",{value:"",children:"选择账号以同步"}),s.map(B=>c.jsx("option",{value:B.id,children:B.nickname},B.id))]}),c.jsxs("button",{onClick:_e,disabled:h||!f,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[c.jsx(pr,{className:`w-4 h-4 ${h?"animate-spin":""}`}),"同步商品"]}),c.jsxs("button",{onClick:Ve,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[c.jsx(ja,{className:"w-4 h-4"}),"添加商品"]}),c.jsxs("button",{onClick:Dt,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-600 text-white hover:bg-emerald-700 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[c.jsx(Zp,{className:"w-4 h-4"}),"发布商品"]}),c.jsxs("button",{onClick:Le,className:"px-5 py-3 rounded-2xl font-bold bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[c.jsx(od,{className:"w-4 h-4"}),"批量铺货"]})]})]}),c.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[t.map(B=>{const Te=ie(B),lt=Te.length>0;return c.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex-col",children:[c.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:[c.jsx("button",{onClick:()=>W(B),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-[#0094f7] hover:text-white transition-colors",title:"编辑",children:c.jsx(bs,{className:"w-3.5 h-3.5"})}),c.jsx("button",{onClick:()=>ye(B),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md hover:bg-red-100 text-red-500 transition-colors",title:"删除",children:c.jsx(xa,{className:"w-3.5 h-3.5"})})]}),c.jsxs("div",{className:"aspect-square bg-gray-100 rounded-xl mb-2.5 overflow-hidden relative",children:[B.item_image?c.jsx("img",{src:B.item_image,alt:"",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}):c.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:c.jsx(sA,{className:"w-8 h-8"})}),c.jsx("div",{className:"absolute top-1.5 left-1.5 bg-black/50 backdrop-blur-md text-white text-[10px] font-bold px-1.5 py-0.5 rounded-md",children:zQ(B.item_price)})]}),c.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4",children:B.item_title}),c.jsxs("div",{className:"flex justify-between items-center text-[10px] text-gray-500 mb-2",children:[c.jsxs("span",{className:"bg-gray-100 px-1.5 py-0.5 rounded truncate max-w-[80px]",children:["ID: ",B.item_id]}),c.jsxs("span",{className:`inline-flex items-center gap-1 font-bold ${lt?"text-emerald-600":"text-amber-600"}`,children:[lt?c.jsx(oA,{className:"w-3 h-3"}):c.jsx(eM,{className:"w-3 h-3"}),lt?`${Te.length} 规则`:"未配置"]})]}),c.jsx("div",{className:"space-y-2 mt-auto",children:c.jsxs("button",{onClick:()=>e(B),className:`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${lt?"bg-gray-900 text-white hover:bg-black":"bg-[#0094f7] text-white hover:bg-[#0071e3] shadow-md shadow-blue-100"}`,children:[c.jsxs("span",{className:"flex items-center Line truncated
@@ -1 +1 @@
*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.pointer-events-none{pointer-events:none}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{top:0;right:0;bottom:0;left:0}.-bottom-1{bottom:-.25rem}.-right-1{rigLine truncated
*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.pointer-events-none{pointer-events:none}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{top:0;right:0;bottom:0;left:0}.-bottom-1{bottom:-.25rem}.-right-1{rigLine truncated
+49
View File
@@ -0,0 +1,49 @@
function ws(M,Sl){for(var W=0;W<Sl.length;W++){const o=Sl[W];if(typeof o!="string"&&!Array.isArray(o)){for(const al in o)if(al!=="default"&&!(al in M)){const vl=Object.getOwnPropertyDescriptor(o,al);vl&&Object.defineProperty(M,al,vl.get?vl:{enumerable:!0,get:()=>o[al]})}}}return Object.freeze(Object.defineProperty(M,Symbol.toStringTag,{value:"Module"}))}function E1(M){return M&&M.__esModule&&Object.prototype.hasOwnProperty.call(M,"default")?M.default:M}var ai={exports:{}},ge={};/**
* @license React
* react-jsx-runtime.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var m1;function Ws(){if(m1)return ge;m1=1;var M=Symbol.for("react.transitional.element"),Sl=Symbol.for("react.fragment");function W(o,al,vl){var Ol=null;if(vl!==void 0&&(Ol=""+vl),al.key!==void 0&&(Ol=""+al.key),"key"in al){vl={};for(var Rl in al)Rl!=="key"&&(vl[Rl]=al[Rl])}else vl=al;return al=vl.ref,{$$typeof:M,type:o,key:Ol,ref:al!==void 0?al:null,props:vl}}return ge.Fragment=Sl,ge.jsx=W,ge.jsxs=W,ge}var s1;function $s(){return s1||(s1=1,ai.exports=Ws()),ai.exports}var ed=$s(),ei={exports:{}},C={};/**
* @license React
* react.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var d1;function Fs(){if(d1)return C;d1=1;var M=Symbol.for("react.transitional.element"),Sl=Symbol.for("react.portal"),W=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),al=Symbol.for("react.profiler"),vl=Symbol.for("react.consumer"),Ol=Symbol.for("react.context"),Rl=Symbol.for("react.forward_ref"),N=Symbol.for("react.suspense"),A=Symbol.for("react.memo"),$=Symbol.for("react.lazy"),R=Symbol.for("react.activity"),il=Symbol.iterator;function wl(v){return v===null||typeof v!="object"?null:(v=il&&v[il]||v["@@iterator"],typeof v=="function"?v:null)}var Bl={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},ql=Object.assign,Ut={};function Wl(v,E,O){this.props=v,this.context=E,this.refs=Ut,this.updater=O||Bl}Wl.prototype.isReactComponent={},Wl.prototype.setState=function(v,E){if(typeof v!="object"&&typeof v!="function"&&v!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,v,E,"setState")},Wl.prototype.forceUpdate=function(v){this.updater.enqueueForceUpdate(this,v,"forceUpdate")};function wt(){}wt.prototype=Wl.prototype;function Nl(v,E,O){this.props=v,this.context=E,this.refs=Ut,this.updater=O||Bl}var nt=Nl.prototype=new wt;nt.constructor=Nl,ql(nt,Wl.prototype),nt.isPureReactComponent=!0;var Tt=Array.isArray;function Gl(){}var x={H:null,A:null,T:null,S:null},Xl=Object.prototype.hasOwnProperty;function Et(v,E,O){var U=O.ref;return{$$typeof:M,type:v,key:E,ref:U!==void 0?U:null,props:O}}function Qu(v,E){return Et(v.type,E,v.props)}function At(v){return typeof v=="object"&&v!==null&&v.$$typeof===M}function Ql(v){var E={"=":"=0",":":"=2"};return"$"+v.replace(/[=:]/g,function(O){return E[O]})}var zu=/\/+/g;function rt(v,E){return typeof v=="object"&&v!==null&&v.key!=null?Ql(""+v.key):E.toString(36)}function St(v){switch(v.status){case"fulfilled":return v.value;case"rejected":throw v.reason;default:switch(typeof v.status=="string"?v.then(Gl,Gl):(v.status="pending",v.then(function(E){v.status==="pending"&&(v.status="fulfilled",v.value=E)},function(E){v.status==="pending"&&(v.status="rejected",v.reason=E)})),v.status){case"fulfilled":return v.value;case"rejected":throw v.reason}}throw v}function b(v,E,O,U,Y){var X=typeof v;(X==="undefined"||X==="boolean")&&(v=null);var F=!1;if(v===null)F=!0;else switch(X){case"bigint":case"string":case"number":F=!0;break;case"object":switch(v.$$typeof){case M:case Sl:F=!0;break;case $:return F=v._init,b(F(v._payload),E,O,U,Y)}}if(F)return Y=Y(v),F=U===""?"."+rt(v,0):U,Tt(Y)?(O="",F!=null&&(O=F.replace(zu,"$&/")+"/"),b(Y,E,O,"",function(Oa){return Oa})):Y!=null&&(At(Y)&&(Y=Qu(Y,O+(Y.key==null||v&&v.key===Y.key?"":(""+Y.key).replace(zu,"$&/")+"/")+F)),E.push(Y)),1;F=0;var Cl=U===""?".":U+":";if(Tt(v))for(var dl=0;dl<v.length;dl++)U=v[dl],X=Cl+rt(U,dl),F+=b(U,E,O,X,Y);else if(dl=wl(v),typeof dl=="function")for(v=dl.call(v),dl=0;!(U=v.next()).done;)U=U.value,X=Cl+rt(U,dl++),F+=b(U,E,O,X,Y);else if(X==="object"){if(typeof v.then=="function")return b(St(v),E,O,U,Y);throw E=String(v),Error("Objects are not valid as a React child (found: "+(E==="[object Object]"?"object with keys {"+Object.keys(v).join(", ")+"}":E)+"). If you meant to render a collection of children, use an array instead.")}return F}function _(v,E,O){if(v==null)return v;var U=[],Y=0;return b(v,U,"","",function(X){return E.call(O,X,Y++)}),U}function q(v){if(v._status===-1){var E=v._result;E=E(),E.then(function(O){(v._status===0||v._status===-1)&&(v._status=1,v._result=O)},function(O){(v._status===0||v._status===-1)&&(v._status=2,v._result=O)}),v._status===-1&&(v._status=0,v._result=E)}if(v._status===1)return v._result.default;throw v._result}var P=typeof reportError=="function"?reportError:function(v){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var E=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof v=="object"&&v!==null&&typeof v.message=="string"?String(v.message):String(v),error:v});if(!window.dispatchEvent(E))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",v);return}console.error(v)},el={map:_,forEach:function(v,E,O){_(v,function(){E.apply(this,arguments)},O)},count:function(v){var E=0;return _(v,function(){E++}),E},toArray:function(v){return _(v,function(E){return E})||[]},only:function(v){if(!At(v))throw Error("React.Children.only expected to receive a single React element child.");return v}};return C.Activity=R,C.Children=el,C.Component=Wl,C.Fragment=W,C.Profiler=al,C.PureComponent=Nl,C.StrictMode=o,C.Suspense=N,C.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=x,C.__COMPILER_RUNTIME={__proto__:null,c:function(v){return x.H.useMemoCache(v)}},C.cache=function(v){return function(){return v.apply(null,arguments)}},C.cacheSignal=function(){return null},C.cloneElement=function(v,E,O){if(v==null)throw Error("The argumentLine truncated
* @license React
* scheduler.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var o1;function Is(){return o1||(o1=1,(function(M){function Sl(b,_){var q=b.length;b.push(_);l:for(;0<q;){var P=q-1>>>1,el=b[P];if(0<al(el,_))b[P]=_,b[q]=el,q=P;else break l}}function W(b){return b.length===0?null:b[0]}function o(b){if(b.length===0)return null;var _=b[0],q=b.pop();if(q!==_){b[0]=q;l:for(var P=0,el=b.length,v=el>>>1;P<v;){var E=2*(P+1)-1,O=b[E],U=E+1,Y=b[U];if(0>al(O,q))U<el&&0>al(Y,O)?(b[P]=Y,b[U]=q,P=U):(b[P]=O,b[E]=q,P=E);else if(U<el&&0>al(Y,q))b[P]=Y,b[U]=q,P=U;else break l}}return _}function al(b,_){var q=b.sortIndex-_.sortIndex;return q!==0?q:b.id-_.id}if(M.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var vl=performance;M.unstable_now=function(){return vl.now()}}else{var Ol=Date,Rl=Ol.now();M.unstable_now=function(){return Ol.now()-Rl}}var N=[],A=[],$=1,R=null,il=3,wl=!1,Bl=!1,ql=!1,Ut=!1,Wl=typeof setTimeout=="function"?setTimeout:null,wt=typeof clearTimeout=="function"?clearTimeout:null,Nl=typeof setImmediate<"u"?setImmediate:null;function nt(b){for(var _=W(A);_!==null;){if(_.callback===null)o(A);else if(_.startTime<=b)o(A),_.sortIndex=_.expirationTime,Sl(N,_);else break;_=W(A)}}function Tt(b){if(ql=!1,nt(b),!Bl)if(W(N)!==null)Bl=!0,Gl||(Gl=!0,Ql());else{var _=W(A);_!==null&&St(Tt,_.startTime-b)}}var Gl=!1,x=-1,Xl=5,Et=-1;function Qu(){return Ut?!0:!(M.unstable_now()-Et<Xl)}function At(){if(Ut=!1,Gl){var b=M.unstable_now();Et=b;var _=!0;try{l:{Bl=!1,ql&&(ql=!1,wt(x),x=-1),wl=!0;var q=il;try{t:{for(nt(b),R=W(N);R!==null&&!(R.expirationTime>b&&Qu());){var P=R.callback;if(typeof P=="function"){R.callback=null,il=R.priorityLevel;var el=P(R.expirationTime<=b);if(b=M.unstable_now(),typeof el=="function"){R.callback=el,nt(b),_=!0;break t}R===W(N)&&o(N),nt(b)}else o(N);R=W(N)}if(R!==null)_=!0;else{var v=W(A);v!==null&&St(Tt,v.startTime-b),_=!1}}break l}finally{R=null,il=q,wl=!1}_=void 0}}finally{_?Ql():Gl=!1}}}var Ql;if(typeof Nl=="function")Ql=function(){Nl(At)};else if(typeof MessageChannel<"u"){var zu=new MessageChannel,rt=zu.port2;zu.port1.onmessage=At,Ql=function(){rt.postMessage(null)}}else Ql=function(){Wl(At,0)};function St(b,_){x=Wl(function(){b(M.unstable_now())},_)}M.unstable_IdlePriority=5,M.unstable_ImmediatePriority=1,M.unstable_LowPriority=4,M.unstable_NormalPriority=3,M.unstable_Profiling=null,M.unstable_UserBlockingPriority=2,M.unstable_cancelCallback=function(b){b.callback=null},M.unstable_forceFrameRate=function(b){0>b||125<b?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):Xl=0<b?Math.floor(1e3/b):5},M.unstable_getCurrentPriorityLevel=function(){return il},M.unstable_next=function(b){switch(il){case 1:case 2:case 3:var _=3;break;default:_=il}var q=il;il=_;try{return b()}finally{il=q}},M.unstable_requestPaint=function(){Ut=!0},M.unstable_runWithPriority=function(b,_){switch(b){case 1:case 2:case 3:case 4:case 5:break;default:b=3}var q=il;il=b;try{return _()}finally{il=q}},M.unstable_scheduleCallback=function(b,_,q){var P=M.unstable_now();switch(typeof q=="object"&&q!==null?(q=q.delay,q=typeof q=="number"&&0<q?P+q:P):q=P,b){case 1:var el=-1;break;case 2:el=250;break;case 5:el=1073741823;break;case 4:el=1e4;break;default:el=5e3}return el=q+el,b={id:$++,callback:_,priorityLevel:b,startTime:q,expirationTime:el,sortIndex:-1},q>P?(b.sortIndex=q,Sl(A,b),W(N)===null&&b===W(A)&&(ql?(wt(x),x=-1):ql=!0,St(Tt,q-P))):(b.sortIndex=el,Sl(N,b),Bl||wl||(Bl=!0,Gl||(Gl=!0,Ql()))),b},M.unstable_shouldYield=Qu,M.unstable_wrapCallback=function(b){var _=il;return function(){var q=il;il=_;try{return b.apply(this,arguments)}finally{il=q}}}})(ci)),ci}var S1;function Ps(){return S1||(S1=1,fi.exports=Is()),fi.exports}var ii={exports:{}},pl={};/**
* @license React
* react-dom.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var g1;function ld(){if(g1)return pl;g1=1;var M=yi();function Sl(N){var A="https://react.dev/errors/"+N;if(1<arguments.length){A+="?args[]="+encodeURIComponent(arguments[1]);for(var $=2;$<arguments.length;$++)A+="&args[]="+encodeURIComponent(arguments[$])}return"Minified React error #"+N+"; visit "+A+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function W(){}var o={d:{f:W,r:function(){throw Error(Sl(522))},D:W,C:W,L:W,m:W,X:W,S:W,M:W},p:0,findDOMNode:null},al=Symbol.for("react.portal");function vl(N,A,$){var R=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:al,key:R==null?null:""+R,children:N,containerInfo:A,implementation:$}}var Ol=M.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function Rl(N,A){if(N==="font")return"";if(typeof A=="string")return A==="use-credentials"?A:""}return pl.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=o,pl.createPortal=function(N,A){var $=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!A||A.nodeType!==1&&A.nodeType!==9&&A.nodeType!==11)throw Error(Sl(299));return vl(N,A,null,$)},pl.flushSync=function(N){var A=Ol.T,$=o.p;try{if(Ol.T=null,o.p=2,N)return N()}finally{Ol.T=A,o.p=$,o.d.f()}},pl.preconnect=function(N,A){typeof N=="string"&&(A?(A=A.crossOrigin,A=typeof A=="string"?A==="use-credentials"?A:"":void 0):A=null,o.d.C(N,A))},pl.prefetchDNS=function(N){typeof N=="string"&&o.d.D(N)},pl.preinit=function(N,A){if(typeof N=="string"&&A&&typeof A.as=="string"){var $=A.as,R=Rl($,A.crossOrigin),il=typeof A.integrity=="string"?A.integrity:void 0,wl=typeof A.fetchPriority=="string"?A.fetchPriority:void 0;$==="style"?o.d.S(N,typeof A.precedence=="string"?A.precedence:void 0,{crossOrigin:R,integrity:il,fetchPriority:wl}):$==="script"&&o.d.X(N,{crossOrigin:R,integrity:il,fetchPriority:wl,nonce:typeof A.nonce=="string"?A.nonce:void 0})}},pl.preinitModule=function(N,A){if(typeof N=="string")if(typeof A=="object"&&A!==null){if(A.as==null||A.as==="script"){var $=Rl(A.as,A.crossOrigin);o.d.M(N,{crossOrigin:$,integrity:typeof A.integrity=="string"?A.integrity:void 0,nonce:typeof A.nonce=="string"?A.nonce:void 0})}}else A==null&&o.d.M(N)},pl.preload=function(N,A){if(typeof N=="string"&&typeof A=="object"&&A!==null&&typeof A.as=="string"){var $=A.as,R=Rl($,A.crossOrigin);o.d.L(N,$,{crossOrigin:R,integrity:typeof A.integrity=="string"?A.integrity:void 0,nonce:typeof A.nonce=="string"?A.nonce:void 0,type:typeof A.type=="string"?A.type:void 0,fetchPriority:typeof A.fetchPriority=="string"?A.fetchPriority:void 0,referrerPolicy:typeof A.referrerPolicy=="string"?A.referrerPolicy:void 0,imageSrcSet:typeof A.imageSrcSet=="string"?A.imageSrcSet:void 0,imageSizes:typeof A.imageSizes=="string"?A.imageSizes:void 0,media:typeof A.media=="string"?A.media:void 0})}},pl.preloadModule=function(N,A){if(typeof N=="string")if(A){var $=Rl(A.as,A.crossOrigin);o.d.m(N,{as:typeof A.as=="string"&&A.as!=="script"?A.as:void 0,crossOrigin:$,integrity:typeof A.integrity=="string"?A.integrity:void 0})}else o.d.m(N)},pl.requestFormReset=function(N){o.d.r(N)},pl.unstable_batchedUpdates=function(N,A){return N(A)},pl.useFormState=function(N,A,$){return Ol.H.useFormState(N,A,$)},pl.useFormStatus=function(){return Ol.H.useHostTransitionStatus()},pl.version="19.2.7",pl}var b1;function _1(){if(b1)return ii.exports;b1=1;function M(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(M)}catch(Sl){console.error(Sl)}}return M(),ii.exports=ld(),ii.exports}/**
* @license React
* react-dom-client.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var z1;function td(){if(z1)return be;z1=1;var M=Ps(),Sl=yi(),W=_1();function o(l){var t="https://react.dev/errors/"+l;if(1<arguments.length){t+="?args[]="+encodeURIComponent(arguments[1]);for(var u=2;u<arguments.length;u++)t+="&args[]="+encodeURIComponent(arguments[u])}return"Minified React error #"+l+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function al(l){return!(!l||l.nodeType!==1&&l.nodeType!==9&&l.nodeType!==11)}function vl(l){var t=l,u=l;if(l.alternate)for(;t.return;)t=t.return;else{l=t;do t=l,(t.flags&4098)!==0&&(u=t.return),l=t.return;while(l)}return t.tag===3?u:null}function Ol(l){if(l.tag===13){var t=l.memoizedState;if(t===null&&(l=l.alternate,l!==null&&(t=l.memoizedState)),t!==null)return t.dehydrated}return null}function Rl(l){if(l.tag===31){var t=l.memoizedState;if(t===null&&(l=l.alternate,l!==null&&(t=l.memoizedState)),t!==null)return t.dehydrated}return null}function N(l){if(vl(l)!==l)throw Error(o(188))}function A(l){var t=l.alternate;if(!t){if(t=vl(l),t===null)throw Error(o(188));return t!==l?null:l}for(var u=l,a=t;;){var e=u.return;if(e===null)break;var n=e.alternate;if(n===null){if(a=e.return,a!==null){u=a;continue}break}if(e.child===n.child){for(n=e.child;n;){if(n===u)return N(e),l;if(n===a)return N(e),t;n=n.sibling}throw Error(o(188))}if(u.return!==a.return)u=e,a=n;else{for(var f=!1,c=e.child;c;){if(c===u){f=!0,u=e,a=n;break}if(c===a){f=!0,a=e,u=n;break}c=c.sibling}if(!f){for(c=n.child;c;){if(c===u){f=!0,u=n,a=e;break}if(c===a){f=!0,a=n,u=e;break}c=c.sibling}if(!f)throw Error(o(189))}}if(u.alternate!==a)throw Error(o(190))}if(u.tag!==3)throw Error(o(188));return u.stateNode.current===u?l:t}function $(l){var t=l.tag;if(t===5||t===26||t===27||t===6)return l;for(l=l.child;l!==null;){if(t=$(l),t!==null)return t;l=l.sibling}return null}var R=Object.assign,il=Symbol.for("react.element"),wl=Symbol.for("react.transitional.element"),Bl=Symbol.for("react.portal"),ql=Symbol.for("react.fragment"),Ut=Symbol.for("react.strict_mode"),Wl=Symbol.for("react.profiler"),wt=Symbol.for("react.consumer"),Nl=Symbol.for("react.context"),nt=Symbol.for("react.forward_ref"),Tt=Symbol.for("react.suspense"),Gl=Symbol.for("react.suspense_list"),x=Symbol.for("react.memo"),Xl=Symbol.for("react.lazy"),Et=Symbol.for("react.activity"),Qu=Symbol.for("react.memo_cache_sentinel"),At=Symbol.iterator;function Ql(l){return l===null||typeof l!="object"?null:(l=At&&l[At]||l["@@iterator"],typeof l=="function"?l:null)}var zu=Symbol.for("react.client.reference");function rt(l){if(l==null)return null;if(typeof l=="function")return l.$$typeof===zu?null:l.displayName||l.name||null;if(typeof l=="string")return l;switch(l){case ql:return"Fragment";case Wl:return"Profiler";case Ut:return"StrictMode";case Tt:return"Suspense";case Gl:return"SuspenseList";case Et:return"Activity"}if(typeof l=="object")switch(l.$$typeof){case Bl:return"Portal";case Nl:return l.displayName||"Context";case wt:return(l._context.displayName||"Context")+".Consumer";case nt:var t=l.render;return l=l.displayName,l||(l=t.displayName||t.name||"",l=l!==""?"ForwardRef("+l+")":"ForwardRef"),l;case x:return t=l.displayName||null,t!==null?t:rt(l.type)||"Memo";case Xl:t=l._payload,l=l._init;try{return rt(l(t))}catch{}}return null}var St=Array.isArray,b=Sl.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,_=W.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,q={pending:!1,data:null,method:null,action:null},P=[],el=-1;function v(l){return{current:l}}function E(l){0>el||(l.current=P[el],P[el]=null,el--)}function O(l,t){el++,P[el]=l.current,l.current=t}var U=v(null),Y=v(null),X=v(null),F=v(null);function Cl(l,t){switch(O(X,t),O(Y,l),O(U,null),t.nodeType){case 9:case 11:l=(l=t.documentElement)&&(l=l.namespaceURI)?Cv(l):0;break;default:if(l=t.tagName,t=t.namespaceURI)t=Cv(t),l=Yv(t,l);else switch(l){case"svg":l=1;break;case"math":l=2;break;default:l=0}}E(U),O(U,l)}function dl(){E(U),E(Y),E(X)}function Oa(l){l.memoizedState!==null&&O(F,l);var t=U.current,u=Yv(t,l.type);t!==u&&(O(Y,l),O(U,u))}function ze(l){Y.current===l&&(E(U),E(Y)),F.current===l&&(E(F),de._currentValue=q)}var Xn,vi;function Tu(l){if(Xn===void 0)try{throw Error()}catch(u){var t=u.stack.trim().match(/\n( *(at )?)/);Xn=t&&t[1]||"",vi=-1<u.stack.indexOf(`
at`)?" (<anonymous>)":-1<u.stack.indexOf("@")?"@unknown:0:0":""}return`
`+Xn+l+vi}var Qn=!1;function jn(l,t){if(!l||Qn)return"";Qn=!0;var u=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var a={DetermineComponentFrameRoot:function(){try{if(t){var T=function(){throw Error()};if(Object.defineProperty(T.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(T,[])}catch(S){var h=S}Reflect.construct(l,[],T)}else{try{T.call()}catch(S){h=S}l.call(T.prototype)}}else{try{throw Error()}catch(S){h=S}(T=l())&&typeof T.catch=="function"&&T.catch(function(){})}}catch(S){if(S&&h&&typeof S.stack=="string")return[S.stack,h.stack]}return[null,null]}};a.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var e=Object.getOwnPropertyDescriptor(a.DetermineComponentFrameRoot,"name");e&&e.configurable&&Object.defineProperty(a.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var n=a.DetermineComponentFrameRoot(),f=n[0],c=n[1];if(f&&c){var i=f.split(`
`),d=c.split(`
`);for(e=a=0;a<i.length&&!i[a].includes("DetermineComponentFrameRoot");)a++;for(;e<d.length&&!d[e].includes("DetermineComponentFrameRoot");)e++;if(a===i.length||e===d.length)for(a=i.length-1,e=d.length-1;1<=a&&0<=e&&i[a]!==d[e];)e--;for(;1<=a&&0<=e;a--,e--)if(i[a]!==d[e]){if(a!==1||e!==1)do if(a--,e--,0>e||i[a]!==d[e]){var g=`
`+i[a].replace(" at new "," at ");return l.displayName&&g.includes("<anonymous>")&&(g=g.replace("<anonymous>",l.displayName)),g}while(1<=a&&0<=e);break}}}finally{Qn=!1,Error.prepareStackTrace=u}return(u=l?l.displayName||l.name:"")?Tu(u):""}function O1(l,t){switch(l.tag){case 26:case 27:case 5:return Tu(l.type);case 16:return Tu("Lazy");case 13:return l.child!==t&&t!==null?Tu("Suspense Fallback"):Tu("Suspense");case 19:return Tu("SuspenseList");case 0:case 15:return jn(l.type,!1);case 11:return jn(l.type.render,!1);case 1:return jn(l.type,!0);case 31:return Tu("Activity");default:return""}}function mi(l){try{var t="",u=null;do t+=O1(l,u),u=l,l=l.return;while(l);return t}catch(a){return`
Error generating stack: `+a.message+`
`+a.stack}}var Zn=Object.prototype.hasOwnProperty,Vn=M.unstable_scheduleCallback,xn=M.unstable_cancelCallback,M1=M.unstable_shouldYield,D1=M.unstable_requestPaint,$l=M.unstable_now,U1=M.unstable_getCurrentPriorityLevel,si=M.unstable_ImmediatePriority,di=M.unstable_UserBlockingPriority,Te=M.unstable_NormalPriority,r1=M.unstable_LowPriority,hi=M.unstable_IdlePriority,H1=M.log,N1=M.unstable_setDisableYieldValue,Ma=null,Fl=null;function Wt(l){if(typeof H1=="function"&&N1(l),Fl&&typeof Fl.setStrictMode=="function")try{Fl.setStrictMode(Ma,l)}catch{}}var kl=Math.clz32?Math.clz32:q1,p1=Math.log,R1=Math.LN2;function q1(l){return l>>>=0,l===0?32:31-(p1(l)/R1|0)|0}var Ee=256,Ae=262144,_e=4194304;function Eu(l){var t=l&42;if(t!==0)return t;switch(l&-l){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return l&261888;case 262144:case 524288:case 1048576:case 2097152:return l&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return l&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return l}}function Oe(l,t,u){var a=l.pendingLanes;if(a===0)return 0;var e=0,n=l.suspendedLanes,f=l.pingedLanes;l=l.warmLanes;var c=a&134217727;return c!==0?(a=c&~n,a!==0?e=Eu(a):(f&=c,f!==0?e=Eu(f):u||(u=c&~l,u!==0&&(e=Eu(u))))):(c=a&~n,c!==0?e=Eu(c):f!==0?e=Eu(f):u||(u=a&~l,u!==0&&(e=Eu(u)))),e===0?0:t!==0&&t!==e&&(t&n)===0&&(n=e&-e,u=t&-t,n>=u||n===32&&(u&4194048)!==0)?t:e}function Da(l,t){return(l.pendingLanes&~(l.suspendedLanes&~l.pingedLanes)&t)===0}function C1(l,t){switch(l){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function oi(){var l=_e;return _e<<=1,(_e&62914560)===0&&(_e=4194304),l}function Ln(l){for(var t=[],u=0;31>u;u++)t.push(l);return t}function Ua(l,t){l.pendingLanes|=t,t!==268435456&&(l.suspendedLanes=0,l.pingedLanes=0,l.warmLanes=0)}function Y1(l,t,u,a,e,n){var f=l.pendingLanes;l.pendingLanes=u,l.suspendedLanes=0,l.pingedLanes=0,l.warmLanes=0,l.expiredLanes&=u,l.entangledLanes&=u,l.errorRecoveryDisabledLanes&=u,l.shellSuspendCounter=0;var c=l.entanglements,i=l.expirationTimes,d=l.hiddenUpdates;for(u=f&~u;0<u;){var g=31-kl(u),T=1<<g;c[g]=0,i[g]=-1;var h=d[g];if(h!==null)for(d[g]=null,g=0;g<h.length;g++){var S=h[g];S!==null&&(S.lane&=-536870913)}u&=~T}a!==0&&Si(l,a,0),n!==0&&e===0&&l.tag!==0&&(l.suspendedLanes|=n&~(f&~t))}function Si(l,t,u){l.pendingLanes|=t,l.suspendedLanes&=~t;var a=31-kl(t);l.entangledLanes|=t,l.entanglements[a]=l.entanglements[a]|1073741824|u&261930}function gi(l,t){var u=l.entangledLanes|=t;for(l=l.entanglements;u;){var a=31-kl(u),e=1<<a;e&t|l[a]&t&&(l[a]|=t),u&=~e}}function bi(l,t){var u=t&-t;return u=(u&42)!==0?1:Kn(u),(u&(l.suspendedLanes|t))!==0?0:u}function Kn(l){switch(l){case 2:l=1;break;case 8:l=4;break;case 32:l=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:l=128;break;case 268435456:l=134217728;break;default:l=0}return l}function Jn(l){return l&=-l,2<l?8<l?(l&134217727)!==0?32:268435456:8:2}function zi(){var l=_.p;return l!==0?l:(l=window.event,l===void 0?32:e1(l.type))}function Ti(l,t){var u=_.p;try{return _.p=l,t()}finally{_.p=u}}var $t=Math.random().toString(36).slice(2),Ml="__reactFiber$"+$t,jl="__reactProps$"+$t,ju="__reactContainer$"+$t,wn="__reactEvents$"+$t,B1="__reactListeners$"+$t,G1="__reactHandles$"+$t,Ei="__reactResources$"+$t,ra="__reactMarker$"+$t;function Wn(l){delete l[Ml],delete l[jl],delete l[wn],delete l[B1],delete l[G1]}function Zu(l){var t=l[Ml];if(t)return t;for(var u=l.parentNode;u;){if(t=u[ju]||u[Ml]){if(u=t.alternate,t.child!==null||u!==null&&u.child!==null)for(l=Vv(l);l!==null;){if(u=l[Ml])return u;l=Vv(l)}return t}l=u,u=l.parentNode}return null}function Vu(l){if(l=l[Ml]||l[ju]){var t=l.tag;if(t===5||t===6||t===13||t===31||t===26||t===27||t===3)return l}return null}function Ha(l){var t=l.tag;if(t===5||t===26||t===27||t===6)return l.stateNode;throw Error(o(33))}function xu(l){var t=l[Ei];return t||(t=l[Ei]={hoistableStyles:new Map,hoistableScripts:new Map}),t}function Al(l){l[ra]=!0}var Ai=new Set,_i={};function Au(l,t){Lu(l,t),Lu(l+"Capture",t)}function Lu(l,t){for(_i[l]=t,l=0;l<t.length;l++)Ai.add(t[l])}var X1=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u21 Line truncated
`).replace(os,"")}function Rv(l,t){return t=pv(t),pv(l)===t}function tl(l,t,u,a,e,n){switch(u){case"children":typeof a=="string"?t==="body"||t==="textarea"&&a===""||Ju(l,a):(typeof a=="number"||typeof a=="bigint")&&t!=="body"&&Ju(l,""+a);break;case"className":De(l,"class",a);break;case"tabIndex":De(l,"tabindex",a);break;case"dir":case"role":case"viewBox":case"width":case"height":De(l,u,a);break;case"style":Ri(l,a,n);break;case"data":if(t!=="object"){De(l,"data",a);break}case"src":case"href":if(a===""&&(t!=="a"||u!=="href")){l.removeAttribute(u);break}if(a==null||typeof a=="function"||typeof a=="symbol"||typeof a=="boolean"){l.removeAttribute(u);break}a=re(""+a),l.setAttribute(u,a);break;case"action":case"formAction":if(typeof a=="function"){l.setAttribute(u,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof n=="function"&&(u==="formAction"?(t!=="input"&&tl(l,t,"name",e.name,e,null),tl(l,t,"formEncType",e.formEncType,e,null),tl(l,t,"formMethod",e.formMethod,e,null),tl(l,t,"formTarget",e.formTarget,e,null)):(tl(l,t,"encType",e.encType,e,null),tl(l,t,"method",e.method,e,null),tl(l,t,"target",e.target,e,null)));if(a==null||typeof a=="symbol"||typeof a=="boolean"){l.removeAttribute(u);break}a=re(""+a),l.setAttribute(u,a);break;case"onClick":a!=null&&(l.onclick=Nt);break;case"onScroll":a!=null&&j("scroll",l);break;case"onScrollEnd":a!=null&&j("scrollend",l);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(o(61));if(u=a.__html,u!=null){if(e.children!=null)throw Error(o(60));l.innerHTML=u}}break;case"multiple":l.multiple=a&&typeof a!="function"&&typeof a!="symbol";break;case"muted":l.muted=a&&typeof a!="function"&&typeof a!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(a==null||typeof a=="function"||typeof a=="boolean"||typeof a=="symbol"){l.removeAttribute("xlink:href");break}u=re(""+a),l.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",u);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":a!=null&&typeof a!="function"&&typeof a!="symbol"?l.setAttribute(u,""+a):l.removeAttribute(u);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":a&&typeof a!="function"&&typeof a!="symbol"?l.setAttribute(u,""):l.removeAttribute(u);break;case"capture":case"download":a===!0?l.setAttribute(u,""):a!==!1&&a!=null&&typeof a!="function"&&typeof a!="symbol"?l.setAttribute(u,a):l.removeAttribute(u);break;case"cols":case"rows":case"size":case"span":a!=null&&typeof a!="function"&&typeof a!="symbol"&&!isNaN(a)&&1<=a?l.setAttribute(u,a):l.removeAttribute(u);break;case"rowSpan":case"start":a==null||typeof a=="function"||typeof a=="symbol"||isNaN(a)?l.removeAttribute(u):l.setAttribute(u,a);break;case"popover":j("beforetoggle",l),j("toggle",l),Me(l,"popover",a);break;case"xlinkActuate":Ht(l,"http://www.w3.org/1999/xlink","xlink:actuate",a);break;case"xlinkArcrole":Ht(l,"http://www.w3.org/1999/xlink","xlink:arcrole",a);break;case"xlinkRole":Ht(l,"http://www.w3.org/1999/xlink","xlink:role",a);break;case"xlinkShow":Ht(l,"http://www.w3.org/1999/xlink","xlink:show",a);break;case"xlinkTitle":Ht(l,"http://www.w3.org/1999/xlink","xlink:title",a);break;case"xlinkType":Ht(l,"http://www.w3.org/1999/xlink","xlink:type",a);break;case"xmlBase":Ht(l,"http://www.w3.org/XML/1998/namespace","xml:base",a);break;case"xmlLang":Ht(l,"http://www.w3.org/XML/1998/namespace","xml:lang",a);break;case"xmlSpace":Ht(l,"http://www.w3.org/XML/1998/namespace","xml:space",a);break;case"is":Me(l,"is",a);break;case"innerText":case"textContent":break;default:(!(2<u.length)||u[0]!=="o"&&u[0]!=="O"||u[1]!=="n"&&u[1]!=="N")&&(u=x1.get(u)||u,Me(l,u,a))}}function Qc(l,t,u,a,e,n){switch(u){case"style":Ri(l,a,n);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(o(61));if(u=a.__html,u!=null){if(e.children!=null)throw Error(o(60));l.innerHTML=u}}break;case"children":typeof a=="string"?Ju(l,a):(typeof a=="number"||typeof a=="bigint")&&Ju(l,""+a);break;case"onScroll":a!=null&&j("scroll",l);break;case"onScrollEnd":a!=null&&j("scrollend",l);break;case"onClick":a!=null&&(l.onclick=Nt);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML" Line truncated
File renamed without changes.

Before

Width:  |  Height:  |  Size: 4.5 KiB

After

Width:  |  Height:  |  Size: 4.5 KiB

@@ -0,0 +1,33 @@
var Yn=Object.defineProperty;var Gn=(e,t,r)=>t in e?Yn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Oe=(e,t,r)=>Gn(e,typeof t!="symbol"?t+"":t,r);import{a as qt,r as K,g as Xn}from"./react-vendor-DZnRGM0-.js";function qr(e){var t,r,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t<i;t++)e[t]&&(r=qr(e[t]))&&(n&&(n+=" "),n+=r)}else for(r in e)e[r]&&(n&&(n+=" "),n+=r);return n}function Uo(){for(var e,t,r=0,n="",i=arguments.length;r<i;r++)(e=arguments[r])&&(t=qr(e))&&(n&&(n+=" "),n+=t);return n}function At(e){return e==="__proto__"}function Yr(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function Yt(e){var t;return typeof e=="string"||typeof e=="symbol"?e:Object.is((t=e==null?void 0:e.valueOf)==null?void 0:t.call(e),-0)?"-0":String(e)}function Gr(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Gr).join(",");const t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function Gt(e){if(Array.isArray(e))return e.map(Yt);if(typeof e=="symbol")return[e];e=Gr(e);const t=[],r=e.length;if(r===0)return t;let n=0,i="",s="",o=!1;for(e.charCodeAt(0)===46&&t.push("");n<r;){const f=e[n];if(s)f==="\\"&&n+1<r?(n++,i+=e[n]):f===s?s="":i+=f;else if(o)f==='"'||f==="'"?s=f:f==="]"?(o=!1,t.push(i),i=""):i+=f;else if(f==="[")o=!0,i&&(t.push(i),i="");else if(f==="."){i&&(t.push(i),i="");const u=e[n+1];(u===void 0||u===".")&&t.push("")}else i+=f;n++}return i&&t.push(i),t}function Xt(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(At(t))return r;const n=e[t];return n===void 0?Yr(t)?Xt(e,Gt(t),r):r:n}case"number":case"symbol":{typeof t=="number"&&(t=Yt(t));const n=e[t];return n===void 0?r:n}default:{if(Array.isArray(t))return Hn(e,t,r);if(Object.is(t==null?void 0:t.valueOf(),-0)?t="-0":t=String(t),At(t))return r;const n=e[t];return n===void 0?r:n}}}function Hn(e,t,r){if(t.length===0)return r;let n=e;for(let i=0;i<t.length;i++){if(n==null||At(t[i]))return r;n=n[t[i]]}return n===void 0?r:n}function Kn(e,t){const r=new Map;for(let n=0;n<e.length;n++){const i=e[n],s=t(i,n,e);r.has(s)||r.set(s,i)}return Array.from(r.values())}function Zn(e,t){return function(...r){return e.apply(this,r.slice(0,t))}}function Xr(e){return e}function Jn(e){return function(t){return Xt(t,e)}}function Pt(e){return e==null||typeof e!="object"&&typeof e!="function"}function Vn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Qn(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function Ht(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const ei="[object RegExp]",Hr="[object String]",Kr="[object Number]",Zr="[object Boolean]",Jr="[object Arguments]",ti="[object Symbol]",ri="[object Date]",ni="[object Map]",ii="[object Set]",si="[object Array]",oi="[object ArrayBuffer]",fi="[object Object]",ui="[object DataView]",ci="[object Uint8Array]",ai="[object Uint8ClampedArray]",li="[object Uint16Array]",di="[object Uint32Array]",hi="[object Int8Array]",pi="[object Int16Array]",yi="[object Int32Array]",mi="[object Float32Array]",_i="[object Float64Array]",sr=typeof globalThis=="object"&&globalThis||typeof window=="object"&&window||typeof self=="object"&&self||typeof global=="object"&&global||(function(){return this})();function gi(e){return typeof sr.Buffer<"u"&&sr.Buffer.isBuffer(e)}function wi(e,t){return te(e,void 0,e,new Map,t)}function te(e,t,r,n=new Map,i=void 0){const s=i==null?void 0:i(e,t,r,n);if(s!==void 0)return s;if(Pt(e))return e;if(n.has(e))return n.get(e);if(Array.isArray(e)){const o=new Array(e.length);n.set(e,o);for(let f=0;f<e.length;f++)o[f]=te(e[f],f,r,n,i);return Object.hasOwn(e,"index")&&(o.index=e.index),Object.hasOwn(e,"input")&&(o.input=e.input),o}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){const o=new RegExp(e.source,e.flags);return o.lastIndex=e.lastIndex,o}if(e instanceof Map){const o=new Map;n.set(e,o);for(const[f,u]of e)o.set(f,te(u,f,r,n,i));return o}if(e instanceof Set){const o=new Set;n.set(e,o);for(const f of e)o.add(te(f,void 0,r,n,i));return o}if(gi(e))return e.subarray();if(Vn(e)){const o=new(Object.getPrototypeOf(e)).constructor(e.length);n.set(e,o);for(let f=0;f<e.length;f++)o[f]=te(e[f],f,r,n,i);return o}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){const o=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return n.set(e,o),j(o,e,r,n,i),o}if(typeof File<"u"&&e instanceof File){const o=new File([e],e.name,{type:e.type});return n.set(e,o),j(o,e,r,n,i),o}if(typeof Blob<"u"&&e instanceof Blob){const o=new Blob([e],{type:e.type});return n.set(e,o),j(o,e,r,n,i),o}if(e instanceof Error){const o=structuredClone(e);return n.set(e,o),o.message=e.message,o.name=e.name,o.staLine truncated
* @license React
* use-sync-external-store-shim.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var or;function Li(){if(or)return at;or=1;var e=qt();function t(l,m){return l===m&&(l!==0||1/l===1/m)||l!==l&&m!==m}var r=typeof Object.is=="function"?Object.is:t,n=e.useState,i=e.useEffect,s=e.useLayoutEffect,o=e.useDebugValue;function f(l,m){var h=m(),y=n({inst:{value:h,getSnapshot:m}}),d=y[0].inst,p=y[1];return s(function(){d.value=h,d.getSnapshot=m,u(d)&&p({inst:d})},[l,h,m]),i(function(){return u(d)&&p({inst:d}),l(function(){u(d)&&p({inst:d})})},[l]),o(h),h}function u(l){var m=l.getSnapshot;l=l.value;try{var h=m();return!r(l,h)}catch{return!0}}function a(l,m){return m()}var c=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?a:f;return at.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:c,at}var fr;function Fi(){return fr||(fr=1,ct.exports=Li()),ct.exports}/**
* @license React
* use-sync-external-store-shim/with-selector.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var ur;function Ti(){if(ur)return ut;ur=1;var e=qt(),t=Fi();function r(a,c){return a===c&&(a!==0||1/a===1/c)||a!==a&&c!==c}var n=typeof Object.is=="function"?Object.is:r,i=t.useSyncExternalStore,s=e.useRef,o=e.useEffect,f=e.useMemo,u=e.useDebugValue;return ut.useSyncExternalStoreWithSelector=function(a,c,l,m,h){var y=s(null);if(y.current===null){var d={hasValue:!1,value:null};y.current=d}else d=y.current;y=f(function(){function g(v){if(!S){if(S=!0,E=v,v=m(v),h!==void 0&&d.hasValue){var A=d.value;if(h(A,v))return w=A}return w=v}if(A=w,n(E,v))return A;var D=m(v);return h!==void 0&&h(A,D)?(E=v,A):(E=v,w=D)}var S=!1,E,w,b=l===void 0?null:l;return[function(){return g(c())},b===null?void 0:function(){return g(b())}]},[c,l,m,h]);var p=i(a,y[0],y[1]);return o(function(){d.hasValue=!0,d.value=p},[p]),u(p),p},ut}var cr;function zi(){return cr||(cr=1,ft.exports=Ti()),ft.exports}var jo=zi();function Ui(e,t=`expected a function, instead received ${typeof e}`){if(typeof e!="function")throw new TypeError(t)}function Bi(e,t="expected all items to be functions, instead received the following types: "){if(!e.every(r=>typeof r=="function")){const r=e.map(n=>typeof n=="function"?`function ${n.name||"unnamed"}()`:typeof n).join(", ");throw new TypeError(`${t}[${r}]`)}}var ar=e=>Array.isArray(e)?e:[e];function ji(e){const t=Array.isArray(e[0])?e[0]:e;return Bi(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}function Wi(e,t){const r=[],{length:n}=e;for(let i=0;i<n;i++)r.push(e[i].apply(null,t));return r}var qi=class{constructor(e){this.value=e}deref(){return this.value}},Yi=()=>typeof WeakRef>"u"?qi:WeakRef,sn=Yi(),Gi=0,lr=1;function Re(){return{s:Gi,v:void 0,o:null,p:null}}function Xi(e){return e instanceof sn?e.deref():e}function on(e,t={}){let r=Re();const{resultEqualityCheck:n}=t;let i,s=0;function o(){let f=r;const{length:u}=arguments;for(let l=0,m=u;l<m;l++){const h=arguments[l];if(typeof h=="function"||typeof h=="object"&&h!==null){let y=f.o;y===null&&(f.o=y=new WeakMap);const d=y.get(h);d===void 0?(f=Re(),y.set(h,f)):f=d}else{let y=f.p;y===null&&(f.p=y=new Map);const d=y.get(h);d===void 0?(f=Re(),y.set(h,f)):f=d}}const a=f;let c;if(f.s===lr)c=f.v;else if(c=e.apply(null,arguments),s++,n){const l=Xi(i);l!=null&&n(l,c)&&(c=l,s!==0&&s--),i=typeof c=="object"&&c!==null||typeof c=="function"?new sn(c):c}return a.s=lr,a.v=c,c}return o.clearCache=()=>{r=Re(),o.resetResultsCount()},o.resultsCount=()=>s,o.resetResultsCount=()=>{s=0},o}function Hi(e,...t){const r=typeof e=="function"?{memoize:e,memoizeOptions:t}:e,n=(...i)=>{let s=0,o=0,f,u={},a=i.pop();typeof a=="object"&&(u=a,a=i.pop()),Ui(a,`createSelector expects an output function after the inputs, but received: [${typeof a}]`);const c={...r,...u},{memoize:l,memoizeOptions:m=[],argsMemoize:h=on,argsMemoizeOptions:y=[]}=c,d=ar(m),p=ar(y),g=ji(i),S=l(function(){return s++,a.apply(null,arguments)},...d),E=h(function(){o++;const b=Wi(g,arguments);return f=S.apply(null,b),f},...p);return Object.assign(E,{resultFunc:a,memoizedResultFunc:S,dependencies:g,dependencyRecomputations:()=>o,resetDependencyRecomputations:()=>{o=0},lastResult:()=>f,recomputations:()=>s,resetRecomputations:()=>{s=0},memoize:l,argsMemoize:h})};return Object.assign(n,{withTypes:()=>n}),n}var Wo=Hi(on);function Ki(e,t=1){const r=[],n=Math.floor(t),i=(s,o)=>{for(let f=0;f<s.length;f++){const u=s[f];Array.isArray(u)&&o<n?i(u,o+1):r.push(u)}};return i(e,0),r}function Rt(e,t,r){return Vr(r)&&(typeof t=="number"&&nn(r)&&rn(t)&&t<r.length||typeof t=="string"&&t in r)?De(r[t],e):!1}function dr(e){return typeof e=="symbol"?1:e===null?2:e===void 0?3:e!==e?4:0}const Zi=(e,t,r)=>{if(e!==t){const n=dr(e),i=dr(t);if(n===i&&n===0){if(e<t)return r==="desc"?1:-1;if(e>t)return r==="desc"?-1:1}return r==="desc"?i-n:n-i}return 0};function fn(e){return typeof e=="symbol"||e instanceof Symbol}const Ji=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Vi=/^\w*$/;function Qi(e,t){return Array.isArray(e)?!1:typeof e=="number"||typeof e=="boolean"||e==null||fn(e)?!0:typeof e=="string"&&(Vi.test(e)||!Ji.test(e))||t!=null}function es(e,t,r,n){if(e==null)return[];r=r,Array.isArray(e)||(e=Object.values(e)),Array.isArray(t)||(t=t==null?[null]:[t]),t.length===0&&(t=[null]),Array.isArray(r)||(r=r==null?[]:[r]),r=r.map(f=>String(f));const i=(f,u)=>{let a=f;for(let c=0;c<u.length&&a!=null;++c)a=a[u[c]];return a},s=(f,u)=>u==null||f==null?u:typeof f=="object"&&"key"in f?Object.hasOwn(u,f.key)?u[f.key]:i(u,f.path):typeof f=="function"?f(u):Array.isArray(f)?i(u,f):typeof u=="object"?u[f]:u,o=t.map(f=>(Array.isArray(f)&&f.length===1&&(f=f[0]),f==null||typeof f=="function"||Array.isArray(f)||Qi(f)?f:{key:f,path:Gt(f)}));return e.map(f=>({original:f,criteria:o.map(u=>s(u,f))})).slice().sort((f,u)=>{for(let a=0;a<o.length;a++){const c=Zi(f.criteria[a],u.criteria[a],r[a]);if(c!==0)return c}return 0}).map(f=>f.original)}function qo(e,...t){const r=t.length;return r>1&&Rt(e,t[0],t[1])?t=[]:r>2&&Rt(Line truncated
* @license React
* use-sync-external-store-with-selector.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var kr;function lo(){if(kr)return _t;kr=1;var e=qt();function t(u,a){return u===a&&(u!==0||1/u===1/a)||u!==u&&a!==a}var r=typeof Object.is=="function"?Object.is:t,n=e.useSyncExternalStore,i=e.useRef,s=e.useEffect,o=e.useMemo,f=e.useDebugValue;return _t.useSyncExternalStoreWithSelector=function(u,a,c,l,m){var h=i(null);if(h.current===null){var y={hasValue:!1,value:null};h.current=y}else y=h.current;h=o(function(){function p(b){if(!g){if(g=!0,S=b,b=l(b),m!==void 0&&y.hasValue){var v=y.value;if(m(v,b))return E=v}return E=b}if(v=E,r(S,b))return v;var A=l(b);return m!==void 0&&m(v,A)?(S=b,v):(S=b,E=A)}var g=!1,S,E,w=c===void 0?null:c;return[function(){return p(a())},w===null?void 0:function(){return p(w())}]},[a,c,l,m]);var d=n(u,h[0],h[1]);return s(function(){y.hasValue=!0,y.value=d},[d]),f(d),d},_t}var Cr;function ho(){return Cr||(Cr=1,mt.exports=lo()),mt.exports}ho();function po(e){e()}function yo(){let e=null,t=null;return{clear(){e=null,t=null},notify(){po(()=>{let r=e;for(;r;)r.callback(),r=r.next})},get(){const r=[];let n=e;for(;n;)r.push(n),n=n.next;return r},subscribe(r){let n=!0;const i=t={callback:r,next:null,prev:t};return i.prev?i.prev.next=i:e=i,function(){!n||e===null||(n=!1,i.next?i.next.prev=i.prev:t=i.prev,i.prev?i.prev.next=i.next:e=i.next)}}}}var Lr={notify(){},get:()=>[]};function mo(e,t){let r,n=Lr,i=0,s=!1;function o(d){c();const p=n.subscribe(d);let g=!1;return()=>{g||(g=!0,p(),l())}}function f(){n.notify()}function u(){y.onStateChange&&y.onStateChange()}function a(){return s}function c(){i++,r||(r=e.subscribe(u),n=yo())}function l(){i--,r&&i===0&&(r(),r=void 0,n.clear(),n=Lr)}function m(){s||(s=!0,c())}function h(){s&&(s=!1,l())}const y={addNestedSub:o,notifyNestedSubs:f,handleChangeWrapper:u,isSubscribed:a,trySubscribe:m,tryUnsubscribe:h,getListeners:()=>n};return y}var _o=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",go=_o(),wo=()=>typeof navigator<"u"&&navigator.product==="ReactNative",bo=wo(),Eo=()=>go||bo?K.useLayoutEffect:K.useEffect,So=Eo();function Fr(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function Vo(e,t){if(Fr(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;const r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i=0;i<r.length;i++)if(!Object.prototype.hasOwnProperty.call(t,r[i])||!Fr(e[r[i]],t[r[i]]))return!1;return!0}var gt=Symbol.for("react-redux-context"),wt=typeof globalThis<"u"?globalThis:{};function vo(){if(!K.createContext)return{};const e=wt[gt]??(wt[gt]=new Map);let t=e.get(K.createContext);return t||(t=K.createContext(null),e.set(K.createContext,t)),t}var Ao=vo();function Po(e){const{children:t,context:r,serverState:n,store:i}=e,s=K.useMemo(()=>{const u=mo(i);return{store:i,subscription:u,getServerState:n?()=>n:void 0}},[i,n]),o=K.useMemo(()=>i.getState(),[i]);So(()=>{const{subscription:u}=s;return u.onStateChange=u.notifyNestedSubs,u.trySubscribe(),o!==i.getState()&&u.notifyNestedSubs(),()=>{u.tryUnsubscribe(),u.onStateChange=void 0}},[s,o]);const f=r||Ao;return K.createElement(f.Provider,{value:s},t)}var Qo=Po;function Oo(e){return fn(e)?NaN:Number(e)}function bt(e){return e?(e=Oo(e),e===1/0||e===-1/0?(e<0?-1:1)*Number.MAX_VALUE:e===e?e:0):e===0?e:0}function ef(e,t,r){r&&typeof r!="number"&&Rt(e,t,r)&&(t=r=void 0),e=bt(e),t===void 0?(t=e,e=0):t=bt(t),r=r===void 0?e<t?1:-1:bt(r);const n=Math.max(Math.ceil((t-e)/(r||1)),0),i=new Array(n);for(let s=0;s<n;s++)i[s]=e,e+=r;return i}var he=1e9,Ro={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:"2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"},ir,M=!0,B="[DecimalError] ",ne=B+"Invalid argument: ",nr=B+"Exponent out of range: ",pe=Math.floor,ee=Math.pow,Mo=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,L,$=1e7,R=7,Un=9007199254740991,He=pe(Un/R),_={};_.absoluteValue=_.abs=function(){var e=new this.constructor(this);return e.s&&(e.s=1),e};_.comparedTo=_.cmp=function(e){var t,r,n,i,s=this;if(e=new s.constructor(e),s.s!==e.s)return s.s||-e.s;if(s.e!==e.e)return s.e>e.e^s.s<0?1:-1;for(n=s.d.length,i=e.d.length,t=0,r=n<i?n:i;t<r;++t)if(s.d[t]!==e.d[t])return s.d[t]>e.d[t]^s.s<0?1:-1;return n===i?0:n>i^s.s<0?1:-1};_.decimalPlaces=_.dp=function(){var e=this,t=e.d.length-1,r=(t-e.e)*R;if(t=e.d[t],t)for(;t%10==0;t/=10)r--;return r<0?0:r};_.dividedBy=_.div=function(e){return Z(this,new this.constructor(e))};_.dividedToIntegerBy=_.idiv=function(e){var t=this,r=t.constructor;return O(Z(t,new r(e),0,1),r.precision)};_.equals=_.eq=function(e){return!this.cmp(e)};_.exponent=function(){return I(this)};_.greaterThan=_.gt=function(e){return this.cmp(e)>0};_.greaterThanOrEqualTo=_.gte=function(e){return this.cmp(e)>=0};_.isInteger=_.isint=function(){return this.e>this.d.length-2};_.isNegative=_.isneg=function(){return this.s<0};_.isPositive=_.ispos=function(){return this.s>0};_.isZero=function(){return this.s===0};_.lessThan=_.lt=function(e){return this.Line truncated
* @license React
* react-is.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var jr;function Co(){if(jr)return P;jr=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),o=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),a=Symbol.for("react.suspense_list"),c=Symbol.for("react.memo"),l=Symbol.for("react.lazy"),m=Symbol.for("react.view_transition"),h=Symbol.for("react.client.reference");function y(d){if(typeof d=="object"&&d!==null){var p=d.$$typeof;switch(p){case e:switch(d=d.type,d){case r:case i:case n:case u:case a:case m:return d;default:switch(d=d&&d.$$typeof,d){case o:case f:case l:case c:return d;case s:return d;default:return p}}case t:return p}}}return P.ContextConsumer=s,P.ContextProvider=o,P.Element=e,P.ForwardRef=f,P.Fragment=r,P.Lazy=l,P.Memo=c,P.Portal=t,P.Profiler=i,P.StrictMode=n,P.Suspense=u,P.SuspenseList=a,P.isContextConsumer=function(d){return y(d)===s},P.isContextProvider=function(d){return y(d)===o},P.isElement=function(d){return typeof d=="object"&&d!==null&&d.$$typeof===e},P.isForwardRef=function(d){return y(d)===f},P.isFragment=function(d){return y(d)===r},P.isLazy=function(d){return y(d)===l},P.isMemo=function(d){return y(d)===c},P.isPortal=function(d){return y(d)===t},P.isProfiler=function(d){return y(d)===i},P.isStrictMode=function(d){return y(d)===n},P.isSuspense=function(d){return y(d)===u},P.isSuspenseList=function(d){return y(d)===a},P.isValidElementType=function(d){return typeof d=="string"||typeof d=="function"||d===r||d===i||d===n||d===u||d===a||typeof d=="object"&&d!==null&&(d.$$typeof===l||d.$$typeof===c||d.$$typeof===o||d.$$typeof===s||d.$$typeof===f||d.$$typeof===h||d.getModuleId!==void 0)},P.typeOf=y,P}var Wr;function Lo(){return Wr||(Wr=1,vt.exports=Co()),vt.exports}var sf=Lo(),Fo="Invariant failed";function of(e,t){throw new Error(Fo)}export{tf as D,nf as E,rf as I,Qo as P,Wo as a,Ho as b,Uo as c,ws as d,Jo as e,Vo as f,Xt as g,sf as h,of as i,le as j,Ko as k,Xo as l,is as m,Rs as n,Go as p,ef as r,qo as s,Zo as t,Bo as u,jo as w};
+6 -2
View File
@@ -6,8 +6,12 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
<script type="module" crossorigin src="/static/assets/index-Bzj0nqFG.js"></script>
<link rel="stylesheet" crossorigin href="/static/assets/index-CjhArDrm.css">
<script type="module" crossorigin src="/static/assets/index-BVGBdlzO.js"></script>
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-DZnRGM0-.js">
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-BmeuAUrP.js">
<link rel="modulepreload" crossorigin href="/static/assets/vendor-w5t2K9ux.js">
<link rel="modulepreload" crossorigin href="/static/assets/charts-vendor-B_BfwiL0.js">
<link rel="stylesheet" crossorigin href="/static/assets/index-DgV81f94.css">
</head>
<body>
<div id="root"></div>
+243
View File
@@ -0,0 +1,243 @@
package cookierefresh
import (
"encoding/json"
"sort"
"strings"
)
const (
metadataSnapshotKey = "cookies_refresh_snapshot"
legacyMetadataSnapshot = "cookie_refresh_snapshot"
)
// BrowserCookie 保存浏览器返回的完整 Cookie 属性。
type BrowserCookie struct {
Name string `json:"name"`
Value string `json:"value"`
Domain string `json:"domain,omitempty"`
Path string `json:"path,omitempty"`
Expires float64 `json:"expires,omitempty"`
HTTPOnly bool `json:"httpOnly,omitempty"`
Secure bool `json:"secure,omitempty"`
SameSite string `json:"sameSite,omitempty"`
}
// ParseCookieString 把 Cookie 头解析为 name -> value。
func ParseCookieString(s string) map[string]string {
out := make(map[string]string)
for _, part := range strings.Split(s, ";") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
eq := strings.Index(part, "=")
if eq <= 0 {
continue
}
out[strings.TrimSpace(part[:eq])] = strings.TrimSpace(part[eq+1:])
}
return out
}
// MarshalCookieString 以稳定顺序把 Cookie map 拼回 Cookie 头。
func MarshalCookieString(m map[string]string) string {
if len(m) == 0 {
return ""
}
keys := make([]string, 0, len(m))
for k := range m {
if strings.TrimSpace(k) != "" {
keys = append(keys, k)
}
}
sort.Strings(keys)
parts := make([]string, 0, len(keys))
for _, k := range keys {
parts = append(parts, k+"="+m[k])
}
return strings.Join(parts, "; ")
}
// MergeSetCookies 将 Set-Cookie 响应头合并进原 Cookie 字符串。
func MergeSetCookies(original string, setCookies []string) string {
m := ParseCookieString(original)
for _, raw := range setCookies {
first := strings.TrimSpace(strings.Split(raw, ";")[0])
eq := strings.Index(first, "=")
if eq <= 0 {
continue
}
name := strings.TrimSpace(first[:eq])
if name == "" {
continue
}
m[name] = strings.TrimSpace(first[eq+1:])
}
return MarshalCookieString(m)
}
// ChangedCookieNames 返回两个 Cookie 字符串之间发生变化的字段名。
func ChangedCookieNames(before, after string) []string {
a := ParseCookieString(before)
b := ParseCookieString(after)
seen := make(map[string]struct{}, len(a)+len(b))
for k := range a {
seen[k] = struct{}{}
}
for k := range b {
seen[k] = struct{}{}
}
names := make([]string, 0, len(seen))
for k := range seen {
if a[k] != b[k] {
names = append(names, k)
}
}
sort.Strings(names)
return names
}
// ChangedSnapshotLabels 返回完整浏览器 Cookie 快照变化标签,格式 name@domain/path。
func ChangedSnapshotLabels(before, after []BrowserCookie) []string {
key := func(c BrowserCookie) string {
path := c.Path
if path == "" {
path = "/"
}
return c.Name + "|" + c.Domain + "|" + path
}
label := func(c BrowserCookie) string {
path := c.Path
if path == "" {
path = "/"
}
if c.Domain != "" {
return c.Name + "@" + c.Domain + path
}
return c.Name
}
oldMap := make(map[string]BrowserCookie)
newMap := make(map[string]BrowserCookie)
for _, c := range NormalizeSnapshot(before) {
oldMap[key(c)] = c
}
for _, c := range NormalizeSnapshot(after) {
newMap[key(c)] = c
}
seen := make(map[string]struct{}, len(oldMap)+len(newMap))
for k := range oldMap {
seen[k] = struct{}{}
}
for k := range newMap {
seen[k] = struct{}{}
}
labels := make([]string, 0, len(seen))
for k := range seen {
old := oldMap[k]
newCookie := newMap[k]
if old == newCookie {
continue
}
if newCookie.Name != "" {
labels = append(labels, label(newCookie))
} else if old.Name != "" {
labels = append(labels, label(old))
}
}
sort.Strings(labels)
return labels
}
// CookieStringFromSnapshot 将浏览器 Cookie 快照压成请求 Cookie 字符串。
func CookieStringFromSnapshot(cookies []BrowserCookie) string {
m := make(map[string]string, len(cookies))
for _, c := range cookies {
if c.Name == "" {
continue
}
m[c.Name] = c.Value
}
return MarshalCookieString(m)
}
// MergeOriginalFields 补回浏览器未返回但原 Cookie 中存在的字段。
func MergeOriginalFields(original, browserCookieString string) string {
m := ParseCookieString(original)
for k, v := range ParseCookieString(browserCookieString) {
m[k] = v
}
return MarshalCookieString(m)
}
// NormalizeSnapshot 排序并补齐默认 path,保证 metadata 稳定。
func NormalizeSnapshot(cookies []BrowserCookie) []BrowserCookie {
out := make([]BrowserCookie, 0, len(cookies))
for _, c := range cookies {
if c.Name == "" {
continue
}
if c.Path == "" {
c.Path = "/"
}
out = append(out, c)
}
sort.Slice(out, func(i, j int) bool {
if out[i].Domain != out[j].Domain {
return out[i].Domain < out[j].Domain
}
if out[i].Path != out[j].Path {
return out[i].Path < out[j].Path
}
return out[i].Name < out[j].Name
})
return out
}
// SnapshotFromMetadata 从 cookies.metadata_json 中读取浏览器 Cookie 快照。
func SnapshotFromMetadata(metadata string) []BrowserCookie {
var m map[string]json.RawMessage
if err := json.Unmarshal([]byte(strings.TrimSpace(metadata)), &m); err != nil {
return nil
}
var out []BrowserCookie
if raw := m[metadataSnapshotKey]; len(raw) > 0 {
_ = json.Unmarshal(raw, &out)
} else if raw := m[legacyMetadataSnapshot]; len(raw) > 0 {
_ = json.Unmarshal(raw, &out)
}
return NormalizeSnapshot(out)
}
// MetadataWithSnapshot 写入浏览器 Cookie 快照,保留 metadata 中的其他键。
func MetadataWithSnapshot(metadata string, cookies []BrowserCookie) string {
m := make(map[string]any)
if strings.TrimSpace(metadata) != "" {
_ = json.Unmarshal([]byte(metadata), &m)
}
delete(m, legacyMetadataSnapshot)
m[metadataSnapshotKey] = NormalizeSnapshot(cookies)
b, err := json.Marshal(m)
if err != nil {
return metadata
}
return string(b)
}
// MetadataWithoutSnapshot 清除浏览器 Cookie 快照。
func MetadataWithoutSnapshot(metadata string) string {
if strings.TrimSpace(metadata) == "" {
return ""
}
m := make(map[string]any)
if err := json.Unmarshal([]byte(metadata), &m); err != nil {
return metadata
}
delete(m, metadataSnapshotKey)
delete(m, legacyMetadataSnapshot)
b, err := json.Marshal(m)
if err != nil {
return metadata
}
return string(b)
}
@@ -0,0 +1,27 @@
package cookierefresh
import "testing"
func TestMetadataSnapshotKeyCompatibility(t *testing.T) {
oldMeta := `{"cookie_refresh_snapshot":[{"name":"a","value":"1","domain":".goofish.com","path":"/"}]}`
snapshot := SnapshotFromMetadata(oldMeta)
if len(snapshot) != 1 || snapshot[0].Name != "a" {
t.Fatalf("旧 key 快照读取失败: %+v", snapshot)
}
newMeta := MetadataWithSnapshot(oldMeta, []BrowserCookie{{Name: "b", Value: "2", Domain: ".taobao.com", Path: "/"}})
if SnapshotFromMetadata(newMeta)[0].Name != "b" {
t.Fatalf("新 key 快照写入失败: %s", newMeta)
}
if got := MetadataWithoutSnapshot(newMeta); len(SnapshotFromMetadata(got)) != 0 {
t.Fatalf("快照应被清除: %s", got)
}
}
func TestChangedSnapshotLabels(t *testing.T) {
before := []BrowserCookie{{Name: "a", Value: "1", Domain: ".goofish.com", Path: "/"}}
after := []BrowserCookie{{Name: "a", Value: "2", Domain: ".goofish.com", Path: "/"}}
got := ChangedSnapshotLabels(before, after)
if len(got) != 1 || got[0] != "a@.goofish.com/" {
t.Fatalf("ChangedSnapshotLabels=%v", got)
}
}
+3 -1
View File
@@ -14,6 +14,8 @@ import (
"xianyu-go/internal/xianyu/protocol"
)
const tokenRetryGap = 500 * time.Millisecond
// RefreshToken 调用 mtop.taobao.idlemessage.pc.login.token 获取 accessToken。
// 遇到 mtop 签名 token 过期时,仅在响应下发了新 Cookie 后低频重试一次。
func (c *ClientImpl) RefreshToken(cookiesStr string) (*RefreshResult, error) {
@@ -50,7 +52,7 @@ func (c *ClientImpl) RefreshTokenWithDeviceIDContext(ctx context.Context, cookie
return &RefreshResult{UpdatedCookies: updatedCookies}, fmt.Errorf("token API 登录凭证已失效: ret=%v (status=%d)", ret, status)
}
currentCookies = updatedCookies
if err := sleepCtx(ctx, MTopRetryGap); err != nil {
if err := sleepCtx(ctx, tokenRetryGap); err != nil {
return &RefreshResult{UpdatedCookies: currentCookies}, err
}
}
+147 -25
View File
@@ -7,9 +7,11 @@ package renew
import (
"context"
cryptorand "crypto/rand"
"encoding/json"
"fmt"
"io"
"math/big"
"net/http"
"net/url"
"sort"
@@ -17,7 +19,6 @@ import (
"strings"
"time"
"xianyu-go/internal/xianyu"
"xianyu-go/internal/xianyu/protocol"
)
@@ -27,6 +28,9 @@ const (
SetLoginSettingsURL = "https://passport.goofish.com/ac/account/setLoginSettings.do"
defaultRequestTimout = 20 * time.Second
maxRenewBodyBytes = 2 << 20
renewUA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36"
hasLoginSecChUA = `"Chromium";v="145", "Not:A-Brand";v="99"`
settingSecChUA = `"Google Chrome";v="146", "Not=A?Brand";v="8"`
)
// Service 是 Cookie 接口续期服务。零值可用;测试可覆盖 URL 和 HTTPClient。
@@ -35,6 +39,7 @@ type Service struct {
HasLoginURL string
SilentHasLoginURL string
SetLoginSettingsURL string
RetryDelay time.Duration
}
// Result 描述一次接口续期的完整结果。
@@ -45,6 +50,8 @@ type Result struct {
UpdatedCookieNames []string
StepDetails []StepResult
Message string
ResponseText string
NeedPasswordLogin bool
}
// StepResult 是单个续期接口的执行结果,便于上层记录日志和定位失败点。
@@ -62,9 +69,38 @@ type StepResult struct {
func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string) (*Result, error) {
cookiesStr = strings.TrimSpace(cookiesStr)
if cookiesStr == "" {
return &Result{RenewMethod: "none", Message: "Cookie为空,无法续期"}, nil
return &Result{RenewMethod: "none", Message: "Cookie为空,无法续期", NeedPasswordLogin: true}, nil
}
return s.renewOnce(ctx, cookiesStr)
res, err := s.renewOnce(ctx, cookiesStr)
if err != nil || res == nil || res.Success {
return res, err
}
if s.RetryDelay < 0 {
return res, nil
}
delay := s.RetryDelay
if delay == 0 {
delay = 2 * time.Second
}
if delay > 0 {
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
timer.Stop()
return res, ctx.Err()
case <-timer.C:
}
}
retry, err := s.renewOnce(ctx, res.NewCookies)
if err != nil {
return res, err
}
if retry == nil {
return res, nil
}
retry.StepDetails = append(res.StepDetails, retry.StepDetails...)
retry.UpdatedCookieNames = ChangedCookieNames(cookiesStr, retry.NewCookies)
return retry, nil
}
func (s Service) renewOnce(ctx context.Context, original string) (*Result, error) {
@@ -101,7 +137,10 @@ func (s Service) renewOnce(ctx context.Context, original string) (*Result, error
allSetCookies = append(allSetCookies, settings.SetCookies...)
}
newCookies := MergeSetCookies(original, allSetCookies)
newCookies := original
if len(allSetCookies) > 0 {
newCookies = MergeSetCookies(original, allSetCookies)
}
updated := ChangedCookieNames(original, newCookies)
success := len(settings.SetCookies) > 0
method := "none"
@@ -117,6 +156,8 @@ func (s Service) renewOnce(ctx context.Context, original string) (*Result, error
UpdatedCookieNames: updated,
StepDetails: steps,
Message: msg,
ResponseText: string(silent.Body),
NeedPasswordLogin: !success,
}, nil
}
@@ -149,14 +190,15 @@ func (s Service) callHasLogin(ctx context.Context, cookiesStr string) (callResul
form.Set("documentReferer", "https://www.goofish.com/")
form.Set("defaultView", "hasLogin")
form.Set("umidTag", "SERVER")
form.Set("pageTraceId", "21504"+strconv.FormatInt(time.Now().UnixMilli(), 10))
form.Set("returnUrl", "")
form.Set("deviceId", "")
form.Set("pageTraceId", "21504"+strconv.FormatInt(time.Now().UnixMilli(), 10)+randomDigits(6))
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.urlOrDefault(s.HasLoginURL, HasLoginURL), strings.NewReader(form.Encode()))
if err != nil {
return callResult{}, err
}
setPassportHeaders(req, cookiesStr)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
setHasLoginHeaders(req, cookiesStr, miniLoginReferer())
if xsrf := cookies["XSRF-TOKEN"]; xsrf != "" {
req.Header.Set("x-xsrf-token", xsrf)
}
@@ -179,21 +221,21 @@ func (s Service) callSilentHasLogin(ctx context.Context, cookiesStr string) (cal
q.Set("fromSite", "0")
q.Set("ltl", "true")
req.URL.RawQuery = q.Encode()
setPassportHeaders(req, cookiesStr)
setSilentHasLoginHeaders(req, cookiesStr)
return s.doRenewRequest(req, "silentHasLogin")
}
func (s Service) callSetLoginSettings(ctx context.Context, cookiesStr string) (callResult, error) {
form := url.Values{}
form.Set("appName", "xianyu")
form.Set("fromSite", "77")
form.Set("keepLogin", "true")
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.urlOrDefault(s.SetLoginSettingsURL, SetLoginSettingsURL), strings.NewReader(form.Encode()))
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.urlOrDefault(s.SetLoginSettingsURL, SetLoginSettingsURL), strings.NewReader("status=0"))
if err != nil {
return callResult{}, err
}
setPassportHeaders(req, cookiesStr)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
q := req.URL.Query()
q.Set("fromSite", "77")
q.Set("appName", "xianyu")
q.Set("bizEntrance", "web")
req.URL.RawQuery = q.Encode()
setLoginSettingsHeaders(req, cookiesStr)
return s.doRenewRequest(req, "setLoginSettings")
}
@@ -202,7 +244,11 @@ func (s Service) doRenewRequest(req *http.Request, name string) (callResult, err
if hc == nil {
hc = &http.Client{Timeout: defaultRequestTimout}
}
resp, err := hc.Do(req)
client := *hc
client.CheckRedirect = func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
}
resp, err := client.Do(req)
if err != nil {
return callResult{}, fmt.Errorf("%s 请求失败: %w", name, err)
}
@@ -211,7 +257,7 @@ func (s Service) doRenewRequest(req *http.Request, name string) (callResult, err
if err != nil {
return callResult{}, fmt.Errorf("%s 响应读取失败: %w", name, err)
}
setCookies := resp.Header.Values("Set-Cookie")
setCookies := filterValidSetCookies(resp.Header.Values("Set-Cookie"))
step := StepResult{
Name: name,
HTTPStatus: resp.StatusCode,
@@ -246,20 +292,54 @@ func renewBusinessOK(body []byte) bool {
return ok
}
func setPassportHeaders(req *http.Request, cookiesStr string) {
func setHasLoginHeaders(req *http.Request, cookiesStr, referer string) {
req.Header.Set("Accept", "application/json, text/plain, */*")
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
req.Header.Set("Cache-Control", "no-cache")
req.Header.Set("Pragma", "no-cache")
req.Header.Set("Origin", "https://passport.goofish.com")
req.Header.Set("Referer", "https://passport.goofish.com/")
req.Header.Set("User-Agent", xianyu.BrowserUA)
req.Header.Set("sec-ch-ua", xianyu.SecChUA)
req.Header.Set("Accept-Language", "zh-CN")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Referer", referer)
req.Header.Set("User-Agent", renewUA)
req.Header.Set("bx-v", "2.5.31")
req.Header.Set("sec-ch-ua", hasLoginSecChUA)
req.Header.Set("sec-ch-ua-mobile", "?0")
req.Header.Set("sec-ch-ua-platform", `"Windows"`)
req.Header.Set("Cookie", strings.ReplaceAll(strings.ReplaceAll(cookiesStr, "\n", ""), "\r", ""))
}
func setSilentHasLoginHeaders(req *http.Request, cookiesStr string) {
req.Header.Set("Accept", "*/*")
req.Header.Set("Accept-Language", "en,zh-CN;q=0.9,zh;q=0.8,ru;q=0.7")
req.Header.Set("Cache-Control", "no-cache")
req.Header.Set("Pragma", "no-cache")
req.Header.Set("Priority", "u=1, i")
req.Header.Set("Referer", "https://www.goofish.com/")
req.Header.Set("User-Agent", renewUA)
req.Header.Set("sec-ch-ua", `"Google Chrome";v="146", "Not=A?Brand";v="8", "Not/A)Brand";v="146"`)
req.Header.Set("sec-ch-ua-arch", `"x86"`)
req.Header.Set("sec-ch-ua-bitness", `"64"`)
req.Header.Set("sec-ch-ua-mobile", "?0")
req.Header.Set("sec-ch-ua-platform", `"Win32"`)
req.Header.Set("sec-ch-ua-platform-version", `"10.0.0"`)
req.Header.Set("sec-fetch-dest", "empty")
req.Header.Set("sec-fetch-mode", "cors")
req.Header.Set("sec-fetch-site", "same-site")
req.Header.Set("Cookie", strings.ReplaceAll(strings.ReplaceAll(cookiesStr, "\n", ""), "\r", ""))
}
func setLoginSettingsHeaders(req *http.Request, cookiesStr string) {
req.Header.Set("Accept", "application/json, text/plain, */*")
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Referer", "https://www.goofish.com/")
req.Header.Set("User-Agent", renewUA)
req.Header.Set("sec-ch-ua", settingSecChUA)
req.Header.Set("sec-ch-ua-mobile", "?0")
req.Header.Set("sec-ch-ua-platform", `"Windows"`)
req.Header.Set("sec-fetch-dest", "empty")
req.Header.Set("sec-fetch-mode", "cors")
req.Header.Set("sec-fetch-site", "same-site")
req.Header.Set("Cookie", strings.ReplaceAll(strings.ReplaceAll(cookiesStr, "\n", ""), "\r", ""))
}
func (s Service) urlOrDefault(v, fallback string) string {
if strings.TrimSpace(v) != "" {
return v
@@ -287,6 +367,48 @@ func firstNonEmpty(values ...string) string {
return ""
}
func miniLoginReferer() string {
return "https://passport.goofish.com/mini_login.htm?lang=zh_cn&appName=xianyu&appEntrance=web&styleType=vertical&bizParams=&notLoadSsoView=false&notKeepLogin=false&isMobile=false&qrCodeFirst=false&stie=77&rnd=" + randomFraction()
}
func randomDigits(n int) string {
if n <= 0 {
return ""
}
min := 1
for i := 1; i < n; i++ {
min *= 10
}
max := min * 9
v, err := cryptorand.Int(cryptorand.Reader, big.NewInt(int64(max)))
if err != nil {
return strings.Repeat("0", n)
}
return strconv.Itoa(min + int(v.Int64()))
}
func randomFraction() string {
v, err := cryptorand.Int(cryptorand.Reader, big.NewInt(1_000_000_000))
if err != nil {
return "0.0"
}
return "0." + fmt.Sprintf("%09d", v.Int64())
}
func filterValidSetCookies(setCookies []string) []string {
if len(setCookies) == 0 {
return nil
}
out := make([]string, 0, len(setCookies))
for _, sc := range setCookies {
if strings.Contains(sc, "Max-Age=0") || strings.Contains(sc, "1970") {
continue
}
out = append(out, sc)
}
return out
}
// MergeSetCookies 将 Set-Cookie 头合并到 Cookie 头字符串。只保留 name=value,
// 忽略 Path/Domain/Expires 等属性,因为后续出站请求只需要 Cookie header。
func MergeSetCookies(original string, setCookies []string) string {
+239
View File
@@ -3,10 +3,14 @@ package renew
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"strings"
"testing"
"time"
)
func TestMergeSetCookies(t *testing.T) {
@@ -35,6 +39,13 @@ func TestRenewAPIFirstSuccess(t *testing.T) {
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
case "/setLoginSettings.do":
// 只有这个接口返回 Set-Cookie 才代表长登录续期真正成功。
body, _ := io.ReadAll(r.Body)
if string(body) != "status=0" {
t.Fatalf("setLoginSettings body=%q, want status=0", string(body))
}
if r.URL.Query().Get("bizEntrance") != "web" {
t.Fatalf("setLoginSettings query=%s", r.URL.RawQuery)
}
http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "lgc"})
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
default:
@@ -48,6 +59,7 @@ func TestRenewAPIFirstSuccess(t *testing.T) {
HasLoginURL: srv.URL + "/hasLogin.do",
SilentHasLoginURL: srv.URL + "/silentHasLogin.do",
SetLoginSettingsURL: srv.URL + "/setLoginSettings.do",
RetryDelay: -1,
}
res, err := svc.RenewAPIFirst(context.Background(), "unb=1; cookie2=c2; _tb_token_=csrf")
if err != nil {
@@ -63,6 +75,171 @@ func TestRenewAPIFirstSuccess(t *testing.T) {
}
}
func TestRenewAPIFirstMatchesReferenceRequestShape(t *testing.T) {
var hasLoginBody string
var hasLoginReferer string
var hasLoginBXV string
var hasLoginHeaders http.Header
var silentHeaders http.Header
var silentQuery url.Values
var settingBody string
var settingHeaders http.Header
var settingQuery url.Values
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/hasLogin.do":
body, _ := io.ReadAll(r.Body)
hasLoginBody = string(body)
hasLoginReferer = r.Header.Get("Referer")
hasLoginBXV = r.Header.Get("bx-v")
hasLoginHeaders = r.Header.Clone()
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
case "/silentHasLogin.do":
silentHeaders = r.Header.Clone()
silentQuery = r.URL.Query()
_, _ = w.Write([]byte(`{"content":{"success":true},"marker":"silent"}`))
case "/setLoginSettings.do":
body, _ := io.ReadAll(r.Body)
settingBody = string(body)
settingHeaders = r.Header.Clone()
settingQuery = r.URL.Query()
http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "lgc"})
_, _ = w.Write([]byte(`{"content":{"success":true},"marker":"settings"}`))
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
svc := Service{
HTTPClient: srv.Client(),
HasLoginURL: srv.URL + "/hasLogin.do",
SilentHasLoginURL: srv.URL + "/silentHasLogin.do",
SetLoginSettingsURL: srv.URL + "/setLoginSettings.do",
RetryDelay: -1,
}
res, err := svc.RenewAPIFirst(context.Background(), "unb=1; cookie2=c2; _tb_token_=csrf; _uab_collina=umid; XSRF-TOKEN=xsrf")
if err != nil {
t.Fatalf("RenewAPIFirst: %v", err)
}
if !strings.Contains(res.ResponseText, `"marker":"silent"`) || strings.Contains(res.ResponseText, `"marker":"settings"`) {
t.Fatalf("ResponseText 应来自 silentHasLogin 响应,got %q", res.ResponseText)
}
values, err := url.ParseQuery(hasLoginBody)
if err != nil {
t.Fatalf("hasLogin body parse: %v", err)
}
for _, key := range []string{"hid", "ltl", "appName", "appEntrance", "_csrf_token", "umidToken", "hsiz", "bizParams", "mainPage", "isMobile", "lang", "returnUrl", "fromSite", "isIframe", "documentReferer", "defaultView", "umidTag", "deviceId", "pageTraceId"} {
if _, ok := values[key]; !ok {
t.Fatalf("hasLogin body missing %s: %s", key, hasLoginBody)
}
}
if !regexp.MustCompile(`^21504\d{19}$`).MatchString(values.Get("pageTraceId")) {
t.Fatalf("pageTraceId=%q", values.Get("pageTraceId"))
}
if !strings.Contains(hasLoginReferer, "mini_login.htm") || !strings.Contains(hasLoginReferer, "rnd=") {
t.Fatalf("hasLogin Referer=%q", hasLoginReferer)
}
if hasLoginBXV != "2.5.31" {
t.Fatalf("hasLogin bx-v=%q", hasLoginBXV)
}
if got := hasLoginHeaders.Get("Accept-Language"); got != "zh-CN" {
t.Fatalf("hasLogin Accept-Language=%q", got)
}
if got := hasLoginHeaders.Get("sec-ch-ua"); got != hasLoginSecChUA {
t.Fatalf("hasLogin sec-ch-ua=%q", got)
}
if got := hasLoginHeaders.Get("x-xsrf-token"); got != "xsrf" {
t.Fatalf("hasLogin x-xsrf-token=%q", got)
}
if silentQuery.Get("documentReferer") != "https://www.goofish.com/" ||
silentQuery.Get("appEntrance") != "xianyu_sdkSilent" ||
silentQuery.Get("fromSite") != "0" {
t.Fatalf("silentHasLogin query=%s", silentQuery.Encode())
}
if got := silentHeaders.Get("Accept"); got != "*/*" {
t.Fatalf("silentHasLogin Accept=%q", got)
}
if got := silentHeaders.Get("sec-ch-ua-platform"); got != `"Win32"` {
t.Fatalf("silentHasLogin sec-ch-ua-platform=%q", got)
}
if got := silentHeaders.Get("sec-fetch-site"); got != "same-site" {
t.Fatalf("silentHasLogin sec-fetch-site=%q", got)
}
if settingBody != "status=0" {
t.Fatalf("setLoginSettings body=%q", settingBody)
}
if settingQuery.Get("fromSite") != "77" || settingQuery.Get("appName") != "xianyu" || settingQuery.Get("bizEntrance") != "web" {
t.Fatalf("setLoginSettings query=%s", settingQuery.Encode())
}
if got := settingHeaders.Get("Content-Type"); got != "application/x-www-form-urlencoded" {
t.Fatalf("setLoginSettings Content-Type=%q", got)
}
if got := settingHeaders.Get("sec-ch-ua"); got != settingSecChUA {
t.Fatalf("setLoginSettings sec-ch-ua=%q", got)
}
for name, headers := range map[string]http.Header{
"hasLogin": hasLoginHeaders,
"silentHasLogin": silentHeaders,
"setLoginSettings": settingHeaders,
} {
if got := headers.Get("Origin"); got != "" {
t.Fatalf("%s Origin should be empty, got %q", name, got)
}
if got := headers.Get("Cookie"); strings.ContainsAny(got, "\r\n") {
t.Fatalf("%s Cookie 未清理换行: %q", name, got)
}
}
}
func TestRenewAPIFirstDoesNotFollowRedirects(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/hasLogin.do":
w.Header().Set("Location", "/unexpected")
w.WriteHeader(http.StatusFound)
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
case "/silentHasLogin.do":
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
case "/setLoginSettings.do":
http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "lgc"})
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
default:
t.Fatalf("request followed redirect to %s", r.URL.Path)
}
}))
defer srv.Close()
svc := Service{
HTTPClient: srv.Client(),
HasLoginURL: srv.URL + "/hasLogin.do",
SilentHasLoginURL: srv.URL + "/silentHasLogin.do",
SetLoginSettingsURL: srv.URL + "/setLoginSettings.do",
RetryDelay: -1,
}
res, err := svc.RenewAPIFirst(context.Background(), "unb=1; cookie2=c2")
if err != nil {
t.Fatalf("RenewAPIFirst: %v", err)
}
if !res.Success {
t.Fatalf("RenewAPIFirst should continue after 302 without redirect: %#v", res)
}
}
func TestMergeSetCookiesIgnoresDeletionCookies(t *testing.T) {
got := MergeSetCookies("old=a", filterValidSetCookies([]string{
"old=; Max-Age=0; Path=/",
"gone=x; Expires=Thu, 01 Jan 1970 00:00:00 GMT",
"new=b; Path=/",
}))
if strings.Contains(got, "gone=") || strings.Contains(got, "old=") && !strings.Contains(got, "old=a") {
t.Fatalf("deletion cookies should be ignored: %q", got)
}
if !strings.Contains(got, "old=a") || !strings.Contains(got, "new=b") {
t.Fatalf("valid cookies missing: %q", got)
}
}
func TestRenewAPIFirstKeepsPartialCookiesWhenLongLoginFails(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
@@ -85,6 +262,7 @@ func TestRenewAPIFirstKeepsPartialCookiesWhenLongLoginFails(t *testing.T) {
HasLoginURL: srv.URL + "/hasLogin.do",
SilentHasLoginURL: srv.URL + "/silentHasLogin.do",
SetLoginSettingsURL: srv.URL + "/setLoginSettings.do",
RetryDelay: -1,
}
res, err := svc.RenewAPIFirst(context.Background(), "unb=1; cookie2=c2")
if err != nil {
@@ -98,6 +276,32 @@ func TestRenewAPIFirstKeepsPartialCookiesWhenLongLoginFails(t *testing.T) {
}
}
func TestRenewAPIFirstKeepsOriginalStringWhenNoSetCookies(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
}))
defer srv.Close()
svc := Service{
HTTPClient: srv.Client(),
HasLoginURL: srv.URL + "/hasLogin.do",
SilentHasLoginURL: srv.URL + "/silentHasLogin.do",
SetLoginSettingsURL: srv.URL + "/setLoginSettings.do",
RetryDelay: -1,
}
original := "unb=1; cookie2=c2"
res, err := svc.RenewAPIFirst(context.Background(), original)
if err != nil {
t.Fatalf("RenewAPIFirst: %v", err)
}
if res.Success {
t.Fatalf("setLoginSettings 无 Set-Cookie 不应成功: %#v", res)
}
if res.NewCookies != original || len(res.UpdatedCookieNames) != 0 {
t.Fatalf("无 Set-Cookie 时不应重排/标记更新: %#v", res)
}
}
func TestRenewAPIFirstSkipsHasLoginWithoutUNB(t *testing.T) {
calls := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -111,6 +315,7 @@ func TestRenewAPIFirstSkipsHasLoginWithoutUNB(t *testing.T) {
HasLoginURL: srv.URL + "/hasLogin.do",
SilentHasLoginURL: srv.URL + "/silentHasLogin.do",
SetLoginSettingsURL: srv.URL + "/setLoginSettings.do",
RetryDelay: -1,
}
_, err := svc.RenewAPIFirst(context.Background(), "cookie2=c2")
if err != nil {
@@ -120,3 +325,37 @@ func TestRenewAPIFirstSkipsHasLoginWithoutUNB(t *testing.T) {
t.Fatalf("缺少 unb 时 hasLogin 应跳过,只调用后两步,calls=%d", calls)
}
}
func TestRenewAPIFirstRetriesLongLoginOnce(t *testing.T) {
setCalls := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/hasLogin.do", "/silentHasLogin.do":
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
case "/setLoginSettings.do":
setCalls++
if setCalls == 2 {
http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "lgc"})
}
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
svc := Service{
HTTPClient: srv.Client(),
HasLoginURL: srv.URL + "/hasLogin.do",
SilentHasLoginURL: srv.URL + "/silentHasLogin.do",
SetLoginSettingsURL: srv.URL + "/setLoginSettings.do",
RetryDelay: time.Nanosecond,
}
res, err := svc.RenewAPIFirst(context.Background(), "unb=1; cookie2=c2")
if err != nil {
t.Fatalf("RenewAPIFirst: %v", err)
}
if !res.Success || setCalls != 2 || !strings.Contains(res.NewCookies, "havana_lgc2_77=lgc") {
t.Fatalf("retry result=%#v setCalls=%d", res, setCalls)
}
}