diff --git a/changelog/unreleased/minimaxcode-provider.md b/changelog/unreleased/minimaxcode-provider.md new file mode 100644 index 00000000..1dccec3c --- /dev/null +++ b/changelog/unreleased/minimaxcode-provider.md @@ -0,0 +1,7 @@ +### English + +- Added a MiniMax Code provider (`minimaxcode/`) with official OAuth device-code sign-in (PKCE S256), CN and global regions, the 10-style work-mode model catalog with a static fallback, streaming/non-streaming chat through the Anthropic Messages gateway, tool calling, and status-only quota display. Route with the `minimaxcode/` model prefix. + +### 中文 + +- 新增 MiniMax Code 供应商(`minimaxcode/`):使用官方 OAuth 设备码登录(PKCE S256),支持国内/国际站点、工作模式模型目录(含静态兜底)、通过 Anthropic Messages 网关的流式/非流式对话、工具调用和状态额度展示,可用 `minimaxcode/` 模型前缀指定路由。 diff --git a/frontend/src/assets/minimaxcode-mark.png b/frontend/src/assets/minimaxcode-mark.png new file mode 100644 index 00000000..5182ff87 Binary files /dev/null and b/frontend/src/assets/minimaxcode-mark.png differ diff --git a/frontend/src/components/AddAccountModal.tsx b/frontend/src/components/AddAccountModal.tsx index ef9bef77..9ecc1c30 100644 --- a/frontend/src/components/AddAccountModal.tsx +++ b/frontend/src/components/AddAccountModal.tsx @@ -73,6 +73,8 @@ const labelKeys: Record = { 'kiro-us-east-1': 'accountTypeKiroUS', 'kiro-eu-central-1': 'accountTypeKiroEU', 'meta-global': 'accountTypeMetaGlobal', + 'minimaxcode-cn': 'accountTypeMiniMaxCodeCN', + 'minimaxcode-global': 'accountTypeMiniMaxCodeGlobal', } const hintKeys: Record = { @@ -93,6 +95,8 @@ const hintKeys: Record = { 'kiro-us-east-1': 'accountTypeKiroUSHint', 'kiro-eu-central-1': 'accountTypeKiroEUHint', 'meta-global': 'accountTypeMetaGlobalHint', + 'minimaxcode-cn': 'accountTypeMiniMaxCodeCNHint', + 'minimaxcode-global': 'accountTypeMiniMaxCodeGlobalHint', } async function loadProviderOptions(): Promise { diff --git a/frontend/src/components/MiniMaxCodeMark.tsx b/frontend/src/components/MiniMaxCodeMark.tsx new file mode 100644 index 00000000..fc4b39e2 --- /dev/null +++ b/frontend/src/components/MiniMaxCodeMark.tsx @@ -0,0 +1,20 @@ +import miniMaxCodeMark from '@/assets/minimaxcode-mark.png' + +type Props = { + size?: number + className?: string +} + +// MiniMax Code brand mark. +export function MiniMaxCodeMark({ size = 16, className = '' }: Props) { + return ( + + ) +} diff --git a/frontend/src/components/ProviderMark.tsx b/frontend/src/components/ProviderMark.tsx index f5d308ef..a1c331bd 100644 --- a/frontend/src/components/ProviderMark.tsx +++ b/frontend/src/components/ProviderMark.tsx @@ -5,6 +5,7 @@ import { DevinMark } from '@/components/DevinMark' import { DoubaoworkMark } from '@/components/DoubaoworkMark' import { KiroMark } from '@/components/KiroMark' import { KimiMark } from '@/components/KimiMark' +import { MiniMaxCodeMark } from '@/components/MiniMaxCodeMark' import { MuseMark } from '@/components/MuseMark' import { QoderMark } from '@/components/QoderMark' import { QwenworkMark } from '@/components/QwenworkMark' @@ -57,5 +58,8 @@ export function ProviderMark({ provider, size = 16, className = '' }: Props) { if (id === 'doubaowork') { return } + if (id === 'minimaxcode') { + return + } return } diff --git a/frontend/src/i18n/messages.ts b/frontend/src/i18n/messages.ts index b77b01d3..0ab9dce2 100644 --- a/frontend/src/i18n/messages.ts +++ b/frontend/src/i18n/messages.ts @@ -833,6 +833,10 @@ export const messages: Record = { accountTypeKiroEUHint: 'Personal Kiro login for the eu-central-1 runtime. Same credential shapes as US East. Experimental.', accountTypeMetaGlobal: 'Muse (Meta)', accountTypeMetaGlobalHint: 'Meta Muse Code subscription via device-code sign-in against auth.meta.com. After approval the console mints an LLM API key at api.meta.ai. You can also paste a Meta Model API key on the PAT tab.', + accountTypeMiniMaxCodeCN: 'MiniMax Code (CN)', + accountTypeMiniMaxCodeCNHint: 'MiniMax Code subscription via its official device-code sign-in. Routes through the CN agent gateway and consumes your MiniMax Code credits.', + accountTypeMiniMaxCodeGlobal: 'MiniMax Code (Global)', + accountTypeMiniMaxCodeGlobalHint: 'MiniMax Code subscription via its official device-code sign-in. Routes through the global agent gateway and consumes your MiniMax Code credits.', providerGroupSubscriptions: 'Subscriptions', providerGroupSubscriptionsHint: 'stable account logins', providerGroupExperimental: 'Experimental', @@ -1837,6 +1841,10 @@ export const messages: Record = { accountTypeKiroEUHint: '个人 Kiro 登录,走 eu-central-1 运行时。凭证格式与美东相同。实验性接入。', accountTypeMetaGlobal: 'Muse (Meta)', accountTypeMetaGlobalHint: 'Meta Muse Code 订阅,走 auth.meta.com 的设备码授权;批准后控制台会在 api.meta.ai 兑换 LLM API Key。也可在 PAT 页粘贴 Meta Model API Key。', + accountTypeMiniMaxCodeCN: 'MiniMax Code(国内)', + accountTypeMiniMaxCodeCNHint: '通过 MiniMax Code 官方设备码登录,走国内 agent 网关,消耗你的 MiniMax Code 额度。', + accountTypeMiniMaxCodeGlobal: 'MiniMax Code(国际)', + accountTypeMiniMaxCodeGlobalHint: '通过 MiniMax Code 官方设备码登录,走国际 agent 网关,消耗你的 MiniMax Code 额度。', providerGroupSubscriptions: '稳定订阅', providerGroupSubscriptionsHint: '稳定的账号登录源', providerGroupExperimental: '实验性', diff --git a/frontend/src/lib/provider.ts b/frontend/src/lib/provider.ts index b8d928e2..2f120258 100644 --- a/frontend/src/lib/provider.ts +++ b/frontend/src/lib/provider.ts @@ -39,6 +39,10 @@ export function isDoubaoworkProvider(provider?: string) { return String(provider || '').toLowerCase() === 'doubaowork' } +export function isMiniMaxCodeProvider(provider?: string) { + return String(provider || '').toLowerCase() === 'minimaxcode' +} + export function isMetaProvider(provider?: string) { const value = String(provider || '').toLowerCase() return value === 'meta' || value === 'muse' @@ -58,6 +62,7 @@ export function accountProviderFamilyLabel( if (isKimiProvider(providerID)) return 'Kimi Code' if (isCodeArtsProvider(providerID)) return 'CodeArts' if (isDoubaoworkProvider(providerID)) return 'Doubao Work' + if (isMiniMaxCodeProvider(providerID)) return 'MiniMax Code' if (isMetaProvider(providerID)) return 'Muse (Meta)' if (isQoderProvider(providerID)) return 'Qoder' return provider || t('account') @@ -97,6 +102,9 @@ export function accountProviderLabel( if (isDoubaoworkProvider(providerID)) { return t('accountTypeDoubaoworkCN') } + if (isMiniMaxCodeProvider(providerID)) { + return regionID === 'global' ? t('accountTypeMiniMaxCodeGlobal') : t('accountTypeMiniMaxCodeCN') + } if (isMetaProvider(providerID)) { return t('accountTypeMetaGlobal') } diff --git a/internal/accounts/policy.go b/internal/accounts/policy.go index b9d3264b..70359145 100644 --- a/internal/accounts/policy.go +++ b/internal/accounts/policy.go @@ -57,7 +57,7 @@ func DefaultDropSystemPrompt(provider string, value *bool) bool { return *value } switch strings.ToLower(strings.TrimSpace(provider)) { - case "trae", "kimi", "codearts": + case "trae", "kimi", "codearts", "minimaxcode": return false default: return true diff --git a/internal/app/app.go b/internal/app/app.go index 272678ea..2eff8bd2 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -30,6 +30,7 @@ import ( "github.com/caigee-cmd/cli2api/internal/providers/kimi" "github.com/caigee-cmd/cli2api/internal/providers/kiro" "github.com/caigee-cmd/cli2api/internal/providers/meta" + "github.com/caigee-cmd/cli2api/internal/providers/minimaxcode" "github.com/caigee-cmd/cli2api/internal/providers/qoder" "github.com/caigee-cmd/cli2api/internal/providers/qwenwork" "github.com/caigee-cmd/cli2api/internal/providers/trae" @@ -128,6 +129,7 @@ func New(cfg config.Config) *App { providerReg.Register(zhipu.NewClient(store).Adapter()) providerReg.Register(qwenwork.NewClient(store).Adapter()) providerReg.Register(kimi.NewClient(store).Adapter()) + providerReg.Register(minimaxcode.NewClient(store).Adapter()) providerReg.Register(codearts.NewClient(store).Adapter()) providerReg.Register(kiro.NewClient(store).Adapter()) providerReg.Register(meta.NewClient(store).Adapter()) diff --git a/internal/console/models.go b/internal/console/models.go index e10b7c5f..03364198 100644 --- a/internal/console/models.go +++ b/internal/console/models.go @@ -13,7 +13,7 @@ import ( func splitModelSettingPath(raw, queryProvider string) (provider, modelKey string) { raw = strings.TrimPrefix(raw, "/api/models/") provider = strings.ToLower(strings.TrimSpace(queryProvider)) - for _, prefix := range []string{"trae/", "workbuddy/", "qoder/", "devin/", "command/", "codex/", "zhipu/", "qwenwork/", "kimi/", "codearts/", "kiro/"} { + for _, prefix := range []string{"trae/", "workbuddy/", "qoder/", "devin/", "command/", "codex/", "zhipu/", "qwenwork/", "kimi/", "codearts/", "kiro/", "minimaxcode/"} { if strings.HasPrefix(strings.ToLower(raw), prefix) { provider = strings.TrimSuffix(prefix, "/") raw = raw[len(prefix):] diff --git a/internal/executor/prepare.go b/internal/executor/prepare.go index 908babaa..568d9501 100644 --- a/internal/executor/prepare.go +++ b/internal/executor/prepare.go @@ -200,7 +200,7 @@ func (e ChatExecutor) Prepare(in PrepareInput) (PreparedRequest, error) { // "/" model id. Command Code's own model ids are org-namespaced // ("deepseek/…", "moonshotai/…"), so its provider prefix sits in front of an // already-namespaced id ("command/deepseek/…"). -var providerPrefixes = []string{"qoder/", "workbuddy/", "trae/", "devin/", "command/", "codex/", "zhipu/", "qwenwork/", "kimi/", "codearts/", "kiro/", "doubaowork/"} +var providerPrefixes = []string{"qoder/", "workbuddy/", "trae/", "devin/", "command/", "codex/", "zhipu/", "qwenwork/", "kimi/", "codearts/", "kiro/", "doubaowork/", "minimaxcode/"} // regionDashSuffixes are the region qualifiers that may be appended to a // provider prefix with a dash: "workbuddy-cn/", "workbuddy-gl/", diff --git a/internal/providers/minimaxcode/catalog.go b/internal/providers/minimaxcode/catalog.go new file mode 100644 index 00000000..7163c02a --- /dev/null +++ b/internal/providers/minimaxcode/catalog.go @@ -0,0 +1,135 @@ +package minimaxcode + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "time" + + "github.com/caigee-cmd/cli2api/internal/providers" +) + +func (c *Client) Models(ctx context.Context, accountID string) ([]providers.ModelInfo, error) { + c.mu.Lock() + cached, ok := c.catalogs[accountID] + c.mu.Unlock() + if ok && c.now().Sub(cached.at) < catalogTTL && len(cached.models) > 0 { + return cached.models, nil + } + models, err := c.fetchCatalogModels(ctx, accountID) + if err != nil || len(models) == 0 { + models = staticModels() + err = nil + } + c.mu.Lock() + c.catalogs[accountID] = catalogCache{models: models, at: c.now()} + c.mu.Unlock() + return models, err +} + +func (c *Client) fetchCatalogModels(ctx context.Context, accountID string) ([]providers.ModelInfo, error) { + credential, err := c.credential(ctx, accountID) + if err != nil { + return nil, err + } + endpoint := credential.agentBase() + modelsPath + "?region=" + urlQueryEscape(credential.region()) + "&buildEnv=prod" + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, err + } + req.Header.Set("Authorization", "Bearer "+credential.AccessToken) + req.Header.Set("User-Agent", UserAgent) + req.Header.Set("X-Mavis-Agent-Id", AgentID) + req.Header.Set("Accept", "application/json") + client, err := c.httpClient(ctx, accountID) + if err != nil { + return nil, err + } + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode >= 300 { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + return nil, fmt.Errorf("minimaxcode model catalog failed (HTTP %d): %s", resp.StatusCode, truncate(string(body), 200)) + } + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 2<<20)) + return parseModels(raw) +} + +func parseModels(raw []byte) ([]providers.ModelInfo, error) { + var payload map[string]any + if json.Unmarshal(raw, &payload) != nil { + return nil, fmt.Errorf("minimaxcode model catalog is not valid json") + } + var entries []any + if providersList, ok := payload["providers"].([]any); ok { + for _, rawProvider := range providersList { + provider, _ := rawProvider.(map[string]any) + config, _ := provider["config"].(map[string]any) + if models, ok := config["models"].([]any); ok { + entries = append(entries, models...) + } + } + } + if len(entries) == 0 { + if models, ok := payload["models"].([]any); ok { + entries = models + } + } + if len(entries) == 0 { + if data, ok := payload["data"].([]any); ok { + entries = data + } + } + models := make([]providers.ModelInfo, 0, len(entries)) + for _, rawModel := range entries { + model, ok := rawModel.(map[string]any) + if !ok { + continue + } + id := first(jsonStr(model, "model"), jsonStr(model, "id"), jsonStr(model, "model_name"), jsonStr(model, "name")) + if id == "" { + continue + } + name := first(jsonStr(model, "display_name"), jsonStr(model, "name"), id) + models = append(models, providers.ModelInfo{NativeModel: id, PublicModel: id, DisplayName: name, Capabilities: providers.ModelCapabilities{Tools: true}}) + } + return models, nil +} + +func staticModels() []providers.ModelInfo { + models := make([]providers.ModelInfo, 0, len(knownModels)) + for _, id := range knownModels { + models = append(models, providers.ModelInfo{NativeModel: id, PublicModel: id, DisplayName: id, Capabilities: providers.ModelCapabilities{Tools: true}}) + } + return models +} + +func normalizedModelKey(snapshot []providers.ModelInfo, requested string) (string, bool) { + want := strings.ToLower(strings.TrimPrefix(strings.TrimSpace(requested), ProviderID+"/")) + if want == "" { + return "", false + } + for _, info := range snapshot { + if strings.ToLower(info.NativeModel) == want || strings.ToLower(info.PublicModel) == want { + return info.NativeModel, true + } + } + return "", false +} + +func jsonStr(payload map[string]any, key string) string { + value, _ := payload[key].(string) + return strings.TrimSpace(value) +} + +func urlQueryEscape(value string) string { + return strings.ReplaceAll(strings.ReplaceAll(value, " ", "%20"), "/", "%2F") +} + +var _ = time.Second diff --git a/internal/providers/minimaxcode/chat.go b/internal/providers/minimaxcode/chat.go new file mode 100644 index 00000000..fd5b2661 --- /dev/null +++ b/internal/providers/minimaxcode/chat.go @@ -0,0 +1,271 @@ +package minimaxcode + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/providers" + "github.com/caigee-cmd/cli2api/internal/translate" +) + +func (c *Client) ChatStream(ctx context.Context, accountID string, req translate.ChatRequest) (*http.Response, providers.ResolvedChat, error) { + upstream, err := c.doChat(ctx, accountID, req, true) + if err != nil { + return nil, providers.ResolvedChat{}, err + } + pr, pw := io.Pipe() + go func() { + defer upstream.Body.Close() + defer pw.Close() + if err := relayStream(pw, upstream.Body, req.Model); err != nil { + _ = pw.CloseWithError(err) + } + }() + return &http.Response{ + StatusCode: http.StatusOK, + Status: "200 OK", + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "Cache-Control": []string{"no-cache"}}, + Body: pr, + Request: upstream.Request, + }, providers.ResolvedChat{}, nil +} + +func (c *Client) ChatNonStream(ctx context.Context, accountID string, req translate.ChatRequest) (providers.ChatOutcome, error) { + upstream, err := c.doChat(ctx, accountID, req, false) + if err != nil { + return providers.ChatOutcome{}, err + } + defer upstream.Body.Close() + raw, err := io.ReadAll(io.LimitReader(upstream.Body, 8<<20)) + if err != nil { + return providers.ChatOutcome{}, err + } + outcome, err := parseNonStream(raw, req.Model) + if err != nil { + return providers.ChatOutcome{}, err + } + outcome.UsageSource = "upstream" + return outcome, nil +} + +func (c *Client) doChat(ctx context.Context, accountID string, req translate.ChatRequest, stream bool) (*http.Response, error) { + credential, err := c.credential(ctx, accountID) + if err != nil { + return nil, err + } + models, err := c.Models(ctx, accountID) + if err != nil { + return nil, err + } + model, found := normalizedModelKey(models, req.Model) + if !found { + return nil, &providers.Error{ + Kind: accounts.KindModelNotAvailable, + Status: http.StatusNotFound, + Message: fmt.Sprintf("minimaxcode model %q is not available", req.Model), + } + } + copyReq := req + copyReq.Stream = stream + body, err := buildChatBody(copyReq, model) + if err != nil { + return nil, err + } + raw, _ := json.Marshal(body) + endpoint := credential.agentBase() + messagesPath + makeRequest := func(token string) (*http.Request, error) { + reqHTTP, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(raw)) + if err != nil { + return nil, err + } + reqHTTP.Header.Set("Content-Type", "application/json") + reqHTTP.Header.Set("Accept", "application/json, text/event-stream") + reqHTTP.Header.Set("Authorization", "Bearer "+token) + reqHTTP.Header.Set("X-Api-Key", "sk-xxx") + reqHTTP.Header.Set("Anthropic-Version", AnthropicVersion) + reqHTTP.Header.Set("User-Agent", UserAgent) + reqHTTP.Header.Set("X-Mavis-Agent-Id", AgentID) + _, zoneOffset := time.Now().Zone() + reqHTTP.Header.Set("X-Mavis-Timezone-Offset", fmt.Sprintf("%d", -zoneOffset)) + reqHTTP.Header.Set("X-Mavis-Session-Id", randomUUID()) + return reqHTTP, nil + } + client, err := c.httpClient(ctx, accountID) + if err != nil { + return nil, err + } + httpReq, err := makeRequest(credential.AccessToken) + if err != nil { + return nil, err + } + resp, err := client.Do(httpReq) + if err != nil { + return nil, &providers.Error{Kind: accounts.KindUnavailable, Status: http.StatusBadGateway, Message: err.Error()} + } + if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden { + payload, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + resp.Body.Close() + refreshed, refreshErr := c.forceRefresh(ctx, accountID) + if refreshErr != nil { + return nil, refreshErr + } + httpReq, err = makeRequest(refreshed.AccessToken) + if err != nil { + return nil, err + } + resp, err = client.Do(httpReq) + if err != nil { + return nil, &providers.Error{Kind: accounts.KindUnavailable, Status: http.StatusBadGateway, Message: err.Error()} + } + _ = payload + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + payload, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + resp.Body.Close() + return nil, newProviderError(resp.StatusCode, string(payload)) + } + return resp, nil +} + +func relayStream(dst io.Writer, src io.Reader, model string) error { + decoder := newAnthropicDecoder() + id := "chatcmpl-" + randomHex(12) + created := time.Now().Unix() + emit := func(delta map[string]any, finish any) error { + choice := map[string]any{"index": 0, "delta": delta} + if finish != nil && finish != "" { + choice["finish_reason"] = finish + } + chunk := map[string]any{"id": id, "object": "chat.completion.chunk", "created": created, "model": model, "choices": []any{choice}} + raw, _ := json.Marshal(chunk) + _, err := fmt.Fprintf(dst, "data: %s\n\n", raw) + return err + } + finish := "" + err := readAnthropicSSE(src, func(eventType, data string) (bool, error) { + deltas, done, err := decoder.frame(eventType, data) + if err != nil { + return false, err + } + for _, delta := range deltas { + out := map[string]any{} + if delta.Content != "" { + out["content"] = delta.Content + } else if len(delta.ToolCalls) == 0 { + out["role"] = "assistant" + } + if len(delta.ToolCalls) > 0 { + calls := make([]any, 0, len(delta.ToolCalls)) + for _, call := range delta.ToolCalls { + function := map[string]any{} + if call.HasName { + function["name"] = call.Name + } + if call.Arguments != "" { + function["arguments"] = call.Arguments + } + entry := map[string]any{"index": call.Index, "type": "function", "function": function} + if call.HasID { + entry["id"] = call.ID + } + calls = append(calls, entry) + } + out["tool_calls"] = calls + } + if len(out) > 0 { + if err := emit(out, nil); err != nil { + return false, err + } + } + } + if done { + finish = decoder.finish + if finish == "" { + finish = "stop" + } + return true, nil + } + return false, nil + }) + if err != nil && err != io.EOF { + return err + } + if finish == "" { + finish = "stop" + } + if err := emit(map[string]any{}, finish); err != nil { + return err + } + _, err = io.WriteString(dst, "data: [DONE]\n\n") + return err +} + +func parseNonStream(raw []byte, model string) (providers.ChatOutcome, error) { + var payload struct { + ID string `json:"id"` + Model string `json:"model"` + StopReason string `json:"stop_reason"` + Content []struct { + Type string `json:"type"` + Text string `json:"text"` + ID string `json:"id"` + Name string `json:"name"` + Input json.RawMessage `json:"input"` + } `json:"content"` + Usage struct { + InputTokens int `json:"input_tokens"` + OutputTokens int `json:"output_tokens"` + } `json:"usage"` + } + if err := json.Unmarshal(raw, &payload); err != nil { + return providers.ChatOutcome{}, err + } + outcome := providers.ChatOutcome{Model: first(model, payload.Model), FinishReason: stopReason(payload.StopReason)} + var toolCalls []map[string]any + for _, block := range payload.Content { + switch block.Type { + case "text": + outcome.Content += block.Text + case "tool_use": + arguments := string(block.Input) + if arguments == "" { + arguments = "{}" + } + toolCalls = append(toolCalls, map[string]any{ + "id": block.ID, "type": "function", + "function": map[string]any{"name": block.Name, "arguments": arguments}, + }) + } + } + if len(toolCalls) > 0 { + encoded, _ := json.Marshal(toolCalls) + outcome.ToolCalls = encoded + outcome.FinishReason = "tool_calls" + } + outcome.PromptTokens = payload.Usage.InputTokens + outcome.CompletionTokens = payload.Usage.OutputTokens + return outcome, nil +} + +func randomUUID() string { + buf := make([]byte, 16) + _, _ = rand.Read(buf) + return fmt.Sprintf("%x-%x-%x-%x-%x", buf[:4], buf[4:6], buf[6:8], buf[8:10], buf[10:]) +} + +func randomHex(size int) string { + buf := make([]byte, size) + _, _ = rand.Read(buf) + return hex.EncodeToString(buf) +} + +var _ = strings.TrimSpace diff --git a/internal/providers/minimaxcode/client.go b/internal/providers/minimaxcode/client.go new file mode 100644 index 00000000..1c97dacb --- /dev/null +++ b/internal/providers/minimaxcode/client.go @@ -0,0 +1,270 @@ +package minimaxcode + +import ( + "context" + "fmt" + "net/http" + "strings" + "sync" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/providers" + proxyutil "github.com/caigee-cmd/cli2api/internal/proxy" +) + +// Store is the persistence surface this adapter needs. It never imports +// internal/store. +type Store interface { + Get(ctx context.Context, id string) (accounts.Account, error) + LoadCredentialPayload(ctx context.Context, accountID string) (string, []byte, error) + SaveCredentialPayload(ctx context.Context, accountID, format string, payload []byte) error + Observe(ctx context.Context, id, remoteUID, status, lastError, lastKind string) error +} + +type SecretReader interface { + GetSecret(context.Context, string) (string, bool, error) +} + +type ModelSettingReader interface { + GetProviderModelSetting(context.Context, string, string) (accounts.ProviderModelSetting, error) +} + +type catalogCache struct { + models []providers.ModelInfo + at time.Time +} + +type loginState struct { + site string + accountBase string + agentBase string + userCode string + deviceCode string + verifier string + verifyURL string + interval time.Duration + expiresAt time.Time + lastPolled time.Time + lastMessage string + pollByUser bool +} + +type Client struct { + store Store + http *http.Client + + transports proxyutil.TransportCache + nowFn func() time.Time + + mu sync.Mutex + catalogs map[string]catalogCache + locks map[string]*sync.Mutex + logins map[string]*loginState +} + +func NewClient(store Store) *Client { + return &Client{ + store: store, + http: &http.Client{ + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + }, + catalogs: map[string]catalogCache{}, + locks: map[string]*sync.Mutex{}, + logins: map[string]*loginState{}, + nowFn: time.Now, + } +} + +func (c *Client) now() time.Time { + if c.nowFn != nil { + return c.nowFn() + } + return time.Now() +} + +func (c *Client) globalProxy(ctx context.Context) (string, error) { + reader, ok := c.store.(SecretReader) + if !ok { + return "", nil + } + value, found, err := reader.GetSecret(ctx, "proxy_url") + if err != nil || !found { + return "", err + } + return strings.TrimSpace(value), nil +} + +func (c *Client) effectiveProxy(ctx context.Context, accountID string) (string, error) { + if strings.TrimSpace(accountID) == "" { + return c.globalProxy(ctx) + } + account, err := c.store.Get(ctx, accountID) + if err != nil { + return "", err + } + if value := strings.TrimSpace(account.ProxyURL); value != "" { + return value, nil + } + return c.globalProxy(ctx) +} + +func (c *Client) httpClient(ctx context.Context, accountID string) (*http.Client, error) { + rawProxy, err := c.effectiveProxy(ctx, accountID) + if err != nil { + return nil, err + } + client := *c.http + transport, err := c.transports.Get(rawProxy) + if err != nil { + return nil, err + } + if transport != nil { + client.Transport = transport + } + return &client, nil +} + +func (c *Client) accountLock(accountID string) *sync.Mutex { + c.mu.Lock() + defer c.mu.Unlock() + if c.locks == nil { + c.locks = map[string]*sync.Mutex{} + } + lock, ok := c.locks[accountID] + if !ok { + lock = &sync.Mutex{} + c.locks[accountID] = lock + } + return lock +} + +func (c *Client) loadCredential(ctx context.Context, accountID string) (Credential, error) { + _, payload, err := c.store.LoadCredentialPayload(ctx, accountID) + if err != nil { + return Credential{}, err + } + credential, err := DecodeCredential(payload) + if err != nil { + return Credential{}, err + } + if !credential.Ready() { + return credential, &providers.Error{ + Kind: accounts.KindAuth, + Status: http.StatusUnauthorized, + Message: "minimaxcode account has no access token; sign in again", + } + } + return credential, nil +} + +func (c *Client) saveCredential(ctx context.Context, accountID string, credential Credential) error { + encoded, err := credential.Encode() + if err != nil { + return err + } + return c.store.SaveCredentialPayload(ctx, accountID, CredentialFormat, encoded) +} + +// credential returns a credential whose access token is usable now. Refresh +// tokens are single-use, so refresh is serialized and persisted immediately. +func (c *Client) credential(ctx context.Context, accountID string) (Credential, error) { + credential, err := c.loadCredential(ctx, accountID) + if err != nil { + return Credential{}, err + } + if !credential.NeedsRefresh(c.now()) { + return credential, nil + } + lock := c.accountLock(accountID) + lock.Lock() + defer lock.Unlock() + current, err := c.loadCredential(ctx, accountID) + if err != nil { + return Credential{}, err + } + if !current.NeedsRefresh(c.now()) { + return current, nil + } + refreshed, err := c.refreshToken(ctx, current) + if err != nil { + return Credential{}, err + } + next := applyToken(current, refreshed, c.now()) + // A failed write must surface: another process would still hold a stale + // single-use token. + if err := c.saveCredential(ctx, accountID, next); err != nil { + return Credential{}, err + } + return next, nil +} + +// forceRefresh is used on a 401 retry. It ignores the expiry heuristic. +func (c *Client) forceRefresh(ctx context.Context, accountID string) (Credential, error) { + lock := c.accountLock(accountID) + lock.Lock() + defer lock.Unlock() + current, err := c.loadCredential(ctx, accountID) + if err != nil { + return Credential{}, err + } + refreshed, err := c.refreshToken(ctx, current) + if err != nil { + return Credential{}, err + } + next := applyToken(current, refreshed, c.now()) + if err := c.saveCredential(ctx, accountID, next); err != nil { + return Credential{}, err + } + return next, nil +} + +// Probe exercises the model catalog with the live bearer token. +func (c *Client) Probe(ctx context.Context, accountID string) (providers.AccountHealth, error) { + if _, err := c.fetchCatalogModels(ctx, accountID); err != nil { + return providers.AccountHealth{LastError: err.Error()}, nil + } + credential, err := c.loadCredential(ctx, accountID) + if err != nil { + return providers.AccountHealth{LastError: err.Error()}, nil + } + _ = c.store.Observe(ctx, accountID, credential.UserID, "ready", "", "") + return providers.AccountHealth{Ready: true, Hot: true, UID: credential.UserID}, nil +} + +func (c *Client) storedReasoning(ctx context.Context, model string) string { + reader, ok := c.store.(ModelSettingReader) + if !ok { + return "" + } + stored, err := reader.GetProviderModelSetting(ctx, ProviderID, accounts.CanonicalModelID(model)) + if err != nil { + return "" + } + return strings.TrimSpace(stored.ReasoningEffort) +} + +func (c *Client) Adapter() providers.Adapter { + return providers.Adapter{ + ID: ProviderID, + Credential: credentialCodec{}, + Login: c, + Chat: c, + Models: c, + Classifier: classifier{}, + ImportExport: importer{}, + Prober: c, + } +} + +type credentialCodec struct{} + +func (credentialCodec) Validate(payload []byte) error { return ValidateCredential(payload) } + +type classifier struct{} + +func (classifier) Classify(status int, body string) providers.ClassifiedError { + return Classify(status, body) +} + +var _ = fmt.Sprintf diff --git a/internal/providers/minimaxcode/constants.go b/internal/providers/minimaxcode/constants.go new file mode 100644 index 00000000..917a5717 --- /dev/null +++ b/internal/providers/minimaxcode/constants.go @@ -0,0 +1,63 @@ +// Package minimaxcode implements an in-process adapter for the MiniMax Code +// subscription product (agent.minimax.cn / agent.minimax.io). It is distinct +// from the MiniMax Open Platform API-key gateway. Authentication uses the +// official OAuth 2.0 device flow (public client mcode-public, PKCE S256) and +// chat uses the Anthropic Messages API the Code CLI talks to. +package minimaxcode + +import "time" + +const ( + ProviderID = "minimaxcode" + CredentialFormat = "minimaxcode-oauth-v1" + + ClientID = "mcode-public" + Scope = "agent.default" + Audience = "agent-backend" + // DeviceGrantType is the RFC 8628 device-code grant. + DeviceGrantType = "urn:ietf:params:oauth:grant-type:device_code" + + AgentID = "main" + UserAgent = "MiniMaxAgent" + AnthropicVersion = "2023-06-01" +) + +type siteConfig struct { + Account string + Agent string + Region string +} + +var sites = map[string]siteConfig{ + "cn": {Account: "https://account.minimax.cn", Agent: "https://agent.minimax.cn", Region: "cn"}, + "global": {Account: "https://account.minimax.io", Agent: "https://agent.minimax.io", Region: "global"}, +} + +const DefaultSite = "cn" + +const ( + deviceCodePath = "/oauth2/device/code" + tokenPath = "/oauth2/token" + messagesPath = "/mavis/api/v1/llm/v1/messages" + modelsPath = "/mavis/api/v1/models" +) + +const ( + refreshLead = 2 * time.Minute + deviceLoginTimeout = 15 * time.Minute + pollFloor = 5 * time.Second + pollSlowDownStep = 5 * time.Second + maxPollInterval = 60 * time.Second + catalogTTL = 10 * time.Minute + metadataTimeout = 20 * time.Second +) + +// knownModels is the static fallback catalog mirroring the Code CLI registry. +var knownModels = []string{ + "MiniMax-M3.1-Flash-Preview", + "MiniMax-M3", + "MiniMax-M2.7", + "MiniMax-M2.7-highspeed", +} + +const defaultModel = "MiniMax-M3" diff --git a/internal/providers/minimaxcode/credential.go b/internal/providers/minimaxcode/credential.go new file mode 100644 index 00000000..d8d5596b --- /dev/null +++ b/internal/providers/minimaxcode/credential.go @@ -0,0 +1,185 @@ +package minimaxcode + +import ( + "encoding/json" + "errors" + "fmt" + "net/url" + "strings" + "time" +) + +// Credential is the canonical stored payload for provider=minimaxcode. +type Credential struct { + Format string `json:"format"` + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token,omitempty"` + ExpiresAt int64 `json:"expires_at,omitempty"` + ExpiresIn int64 `json:"expires_in,omitempty"` + TokenType string `json:"token_type,omitempty"` + Scope string `json:"scope,omitempty"` + // Site is cn/global; AccountBase/AgentBase record the endpoints this token + // belongs to (empty means the site defaults). + Site string `json:"site,omitempty"` + AccountBase string `json:"account_base,omitempty"` + AgentBase string `json:"agent_base,omitempty"` + Region string `json:"region,omitempty"` + // Model/plan/user are display-only. + UserID string `json:"user_id,omitempty"` + UserName string `json:"user_name,omitempty"` + Plan string `json:"plan,omitempty"` +} + +type wireCredential struct { + Format string `json:"format"` + AccessToken string `json:"access_token"` + AccessTokenC string `json:"accessToken"` + Token string `json:"token"` + RefreshToken string `json:"refresh_token"` + RefreshTokenC string `json:"refreshToken"` + ExpiresAt int64 `json:"expires_at"` + ExpiresAtC int64 `json:"expiresAt"` + ExpiresIn int64 `json:"expires_in"` + TokenType string `json:"token_type"` + Scope string `json:"scope"` + Site string `json:"site"` + AccountBase string `json:"account_base"` + AgentBase string `json:"agent_base"` + Region string `json:"region"` + UserID string `json:"user_id"` + UserName string `json:"user_name"` + Plan string `json:"plan"` +} + +func DecodeCredential(payload []byte) (Credential, error) { + var wire wireCredential + if err := json.Unmarshal(payload, &wire); err != nil { + return Credential{}, fmt.Errorf("minimaxcode credential is not valid json") + } + expiresAt := firstNonZero(wire.ExpiresAt, wire.ExpiresAtC) + if expiresAt <= 0 && wire.ExpiresIn > 0 { + expiresAt = time.Now().Unix() + wire.ExpiresIn + } + credential := Credential{ + Format: first(wire.Format, CredentialFormat), + AccessToken: strings.TrimSpace(first(wire.AccessToken, wire.AccessTokenC, wire.Token)), + RefreshToken: strings.TrimSpace(first(wire.RefreshToken, wire.RefreshTokenC)), + ExpiresAt: expiresAt, + ExpiresIn: wire.ExpiresIn, + TokenType: strings.TrimSpace(wire.TokenType), + Scope: strings.TrimSpace(wire.Scope), + Site: normalizeSite(wire.Site), + AccountBase: normalizeURL(wire.AccountBase), + AgentBase: normalizeURL(wire.AgentBase), + Region: strings.TrimSpace(wire.Region), + UserID: strings.TrimSpace(wire.UserID), + UserName: strings.TrimSpace(wire.UserName), + Plan: strings.TrimSpace(wire.Plan), + } + if credential.Site == "" { + credential.Site = DefaultSite + } + if credential.Region == "" { + credential.Region = sites[credential.Site].Region + } + return credential, nil +} + +func (c Credential) Encode() ([]byte, error) { + c.Format = CredentialFormat + c.AccessToken = strings.TrimSpace(c.AccessToken) + c.RefreshToken = strings.TrimSpace(c.RefreshToken) + c.Site = normalizeSite(c.Site) + c.AccountBase = normalizeURL(c.AccountBase) + c.AgentBase = normalizeURL(c.AgentBase) + return json.Marshal(c) +} + +func (c Credential) Ready() bool { return strings.TrimSpace(c.AccessToken) != "" } + +func (c Credential) NeedsRefresh(now time.Time) bool { + if c.ExpiresAt <= 0 { + return false + } + return now.Add(refreshLead).Unix() >= c.ExpiresAt +} + +func (c Credential) accountBase() string { + if base := normalizeURL(c.AccountBase); base != "" { + return base + } + return sites[c.Site].Account +} + +func (c Credential) agentBase() string { + if base := normalizeURL(c.AgentBase); base != "" { + return base + } + return sites[c.Site].Agent +} + +func (c Credential) region() string { + if c.Region != "" { + return c.Region + } + return sites[c.Site].Region +} + +var errNoAccessToken = errors.New("minimaxcode credential requires an access token") + +func ValidateCredential(payload []byte) error { + credential, err := DecodeCredential(payload) + if err != nil { + return err + } + if !credential.Ready() { + return errNoAccessToken + } + return ValidateEndpoints(credential.AccountBase, credential.AgentBase) +} + +func ValidateEndpoints(accountBase, agentBase string) error { + for _, raw := range []string{accountBase, agentBase} { + if raw == "" { + continue + } + parsed, err := url.Parse(raw) + if err != nil || parsed.Host == "" || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" { + return fmt.Errorf("minimaxcode endpoint must be an absolute URL without credentials or query") + } + if !strings.EqualFold(parsed.Scheme, "https") && !acceptTestEndpoint { + return fmt.Errorf("minimaxcode endpoint must be an https URL") + } + } + return nil +} + +var acceptTestEndpoint = false + +func normalizeSite(raw string) string { + value := strings.ToLower(strings.TrimSpace(raw)) + if value == "global" { + return "global" + } + return DefaultSite +} + +func normalizeURL(raw string) string { return strings.TrimRight(strings.TrimSpace(raw), "/") } + +func first(values ...string) string { + for _, value := range values { + if trimmed := strings.TrimSpace(value); trimmed != "" { + return trimmed + } + } + return "" +} + +func firstNonZero(values ...int64) int64 { + for _, value := range values { + if value != 0 { + return value + } + } + return 0 +} diff --git a/internal/providers/minimaxcode/doc.go b/internal/providers/minimaxcode/doc.go new file mode 100644 index 00000000..6217b4d9 --- /dev/null +++ b/internal/providers/minimaxcode/doc.go @@ -0,0 +1,12 @@ +// Package minimaxcode implements an in-process adapter for the MiniMax Code +// subscription product (agent.minimax.cn / agent.minimax.io). It is not the +// MiniMax Open Platform API-key gateway. +// +// Authentication uses MiniMax Code's own OAuth 2.0 device flow with PKCE S256 +// (public client mcode-public). Refresh tokens are single-use, so refreshes are +// serialized per account and persisted immediately. Chat speaks the Anthropic +// Messages protocol the Code CLI uses and is translated to/from the gateway's +// OpenAI-compatible surface. Model discovery reads the live catalog with a +// static fallback; quota is status-only because the gateway exposes no numeric +// balance endpoint over this surface. +package minimaxcode diff --git a/internal/providers/minimaxcode/errors.go b/internal/providers/minimaxcode/errors.go new file mode 100644 index 00000000..2604c036 --- /dev/null +++ b/internal/providers/minimaxcode/errors.go @@ -0,0 +1,61 @@ +package minimaxcode + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/providers" +) + +func Classify(status int, body string) providers.ClassifiedError { + message := upstreamMessage(body) + lower := strings.ToLower(message) + switch { + case status == http.StatusUnauthorized || strings.Contains(lower, "unauthorized") || strings.Contains(lower, "invalid token"): + return providers.ClassifiedError{Kind: accounts.KindAuth, Status: http.StatusUnauthorized, Message: message} + case status == http.StatusPaymentRequired || strings.Contains(lower, "insufficient balance") || strings.Contains(lower, "quota") || strings.Contains(message, "余额不足"): + return providers.ClassifiedError{Kind: accounts.KindQuota, Status: http.StatusPaymentRequired, Message: message} + case status == http.StatusTooManyRequests || strings.Contains(lower, "rate limit"): + return providers.ClassifiedError{Kind: accounts.KindRateLimit, Status: http.StatusTooManyRequests, Message: message} + case status == http.StatusNotFound || strings.Contains(lower, "model not found") || strings.Contains(lower, "not registered"): + return providers.ClassifiedError{Kind: accounts.KindModelNotAvailable, Status: http.StatusNotFound, Message: message} + case status == http.StatusBadRequest || status == http.StatusUnprocessableEntity || accounts.IsInvalidRequestText(message): + return providers.ClassifiedError{Kind: accounts.KindInvalidRequest, Status: http.StatusBadRequest, Message: message} + case status == 499 || strings.Contains(lower, "canceled") || strings.Contains(lower, "cancelled"): + return providers.ClassifiedError{Kind: accounts.KindCanceled, Status: 499, Message: message} + default: + return providers.ClassifiedError{Kind: accounts.KindUnavailable, Status: http.StatusBadGateway, Message: message} + } +} + +func upstreamMessage(body string) string { + var payload map[string]any + if json.Unmarshal([]byte(body), &payload) == nil { + if errObj, ok := payload["error"].(map[string]any); ok { + if text := jsonStr(errObj, "message"); text != "" { + return text + } + } + if text := jsonStr(payload, "message"); text != "" { + return text + } + if resp, ok := payload["base_resp"].(map[string]any); ok { + if text := jsonStr(resp, "status_msg"); text != "" { + return text + } + } + } + trimmed := strings.TrimSpace(body) + if trimmed == "" { + return "minimaxcode upstream error" + } + return trimmed +} + +func newProviderError(status int, body string) error { + classified := Classify(status, body) + return &providers.Error{Kind: classified.Kind, Status: classified.Status, Message: fmt.Sprintf("minimaxcode upstream: %s", classified.Message)} +} diff --git a/internal/providers/minimaxcode/import.go b/internal/providers/minimaxcode/import.go new file mode 100644 index 00000000..bf307054 --- /dev/null +++ b/internal/providers/minimaxcode/import.go @@ -0,0 +1,37 @@ +package minimaxcode + +import ( + "context" + + "github.com/caigee-cmd/cli2api/internal/providers" +) + +func (credentialCodec) Format() string { return CredentialFormat } + +func (credentialCodec) PrepareImport(payload []byte) (providers.CredentialImport, error) { + credential, err := DecodeCredential(payload) + if err != nil { + return providers.CredentialImport{}, err + } + if !credential.Ready() { + return providers.CredentialImport{}, errNoAccessToken + } + if err := ValidateEndpoints(credential.AccountBase, credential.AgentBase); err != nil { + return providers.CredentialImport{}, err + } + encoded, err := credential.Encode() + if err != nil { + return providers.CredentialImport{}, err + } + return providers.CredentialImport{Payload: encoded, Ready: true, Region: credential.Site}, nil +} + +type importer struct{} + +func (importer) ValidateImport(payload []byte) error { + return credentialCodec{}.Validate(payload) +} + +func (importer) Export(context.Context, string) (map[string]any, error) { + return nil, providers.ErrUnsupported +} diff --git a/internal/providers/minimaxcode/login.go b/internal/providers/minimaxcode/login.go new file mode 100644 index 00000000..ef806906 --- /dev/null +++ b/internal/providers/minimaxcode/login.go @@ -0,0 +1,165 @@ +package minimaxcode + +import ( + "context" + "fmt" + "time" + + "github.com/caigee-cmd/cli2api/internal/providers" +) + +const loginStateTTL = deviceLoginTimeout + 5*time.Minute + +// StartLogin opens an OAuth device-authorization round. The verification URI +// is returned as AuthURL and the user code is surfaced through PollLogin +// messages, matching the existing device-flow providers. +func (c *Client) StartLogin(ctx context.Context, accountID string) (providers.LoginSession, error) { + siteID := DefaultSite + accountBase := sites[siteID].Account + agentBase := sites[siteID].Agent + if credential, err := c.loadCredential(ctx, accountID); err == nil { + if credential.Site != "" { + siteID = credential.Site + } + accountBase = credential.accountBase() + agentBase = credential.agentBase() + } + pair, err := newPKCE() + if err != nil { + return providers.LoginSession{}, err + } + auth, err := c.requestDeviceCode(ctx, accountBase, pair) + if err != nil { + return providers.LoginSession{}, err + } + now := c.now() + c.mu.Lock() + if c.logins == nil { + c.logins = map[string]*loginState{} + } + for id, pending := range c.logins { + if now.Sub(pending.expiresAt) > loginStateTTL { + delete(c.logins, id) + } + } + c.logins[accountID] = &loginState{ + site: siteID, + accountBase: accountBase, + agentBase: agentBase, + userCode: auth.UserCode, + deviceCode: auth.DeviceCode, + verifier: pair.Verifier, + verifyURL: auth.VerifyURI, + interval: auth.Interval, + expiresAt: now.Add(auth.ExpiresIn), + pollByUser: auth.PollByUser, + } + c.mu.Unlock() + return providers.LoginSession{AuthURL: auth.VerifyURI, State: auth.UserCode}, nil +} + +func (c *Client) PollLogin(ctx context.Context, accountID string) (bool, string, error) { + c.mu.Lock() + state := c.logins[accountID] + c.mu.Unlock() + if state == nil { + return false, "", fmt.Errorf("login not started for account %s", accountID) + } + now := c.now() + if now.After(state.expiresAt) { + session, err := c.StartLogin(ctx, accountID) + if err != nil { + c.clearLogin(accountID) + return false, "", err + } + return false, fmt.Sprintf("the code expired; open %s and enter %s", session.AuthURL, session.State), nil + } + c.mu.Lock() + if !state.lastPolled.IsZero() && now.Sub(state.lastPolled) < state.interval { + message := state.lastMessage + if message == "" { + message = waitingMessage(state.userCode) + } + c.mu.Unlock() + return false, message, nil + } + state.lastPolled = now + c.mu.Unlock() + + result, err := c.pollDeviceToken(ctx, state.accountBase, state.deviceCode, state.verifier, state.pollByUser) + if err != nil { + return false, "", err + } + switch result.Kind { + case pollPending: + message := waitingMessage(state.userCode) + c.setLoginMessage(accountID, message) + return false, message, nil + case pollSlowDown: + c.backOffLogin(accountID) + message := waitingMessage(state.userCode) + c.setLoginMessage(accountID, message) + return false, message, nil + case pollDenied: + c.clearLogin(accountID) + return false, "", fmt.Errorf("minimaxcode authorization was denied") + case pollExpired: + session, startErr := c.StartLogin(ctx, accountID) + if startErr != nil { + c.clearLogin(accountID) + return false, "", startErr + } + return false, fmt.Sprintf("the code expired; open %s and enter %s", session.AuthURL, session.State), nil + case pollFailed: + return false, "", fmt.Errorf("minimaxcode device poll failed: %s", result.Error) + } + + credential := Credential{ + Format: CredentialFormat, + Site: state.site, + AccountBase: state.accountBase, + AgentBase: state.agentBase, + Region: sites[state.site].Region, + } + credential = applyToken(credential, result.Token, c.now()) + if err := c.saveCredential(ctx, accountID, credential); err != nil { + return false, "", err + } + _ = c.store.Observe(ctx, accountID, credential.UserID, "ready", "", "") + c.clearLogin(accountID) + return true, "login complete", nil +} + +func waitingMessage(userCode string) string { + if userCode == "" { + return "waiting for authorization" + } + return fmt.Sprintf("waiting for authorization; the code is %s", userCode) +} + +func (c *Client) setLoginMessage(accountID, message string) { + c.mu.Lock() + defer c.mu.Unlock() + if state := c.logins[accountID]; state != nil { + state.lastMessage = message + } +} + +func (c *Client) backOffLogin(accountID string) { + c.mu.Lock() + defer c.mu.Unlock() + state := c.logins[accountID] + if state == nil { + return + } + state.interval += pollSlowDownStep + if state.interval > maxPollInterval { + state.interval = maxPollInterval + } +} + +func (c *Client) clearLogin(accountID string) { + c.mu.Lock() + defer c.mu.Unlock() + delete(c.logins, accountID) +} diff --git a/internal/providers/minimaxcode/minimaxcode_test.go b/internal/providers/minimaxcode/minimaxcode_test.go new file mode 100644 index 00000000..30af4f28 --- /dev/null +++ b/internal/providers/minimaxcode/minimaxcode_test.go @@ -0,0 +1,204 @@ +package minimaxcode + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/translate" +) + +type memoryStore struct { + mu sync.Mutex + payload []byte + account accounts.Account +} + +func (s *memoryStore) Get(context.Context, string) (accounts.Account, error) { return s.account, nil } +func (s *memoryStore) LoadCredentialPayload(context.Context, string) (string, []byte, error) { + s.mu.Lock() + defer s.mu.Unlock() + return CredentialFormat, append([]byte(nil), s.payload...), nil +} +func (s *memoryStore) SaveCredentialPayload(_ context.Context, _, _ string, payload []byte) error { + s.mu.Lock() + defer s.mu.Unlock() + s.payload = append([]byte(nil), payload...) + return nil +} +func (s *memoryStore) Observe(context.Context, string, string, string, string, string) error { + return nil +} + +func newTestClient(t *testing.T, accountBase, agentBase string) (*Client, *memoryStore) { + t.Helper() + store := &memoryStore{account: accounts.Account{Enabled: true}} + cred := Credential{Format: CredentialFormat, AccessToken: "tok", Site: "cn", AccountBase: accountBase, AgentBase: agentBase, Region: "cn", ExpiresAt: time.Now().Add(time.Hour).Unix()} + payload, _ := cred.Encode() + store.payload = payload + client := NewClient(store) + client.http = &http.Client{} + acceptTestEndpoint = true + return client, store +} + +func TestCredentialRoundTrip(t *testing.T) { + cred := Credential{AccessToken: "access", RefreshToken: "refresh", Site: "global", ExpiresIn: 3600} + payload, err := cred.Encode() + if err != nil { + t.Fatal(err) + } + decoded, err := DecodeCredential(payload) + if err != nil { + t.Fatal(err) + } + if decoded.AccessToken != "access" || decoded.Site != "global" { + t.Fatalf("decoded = %+v", decoded) + } +} + +func TestDeviceLoginFlow(t *testing.T) { + deviceCodeIssued := false + tokenApproved := false + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case deviceCodePath: + deviceCodeIssued = true + _, _ = io.WriteString(w, `{"device_code":"dev-1","user_code":"ABCD-1234","verification_uri_complete":"https://example.com/device","expires_in":600,"interval":1}`) + case tokenPath: + if !tokenApproved { + _, _ = io.WriteString(w, `{"status":"pending"}`) + return + } + _, _ = io.WriteString(w, `{"access_token":"new-access","refresh_token":"new-refresh","expires_in":3600}`) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + client, _ := newTestClient(t, server.URL, server.URL) + // Login starts against the credential's account base. + session, err := client.StartLogin(context.Background(), "acct-1") + if err != nil { + t.Fatal(err) + } + if session.AuthURL != "https://example.com/device" || session.State != "ABCD-1234" { + t.Fatalf("session = %+v", session) + } + if !deviceCodeIssued { + t.Fatal("device code endpoint not called") + } + done, msg, err := client.PollLogin(context.Background(), "acct-1") + if err != nil || done { + t.Fatalf("pending poll: done=%v msg=%q err=%v", done, msg, err) + } + if !strings.Contains(msg, "ABCD-1234") { + t.Fatalf("user code not surfaced: %q", msg) + } + tokenApproved = true + // Force the next poll past the interval gate. + client.mu.Lock() + client.logins["acct-1"].lastPolled = time.Time{} + client.mu.Unlock() + done, _, err = client.PollLogin(context.Background(), "acct-1") + if err != nil || !done { + t.Fatalf("approval poll: done=%v err=%v", done, err) + } +} + +func TestChatNonStream(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == modelsPath { + _, _ = io.WriteString(w, `{"models":[{"id":"MiniMax-M3","name":"MiniMax M3"}]}`) + return + } + if r.URL.Path == messagesPath { + if r.Header.Get("Authorization") != "Bearer tok" { + t.Error("missing bearer") + } + if r.Header.Get("X-Mavis-Agent-Id") != AgentID { + t.Error("missing mavis agent header") + } + body, _ := io.ReadAll(r.Body) + var anthropic map[string]any + if json.Unmarshal(body, &anthropic) != nil { + t.Error("invalid anthropic body") + } + if anthropic["model"] != "MiniMax-M3" { + t.Errorf("model = %v", anthropic["model"]) + } + if anthropic["system"] != "be brief" { + t.Errorf("system = %v", anthropic["system"]) + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"id":"msg-1","model":"MiniMax-M3","stop_reason":"end_turn","content":[{"type":"text","text":"hello"}],"usage":{"input_tokens":3,"output_tokens":2}}`) + return + } + http.NotFound(w, r) + })) + defer server.Close() + client, _ := newTestClient(t, server.URL, server.URL) + req := translate.ChatRequest{ + Model: "minimaxcode/MiniMax-M3", + Messages: []translate.ChatMessage{ + {Role: "system", Content: "be brief"}, + {Role: "user", Content: "hi"}, + }, + } + outcome, err := client.ChatNonStream(context.Background(), "acct-1", req) + if err != nil { + t.Fatal(err) + } + if outcome.Content != "hello" { + t.Fatalf("content = %q", outcome.Content) + } + if outcome.PromptTokens != 3 || outcome.CompletionTokens != 2 { + t.Fatalf("usage = %+v", outcome) + } +} + +func TestClassify(t *testing.T) { + cases := []struct { + status int + body string + kind string + }{ + {401, `{"type":"error","error":{"message":"unauthorized"}}`, accounts.KindAuth}, + {402, `{"error":{"message":"insufficient balance"}}`, accounts.KindQuota}, + {429, `{"error":{"message":"rate limit"}}`, accounts.KindRateLimit}, + {500, `boom`, accounts.KindUnavailable}, + } + for _, tc := range cases { + got := Classify(tc.status, tc.body) + if got.Kind != tc.kind { + t.Errorf("status %d: kind = %q want %q", tc.status, got.Kind, tc.kind) + } + } +} + +func TestModelsFallback(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusUnauthorized) + _, _ = io.WriteString(w, `{"error":{"message":"unauthorized"}}`) + })) + defer server.Close() + client, _ := newTestClient(t, server.URL, server.URL) + models, err := client.Models(context.Background(), "acct-1") + if err != nil { + t.Fatal(err) + } + if len(models) != len(knownModels) { + t.Fatalf("fallback models = %d", len(models)) + } +} + +var _ = fmt.Sprintf diff --git a/internal/providers/minimaxcode/oauth.go b/internal/providers/minimaxcode/oauth.go new file mode 100644 index 00000000..7fac2489 --- /dev/null +++ b/internal/providers/minimaxcode/oauth.go @@ -0,0 +1,275 @@ +package minimaxcode + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +type pkcePair struct { + Verifier string + Challenge string +} + +func newPKCE() (pkcePair, error) { + buf := make([]byte, 32) + if _, err := rand.Read(buf); err != nil { + return pkcePair{}, err + } + verifier := base64.RawURLEncoding.EncodeToString(buf) + sum := sha256.Sum256([]byte(verifier)) + return pkcePair{Verifier: verifier, Challenge: base64.RawURLEncoding.EncodeToString(sum[:])}, nil +} + +type deviceAuth struct { + DeviceCode string + UserCode string + VerifyURI string + ExpiresIn time.Duration + Interval time.Duration + PollByUser bool +} + +type tokenResult struct { + AccessToken string + RefreshToken string + ExpiresIn int64 + TokenType string + Scope string +} + +type pollKind int + +const ( + pollReady pollKind = iota + pollPending + pollSlowDown + pollDenied + pollExpired + pollFailed +) + +type pollResult struct { + Kind pollKind + Token tokenResult + Error string +} + +func applyToken(credential Credential, token tokenResult, now time.Time) Credential { + credential.AccessToken = token.AccessToken + if token.RefreshToken != "" { + credential.RefreshToken = token.RefreshToken + } + if token.TokenType != "" { + credential.TokenType = token.TokenType + } + if token.Scope != "" { + credential.Scope = token.Scope + } + expiresIn := token.ExpiresIn + if expiresIn <= 0 { + expiresIn = 3600 + } + credential.ExpiresAt = now.Add(time.Duration(expiresIn) * time.Second).Unix() + return credential +} + +func (c *Client) requestDeviceCode(ctx context.Context, accountBase string, pair pkcePair) (deviceAuth, error) { + form := url.Values{ + "client_id": {ClientID}, + "scope": {Scope}, + "audience": {Audience}, + "code_challenge": {pair.Challenge}, + "code_challenge_method": {"S256"}, + } + body, status, err := c.postForm(ctx, accountBase+deviceCodePath, form) + if err != nil { + return deviceAuth{}, err + } + var payload map[string]any + _ = json.Unmarshal(body, &payload) + userCode := jsonString(payload, "user_code") + uri := first(jsonString(payload, "verification_uri_complete"), jsonString(payload, "verification_uri"), jsonString(payload, "verification_url")) + deviceCode := jsonString(payload, "device_code") + if status >= 400 || userCode == "" || uri == "" { + return deviceAuth{}, fmt.Errorf("minimaxcode device code request failed (HTTP %d): %s", status, truncate(string(body), 300)) + } + expires := jsonDeadline(payload) + interval := jsonInterval(payload, deviceCode == "") + if interval <= 0 { + interval = 2 * time.Second + } + return deviceAuth{ + DeviceCode: first(deviceCode, userCode), + UserCode: userCode, + VerifyURI: uri, + ExpiresIn: expires, + Interval: interval, + PollByUser: deviceCode == "", + }, nil +} + +func (c *Client) pollDeviceToken(ctx context.Context, accountBase, deviceCode, verifier string, pollByUser bool) (pollResult, error) { + form := url.Values{ + "grant_type": {DeviceGrantType}, + "client_id": {ClientID}, + "code_verifier": {verifier}, + } + if pollByUser { + form.Set("user_code", deviceCode) + } else { + form.Set("device_code", deviceCode) + } + body, status, err := c.postForm(ctx, accountBase+tokenPath, form) + if err != nil { + return pollResult{}, err + } + var payload map[string]any + _ = json.Unmarshal(body, &payload) + if st := jsonString(payload, "status"); st != "" { + switch st { + case "pending": + return pollResult{Kind: pollPending}, nil + case "slow_down": + return pollResult{Kind: pollSlowDown}, nil + case "denied", "access_denied": + return pollResult{Kind: pollDenied}, nil + case "expired", "expired_token": + return pollResult{Kind: pollExpired}, nil + default: + return pollResult{Kind: pollFailed, Error: "unexpected_status:" + st}, nil + } + } + if code := jsonString(payload, "error"); code != "" { + return pollResult{Kind: pollFailed, Error: code + ": " + jsonString(payload, "error_description")}, nil + } + access := jsonString(payload, "access_token") + if access == "" { + if status >= 400 { + return pollResult{Kind: pollFailed, Error: fmt.Sprintf("no access token (HTTP %d)", status)}, nil + } + return pollResult{Kind: pollPending}, nil + } + return pollResult{Kind: pollReady, Token: tokenFromJSON(payload)}, nil +} + +func (c *Client) refreshToken(ctx context.Context, credential Credential) (tokenResult, error) { + form := url.Values{ + "grant_type": {"refresh_token"}, + "refresh_token": {credential.RefreshToken}, + "client_id": {ClientID}, + "scope": {Scope}, + "audience": {Audience}, + } + body, status, err := c.postForm(ctx, credential.accountBase()+tokenPath, form) + if err != nil { + return tokenResult{}, err + } + var payload map[string]any + _ = json.Unmarshal(body, &payload) + if jsonString(payload, "access_token") == "" { + return tokenResult{}, fmt.Errorf("minimaxcode token refresh failed (HTTP %d)", status) + } + return tokenFromJSON(payload), nil +} + +func (c *Client) postForm(ctx context.Context, endpoint string, form url.Values) ([]byte, int, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode())) + if err != nil { + return nil, 0, err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + client, err := c.httpClient(ctx, "") + if err != nil { + return nil, 0, err + } + resp, err := client.Do(req) + if err != nil { + return nil, 0, err + } + defer resp.Body.Close() + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + return body, resp.StatusCode, nil +} + +func tokenFromJSON(payload map[string]any) tokenResult { + return tokenResult{ + AccessToken: jsonString(payload, "access_token"), + RefreshToken: jsonString(payload, "refresh_token"), + ExpiresIn: jsonInt(payload, "expires_in", "expired_in"), + TokenType: jsonString(payload, "token_type"), + Scope: jsonString(payload, "scope"), + } +} + +func jsonString(payload map[string]any, key string) string { + value, _ := payload[key].(string) + return strings.TrimSpace(value) +} + +func jsonInt(payload map[string]any, keys ...string) int64 { + for _, key := range keys { + switch value := payload[key].(type) { + case float64: + return int64(value) + case json.Number: + n, _ := strconv.ParseInt(value.String(), 10, 64) + return n + case string: + n, _ := strconv.ParseInt(strings.TrimSpace(value), 10, 64) + if n != 0 { + return n + } + } + } + return 0 +} + +func jsonDeadline(payload map[string]any) time.Duration { + seconds := jsonInt(payload, "expires_in", "expired_in") + if seconds <= 0 { + return 10 * time.Minute + } + if seconds > 10_000_000 { + return time.Duration(maxInt64(1, seconds-time.Now().UnixMilli()/1000)) * time.Second + } + return time.Duration(seconds) * time.Second +} + +func jsonInterval(payload map[string]any, pollByUser bool) time.Duration { + raw := jsonInt(payload, "interval") + if raw <= 0 { + if pollByUser { + return 5 * time.Second + } + return 2 * time.Second + } + if pollByUser && raw > 100 { + return time.Duration(maxInt64(1, raw/1000)) * time.Second + } + return time.Duration(raw) * time.Second +} + +func maxInt64(a, b int64) int64 { + if a > b { + return a + } + return b +} + +func truncate(text string, limit int) string { + if len(text) > limit { + return text[:limit] + } + return text +} diff --git a/internal/providers/minimaxcode/payload.go b/internal/providers/minimaxcode/payload.go new file mode 100644 index 00000000..b104c7d8 --- /dev/null +++ b/internal/providers/minimaxcode/payload.go @@ -0,0 +1,147 @@ +package minimaxcode + +import ( + "encoding/json" + "strings" + + "github.com/caigee-cmd/cli2api/internal/translate" +) + +// buildChatBody translates an OpenAI chat request into the Anthropic Messages +// body the MiniMax Code gateway expects. +func buildChatBody(req translate.ChatRequest, model string) (map[string]any, error) { + systemParts := []string{} + messages := make([]any, 0, len(req.Messages)) + for _, msg := range req.Messages { + switch msg.Role { + case "system", "developer": + if text := messageText(msg.Content); strings.TrimSpace(text) != "" { + systemParts = append(systemParts, text) + } + continue + case "tool", "function": + messages = append(messages, map[string]any{ + "role": "user", + "content": []any{map[string]any{ + "type": "tool_result", "tool_use_id": first(msg.ToolCallID, msg.Name, "tool"), + "content": messageText(msg.Content), + }}, + }) + continue + case "assistant": + blocks := make([]any, 0) + if text := messageText(msg.Content); strings.TrimSpace(text) != "" { + blocks = append(blocks, map[string]any{"type": "text", "text": text}) + } + if len(msg.ToolCalls) > 0 { + var calls []map[string]any + if json.Unmarshal(msg.ToolCalls, &calls) == nil { + for _, call := range calls { + id, _ := call["id"].(string) + function, _ := call["function"].(map[string]any) + name, _ := function["name"].(string) + arguments, _ := function["arguments"].(string) + var input any = map[string]any{} + if arguments != "" { + _ = json.Unmarshal([]byte(arguments), &input) + } + blocks = append(blocks, map[string]any{"type": "tool_use", "id": first(id, newToolID()), "name": first(name, "tool"), "input": input}) + } + } + } + if len(blocks) > 0 { + messages = append(messages, map[string]any{"role": "assistant", "content": blocks}) + } + continue + default: + messages = append(messages, map[string]any{"role": "user", "content": contentBlocks(msg.Content)}) + } + } + body := map[string]any{ + "model": model, + "max_tokens": 8192, + "messages": messages, + } + if len(systemParts) > 0 { + body["system"] = strings.Join(systemParts, "\n\n") + } + if req.Stream { + body["stream"] = true + } + if len(req.Tools) > 0 { + var tools []map[string]any + if json.Unmarshal(req.Tools, &tools) == nil { + anthropicTools := make([]any, 0, len(tools)) + for _, tool := range tools { + typ, _ := tool["type"].(string) + function, _ := tool["function"].(map[string]any) + name, _ := function["name"].(string) + if typ != "function" || name == "" { + continue + } + description, _ := function["description"].(string) + params := function["parameters"] + if params == nil { + params = map[string]any{"type": "object", "properties": map[string]any{}} + } + entry := map[string]any{"name": name, "input_schema": params} + if description != "" { + entry["description"] = description + } + anthropicTools = append(anthropicTools, entry) + } + if len(anthropicTools) > 0 { + body["tools"] = anthropicTools + } + } + } + return body, nil +} + +func messageText(content any) string { + switch value := content.(type) { + case string: + return value + case []any: + parts := make([]string, 0, len(value)) + for _, raw := range value { + part, ok := raw.(map[string]any) + if !ok { + continue + } + if text, ok := part["text"].(string); ok { + parts = append(parts, text) + } + } + return strings.Join(parts, "\n") + default: + return "" + } +} + +func contentBlocks(content any) []any { + switch value := content.(type) { + case string: + return []any{map[string]any{"type": "text", "text": value}} + case []any: + blocks := make([]any, 0, len(value)) + for _, raw := range value { + part, ok := raw.(map[string]any) + if !ok { + continue + } + typ, _ := part["type"].(string) + if text, ok := part["text"].(string); ok && (typ == "text" || text != "") { + blocks = append(blocks, map[string]any{"type": "text", "text": text}) + } + } + if len(blocks) > 0 { + return blocks + } + } + return []any{map[string]any{"type": "text", "text": ""}} +} + +func newToolID() string { + return "toolu_" + randomHex(8) +} diff --git a/internal/providers/minimaxcode/quota.go b/internal/providers/minimaxcode/quota.go new file mode 100644 index 00000000..bf3c940b --- /dev/null +++ b/internal/providers/minimaxcode/quota.go @@ -0,0 +1,30 @@ +package minimaxcode + +import ( + "context" + "strings" + + "github.com/caigee-cmd/cli2api/internal/providers" +) + +// Quota reports a minimal status window. The MiniMax Code gateway does not +// expose a quota endpoint over the Claude-compatible surface, so no numeric +// balance is invented; the account label is shown instead. +func (c *Client) Quota(ctx context.Context, accountID string) (*providers.QuotaInfo, error) { + credential, err := c.loadCredential(ctx, accountID) + if err != nil { + return nil, err + } + label := strings.TrimSpace(credential.Plan) + if label == "" { + label = "MiniMax Code" + } + info := providers.QuotaInfo{ + ProviderID: ProviderID, + Unit: "状态", + Plan: label, + FetchedAt: c.now().UTC().Format("2006-01-02T15:04:05Z"), + Windows: []providers.QuotaWindow{{ID: "plan", Label: label, Unit: "状态"}}, + } + return &info, nil +} diff --git a/internal/providers/minimaxcode/sse.go b/internal/providers/minimaxcode/sse.go new file mode 100644 index 00000000..191eefbc --- /dev/null +++ b/internal/providers/minimaxcode/sse.go @@ -0,0 +1,140 @@ +package minimaxcode + +import ( + "bufio" + "encoding/json" + "io" + "strings" +) + +type openAIDelta struct { + Content string + Reasoning string + ToolCalls []toolCallDelta + Finish string // non-empty when a finish reason is known +} + +type toolCallDelta struct { + Index int + ID string + Name string + Arguments string + HasID bool + HasName bool +} + +type anthropicDecoder struct { + sentRole bool + toolIndex int + finish string +} + +func newAnthropicDecoder() *anthropicDecoder { return &anthropicDecoder{toolIndex: -1} } + +func stopReason(reason string) string { + switch reason { + case "end_turn", "stop_sequence": + return "stop" + case "max_tokens": + return "length" + case "tool_use": + return "tool_calls" + case "refusal": + return "content_filter" + default: + return "stop" + } +} + +func (d *anthropicDecoder) frame(eventType string, payload string) ([]openAIDelta, bool, error) { + var event map[string]any + if json.Unmarshal([]byte(payload), &event) != nil { + return nil, false, nil + } + kind := first(jsonStr(event, "type"), eventType) + switch kind { + case "message_start", "message": + if d.sentRole { + return nil, false, nil + } + d.sentRole = true + return []openAIDelta{{}}, false, nil // role delta handled by chat layer + case "content_block_start": + block, _ := event["content_block"].(map[string]any) + if jsonStr(block, "type") == "tool_use" { + d.toolIndex++ + call := toolCallDelta{Index: d.toolIndex, ID: jsonStr(block, "id"), Name: jsonStr(block, "name"), HasID: true, HasName: true} + if call.ID == "" { + call.ID = newToolID() + } + return []openAIDelta{{ToolCalls: []toolCallDelta{call}}}, false, nil + } + case "content_block_delta": + delta, _ := event["delta"].(map[string]any) + switch jsonStr(delta, "type") { + case "text_delta": + if text := jsonStr(delta, "text"); text != "" { + return []openAIDelta{{Content: text}}, false, nil + } + case "input_json_delta": + if partial := jsonStr(delta, "partial_json"); partial != "" { + call := toolCallDelta{Index: d.toolIndex, Arguments: partial} + return []openAIDelta{{ToolCalls: []toolCallDelta{call}}}, false, nil + } + } + case "message_delta": + delta, _ := event["delta"].(map[string]any) + if reason := jsonStr(delta, "stop_reason"); reason != "" { + d.finish = stopReason(reason) + } + case "message_stop": + finish := d.finish + if finish == "" { + finish = "stop" + } + return nil, true, nil + } + return nil, false, nil +} + +func readAnthropicSSE(src io.Reader, handle func(eventType, data string) (done bool, err error)) error { + reader := bufio.NewReaderSize(src, 64<<10) + var eventType string + var dataLines []string + dispatch := func() (bool, error) { + if eventType == "" && len(dataLines) == 0 { + return false, nil + } + payload := strings.Join(dataLines, "\n") + event, data := eventType, payload + eventType, dataLines = "", nil + if strings.TrimSpace(payload) == "" { + return false, nil + } + return handle(event, data) + } + for { + line, err := reader.ReadString('\n') + line = strings.TrimRight(line, "\r\n") + if line == "" { + done, handleErr := dispatch() + if handleErr != nil { + return handleErr + } + if done { + return nil + } + } else if strings.HasPrefix(line, "event:") { + eventType = strings.TrimSpace(strings.TrimPrefix(line, "event:")) + } else if strings.HasPrefix(line, "data:") { + dataLines = append(dataLines, strings.TrimSpace(strings.TrimPrefix(line, "data:"))) + } + if err != nil { + if err == io.EOF { + _, handleErr := dispatch() + return handleErr + } + return err + } + } +} diff --git a/internal/providers/registry.go b/internal/providers/registry.go index ff7d7075..3fd3ea70 100644 --- a/internal/providers/registry.go +++ b/internal/providers/registry.go @@ -433,20 +433,50 @@ var DoubaoWork = ProviderDescriptor{ DefaultRegion: "cn", } +// MiniMaxCode is the MiniMax Code subscription product, reached through its +// OAuth device flow and Anthropic-compatible agent gateway. It is distinct +// from the MiniMax Open Platform API-key gateway. +var MiniMaxCode = ProviderDescriptor{ + ID: "minimaxcode", + Label: "MiniMax Code", + Runtime: RuntimeInProcess, + AuthTypes: []AuthType{AuthOAuth}, + CredentialFormats: []string{"minimaxcode-oauth-v1"}, + Capabilities: ProviderCapabilities{ + Chat: true, Stream: true, Tools: true, Images: true, Reasoning: false, + ModelCatalog: true, Usage: true, Login: true, BrowserLogin: true, + PATLogin: false, ImportExport: true, + }, + Regions: []RegionDescriptor{ + { + ID: "cn", Label: "CN", ChatBase: "https://agent.minimax.cn", + BillingBase: "https://agent.minimax.cn", AuthBase: "https://account.minimax.cn", + DefaultDomain: "minimax.cn", + }, + { + ID: "global", Label: "Global", ChatBase: "https://agent.minimax.io", + BillingBase: "https://agent.minimax.io", AuthBase: "https://account.minimax.io", + DefaultDomain: "minimax.io", + }, + }, + DefaultRegion: "cn", +} + var registry = map[string]ProviderDescriptor{ - Qoder.ID: Qoder, - WorkBuddy.ID: WorkBuddy, - Trae.ID: Trae, - Devin.ID: Devin, - Command.ID: Command, - Codex.ID: Codex, - Zhipu.ID: Zhipu, - QwenWork.ID: QwenWork, - Kimi.ID: Kimi, - CodeArts.ID: CodeArts, - Kiro.ID: Kiro, - Meta.ID: Meta, - DoubaoWork.ID: DoubaoWork, + Qoder.ID: Qoder, + WorkBuddy.ID: WorkBuddy, + Trae.ID: Trae, + Devin.ID: Devin, + Command.ID: Command, + Codex.ID: Codex, + Zhipu.ID: Zhipu, + QwenWork.ID: QwenWork, + Kimi.ID: Kimi, + CodeArts.ID: CodeArts, + Kiro.ID: Kiro, + Meta.ID: Meta, + DoubaoWork.ID: DoubaoWork, + MiniMaxCode.ID: MiniMaxCode, } func Get(id string) (ProviderDescriptor, bool) { @@ -459,7 +489,7 @@ func Get(id string) (ProviderDescriptor, bool) { } func List() []ProviderDescriptor { - return []ProviderDescriptor{Qoder, WorkBuddy, Trae, Devin, Command, Codex, Zhipu, QwenWork, Kimi, CodeArts, Kiro, Meta, DoubaoWork} + return []ProviderDescriptor{Qoder, WorkBuddy, Trae, Devin, Command, Codex, Zhipu, QwenWork, Kimi, CodeArts, Kiro, Meta, DoubaoWork, MiniMaxCode} } // Resolve validates a provider/region pair. Empty values fall back to the diff --git a/internal/webui/static/assets/CartesianGrid-DXT2DP8n.js b/internal/webui/static/assets/CartesianGrid-DaumKfTu.js similarity index 99% rename from internal/webui/static/assets/CartesianGrid-DXT2DP8n.js rename to internal/webui/static/assets/CartesianGrid-DaumKfTu.js index f3ece6eb..65e79b69 100644 --- a/internal/webui/static/assets/CartesianGrid-DXT2DP8n.js +++ b/internal/webui/static/assets/CartesianGrid-DaumKfTu.js @@ -1,4 +1,4 @@ -import{$t as e,A as t,At as n,Bt as r,Cn as i,Ct as a,Dt as o,E as s,Et as c,F as l,Ft as u,Gt as d,H as f,Ht as p,I as m,It as h,J as g,Jt as _,K as v,Kt as y,L as b,Lt as x,M as S,Mt as C,N as w,Nt as T,O as E,Ot as D,P as O,Pt as k,R as ee,Rt as te,Sn as A,St as j,Tn as M,Tt as ne,Ut as re,Vt as ie,W as N,Wt as ae,X as oe,Xt as se,Y as P,Yt as ce,Z as le,Zt as ue,an as F,bt as de,cn as fe,ct as I,dn as pe,dt as me,en as L,et as he,fn as ge,gt as _e,ht as ve,it as ye,j as be,jt as xe,k as Se,kt as Ce,l as we,ln as Te,nn as Ee,nt as De,on as Oe,ot as ke,pn as Ae,q as R,qt as je,rt as Me,sn as Ne,st as Pe,tn as z,tt as Fe,u as Ie,ut as Le,vt as Re,wn as ze,wt as Be,xt as Ve,yt as B,z as He,zt as Ue}from"./index-CnBhKFzp.js";function We(e,t){let n=new Map;for(let r=0;rvoid 0)}function et(e,t,n,r,i=!1){if(t===e)return!0;switch(typeof t){case`object`:return tt(e,t,n,r,i);case`function`:return Object.keys(t).length>0?et(e,{...t},n,r,i):j(e,t);default:return Ve(e)&&i?typeof t!=`string`||t===``:j(e,t)}}function tt(e,t,n,r,i=!1){if(t==null)return!0;if(Array.isArray(t))return rt(e,t,n,r);if(t instanceof Map)return nt(e,t,n,r);if(t instanceof Set)return it(e,t,n,r);let a=Object.keys(t);if(e==null)return i&&a.length===0;if(i)Je(e)&&(e=Object(e));else{let t=y(e);if(t!==`[object Object]`&&t!==`[object Arguments]`)return!1}if(a.length===0)return!0;if(r?.has(t))return r.get(t)===e;r?.set(t,e);try{for(let i=0;ivoid 0)}function ot(e){return e=Qe(e),t=>at(t,e)}function st(e,t){return Xe(e,(n,i,a,s)=>{let c=t?.(n,i,a,s);if(c!==void 0)return c;if(typeof e==`object`){if(y(e)===`[object Object]`&&typeof e.constructor!=`function`){let t={};return s.set(e,t),H(t,e,a,s),t}switch(Object.prototype.toString.call(e)){case h:case r:case o:{let t=new e.constructor(e?.valueOf());return H(t,e),t}case Be:{let t={};return H(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}}})}function ct(e){return st(e)}function lt(e){return typeof e==`object`&&!!e&&y(e)===`[object Arguments]`}function ut(e,t){let n;if(n=Array.isArray(t)?t:typeof t==`string`&&Te(t)&&!(t in Object(e))?Ne(t):[t],n.length===0)return!1;let r=e;for(let e=0;evoid 0)}function et(e,t,n,r,i=!1){if(t===e)return!0;switch(typeof t){case`object`:return tt(e,t,n,r,i);case`function`:return Object.keys(t).length>0?et(e,{...t},n,r,i):j(e,t);default:return Ve(e)&&i?typeof t!=`string`||t===``:j(e,t)}}function tt(e,t,n,r,i=!1){if(t==null)return!0;if(Array.isArray(t))return rt(e,t,n,r);if(t instanceof Map)return nt(e,t,n,r);if(t instanceof Set)return it(e,t,n,r);let a=Object.keys(t);if(e==null)return i&&a.length===0;if(i)Je(e)&&(e=Object(e));else{let t=y(e);if(t!==`[object Object]`&&t!==`[object Arguments]`)return!1}if(a.length===0)return!0;if(r?.has(t))return r.get(t)===e;r?.set(t,e);try{for(let i=0;ivoid 0)}function ot(e){return e=Qe(e),t=>at(t,e)}function st(e,t){return Xe(e,(n,i,a,s)=>{let c=t?.(n,i,a,s);if(c!==void 0)return c;if(typeof e==`object`){if(y(e)===`[object Object]`&&typeof e.constructor!=`function`){let t={};return s.set(e,t),H(t,e,a,s),t}switch(Object.prototype.toString.call(e)){case h:case r:case o:{let t=new e.constructor(e?.valueOf());return H(t,e),t}case Be:{let t={};return H(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}}})}function ct(e){return st(e)}function lt(e){return typeof e==`object`&&!!e&&y(e)===`[object Arguments]`}function ut(e,t){let n;if(n=Array.isArray(t)?t:typeof t==`string`&&Te(t)&&!(t in Object(e))?Ne(t):[t],n.length===0)return!1;let r=e;for(let e=0;ee.length)&&(t=e.length);for(var n=0,r=Array(t);nW||Math.abs(e.left-t.left)>W||Math.abs(e.top-t.top)>W||Math.abs(e.width-t.width)>W}function wt(e){var t=e.getBoundingClientRect();return{height:t.height,left:t.left,top:t.top,width:t.width}}function Tt(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=_t((0,U.useState)({height:0,left:0,top:0,width:0}),2),n=t[0],r=t[1],i=(0,U.useRef)(null),a=(0,U.useRef)(n);a.current=n;var o=(0,U.useCallback)(e=>{if(i.current!=null&&(i.current.disconnect(),i.current=null),e!=null){var t=wt(e);if(Ct(t,a.current)&&r(t),typeof ResizeObserver<`u`){var n=new ResizeObserver(()=>{var t=wt(e);Ct(t,a.current)&&r(t)});n.observe(e),i.current=n}}},[...e]);return(0,U.useEffect)(()=>()=>{var e;(e=i.current)==null||e.disconnect()},[]),[n,o]}function Et(){return Et=Object.assign?Object.assign.bind():function(e){for(var t=1;te.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=t.separator,r=n===void 0?K.separator:n,i=t.contentStyle,a=t.itemStyle,o=t.labelStyle,s=o===void 0?K.labelStyle:o,c=t.payload,l=t.formatter,u=t.itemSorter,d=t.wrapperClassName,f=t.labelClassName,p=t.label,m=t.labelFormatter,h=t.accessibilityLayer,g=h===void 0?K.accessibilityLayer:h,_=()=>{if(c&&c.length){var e={padding:0,margin:0},t=Rt(c,u).map((e,t)=>{if(!e||e.type===`none`)return null;var n=e.formatter||l||Lt,i=e.value,o=e.name,s=i,u=o;if(n){var d=n(i,o,e,t,c);if(Array.isArray(d)){var f=jt(d,2);s=f[0],u=f[1]}else if(d!=null)s=d;else return null}var p=G(G({},K.itemStyle),{},{color:e.color||K.itemStyle.color},a);return U.createElement(`li`,{className:`recharts-tooltip-item`,key:`tooltip-item-${t}`,style:p},L(u)?U.createElement(`span`,{className:`recharts-tooltip-item-name`},u):null,L(u)?U.createElement(`span`,{className:`recharts-tooltip-item-separator`},r):null,U.createElement(`span`,{className:`recharts-tooltip-item-value`},s),U.createElement(`span`,{className:`recharts-tooltip-item-unit`},e.unit||``))});return U.createElement(`ul`,{className:`recharts-tooltip-item-list`,style:e},t)}return null},v=G(G({},K.contentStyle),i),y=G({margin:0},s),b=!e(p),x=b?p:``,S=A(`recharts-default-tooltip`,d),C=A(`recharts-tooltip-label`,f);b&&m&&c!=null&&(x=m(p,c));var w=g?{role:`status`,"aria-live":`assertive`}:{};return U.createElement(`div`,Et({className:S,style:v},w),U.createElement(`p`,{className:C,style:y},U.isValidElement(x)?x:`${x}`),_())},q=`recharts-tooltip-wrapper`,Bt={visibility:`hidden`};function Vt(e){var t=e.coordinate,n=e.translateX,r=e.translateY;return A(q,{[`${q}-right`]:z(n)&&t&&z(t.x)&&n>=t.x,[`${q}-left`]:z(n)&&t&&z(t.x)&&n=t.y,[`${q}-top`]:z(r)&&t&&z(t.y)&&r0?i:0),d=n[r]+i;if(t[r])return o[r]?u:d;var f=c[r];return f==null?0:o[r]?Math.max(uf+l?Math.max(u,f):Math.max(d,f)}function Ut(e){var t=e.translateX,n=e.translateY;return{transform:e.useTranslate3d?`translate3d(${t}px, ${n}px, 0)`:`translate(${t}px, ${n}px)`}}function Wt(e){var t=e.allowEscapeViewBox,n=e.coordinate,r=e.offsetTop,i=e.offsetLeft,a=e.position,o=e.reverseDirection,s=e.tooltipBox,c=e.useTranslate3d,l=e.viewBox,u,d,f;return s&&s.height>0&&s.width>0&&n?(d=Ht({allowEscapeViewBox:t,coordinate:n,key:`x`,offset:i,position:a,reverseDirection:o,tooltipDimension:s.width,viewBox:l,viewBoxDimension:l.width}),f=Ht({allowEscapeViewBox:t,coordinate:n,key:`y`,offset:r,position:a,reverseDirection:o,tooltipDimension:s.height,viewBox:l,viewBoxDimension:l.height}),u=Ut({translateX:d,translateY:f,useTranslate3d:c})):u=Bt,{cssProperties:u,cssClasses:Vt({translateX:d,translateY:f,coordinate:n})}}function Gt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function J(e){for(var t=1;te.length)&&(t=e.length);for(var n=0,r=Array(t);n({dismissed:!1,dismissedAtCoordinate:{x:0,y:0}})),2),r=n[0],i=n[1];U.useEffect(()=>{var t=t=>{t.key===`Escape`&&i({dismissed:!0,dismissedAtCoordinate:{x:e.coordinate?.x??0,y:e.coordinate?.y??0}})};return document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`keydown`,t)}},[e.coordinate?.x,e.coordinate?.y]),r.dismissed&&((e.coordinate?.x??0)!==r.dismissedAtCoordinate.x||(e.coordinate?.y??0)!==r.dismissedAtCoordinate.y)&&i(J(J({},r),{},{dismissed:!1}));var a=Wt({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:e.lastBoundingBox,useTranslate3d:e.useTranslate3d,viewBox:e.viewBox}),o=a.cssClasses,s=a.cssProperties,c=J(J({},e.hasPortalFromProps?{}:J(J({transition:tn({prefersReducedMotion:t,isAnimationActive:e.isAnimationActive,active:e.active,animationDuration:e.animationDuration,animationEasing:e.animationEasing})},s),{},{pointerEvents:`none`,position:`absolute`,top:0,left:0})),{},{visibility:!r.dismissed&&e.active&&e.hasPayload?`visible`:`hidden`},e.wrapperStyle);return U.createElement(`div`,{xmlns:`http://www.w3.org/1999/xhtml`,tabIndex:-1,className:o,style:c,ref:e.innerRef},e.children)}var rn=U.memo(nn),an=[`x`,`y`,`top`,`left`,`width`,`height`,`className`];function on(){return on=Object.assign?Object.assign.bind():function(e){for(var t=1;t`M${e},${i}v${r}M${a},${t}h${n}`,hn=e=>{var t=e.x,n=t===void 0?0:t,r=e.y,i=r===void 0?0:r,a=e.top,o=a===void 0?0:a,s=e.left,c=s===void 0?0:s,l=e.width,u=l===void 0?0:l,d=e.height,f=d===void 0?0:d,p=e.className,m=fn(e,an),h=cn({x:n,y:i,top:o,left:c,width:u,height:f},m);return!z(n)||!z(i)||!z(u)||!z(f)||!z(o)||!z(c)?null:U.createElement(`path`,on({},pe(h),{className:A(`recharts-cross`,p),d:mn(n,i,u,f,o,c)}))};function gn(e,t,n,r){var i=r/2;return{stroke:`none`,fill:`#ccc`,x:e===`horizontal`?t.x-i:n.left+.5,y:e===`horizontal`?n.top+.5:t.y-i,width:e===`horizontal`?r:n.width-1,height:e===`horizontal`?n.height-1:r}}function _n(e){var t=e.cx,n=e.cy,r=e.radius,i=e.startAngle,a=e.endAngle;return{points:[R(t,n,r,i),R(t,n,r,a)],cx:t,cy:n,radius:r,startAngle:i,endAngle:a}}var vn,yn,bn,xn,Sn,Cn,wn;function Tn(){return Tn=Object.assign?Object.assign.bind():function(e){for(var t=1;tEe(t-e)*Math.min(Math.abs(t-e),359.999),X=e=>{var t=e.cx,n=e.cy,r=e.radius,i=e.angle,a=e.sign,o=e.isExternal,s=e.cornerRadius,c=e.cornerIsExternal,l=s*(o?1:-1)+r,u=Math.asin(s/l)/v,d=c?i:i+a*u,f=R(t,n,l,d),p=R(t,n,r,d),m=c?i-a*u:i;return{center:f,circleTangency:p,lineTangency:R(t,n,l*Math.cos(u*v),m),theta:u}},Dn=e=>{var t=e.cx,n=e.cy,r=e.innerRadius,i=e.outerRadius,a=e.startAngle,o=e.endAngle,s=En(a,o),c=a+s,l=R(t,n,i,a),u=R(t,n,i,c),d=F(vn||=Y([`M `,`,`,` diff --git a/internal/webui/static/assets/CostChart-D5w4taWC.js b/internal/webui/static/assets/CostChart-bIckh8_5.js similarity index 96% rename from internal/webui/static/assets/CostChart-D5w4taWC.js rename to internal/webui/static/assets/CostChart-bIckh8_5.js index ec68d726..d6327da8 100644 --- a/internal/webui/static/assets/CostChart-D5w4taWC.js +++ b/internal/webui/static/assets/CostChart-bIckh8_5.js @@ -1 +1 @@ -import{n as e,t}from"./CartesianGrid-DXT2DP8n.js";import{Tn as n,_n as r,a as i,at as a,gn as o,i as s,r as c,t as l,vn as u,wn as d,xn as f}from"./index-CnBhKFzp.js";var p=n(d(),1),m=f(),h=[`var(--accent)`,`var(--muted)`,`var(--success)`,`var(--warning)`];function g(e,t,n){let r=new Date(e);return Number.isFinite(r.getTime())?new Intl.DateTimeFormat(n===`zh`?`zh-CN`:`en-US`,t?{month:`short`,day:`numeric`}:{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r):``}function _(e,t){return t===`credits`?e.per_model_credits??{}:t===`tokens`?e.per_model_tokens??{}:e.per_model??{}}function v(e,t){return t===`cost`?o(e):t===`tokens`?r(e):u(e)}function y(e,t){return t===`cost`?`¥${e>=10?Math.round(e):Number(e.toFixed(1))}`:t===`tokens`?r(e):u(e)}function b({active:e,payload:t,label:n,daily:r,lang:i,models:a,totalLabel:o,metric:s}){if(!e||!t?.length)return null;let c=new Map(a.map(e=>[e.id,e.label])),l=t.filter(e=>(e.value??0)>0).sort((e,t)=>t.value-e.value),u=t.reduce((e,t)=>e+(t.value??0),0);return(0,m.jsxs)(`div`,{className:`rounded-xl bg-overlay px-3 py-2 text-caption text-overlay-foreground shadow-overlay`,children:[(0,m.jsx)(`div`,{className:`mono text-muted`,children:g(String(n),r,i)}),(0,m.jsxs)(`div`,{className:`mt-1.5 grid gap-1`,children:[l.map(e=>(0,m.jsxs)(`div`,{className:`flex items-center justify-between gap-6`,children:[(0,m.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,m.jsx)(`span`,{className:`size-1.5 rounded-full`,style:{background:h[a.findIndex(t=>t.id===e.dataKey)%h.length]}}),c.get(e.dataKey)||e.dataKey]}),(0,m.jsx)(`span`,{className:`mono font-medium`,children:v(e.value,s)})]},e.dataKey)),(0,m.jsxs)(`div`,{className:`flex items-center justify-between gap-6 border-t border-separator pt-1`,children:[(0,m.jsx)(`span`,{className:`text-muted`,children:o}),(0,m.jsx)(`span`,{className:`mono font-medium`,children:v(u,s)})]})]})]})}function x({series:n,models:r,lang:o,emptyLabel:u,totalLabel:d,metric:f=`credits`}){let v=(0,p.useMemo)(()=>r.map(e=>e.id),[r]),x=(0,p.useMemo)(()=>n.map(e=>{let t=_(e,f),n={at:e.at};for(let e of v){let r=Number(t[e]??0);n[e]=f===`tokens`?r:Number(r.toFixed(4))}return n}),[n,v,f]),S=Math.max(0,...x.map(e=>v.reduce((t,n)=>t+Number(e[n]??0),0)))>0,C=(x.length>1?Date.parse(x[x.length-1].at)-Date.parse(x[0].at):0)>1728e5;return!n.length||!S?(0,m.jsx)(`div`,{className:`grid min-h-56 place-items-center px-6 py-12 text-center text-sm text-muted`,children:u}):(0,m.jsxs)(`div`,{className:`min-w-0`,children:[(0,m.jsx)(`div`,{className:`h-72 w-full`,children:(0,m.jsx)(a,{width:`100%`,height:`100%`,children:(0,m.jsxs)(l,{data:x,margin:{top:8,right:8,bottom:0,left:0},children:[(0,m.jsx)(`defs`,{children:v.map((e,t)=>(0,m.jsxs)(`linearGradient`,{id:`cost-${f}-${e}`,x1:`0`,y1:`0`,x2:`0`,y2:`1`,children:[(0,m.jsx)(`stop`,{offset:`0%`,stopColor:h[t%h.length],stopOpacity:.32}),(0,m.jsx)(`stop`,{offset:`100%`,stopColor:h[t%h.length],stopOpacity:.04})]},e))}),(0,m.jsx)(t,{vertical:!1,stroke:`var(--separator)`,strokeDasharray:`3 6`}),(0,m.jsx)(s,{dataKey:`at`,tickLine:!1,axisLine:!1,minTickGap:28,tick:{fill:`var(--muted)`,fontSize:10,fontFamily:`var(--font-mono)`},tickFormatter:e=>g(e,C,o)}),(0,m.jsx)(c,{width:52,tickLine:!1,axisLine:!1,tick:{fill:`var(--muted)`,fontSize:10,fontFamily:`var(--font-mono)`},tickFormatter:e=>y(e,f)}),(0,m.jsx)(e,{cursor:{stroke:`var(--border)`,strokeDasharray:`3 3`},content:(0,m.jsx)(b,{daily:C,lang:o,models:r,totalLabel:d,metric:f})}),v.map((e,t)=>(0,m.jsx)(i,{type:`monotone`,dataKey:e,stackId:`usage`,stroke:h[t%h.length],strokeWidth:1.5,fill:`url(#cost-${f}-${e})`,isAnimationActive:!1,dot:!1,activeDot:{r:3,strokeWidth:1.2}},e))]})})}),(0,m.jsx)(`div`,{className:`mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-[10px] text-muted`,children:r.map((e,t)=>(0,m.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,m.jsx)(`span`,{className:`size-1.5 rounded-full`,style:{background:h[t%h.length]}}),e.label]},e.id))})]})}export{x as CostChart}; \ No newline at end of file +import{n as e,t}from"./CartesianGrid-DaumKfTu.js";import{Tn as n,_n as r,a as i,at as a,gn as o,i as s,r as c,t as l,vn as u,wn as d,xn as f}from"./index-fj0jyJpQ.js";var p=n(d(),1),m=f(),h=[`var(--accent)`,`var(--muted)`,`var(--success)`,`var(--warning)`];function g(e,t,n){let r=new Date(e);return Number.isFinite(r.getTime())?new Intl.DateTimeFormat(n===`zh`?`zh-CN`:`en-US`,t?{month:`short`,day:`numeric`}:{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r):``}function _(e,t){return t===`credits`?e.per_model_credits??{}:t===`tokens`?e.per_model_tokens??{}:e.per_model??{}}function v(e,t){return t===`cost`?o(e):t===`tokens`?r(e):u(e)}function y(e,t){return t===`cost`?`¥${e>=10?Math.round(e):Number(e.toFixed(1))}`:t===`tokens`?r(e):u(e)}function b({active:e,payload:t,label:n,daily:r,lang:i,models:a,totalLabel:o,metric:s}){if(!e||!t?.length)return null;let c=new Map(a.map(e=>[e.id,e.label])),l=t.filter(e=>(e.value??0)>0).sort((e,t)=>t.value-e.value),u=t.reduce((e,t)=>e+(t.value??0),0);return(0,m.jsxs)(`div`,{className:`rounded-xl bg-overlay px-3 py-2 text-caption text-overlay-foreground shadow-overlay`,children:[(0,m.jsx)(`div`,{className:`mono text-muted`,children:g(String(n),r,i)}),(0,m.jsxs)(`div`,{className:`mt-1.5 grid gap-1`,children:[l.map(e=>(0,m.jsxs)(`div`,{className:`flex items-center justify-between gap-6`,children:[(0,m.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,m.jsx)(`span`,{className:`size-1.5 rounded-full`,style:{background:h[a.findIndex(t=>t.id===e.dataKey)%h.length]}}),c.get(e.dataKey)||e.dataKey]}),(0,m.jsx)(`span`,{className:`mono font-medium`,children:v(e.value,s)})]},e.dataKey)),(0,m.jsxs)(`div`,{className:`flex items-center justify-between gap-6 border-t border-separator pt-1`,children:[(0,m.jsx)(`span`,{className:`text-muted`,children:o}),(0,m.jsx)(`span`,{className:`mono font-medium`,children:v(u,s)})]})]})]})}function x({series:n,models:r,lang:o,emptyLabel:u,totalLabel:d,metric:f=`credits`}){let v=(0,p.useMemo)(()=>r.map(e=>e.id),[r]),x=(0,p.useMemo)(()=>n.map(e=>{let t=_(e,f),n={at:e.at};for(let e of v){let r=Number(t[e]??0);n[e]=f===`tokens`?r:Number(r.toFixed(4))}return n}),[n,v,f]),S=Math.max(0,...x.map(e=>v.reduce((t,n)=>t+Number(e[n]??0),0)))>0,C=(x.length>1?Date.parse(x[x.length-1].at)-Date.parse(x[0].at):0)>1728e5;return!n.length||!S?(0,m.jsx)(`div`,{className:`grid min-h-56 place-items-center px-6 py-12 text-center text-sm text-muted`,children:u}):(0,m.jsxs)(`div`,{className:`min-w-0`,children:[(0,m.jsx)(`div`,{className:`h-72 w-full`,children:(0,m.jsx)(a,{width:`100%`,height:`100%`,children:(0,m.jsxs)(l,{data:x,margin:{top:8,right:8,bottom:0,left:0},children:[(0,m.jsx)(`defs`,{children:v.map((e,t)=>(0,m.jsxs)(`linearGradient`,{id:`cost-${f}-${e}`,x1:`0`,y1:`0`,x2:`0`,y2:`1`,children:[(0,m.jsx)(`stop`,{offset:`0%`,stopColor:h[t%h.length],stopOpacity:.32}),(0,m.jsx)(`stop`,{offset:`100%`,stopColor:h[t%h.length],stopOpacity:.04})]},e))}),(0,m.jsx)(t,{vertical:!1,stroke:`var(--separator)`,strokeDasharray:`3 6`}),(0,m.jsx)(s,{dataKey:`at`,tickLine:!1,axisLine:!1,minTickGap:28,tick:{fill:`var(--muted)`,fontSize:10,fontFamily:`var(--font-mono)`},tickFormatter:e=>g(e,C,o)}),(0,m.jsx)(c,{width:52,tickLine:!1,axisLine:!1,tick:{fill:`var(--muted)`,fontSize:10,fontFamily:`var(--font-mono)`},tickFormatter:e=>y(e,f)}),(0,m.jsx)(e,{cursor:{stroke:`var(--border)`,strokeDasharray:`3 3`},content:(0,m.jsx)(b,{daily:C,lang:o,models:r,totalLabel:d,metric:f})}),v.map((e,t)=>(0,m.jsx)(i,{type:`monotone`,dataKey:e,stackId:`usage`,stroke:h[t%h.length],strokeWidth:1.5,fill:`url(#cost-${f}-${e})`,isAnimationActive:!1,dot:!1,activeDot:{r:3,strokeWidth:1.2}},e))]})})}),(0,m.jsx)(`div`,{className:`mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-[10px] text-muted`,children:r.map((e,t)=>(0,m.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,m.jsx)(`span`,{className:`size-1.5 rounded-full`,style:{background:h[t%h.length]}}),e.label]},e.id))})]})}export{x as CostChart}; \ No newline at end of file diff --git a/internal/webui/static/assets/LiveSparkline-Dinqoyx0.js b/internal/webui/static/assets/LiveSparkline-IqYklHcO.js similarity index 80% rename from internal/webui/static/assets/LiveSparkline-Dinqoyx0.js rename to internal/webui/static/assets/LiveSparkline-IqYklHcO.js index e8876343..425046dc 100644 --- a/internal/webui/static/assets/LiveSparkline-Dinqoyx0.js +++ b/internal/webui/static/assets/LiveSparkline-IqYklHcO.js @@ -1 +1 @@ -import{a as e,at as t,r as n,t as r,xn as i}from"./index-CnBhKFzp.js";var a=i();function o({samples:i,capacity:o,label:s}){let c=i.length?i:[{at:0,value:0}],l=Math.max(1,o,...c.map(e=>e.value));return(0,a.jsx)(`div`,{className:`h-6 w-[120px] shrink-0`,role:`img`,"aria-label":s,children:(0,a.jsx)(t,{width:`100%`,height:`100%`,children:(0,a.jsxs)(r,{data:c,margin:{top:1,right:0,bottom:1,left:0},children:[(0,a.jsx)(n,{hide:!0,domain:[0,l]}),(0,a.jsx)(e,{type:`monotone`,dataKey:`value`,stroke:`var(--foreground)`,strokeOpacity:.7,strokeWidth:1.25,fill:`var(--foreground)`,fillOpacity:.08,isAnimationActive:!1,dot:!1})]})})})}export{o as LiveSparkline}; \ No newline at end of file +import{a as e,at as t,r as n,t as r,xn as i}from"./index-fj0jyJpQ.js";var a=i();function o({samples:i,capacity:o,label:s}){let c=i.length?i:[{at:0,value:0}],l=Math.max(1,o,...c.map(e=>e.value));return(0,a.jsx)(`div`,{className:`h-6 w-[120px] shrink-0`,role:`img`,"aria-label":s,children:(0,a.jsx)(t,{width:`100%`,height:`100%`,children:(0,a.jsxs)(r,{data:c,margin:{top:1,right:0,bottom:1,left:0},children:[(0,a.jsx)(n,{hide:!0,domain:[0,l]}),(0,a.jsx)(e,{type:`monotone`,dataKey:`value`,stroke:`var(--foreground)`,strokeOpacity:.7,strokeWidth:1.25,fill:`var(--foreground)`,fillOpacity:.08,isAnimationActive:!1,dot:!1})]})})})}export{o as LiveSparkline}; \ No newline at end of file diff --git a/internal/webui/static/assets/TrafficChart-Cj0nupcy.js b/internal/webui/static/assets/TrafficChart-CAX_ltfB.js similarity index 99% rename from internal/webui/static/assets/TrafficChart-Cj0nupcy.js rename to internal/webui/static/assets/TrafficChart-CAX_ltfB.js index c1a60aa9..1fffed57 100644 --- a/internal/webui/static/assets/TrafficChart-Cj0nupcy.js +++ b/internal/webui/static/assets/TrafficChart-CAX_ltfB.js @@ -1 +1 @@ -import{n as e,t}from"./CartesianGrid-DXT2DP8n.js";import{$ as n,$t as r,B as i,C as a,D as o,G as s,Q as c,Qt as l,S as u,Sn as d,T as f,Tn as p,U as m,V as h,W as g,Y as _,Yt as v,_ as y,_n as b,_t as x,a as S,at as C,b as w,bn as T,c as E,ct as D,d as ee,dn as O,f as k,fn as A,ft as j,g as M,h as te,hn as ne,i as re,in as N,k as P,lt as F,m as I,mn as ie,mt as L,n as ae,o as oe,p as se,pt as R,r as ce,rn as le,s as ue,st as z,tt as de,un as fe,v as pe,w as me,wn as he,x as ge,xn as _e,y as ve,yn as B,yt as ye}from"./index-CnBhKFzp.js";var V=p(he()),be=[`animationElapsedTime`,`isAnimating`,`isEntrance`,`visibleLength`,`strokeDasharray`,`connectNulls`];function H(){return H=Object.assign?Object.assign.bind():function(e){for(var t=1;te+t,0);if(!i)return U(t,e);for(var a=Math.floor(e/i),o=e%i,s=[],c=0,l=0;co){s=[...r.slice(0,c),o-l];break}}var f=s.length%2==0?[0,t]:[t];return[...Te(r,a),...s,...f].map(e=>`${e}px`).join(`, `)}function De(e,t,n){return e?Ee(n,t,`${e}`.split(/[,\s]+/gim).map(e=>parseFloat(e))):U(t,n)}function Oe(e){e.animationElapsedTime,e.isAnimating,e.isEntrance;var t=e.visibleLength,n=e.strokeDasharray,r=e.connectNulls,i=xe(e,be),a=r??!1,o;if(t!=null){var s=i.pathRef;o=De(n,Ce(s?.current??null),t)}else n!=null&&(o=String(n));return V.createElement(_,H({},i,{connectNulls:a,strokeDasharray:o}))}function ke(e){var t=(0,V.useRef)(0),n=(0,V.useRef)(0),r=(0,V.useRef)(!1),i=(0,V.useRef)(e);return i.current!==e&&(t.current=n.current,i.current=e),(0,V.useCallback)((e,i)=>{if(r.current)return null;var a=Math.min(N(t.current+e*i),i);return e>0&&i>0&&(n.current=Math.max(n.current,a),a>=i)?(r.current=!0,null):a},[])}var Ae=[`children`];function je(e,t){if(e==null)return{};var n,r,i=Me(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r({x:0,y:0,value:0}),errorBarOffset:0});function Pe(e){var t=e.children,n=je(e,Ae);return V.createElement(Ne.Provider,{value:n},t)}var W=(e,t,n,r)=>i(e,`xAxis`,t,r),G=(e,t,n,r)=>h(e,`xAxis`,t,r),K=(e,t,n,r)=>i(e,`yAxis`,n,r),q=(e,t,n,r)=>h(e,`yAxis`,n,r),Fe=x([n,W,K,G,q],(e,t,n,r,i)=>L(e,`xAxis`)?D(t,r,!1):D(n,i,!1)),Ie=(e,t,n,r,i)=>i;function Le(e){return e.type===`line`}var Re=x([m,Ie],(e,t)=>e.filter(Le).find(e=>e.id===t)),ze=x([n,W,K,G,q,Re,Fe,s],(e,t,n,r,i,a,o,s)=>{var c=s.chartData,l=s.dataStartIndex,u=s.dataEndIndex;if(!(a==null||t==null||n==null||r==null||i==null||r.length===0||i.length===0||o==null||e!==`horizontal`&&e!==`vertical`)){var d=a.dataKey,f=a.data,p=f!=null&&f.length>0?f:c?.slice(l,u+1);if(p!=null)return at({layout:e,xAxis:t,yAxis:n,xAxisTicks:r,yAxisTicks:i,dataKey:d,bandSize:o,displayedData:p})}}),Be=[`id`],Ve=[`type`,`layout`,`connectNulls`,`needClip`,`shape`,`strokeDasharray`],He=[`activeDot`,`animateNewValues`,`animationBegin`,`animationDuration`,`animationEasing`,`connectNulls`,`dot`,`hide`,`isAnimationActive`,`label`,`legendType`,`xAxisId`,`yAxisId`,`id`];function J(){return J=Object.assign?Object.assign.bind():function(e){for(var t=1;t0?t/n:0}var Q={activeDot:!0,animateNewValues:!0,animationBegin:0,animationDuration:1500,animationEasing:`ease`,animationInterpolateFn:(e,t)=>{if(e==null)return[];if(t===1)return e.flatMap(e=>e.status===`removed`?[]:[e.next]);var n=Je(e),r=[];for(var i of e)if(i.status===`matched`)r.push(Z(Z({},i.next),{},{x:l(i.prev.x,i.next.x,t),y:l(i.prev.y,i.next.y,t)}));else if(i.status===`added`){if(i.next.x!=null){var a=i.next.x-n;r.push(Z(Z({},i.next),{},{x:l(a,i.next.x,t),y:i.next.y}))}else r.push(i.next)}else if(i.status===`removed`&&i.prev.x!=null){var o=i.prev.x+n;r.push(Z(Z({},i.prev),{},{x:l(i.prev.x,o,t),y:i.prev.y}))}return r},animationMatchBy:ve,connectNulls:!1,dot:!0,fill:`#fff`,hide:!1,isAnimationActive:`auto`,label:!1,legendType:`line`,shape:Oe,stroke:`#3182bd`,strokeWidth:1,xAxisId:0,yAxisId:0,zIndex:g.line,type:`linear`},Ye=e=>{var t=e.dataKey,n=e.name,r=e.stroke,i=e.legendType;return[{inactive:e.hide,dataKey:t,type:i,color:r,value:j(n,t),payload:e}]},Xe=V.memo(e=>{var t=e.dataKey,n=e.data,r=e.stroke,i=e.strokeWidth,a=e.fill,o=e.name,s=e.hide,c=e.unit,l=e.formatter,u=e.tooltipType,d=e.id,f={dataDefinedOnItem:n,getPosition:le,settings:{stroke:r,strokeWidth:i,fill:a,dataKey:t,nameKey:void 0,name:j(o,t),hide:s,type:u,color:r,unit:c,formatter:l,graphicalItemId:d}};return V.createElement(ge,{tooltipEntrySettings:f})});function Ze(e){var t=e.clipPathId,n=e.points,r=e.props,i=r.dot,a=r.dataKey,o=r.needClip;r.id;var s=Y(r,Be),c=A(s);return V.createElement(I,{points:n,dot:i,className:`recharts-line-dots`,dotClassName:`recharts-line-dot`,dataKey:a,baseProps:c,needClip:o,clipPathId:t})}function Qe(e){var t=e.showLabels,n=e.children,r=e.points,i=(0,V.useMemo)(()=>r?.map(e=>{var t={x:e.x??0,y:e.y??0,width:0,lowerWidth:0,upperWidth:0,height:0};return Z(Z({},t),{},{value:e.value,payload:e.payload,viewBox:t,parentViewBox:void 0,fill:void 0})}),[r]);return V.createElement(me,{value:t?i:void 0},n)}function $e(e){var t=e.clipPathId,n=e.pathRef,r=e.points,i=e.props,a=e.animationElapsedTime,o=e.isAnimating,s=e.isEntrance,c=e.visibleLength,l=i.type,d=i.layout,f=i.connectNulls,p=i.needClip,m=i.shape,h=i.strokeDasharray,g=Y(i,Ve),_=Z(Z({},O(g)),{},{fill:`none`,className:`recharts-line-curve`,clipPath:p?`url(#clipPath-${t})`:void 0,points:r,type:l,layout:d,connectNulls:f,strokeDasharray:h??i.strokeDasharray,pathRef:n,animationElapsedTime:a,isAnimating:o,isEntrance:i.animateNewValues?s:!1,visibleLength:c});return V.createElement(V.Fragment,null,r?.length>1&&V.createElement(u,{option:m,DefaultShape:Q.shape,shapeProps:_}),V.createElement(Ze,{points:r,clipPathId:t,props:i}))}function et(e){var t=e.clipPathId,n=e.props,r=e.pathRef,i=e.previousPointsRef,a=n.points,o=n.isAnimationActive,s=n.animationBegin,c=n.animationDuration,l=n.animationEasing,u=n.animationMatchBy,d=n.animationInterpolateFn,p=n.layout,m=qe(r.current),h=pe(n.onAnimationStart,n.onAnimationEnd),g=h.isAnimating,_=h.handleAnimationStart,v=h.handleAnimationEnd,b=!g,x=ke(a),S=(0,V.useCallback)(e=>e>0&&m>0,[m]);return V.createElement(Qe,{points:a,showLabels:b},n.children,V.createElement(y,{animationInput:a,animationIdPrefix:`recharts-line-`,items:a,previousItemsRef:i,isAnimationActive:o,animationBegin:s,animationDuration:c,animationEasing:l,onAnimationStart:_,onAnimationEnd:v,animationInterpolateFn:d,animationMatchBy:u,shouldUpdatePreviousRef:S,layout:p},(e,i,a)=>{var o=g||i<1,s=o?x(i,m):null;return V.createElement($e,{props:n,points:e,clipPathId:t,pathRef:r,animationElapsedTime:i,isAnimating:o,isEntrance:a,visibleLength:s})}),V.createElement(f,{label:n.label}))}function tt(e){var t=e.clipPathId,n=e.props,r=(0,V.useRef)(null),i=(0,V.useRef)(null);return V.createElement(et,{props:n,clipPathId:t,previousPointsRef:r,pathRef:i})}var nt=(e,t)=>({x:e.x??void 0,y:e.y??void 0,value:e.value,errorVal:R(e.payload,t)}),rt=class extends V.Component{render(){var e=this.props,t=e.hide,n=e.dot,r=e.points,i=e.className,o=e.xAxisId,s=e.yAxisId,c=e.top,l=e.left,u=e.width,f=e.height,p=e.id,m=e.needClip,h=e.zIndex;if(t)return null;var g=d(`recharts-line`,i),_=p,v=oe(n),y=v.r,b=v.strokeWidth,x=a(n),S=y*2+b,C=m?`url(#clipPath-${x?``:`dots-`}${_})`:void 0;return V.createElement(P,{zIndex:h},V.createElement(fe,{className:g},m&&V.createElement(`defs`,null,V.createElement(ue,{clipPathId:_,xAxisId:o,yAxisId:s}),!x&&V.createElement(`clipPath`,{id:`clipPath-dots-${_}`},V.createElement(`rect`,{x:l-S/2,y:c-S/2,width:u+S,height:f+S}))),V.createElement(Pe,{xAxisId:o,yAxisId:s,data:r,dataPointFormatter:nt,errorBarOffset:0},V.createElement(tt,{props:this.props,clipPathId:_}))),V.createElement(k,{activeDot:this.props.activeDot,points:r,mainColor:this.props.stroke,itemDataKey:this.props.dataKey,clipPath:C}))}};function it(e){var t=v(e,Q),n=t.activeDot,r=t.animateNewValues,i=t.animationBegin,a=t.animationDuration,o=t.animationEasing,s=t.connectNulls,c=t.dot,l=t.hide,u=t.isAnimationActive,d=t.label,f=t.legendType,p=t.xAxisId,m=t.yAxisId,h=t.id,g=Y(t,He),_=E(p,m).needClip,y=se(),b=de(),x=z(),S=ye(e=>ze(e,p,m,x,h));if(b!==`horizontal`&&b!==`vertical`||S==null||y==null)return null;var C=y.height,w=y.width,T=y.x,D=y.y;return V.createElement(rt,J({},g,{id:h,connectNulls:s,dot:c,activeDot:n,animateNewValues:r,animationBegin:i,animationDuration:a,animationEasing:o,isAnimationActive:u,hide:l,label:d,legendType:f,xAxisId:p,yAxisId:m,points:S,layout:b,height:C,width:w,left:T,top:D,needClip:_}))}function at(e){var t=e.layout,n=e.xAxis,i=e.yAxis,a=e.xAxisTicks,o=e.yAxisTicks,s=e.dataKey,c=e.bandSize;return e.displayedData.map((e,l)=>{var u=R(e,s);if(t===`horizontal`)return{x:F({axis:n,ticks:a,bandSize:c,entry:e,index:l}),y:(r(u)?null:i.scale.map(u))??null,value:u,payload:e};var d=r(u)?null:n.scale.map(u),f=F({axis:i,ticks:o,bandSize:c,entry:e,index:l});return d==null||f==null?null:{x:d,y:f,value:u,payload:e}}).filter(Boolean)}function ot(e){var t=v(e,Q),n=z();return V.createElement(M,{id:t.id,type:`line`},e=>V.createElement(V.Fragment,null,V.createElement(w,{legendPayload:Ye(t)}),V.createElement(Xe,{dataKey:t.dataKey,data:t.data,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,name:t.name,hide:t.hide,unit:t.unit,formatter:t.formatter,tooltipType:t.tooltipType,id:e}),V.createElement(te,{type:`line`,id:e,data:t.data,xAxisId:t.xAxisId,yAxisId:t.yAxisId,zAxisId:0,dataKey:t.dataKey,hide:t.hide,isPanorama:n}),V.createElement(it,J({},t,{id:e}))))}var st=V.memo(ot,c);st.displayName=`Line`;var ct=[`axis`],lt=(0,V.forwardRef)((e,t)=>V.createElement(ae,{chartName:`ComposedChart`,defaultTooltipEventType:`axis`,validateTooltipEventTypes:ct,tooltipPayloadSearcher:o,categoricalChartProps:e,ref:t})),ut={metric:24,title:18,section:15,body:13,xs:12,caption:12},$=_e();function dt(e,t,n){let r=new Date(e);return Number.isFinite(r.getTime())?new Intl.DateTimeFormat(n===`zh`?`zh-CN`:`en-US`,t?{month:`short`,day:`numeric`}:{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r):``}function ft(e){if(e<=1)return 1;let t=10**Math.floor(Math.log10(e)),n=e/t;return(n<=1?1:n<=2?2:n<=5?5:10)*t}function pt(e){let t=Math.max(0,e.ok??e.requests-e.error),n=Math.min(Math.max(0,e.requests-t),Math.max(0,e.requests));return{...e,okCount:t,errorCount:n,inputTokens:e.prompt_tokens??0,outputTokens:e.completion_tokens??0,cacheTokens:e.cache_read_tokens??0,p50:e.latency_p50_ms??null,p95:e.latency_p95_ms??null}}function mt({active:e,payload:t,daily:n,lang:r,specs:i,format:a,totalLabel:o,total:s}){if(!e||!t?.[0])return null;let c=t[0].payload;return(0,$.jsxs)(`div`,{className:`rounded-xl bg-overlay px-3 py-2 text-caption text-overlay-foreground shadow-overlay`,children:[(0,$.jsx)(`div`,{className:`mono text-muted`,children:dt(c.at,n,r)}),(0,$.jsxs)(`div`,{className:`mt-1.5 grid gap-1`,children:[i.map(e=>(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-6`,children:[(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:`size-1.5 rounded-full`,style:{background:e.color}}),e.label]}),(0,$.jsx)(`span`,{className:`mono font-medium`,children:a(c[e.key])})]},String(e.key))),s&&o?(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-6 pt-1`,children:[(0,$.jsx)(`span`,{className:`text-muted`,children:o}),(0,$.jsx)(`span`,{className:`mono font-medium`,children:a(s(c))})]}):null]})]})}function ht({series:n,lang:r,emptyLabel:i,okLabel:a,errorLabel:o,onSelectRange:s,selectHint:c,labels:l,initialMetric:u=`requests`}){let[d,f]=(0,V.useState)(u),[p,m]=(0,V.useState)(null),[h,g]=(0,V.useState)(null),_=(0,V.useRef)(!1),v=(0,V.useRef)(null),y=(0,V.useMemo)(()=>n.map(pt),[n]),x=y[0],w=y[y.length-1],E=(x&&w?Date.parse(w.at)-Date.parse(x.at):0)>1728e5,D=l??{requests:`Requests`,tokens:`Tokens`,latency:`p95 latency`,input:`input`,output:`output`,cacheRead:`cache read`,p50:`p50`,p95:`p95`,total:`total`},O=d===`tokens`?[{key:`inputTokens`,label:D.input,color:`var(--foreground)`,area:!0,width:1.5,opacity:.75},{key:`outputTokens`,label:D.output,color:`var(--success)`,area:!0,width:1.5},{key:`cacheTokens`,label:D.cacheRead,color:`var(--muted)`,width:1.25,opacity:.8}]:d===`latency`?[{key:`p95`,label:D.p95,color:`var(--warning)`,area:!0,width:1.75},{key:`p50`,label:D.p50,color:`var(--muted)`,width:1.25,opacity:.85}]:[{key:`okCount`,label:a,color:`var(--success)`,area:!0,width:1.75},{key:`errorCount`,label:o,color:`var(--danger)`,area:!0,width:1.25,opacity:.7}],k=e=>e==null?`—`:d===`latency`?B(e):b(e),A=d===`requests`?e=>e.requests:d===`tokens`?e=>e.inputTokens+e.outputTokens:void 0,j=y.flatMap(e=>O.map(t=>Number(e[t.key]??0))),M=d===`requests`?Math.max(0,...y.map(e=>e.requests)):Math.max(0,...j),te=ft(M),N=y.some(e=>e.requests>0),P=y.map(e=>`${e.at}:${e.requests}:${e.error}`).join(`|`);(0,V.useLayoutEffect)(()=>{let e=v.current;if(!e||!N||_.current)return;let t=!1,n=null,r=T.context(()=>{let r=T.matchMedia(),i=()=>{let t=T.utils.toArray(`.recharts-area-area`,e),n=T.utils.toArray(`.recharts-line-curve`,e);return!t.length&&!n.length?!1:(r.add(`(prefers-reduced-motion: reduce)`,()=>{T.set(n,{clearProps:`strokeDashoffset,strokeDasharray`}),T.set(t,{clearProps:`autoAlpha`})}),r.add(`(prefers-reduced-motion: no-preference)`,()=>{T.fromTo(t,{autoAlpha:0},{autoAlpha:1,duration:.45,ease:`power2.out`,stagger:.05}),n.forEach((e,t)=>{let n=e.getTotalLength();T.fromTo(e,{strokeDasharray:n,strokeDashoffset:n},{strokeDashoffset:0,duration:.7,delay:t*.05,ease:`power2.out`})})}),!0)};if(i()){t=!0,_.current=!0;return}n=new MutationObserver(()=>{t||i()&&(t=!0,_.current=!0,n?.disconnect())}),n.observe(e,{childList:!0,subtree:!0})},e);return()=>{n?.disconnect(),r.revert()}},[N,P]);let F=y.length>1?Date.parse(y[1].at)-Date.parse(y[0].at):36e5,I=()=>{if(p&&h&&s){let e=Date.parse(p),t=Date.parse(h);if(Number.isFinite(e)&&Number.isFinite(t)){let n=Math.min(e,t),r=Math.max(e,t)+F;s(new Date(n).toISOString(),new Date(r).toISOString())}}m(null),g(null)},L=e=>{let t=e?.activeLabel;return t==null?null:String(t)};return!n.length||!N?(0,$.jsx)(ne,{emptyLabel:i}):(0,$.jsxs)(`div`,{ref:v,className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`mb-3 flex justify-end`,children:(0,$.jsx)(ie,{value:d,onChange:e=>f(e),ariaLabel:D.requests,options:[{id:`requests`,label:D.requests},{id:`tokens`,label:D.tokens},{id:`latency`,label:D.latency}]})}),(0,$.jsx)(`div`,{className:`h-56 w-full`,children:(0,$.jsx)(C,{width:`100%`,height:`100%`,children:(0,$.jsxs)(lt,{data:y,margin:{top:8,right:8,bottom:0,left:0},style:s?{cursor:`crosshair`,userSelect:`none`}:void 0,onMouseDown:s?e=>{let t=L(e);t&&(m(t),g(t))}:void 0,onMouseMove:s?e=>{if(!p)return;let t=L(e);t&&g(t)}:void 0,onMouseUp:s?I:void 0,onMouseLeave:s?()=>{m(null),g(null)}:void 0,children:[(0,$.jsx)(`defs`,{children:O.filter(e=>e.area).map(e=>(0,$.jsxs)(`linearGradient`,{id:`traffic-fill-${String(e.key)}`,x1:`0`,y1:`0`,x2:`0`,y2:`1`,children:[(0,$.jsx)(`stop`,{offset:`0%`,stopColor:e.color,stopOpacity:.22}),(0,$.jsx)(`stop`,{offset:`100%`,stopColor:e.color,stopOpacity:.02})]},String(e.key)))}),(0,$.jsx)(t,{vertical:!1,stroke:`var(--separator)`,strokeDasharray:`3 6`}),(0,$.jsx)(re,{dataKey:`at`,tickLine:!1,axisLine:!1,minTickGap:28,tick:{fill:`var(--muted)`,fontSize:ut.caption,fontFamily:`var(--font-mono)`},tickFormatter:e=>dt(e,E,r)}),(0,$.jsx)(ce,{width:d===`latency`?44:36,domain:[0,te],tickLine:!1,axisLine:!1,allowDecimals:!1,tick:{fill:`var(--muted)`,fontSize:ut.caption,fontFamily:`var(--font-mono)`},tickFormatter:e=>d===`latency`?B(e):b(e)}),(0,$.jsx)(e,{cursor:{stroke:`var(--border)`,strokeDasharray:`3 3`},content:(0,$.jsx)(mt,{daily:E,lang:r,specs:O,format:k,totalLabel:D.total,total:A})}),O.filter(e=>e.area).map(e=>(0,$.jsx)(S,{type:`monotone`,dataKey:e.key,stroke:`none`,fill:`url(#traffic-fill-${String(e.key)})`,isAnimationActive:!1,activeDot:!1,dot:!1,connectNulls:!0},`area-${String(e.key)}`)),O.map(e=>(0,$.jsx)(st,{type:`monotone`,dataKey:e.key,stroke:e.color,strokeWidth:e.width??1.5,strokeOpacity:e.opacity??1,dot:!1,isAnimationActive:!1,connectNulls:!0,activeDot:{r:4,fill:`var(--surface)`,stroke:e.color,strokeWidth:1.5}},`line-${String(e.key)}`)),p&&h?(0,$.jsx)(ee,{x1:p,x2:h,fill:`var(--foreground)`,fillOpacity:.06,stroke:`none`,ifOverflow:`visible`}):null]})})}),(0,$.jsxs)(`div`,{className:`mt-2 flex min-h-5 items-center justify-between gap-3 text-caption text-muted`,children:[(0,$.jsx)(`div`,{className:`flex items-center gap-3`,children:O.map(e=>(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:`size-1.5 rounded-full`,style:{background:e.color}}),e.label]},String(e.key)))}),(0,$.jsxs)(`span`,{className:`flex items-center gap-3`,children:[s&&c?(0,$.jsx)(`span`,{children:c}):null,(0,$.jsxs)(`span`,{className:`mono`,children:[k(M),` peak`]})]})]})]})}export{ht as TrafficChart}; \ No newline at end of file +import{n as e,t}from"./CartesianGrid-DaumKfTu.js";import{$ as n,$t as r,B as i,C as a,D as o,G as s,Q as c,Qt as l,S as u,Sn as d,T as f,Tn as p,U as m,V as h,W as g,Y as _,Yt as v,_ as y,_n as b,_t as x,a as S,at as C,b as w,bn as T,c as E,ct as D,d as ee,dn as O,f as k,fn as A,ft as j,g as M,h as te,hn as ne,i as re,in as N,k as P,lt as F,m as I,mn as ie,mt as L,n as ae,o as oe,p as se,pt as R,r as ce,rn as le,s as ue,st as z,tt as de,un as fe,v as pe,w as me,wn as he,x as ge,xn as _e,y as ve,yn as B,yt as ye}from"./index-fj0jyJpQ.js";var V=p(he()),be=[`animationElapsedTime`,`isAnimating`,`isEntrance`,`visibleLength`,`strokeDasharray`,`connectNulls`];function H(){return H=Object.assign?Object.assign.bind():function(e){for(var t=1;te+t,0);if(!i)return U(t,e);for(var a=Math.floor(e/i),o=e%i,s=[],c=0,l=0;co){s=[...r.slice(0,c),o-l];break}}var f=s.length%2==0?[0,t]:[t];return[...Te(r,a),...s,...f].map(e=>`${e}px`).join(`, `)}function De(e,t,n){return e?Ee(n,t,`${e}`.split(/[,\s]+/gim).map(e=>parseFloat(e))):U(t,n)}function Oe(e){e.animationElapsedTime,e.isAnimating,e.isEntrance;var t=e.visibleLength,n=e.strokeDasharray,r=e.connectNulls,i=xe(e,be),a=r??!1,o;if(t!=null){var s=i.pathRef;o=De(n,Ce(s?.current??null),t)}else n!=null&&(o=String(n));return V.createElement(_,H({},i,{connectNulls:a,strokeDasharray:o}))}function ke(e){var t=(0,V.useRef)(0),n=(0,V.useRef)(0),r=(0,V.useRef)(!1),i=(0,V.useRef)(e);return i.current!==e&&(t.current=n.current,i.current=e),(0,V.useCallback)((e,i)=>{if(r.current)return null;var a=Math.min(N(t.current+e*i),i);return e>0&&i>0&&(n.current=Math.max(n.current,a),a>=i)?(r.current=!0,null):a},[])}var Ae=[`children`];function je(e,t){if(e==null)return{};var n,r,i=Me(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r({x:0,y:0,value:0}),errorBarOffset:0});function Pe(e){var t=e.children,n=je(e,Ae);return V.createElement(Ne.Provider,{value:n},t)}var W=(e,t,n,r)=>i(e,`xAxis`,t,r),G=(e,t,n,r)=>h(e,`xAxis`,t,r),K=(e,t,n,r)=>i(e,`yAxis`,n,r),q=(e,t,n,r)=>h(e,`yAxis`,n,r),Fe=x([n,W,K,G,q],(e,t,n,r,i)=>L(e,`xAxis`)?D(t,r,!1):D(n,i,!1)),Ie=(e,t,n,r,i)=>i;function Le(e){return e.type===`line`}var Re=x([m,Ie],(e,t)=>e.filter(Le).find(e=>e.id===t)),ze=x([n,W,K,G,q,Re,Fe,s],(e,t,n,r,i,a,o,s)=>{var c=s.chartData,l=s.dataStartIndex,u=s.dataEndIndex;if(!(a==null||t==null||n==null||r==null||i==null||r.length===0||i.length===0||o==null||e!==`horizontal`&&e!==`vertical`)){var d=a.dataKey,f=a.data,p=f!=null&&f.length>0?f:c?.slice(l,u+1);if(p!=null)return at({layout:e,xAxis:t,yAxis:n,xAxisTicks:r,yAxisTicks:i,dataKey:d,bandSize:o,displayedData:p})}}),Be=[`id`],Ve=[`type`,`layout`,`connectNulls`,`needClip`,`shape`,`strokeDasharray`],He=[`activeDot`,`animateNewValues`,`animationBegin`,`animationDuration`,`animationEasing`,`connectNulls`,`dot`,`hide`,`isAnimationActive`,`label`,`legendType`,`xAxisId`,`yAxisId`,`id`];function J(){return J=Object.assign?Object.assign.bind():function(e){for(var t=1;t0?t/n:0}var Q={activeDot:!0,animateNewValues:!0,animationBegin:0,animationDuration:1500,animationEasing:`ease`,animationInterpolateFn:(e,t)=>{if(e==null)return[];if(t===1)return e.flatMap(e=>e.status===`removed`?[]:[e.next]);var n=Je(e),r=[];for(var i of e)if(i.status===`matched`)r.push(Z(Z({},i.next),{},{x:l(i.prev.x,i.next.x,t),y:l(i.prev.y,i.next.y,t)}));else if(i.status===`added`){if(i.next.x!=null){var a=i.next.x-n;r.push(Z(Z({},i.next),{},{x:l(a,i.next.x,t),y:i.next.y}))}else r.push(i.next)}else if(i.status===`removed`&&i.prev.x!=null){var o=i.prev.x+n;r.push(Z(Z({},i.prev),{},{x:l(i.prev.x,o,t),y:i.prev.y}))}return r},animationMatchBy:ve,connectNulls:!1,dot:!0,fill:`#fff`,hide:!1,isAnimationActive:`auto`,label:!1,legendType:`line`,shape:Oe,stroke:`#3182bd`,strokeWidth:1,xAxisId:0,yAxisId:0,zIndex:g.line,type:`linear`},Ye=e=>{var t=e.dataKey,n=e.name,r=e.stroke,i=e.legendType;return[{inactive:e.hide,dataKey:t,type:i,color:r,value:j(n,t),payload:e}]},Xe=V.memo(e=>{var t=e.dataKey,n=e.data,r=e.stroke,i=e.strokeWidth,a=e.fill,o=e.name,s=e.hide,c=e.unit,l=e.formatter,u=e.tooltipType,d=e.id,f={dataDefinedOnItem:n,getPosition:le,settings:{stroke:r,strokeWidth:i,fill:a,dataKey:t,nameKey:void 0,name:j(o,t),hide:s,type:u,color:r,unit:c,formatter:l,graphicalItemId:d}};return V.createElement(ge,{tooltipEntrySettings:f})});function Ze(e){var t=e.clipPathId,n=e.points,r=e.props,i=r.dot,a=r.dataKey,o=r.needClip;r.id;var s=Y(r,Be),c=A(s);return V.createElement(I,{points:n,dot:i,className:`recharts-line-dots`,dotClassName:`recharts-line-dot`,dataKey:a,baseProps:c,needClip:o,clipPathId:t})}function Qe(e){var t=e.showLabels,n=e.children,r=e.points,i=(0,V.useMemo)(()=>r?.map(e=>{var t={x:e.x??0,y:e.y??0,width:0,lowerWidth:0,upperWidth:0,height:0};return Z(Z({},t),{},{value:e.value,payload:e.payload,viewBox:t,parentViewBox:void 0,fill:void 0})}),[r]);return V.createElement(me,{value:t?i:void 0},n)}function $e(e){var t=e.clipPathId,n=e.pathRef,r=e.points,i=e.props,a=e.animationElapsedTime,o=e.isAnimating,s=e.isEntrance,c=e.visibleLength,l=i.type,d=i.layout,f=i.connectNulls,p=i.needClip,m=i.shape,h=i.strokeDasharray,g=Y(i,Ve),_=Z(Z({},O(g)),{},{fill:`none`,className:`recharts-line-curve`,clipPath:p?`url(#clipPath-${t})`:void 0,points:r,type:l,layout:d,connectNulls:f,strokeDasharray:h??i.strokeDasharray,pathRef:n,animationElapsedTime:a,isAnimating:o,isEntrance:i.animateNewValues?s:!1,visibleLength:c});return V.createElement(V.Fragment,null,r?.length>1&&V.createElement(u,{option:m,DefaultShape:Q.shape,shapeProps:_}),V.createElement(Ze,{points:r,clipPathId:t,props:i}))}function et(e){var t=e.clipPathId,n=e.props,r=e.pathRef,i=e.previousPointsRef,a=n.points,o=n.isAnimationActive,s=n.animationBegin,c=n.animationDuration,l=n.animationEasing,u=n.animationMatchBy,d=n.animationInterpolateFn,p=n.layout,m=qe(r.current),h=pe(n.onAnimationStart,n.onAnimationEnd),g=h.isAnimating,_=h.handleAnimationStart,v=h.handleAnimationEnd,b=!g,x=ke(a),S=(0,V.useCallback)(e=>e>0&&m>0,[m]);return V.createElement(Qe,{points:a,showLabels:b},n.children,V.createElement(y,{animationInput:a,animationIdPrefix:`recharts-line-`,items:a,previousItemsRef:i,isAnimationActive:o,animationBegin:s,animationDuration:c,animationEasing:l,onAnimationStart:_,onAnimationEnd:v,animationInterpolateFn:d,animationMatchBy:u,shouldUpdatePreviousRef:S,layout:p},(e,i,a)=>{var o=g||i<1,s=o?x(i,m):null;return V.createElement($e,{props:n,points:e,clipPathId:t,pathRef:r,animationElapsedTime:i,isAnimating:o,isEntrance:a,visibleLength:s})}),V.createElement(f,{label:n.label}))}function tt(e){var t=e.clipPathId,n=e.props,r=(0,V.useRef)(null),i=(0,V.useRef)(null);return V.createElement(et,{props:n,clipPathId:t,previousPointsRef:r,pathRef:i})}var nt=(e,t)=>({x:e.x??void 0,y:e.y??void 0,value:e.value,errorVal:R(e.payload,t)}),rt=class extends V.Component{render(){var e=this.props,t=e.hide,n=e.dot,r=e.points,i=e.className,o=e.xAxisId,s=e.yAxisId,c=e.top,l=e.left,u=e.width,f=e.height,p=e.id,m=e.needClip,h=e.zIndex;if(t)return null;var g=d(`recharts-line`,i),_=p,v=oe(n),y=v.r,b=v.strokeWidth,x=a(n),S=y*2+b,C=m?`url(#clipPath-${x?``:`dots-`}${_})`:void 0;return V.createElement(P,{zIndex:h},V.createElement(fe,{className:g},m&&V.createElement(`defs`,null,V.createElement(ue,{clipPathId:_,xAxisId:o,yAxisId:s}),!x&&V.createElement(`clipPath`,{id:`clipPath-dots-${_}`},V.createElement(`rect`,{x:l-S/2,y:c-S/2,width:u+S,height:f+S}))),V.createElement(Pe,{xAxisId:o,yAxisId:s,data:r,dataPointFormatter:nt,errorBarOffset:0},V.createElement(tt,{props:this.props,clipPathId:_}))),V.createElement(k,{activeDot:this.props.activeDot,points:r,mainColor:this.props.stroke,itemDataKey:this.props.dataKey,clipPath:C}))}};function it(e){var t=v(e,Q),n=t.activeDot,r=t.animateNewValues,i=t.animationBegin,a=t.animationDuration,o=t.animationEasing,s=t.connectNulls,c=t.dot,l=t.hide,u=t.isAnimationActive,d=t.label,f=t.legendType,p=t.xAxisId,m=t.yAxisId,h=t.id,g=Y(t,He),_=E(p,m).needClip,y=se(),b=de(),x=z(),S=ye(e=>ze(e,p,m,x,h));if(b!==`horizontal`&&b!==`vertical`||S==null||y==null)return null;var C=y.height,w=y.width,T=y.x,D=y.y;return V.createElement(rt,J({},g,{id:h,connectNulls:s,dot:c,activeDot:n,animateNewValues:r,animationBegin:i,animationDuration:a,animationEasing:o,isAnimationActive:u,hide:l,label:d,legendType:f,xAxisId:p,yAxisId:m,points:S,layout:b,height:C,width:w,left:T,top:D,needClip:_}))}function at(e){var t=e.layout,n=e.xAxis,i=e.yAxis,a=e.xAxisTicks,o=e.yAxisTicks,s=e.dataKey,c=e.bandSize;return e.displayedData.map((e,l)=>{var u=R(e,s);if(t===`horizontal`)return{x:F({axis:n,ticks:a,bandSize:c,entry:e,index:l}),y:(r(u)?null:i.scale.map(u))??null,value:u,payload:e};var d=r(u)?null:n.scale.map(u),f=F({axis:i,ticks:o,bandSize:c,entry:e,index:l});return d==null||f==null?null:{x:d,y:f,value:u,payload:e}}).filter(Boolean)}function ot(e){var t=v(e,Q),n=z();return V.createElement(M,{id:t.id,type:`line`},e=>V.createElement(V.Fragment,null,V.createElement(w,{legendPayload:Ye(t)}),V.createElement(Xe,{dataKey:t.dataKey,data:t.data,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,name:t.name,hide:t.hide,unit:t.unit,formatter:t.formatter,tooltipType:t.tooltipType,id:e}),V.createElement(te,{type:`line`,id:e,data:t.data,xAxisId:t.xAxisId,yAxisId:t.yAxisId,zAxisId:0,dataKey:t.dataKey,hide:t.hide,isPanorama:n}),V.createElement(it,J({},t,{id:e}))))}var st=V.memo(ot,c);st.displayName=`Line`;var ct=[`axis`],lt=(0,V.forwardRef)((e,t)=>V.createElement(ae,{chartName:`ComposedChart`,defaultTooltipEventType:`axis`,validateTooltipEventTypes:ct,tooltipPayloadSearcher:o,categoricalChartProps:e,ref:t})),ut={metric:24,title:18,section:15,body:13,xs:12,caption:12},$=_e();function dt(e,t,n){let r=new Date(e);return Number.isFinite(r.getTime())?new Intl.DateTimeFormat(n===`zh`?`zh-CN`:`en-US`,t?{month:`short`,day:`numeric`}:{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r):``}function ft(e){if(e<=1)return 1;let t=10**Math.floor(Math.log10(e)),n=e/t;return(n<=1?1:n<=2?2:n<=5?5:10)*t}function pt(e){let t=Math.max(0,e.ok??e.requests-e.error),n=Math.min(Math.max(0,e.requests-t),Math.max(0,e.requests));return{...e,okCount:t,errorCount:n,inputTokens:e.prompt_tokens??0,outputTokens:e.completion_tokens??0,cacheTokens:e.cache_read_tokens??0,p50:e.latency_p50_ms??null,p95:e.latency_p95_ms??null}}function mt({active:e,payload:t,daily:n,lang:r,specs:i,format:a,totalLabel:o,total:s}){if(!e||!t?.[0])return null;let c=t[0].payload;return(0,$.jsxs)(`div`,{className:`rounded-xl bg-overlay px-3 py-2 text-caption text-overlay-foreground shadow-overlay`,children:[(0,$.jsx)(`div`,{className:`mono text-muted`,children:dt(c.at,n,r)}),(0,$.jsxs)(`div`,{className:`mt-1.5 grid gap-1`,children:[i.map(e=>(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-6`,children:[(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:`size-1.5 rounded-full`,style:{background:e.color}}),e.label]}),(0,$.jsx)(`span`,{className:`mono font-medium`,children:a(c[e.key])})]},String(e.key))),s&&o?(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-6 pt-1`,children:[(0,$.jsx)(`span`,{className:`text-muted`,children:o}),(0,$.jsx)(`span`,{className:`mono font-medium`,children:a(s(c))})]}):null]})]})}function ht({series:n,lang:r,emptyLabel:i,okLabel:a,errorLabel:o,onSelectRange:s,selectHint:c,labels:l,initialMetric:u=`requests`}){let[d,f]=(0,V.useState)(u),[p,m]=(0,V.useState)(null),[h,g]=(0,V.useState)(null),_=(0,V.useRef)(!1),v=(0,V.useRef)(null),y=(0,V.useMemo)(()=>n.map(pt),[n]),x=y[0],w=y[y.length-1],E=(x&&w?Date.parse(w.at)-Date.parse(x.at):0)>1728e5,D=l??{requests:`Requests`,tokens:`Tokens`,latency:`p95 latency`,input:`input`,output:`output`,cacheRead:`cache read`,p50:`p50`,p95:`p95`,total:`total`},O=d===`tokens`?[{key:`inputTokens`,label:D.input,color:`var(--foreground)`,area:!0,width:1.5,opacity:.75},{key:`outputTokens`,label:D.output,color:`var(--success)`,area:!0,width:1.5},{key:`cacheTokens`,label:D.cacheRead,color:`var(--muted)`,width:1.25,opacity:.8}]:d===`latency`?[{key:`p95`,label:D.p95,color:`var(--warning)`,area:!0,width:1.75},{key:`p50`,label:D.p50,color:`var(--muted)`,width:1.25,opacity:.85}]:[{key:`okCount`,label:a,color:`var(--success)`,area:!0,width:1.75},{key:`errorCount`,label:o,color:`var(--danger)`,area:!0,width:1.25,opacity:.7}],k=e=>e==null?`—`:d===`latency`?B(e):b(e),A=d===`requests`?e=>e.requests:d===`tokens`?e=>e.inputTokens+e.outputTokens:void 0,j=y.flatMap(e=>O.map(t=>Number(e[t.key]??0))),M=d===`requests`?Math.max(0,...y.map(e=>e.requests)):Math.max(0,...j),te=ft(M),N=y.some(e=>e.requests>0),P=y.map(e=>`${e.at}:${e.requests}:${e.error}`).join(`|`);(0,V.useLayoutEffect)(()=>{let e=v.current;if(!e||!N||_.current)return;let t=!1,n=null,r=T.context(()=>{let r=T.matchMedia(),i=()=>{let t=T.utils.toArray(`.recharts-area-area`,e),n=T.utils.toArray(`.recharts-line-curve`,e);return!t.length&&!n.length?!1:(r.add(`(prefers-reduced-motion: reduce)`,()=>{T.set(n,{clearProps:`strokeDashoffset,strokeDasharray`}),T.set(t,{clearProps:`autoAlpha`})}),r.add(`(prefers-reduced-motion: no-preference)`,()=>{T.fromTo(t,{autoAlpha:0},{autoAlpha:1,duration:.45,ease:`power2.out`,stagger:.05}),n.forEach((e,t)=>{let n=e.getTotalLength();T.fromTo(e,{strokeDasharray:n,strokeDashoffset:n},{strokeDashoffset:0,duration:.7,delay:t*.05,ease:`power2.out`})})}),!0)};if(i()){t=!0,_.current=!0;return}n=new MutationObserver(()=>{t||i()&&(t=!0,_.current=!0,n?.disconnect())}),n.observe(e,{childList:!0,subtree:!0})},e);return()=>{n?.disconnect(),r.revert()}},[N,P]);let F=y.length>1?Date.parse(y[1].at)-Date.parse(y[0].at):36e5,I=()=>{if(p&&h&&s){let e=Date.parse(p),t=Date.parse(h);if(Number.isFinite(e)&&Number.isFinite(t)){let n=Math.min(e,t),r=Math.max(e,t)+F;s(new Date(n).toISOString(),new Date(r).toISOString())}}m(null),g(null)},L=e=>{let t=e?.activeLabel;return t==null?null:String(t)};return!n.length||!N?(0,$.jsx)(ne,{emptyLabel:i}):(0,$.jsxs)(`div`,{ref:v,className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`mb-3 flex justify-end`,children:(0,$.jsx)(ie,{value:d,onChange:e=>f(e),ariaLabel:D.requests,options:[{id:`requests`,label:D.requests},{id:`tokens`,label:D.tokens},{id:`latency`,label:D.latency}]})}),(0,$.jsx)(`div`,{className:`h-56 w-full`,children:(0,$.jsx)(C,{width:`100%`,height:`100%`,children:(0,$.jsxs)(lt,{data:y,margin:{top:8,right:8,bottom:0,left:0},style:s?{cursor:`crosshair`,userSelect:`none`}:void 0,onMouseDown:s?e=>{let t=L(e);t&&(m(t),g(t))}:void 0,onMouseMove:s?e=>{if(!p)return;let t=L(e);t&&g(t)}:void 0,onMouseUp:s?I:void 0,onMouseLeave:s?()=>{m(null),g(null)}:void 0,children:[(0,$.jsx)(`defs`,{children:O.filter(e=>e.area).map(e=>(0,$.jsxs)(`linearGradient`,{id:`traffic-fill-${String(e.key)}`,x1:`0`,y1:`0`,x2:`0`,y2:`1`,children:[(0,$.jsx)(`stop`,{offset:`0%`,stopColor:e.color,stopOpacity:.22}),(0,$.jsx)(`stop`,{offset:`100%`,stopColor:e.color,stopOpacity:.02})]},String(e.key)))}),(0,$.jsx)(t,{vertical:!1,stroke:`var(--separator)`,strokeDasharray:`3 6`}),(0,$.jsx)(re,{dataKey:`at`,tickLine:!1,axisLine:!1,minTickGap:28,tick:{fill:`var(--muted)`,fontSize:ut.caption,fontFamily:`var(--font-mono)`},tickFormatter:e=>dt(e,E,r)}),(0,$.jsx)(ce,{width:d===`latency`?44:36,domain:[0,te],tickLine:!1,axisLine:!1,allowDecimals:!1,tick:{fill:`var(--muted)`,fontSize:ut.caption,fontFamily:`var(--font-mono)`},tickFormatter:e=>d===`latency`?B(e):b(e)}),(0,$.jsx)(e,{cursor:{stroke:`var(--border)`,strokeDasharray:`3 3`},content:(0,$.jsx)(mt,{daily:E,lang:r,specs:O,format:k,totalLabel:D.total,total:A})}),O.filter(e=>e.area).map(e=>(0,$.jsx)(S,{type:`monotone`,dataKey:e.key,stroke:`none`,fill:`url(#traffic-fill-${String(e.key)})`,isAnimationActive:!1,activeDot:!1,dot:!1,connectNulls:!0},`area-${String(e.key)}`)),O.map(e=>(0,$.jsx)(st,{type:`monotone`,dataKey:e.key,stroke:e.color,strokeWidth:e.width??1.5,strokeOpacity:e.opacity??1,dot:!1,isAnimationActive:!1,connectNulls:!0,activeDot:{r:4,fill:`var(--surface)`,stroke:e.color,strokeWidth:1.5}},`line-${String(e.key)}`)),p&&h?(0,$.jsx)(ee,{x1:p,x2:h,fill:`var(--foreground)`,fillOpacity:.06,stroke:`none`,ifOverflow:`visible`}):null]})})}),(0,$.jsxs)(`div`,{className:`mt-2 flex min-h-5 items-center justify-between gap-3 text-caption text-muted`,children:[(0,$.jsx)(`div`,{className:`flex items-center gap-3`,children:O.map(e=>(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:`size-1.5 rounded-full`,style:{background:e.color}}),e.label]},String(e.key)))}),(0,$.jsxs)(`span`,{className:`flex items-center gap-3`,children:[s&&c?(0,$.jsx)(`span`,{children:c}):null,(0,$.jsxs)(`span`,{className:`mono`,children:[k(M),` peak`]})]})]})]})}export{ht as TrafficChart}; \ No newline at end of file diff --git a/internal/webui/static/assets/index-CnBhKFzp.js b/internal/webui/static/assets/index-fj0jyJpQ.js similarity index 67% rename from internal/webui/static/assets/index-CnBhKFzp.js rename to internal/webui/static/assets/index-fj0jyJpQ.js index 66649ec5..f51d5566 100644 --- a/internal/webui/static/assets/index-CnBhKFzp.js +++ b/internal/webui/static/assets/index-fj0jyJpQ.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TrafficChart-Cj0nupcy.js","assets/CartesianGrid-DXT2DP8n.js","assets/CostChart-D5w4taWC.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TrafficChart-CAX_ltfB.js","assets/CartesianGrid-DaumKfTu.js","assets/CostChart-bIckh8_5.js"])))=>i.map(i=>d[i]); var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;li[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,o)=>(o=n==null?{}:e(i(n)),c(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var u=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.iterator;function m(e){return typeof e!=`object`||!e?null:(e=p&&e[p]||e[`@@iterator`],typeof e==`function`?e:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,_={};function v(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=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,e,t,`setState`)},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function y(){}y.prototype=v.prototype;function b(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}var x=b.prototype=new y;x.constructor=b,g(x,v.prototype),x.isPureReactComponent=!0;var S=Array.isArray;function C(){}var w={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function E(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function D(e,t){return E(e.type,t,e.props)}function O(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function k(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var A=/\/+/g;function j(e,t){return typeof e==`object`&&e&&e.key!=null?k(``+e.key):t.toString(36)}function M(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(C,C):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function N(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,N(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+j(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(A,`$&/`)+`/`),N(o,r,i,``,function(e){return e})):o!=null&&(O(o)&&(o=D(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(A,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u{t.exports=u()})),f=o((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m){if(n(c)!==null)m=!0,S||(S=!0,O());else{var t=n(l);t!==null&&j(x,t.startTime-e)}}}var S=!1,C=-1,w=5,T=-1;function E(){return g?!0:!(e.unstable_now()-Tt&&E());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&j(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?O():S=!1}}}var O;if(typeof y==`function`)O=function(){y(D)};else if(typeof MessageChannel<`u`){var k=new MessageChannel,A=k.port2;k.port1.onmessage=D,O=function(){A.postMessage(null)}}else O=function(){_(D,0)};function j(t,n){C=_(function(){t(e.unstable_now())},n)}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(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,j(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,O()))),r},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),p=o(((e,t)=>{t.exports=f()})),m=o((e=>{var t=d();function n(e){var t=`https://react.dev/errors/`+e;if(1{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=m()})),g=o((e=>{var t=p(),n=d(),r=h();function i(e){var t=`https://react.dev/errors/`+e;if(1ee||(e.current=z[ee],z[ee]=null,ee--)}function te(e,t){ee++,z[ee]=e.current,e.current=t}var H=B(null),ne=B(null),re=B(null),ie=B(null);function ae(e,t){switch(te(re,t),te(ne,e),te(H,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Jd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Jd(t),e=Yd(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}V(H),te(H,e)}function oe(){V(H),V(ne),V(re)}function se(e){e.memoizedState!==null&&te(ie,e);var t=H.current,n=Yd(t,e.type);t!==n&&(te(ne,e),te(H,n))}function ce(e){ne.current===e&&(V(H),V(ne)),ie.current===e&&(V(ie),ap._currentValue=R)}var le,ue;function de(e){if(le===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);le=t&&t[1]||``,ue=-1)`:-1>>=0,e===0?32:31-(Ne(e)/Pe|0)|0}var Ie=256,Le=262144,Re=4194304;function ze(e){var t=e&42;if(t!==0)return t;switch(e&-e){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 e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Be(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=ze(n))):i=ze(o):i=ze(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=ze(n))):i=ze(o)):i=ze(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function Ve(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function He(e,t){switch(e){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 Ue(){var e=Re;return Re<<=1,!(Re&62914560)&&(Re=4194304),e}function We(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Ge(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Ke(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0`u`||window.document===void 0||window.document.createElement===void 0),an=!1;if(rn)try{var on={};Object.defineProperty(on,"passive",{get:function(){an=!0}}),window.addEventListener(`test`,on,on),window.removeEventListener(`test`,on,on)}catch{an=!1}var sn=null,cn=null,ln=null;function un(){if(ln)return ln;var e,t=cn,n=t.length,r,i=`value`in sn?sn.value:sn.textContent,a=i.length;for(e=0;e=Hn),Gn=` `,Kn=!1;function qn(e,t){switch(e){case`keyup`:return Bn.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function Jn(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var Yn=!1;function Xn(e,t){switch(e){case`compositionend`:return Jn(t);case`keypress`:return t.which===32?(Kn=!0,Gn):null;case`textInput`:return e=t.data,e===Gn&&Kn?null:e;default:return null}}function Zn(e,t){if(Yn)return e===`compositionend`||!Vn&&qn(e,t)?(e=un(),ln=cn=sn=null,Yn=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=yr(n)}}function xr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?xr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Sr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=jt(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=jt(e.document)}return t}function Cr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var wr=rn&&`documentMode`in document&&11>=document.documentMode,Tr=null,Er=null,Dr=null,Or=!1;function kr(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Or||Tr==null||Tr!==jt(r)||(r=Tr,`selectionStart`in r&&Cr(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Dr&&vr(Dr,r)||(Dr=r,r=Md(Er,`onSelect`),0>=o,i-=o,xi=1<<32-Me(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),Ai&&Ci(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(a,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(a,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(a,h),Ai&&Ci(a,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(a,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return Ai&&Ci(a,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,a,g,v.value,l),v!==null&&(e&&v.alternate!==null&&h.delete(v.key===null?g:v.key),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(a,e)}),Ai&&Ci(a,g),u}function b(e,r,o,c){if(typeof o==`object`&&o&&o.type===y&&o.key===null&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case _:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===y){if(r.tag===7){n(e,r.sibling),c=a(r,o.props.children),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===O&&wa(l)===r.type){n(e,r.sibling),c=a(r,o.props),ja(c,o),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}o.type===y?(c=ci(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=si(o.type,o.key,o.props,null,e.mode,c),ja(c,o),c.return=e,e=c)}return s(e);case v:a:{for(l=o.key;r!==null;){if(r.key===l){if(r.tag===4&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),c=a(r,o.children||[]),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}c=di(o,e.mode,c),c.return=e,e=c}return s(e);case O:return o=wa(o),b(e,r,o,c)}if(F(o))return h(e,r,o,c);if(M(o)){if(l=M(o),typeof l!=`function`)throw Error(i(150));return o=l.call(o),g(e,r,o,c)}if(typeof o.then==`function`)return b(e,r,Aa(o),c);if(o.$$typeof===C)return b(e,r,Qi(e,o),c);Ma(e,o)}return typeof o==`string`&&o!==``||typeof o==`number`||typeof o==`bigint`?(o=``+o,r!==null&&r.tag===6?(n(e,r.sibling),c=a(r,o),c.return=e,e=c):(n(e,r),c=li(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{ka=0;var i=b(e,t,n,r);return Oa=null,i}catch(t){if(t===va||t===ba)throw t;var a=ri(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var Pa=Na(!0),Fa=Na(!1),Ia=!1;function La(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Ra(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function za(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Ba(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Rl&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=ei(e),$r(e,null,n),t}return Xr(e,r,t,n),ei(e)}function Va(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Je(e,n)}}function Ha(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Ua=!1;function Wa(){if(Ua){var e=la;if(e!==null)throw e}}function Ga(e,t,n,r){Ua=!1;var i=e.updateQueue;Ia=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane&-536870913,p=f!==s.lane;if(p?(Vl&f)===f:(r&f)===f){f!==0&&f===ca&&(Ua=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var h=e,g=s;f=t;var _=n;switch(g.tag){case 1:if(h=g.payload,typeof h==`function`){d=h.call(_,d,f);break a}d=h;break a;case 3:h.flags=h.flags&-65537|128;case 0:if(h=g.payload,f=typeof h==`function`?h.call(_,d,f):h,f==null)break a;d=m({},d,f);break a;case 2:Ia=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),Yl|=o,e.lanes=o,e.memoizedState=d}}function Ka(e,t){if(typeof e!=`function`)throw Error(i(191,e));e.call(t)}function qa(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=I.T,s={};I.T=s,Ns(e,!1,t,n);try{var c=i(),l=I.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?Ms(e,t,fa(c,r),_u(e)):Ms(e,t,r,_u(e))}catch(n){Ms(e,t,{then:function(){},status:`rejected`,reason:n},_u())}finally{L.p=a,o!==null&&s.types!==null&&(o.types=s.types),I.T=o}}function Cs(){}function ws(e,t,n,r){if(e.tag!==5)throw Error(i(476));var a=Ts(e).queue;Ss(e,a,t,R,n===null?Cs:function(){return Es(e),n(r)})}function Ts(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:R,baseState:R,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Fo,lastRenderedState:R},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Fo,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Es(e){var t=Ts(e);t.next===null&&(t=e.alternate.memoizedState),Ms(e,t.next.queue,{},_u())}function Ds(){return Zi(ap)}function W(){return Ao().memoizedState}function Os(){return Ao().memoizedState}function ks(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=_u();e=za(n);var r=Ba(t,e,n);r!==null&&(yu(r,t,n),Va(r,t,n)),t={cache:ia()},e.payload=t;return}t=t.return}}function As(e,t,n){var r=_u();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Ps(e)?Fs(t,n):(n=Zr(e,t,n,r),n!==null&&(yu(n,e,r),G(n,t,r)))}function js(e,t,n){Ms(e,t,n,_u())}function Ms(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ps(e))Fs(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,_r(s,o))return Xr(e,t,i,0),zl===null&&Yr(),!1}catch{}if(n=Zr(e,t,i,r),n!==null)return yu(n,e,r),G(n,t,r),!0}return!1}function Ns(e,t,n,r){if(r={lane:2,revertLane:gd(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Ps(e)){if(t)throw Error(i(479))}else t=Zr(e,n,r,2),t!==null&&yu(t,e,2)}function Ps(e){var t=e.alternate;return e===lo||t!==null&&t===lo}function Fs(e,t){mo=po=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function G(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Je(e,n)}}var Is={readContext:Zi,use:No,useCallback:bo,useContext:bo,useEffect:bo,useImperativeHandle:bo,useLayoutEffect:bo,useInsertionEffect:bo,useMemo:bo,useReducer:bo,useRef:bo,useState:bo,useDebugValue:bo,useDeferredValue:bo,useTransition:bo,useSyncExternalStore:bo,useId:bo,useHostTransitionStatus:bo,useFormState:bo,useActionState:bo,useOptimistic:bo,useMemoCache:bo,useCacheRefresh:bo};Is.useEffectEvent=bo;var Ls={readContext:Zi,use:No,useCallback:function(e,t){return ko().memoizedState=[e,t===void 0?null:t],e},useContext:Zi,useEffect:ls,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),ss(4194308,4,hs.bind(null,t,e),n)},useLayoutEffect:function(e,t){return ss(4194308,4,e,t)},useInsertionEffect:function(e,t){ss(4,2,e,t)},useMemo:function(e,t){var n=ko();t=t===void 0?null:t;var r=e();if(ho){je(!0);try{e()}finally{je(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=ko();if(n!==void 0){var i=n(t);if(ho){je(!0);try{n(t)}finally{je(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=As.bind(null,lo,e),[r.memoizedState,e]},useRef:function(e){var t=ko();return e={current:e},t.memoizedState=e},useState:function(e){e=Go(e);var t=e.queue,n=js.bind(null,lo,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:_s,useDeferredValue:function(e,t){return bs(ko(),e,t)},useTransition:function(){var e=Go(!1);return e=Ss.bind(null,lo,e.queue,!0,!1),ko().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=lo,a=ko();if(Ai){if(n===void 0)throw Error(i(407));n=n()}else{if(n=t(),zl===null)throw Error(i(349));Vl&127||Bo(r,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,ls(Ho.bind(null,r,o,e),[e]),r.flags|=2048,as(9,{destroy:void 0},Vo.bind(null,r,o,n,t),null),n},useId:function(){var e=ko(),t=zl.identifierPrefix;if(Ai){var n=Si,r=xi;n=(r&~(1<<32-Me(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=go++,0<\/script>`,o=o.removeChild(o.firstChild);break;case`select`:o=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?o.multiple=!0:r.size&&(o.size=r.size);break;default:o=typeof r.is==`string`?s.createElement(a,{is:r.is}):s.createElement(a)}}o[tt]=t,o[nt]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)o.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=o;a:switch(Vd(o,a,r),a){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&jc(t)}}return Ic(t),Mc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&jc(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(i(166));if(e=re.current,Li(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=Oi,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[tt]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||Rd(e.nodeValue,n)),e||Pi(t,!0)}else e=qd(e).createTextNode(r),e[tt]=t,t.stateNode=e}return Ic(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=Li(t),n!==null){if(e===null){if(!r)throw Error(i(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(i(557));e[tt]=t}else Ri(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Ic(t),e=!1}else n=zi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(ao(t),t):(ao(t),null);if(t.flags&128)throw Error(i(558))}return Ic(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=Li(t),r!==null&&r.dehydrated!==null){if(e===null){if(!a)throw Error(i(318));if(a=t.memoizedState,a=a===null?null:a.dehydrated,!a)throw Error(i(317));a[tt]=t}else Ri(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Ic(t),a=!1}else a=zi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(ao(t),t):(ao(t),null)}return ao(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,a=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(a=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==a&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Pc(t,t.updateQueue),Ic(t),null);case 4:return oe(),e===null&&Od(t.stateNode.containerInfo),Ic(t),null;case 10:return Gi(t.type),Ic(t),null;case 19:if(V(oo),r=t.memoizedState,r===null)return Ic(t),null;if(a=!!(t.flags&128),o=r.rendering,o===null){if(a)Fc(r,!1);else{if(Jl!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=so(e),o!==null){for(t.flags|=128,Fc(r,!1),e=o.updateQueue,t.updateQueue=e,Pc(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)oi(n,e),n=n.sibling;return te(oo,oo.current&1|2),Ai&&Ci(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&U()>au&&(t.flags|=128,a=!0,Fc(r,!1),t.lanes=4194304)}}else{if(!a){if(e=so(o),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,Pc(t,e),Fc(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!Ai)return Ic(t),null}else 2*U()-r.renderingStartTime>au&&n!==536870912&&(t.flags|=128,a=!0,Fc(r,!1),t.lanes=4194304)}r.isBackwards?(o.sibling=t.child,t.child=o):(e=r.last,e===null?t.child=o:e.sibling=o,r.last=o)}return r.tail===null?(Ic(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=U(),e.sibling=null,n=oo.current,te(oo,a?n&1|2:n&1),Ai&&Ci(t,r.treeForkCount),e);case 22:case 23:return ao(t),Qa(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(Ic(t),t.subtreeFlags&6&&(t.flags|=8192)):Ic(t),n=t.updateQueue,n!==null&&Pc(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&V(ma),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),Gi(ra),Ic(t),null;case 25:return null;case 30:return null}throw Error(i(156,t.tag))}function Rc(e,t){switch(Ei(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Gi(ra),oe(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return ce(t),null;case 31:if(t.memoizedState!==null){if(ao(t),t.alternate===null)throw Error(i(340));Ri()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(ao(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));Ri()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return V(oo),null;case 4:return oe(),null;case 10:return Gi(t.type),null;case 22:case 23:return ao(t),Qa(),e!==null&&V(ma),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Gi(ra),null;case 25:return null;default:return null}}function zc(e,t){switch(Ei(t),t.tag){case 3:Gi(ra),oe();break;case 26:case 27:case 5:ce(t);break;case 4:oe();break;case 31:t.memoizedState!==null&&ao(t);break;case 13:ao(t);break;case 19:V(oo);break;case 10:Gi(t.type);break;case 22:case 23:ao(t),Qa(),e!==null&&V(ma);break;case 24:Gi(ra)}}function Bc(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){Yu(t,t.return,e)}}function Vc(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){Yu(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){Yu(t,t.return,e)}}function Hc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{qa(t,n)}catch(t){Yu(e,e.return,t)}}}function Uc(e,t,n){n.props=Ws(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Yu(e,t,n)}}function Wc(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){Yu(e,t,n)}}function Gc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null){if(typeof r==`function`)try{r()}catch(n){Yu(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){Yu(e,t,n)}else n.current=null}}function Kc(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{a:switch(t){case`button`:case`input`:case`select`:case`textarea`:n.autoFocus&&r.focus();break a;case`img`:n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(t){Yu(e,e.return,t)}}function K(e,t,n){try{var r=e.stateNode;Hd(r,e.type,n,t),r[nt]=t}catch(t){Yu(e,e.return,t)}}function qc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&af(e.type)||e.tag===4}function Jc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||qc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&af(e.type)||e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Yc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?(n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n).insertBefore(e,t):(t=n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n,t.appendChild(e),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Jt));else if(r!==4&&(r===27&&af(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Yc(e,t,n),e=e.sibling;e!==null;)Yc(e,t,n),e=e.sibling}function Xc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(r===27&&af(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(Xc(e,t,n),e=e.sibling;e!==null;)Xc(e,t,n),e=e.sibling}function Zc(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);Vd(t,r,n),t[tt]=e,t[nt]=n}catch(t){Yu(e,e.return,t)}}var Qc=!1,$c=!1,el=!1,tl=typeof WeakSet==`function`?WeakSet:Set,nl=null;function rl(e,t){if(e=e.containerInfo,Gd=mp,e=Sr(e),Cr(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||a!==0&&f.nodeType!==3||(c=s+a),f!==o||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===a&&(c=s),p===o&&++d===r&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(Kd={focusedElem:e,selectionRange:n},mp=!1,nl=t;nl!==null;)if(t=nl,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,nl=e;else for(;nl!==null;){switch(t=nl,o=t.alternate,e=t.flags,t.tag){case 0:if(e&4&&(e=t.updateQueue,e=e===null?null:e.events,e!==null))for(n=0;n title`))),Vd(o,r,n),o[tt]=e,mt(o),r=o;break a;case`link`:var s=Jf(`link`,`href`,a).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=br(s,h),v=br(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,I.T=null,n=pu,pu=null;var o=lu,s=du;if(cu=0,uu=lu=null,du=0,Rl&6)throw Error(i(331));var c=Rl;if(Rl|=4,Nl(o.current),Tl(o,o.current,s,n),Rl=c,ld(0,!1),Ae&&typeof Ae.onPostCommitFiberRoot==`function`)try{Ae.onPostCommitFiberRoot(ke,o)}catch{}return!0}finally{L.p=a,I.T=r,Gu(e,t)}}function Ju(e,t,n){t=pi(n,t),t=Xs(e.stateNode,t,2),e=Ba(e,t,2),e!==null&&(Ge(e,2),cd(e))}function Yu(e,t,n){if(e.tag===3)Ju(e,e,n);else for(;t!==null;){if(t.tag===3){Ju(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(su===null||!su.has(r))){e=pi(n,e),n=Zs(2),r=Ba(t,n,2),r!==null&&(Qs(n,r,t,e),Ge(r,2),cd(r));break}}t=t.return}}function Xu(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Ll;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(Kl=!0,i.add(n),e=Zu.bind(null,e,t,n),t.then(e,e))}function Zu(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,zl===e&&(Vl&n)===n&&(Jl===4||Jl===3&&(Vl&62914560)===Vl&&300>U()-ru?!(Rl&2)&&Eu(e,0):Zl|=n,$l===Vl&&($l=0)),cd(e)}function Qu(e,t){t===0&&(t=Ue()),e=Qr(e,t),e!==null&&(Ge(e,t),cd(e))}function $u(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Qu(e,n)}function ed(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(i(314))}r!==null&&r.delete(t),Qu(e,n)}function td(e,t){return _e(e,t)}var nd=null,rd=null,id=!1,ad=!1,od=!1,sd=0;function cd(e){e!==rd&&e.next===null&&(rd===null?nd=rd=e:rd=rd.next=e),ad=!0,id||(id=!0,hd())}function ld(e,t){if(!od&&ad){od=!0;do for(var n=!1,r=nd;r!==null;){if(!t){if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-Me(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,md(r,a))}else a=Vl,a=Be(r,r===zl?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||Ve(r,a)||(n=!0,md(r,a))}r=r.next}while(n);od=!1}}function ud(){dd()}function dd(){ad=id=!1;var e=0;sd!==0&&Qd()&&(e=sd);for(var t=U(),n=null,r=nd;r!==null;){var i=r.next,a=fd(r,t);a===0?(r.next=null,n===null?nd=i:n.next=i,i===null&&(rd=n)):(n=r,(e!==0||a&3)&&(ad=!0)),r=i}cu!==0&&cu!==5||ld(e,!1),sd!==0&&(sd=0)}function fd(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&Ud(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function Of(e,t,n){var r=Df;if(r&&typeof t==`string`&&t){var i=Nt(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),Sf.has(i)||(Sf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),Vd(t,`link`,e),mt(t),r.head.appendChild(t)))}}function kf(e){wf.D(e),Of(`dns-prefetch`,e,null)}function Af(e,t){wf.C(e,t),Of(`preconnect`,e,t)}function jf(e,t,n){wf.L(e,t,n);var r=Df;if(r&&e&&t){var i=`link[rel="preload"][as="`+Nt(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Nt(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Nt(n.imageSizes)+`"]`)):i+=`[href="`+Nt(e)+`"]`;var a=i;switch(t){case`style`:a=Lf(e);break;case`script`:a=Vf(e)}xf.has(a)||(e=m({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),xf.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Rf(a))||t===`script`&&r.querySelector(Hf(a))||(t=r.createElement(`link`),Vd(t,`link`,e),mt(t),r.head.appendChild(t)))}}function Mf(e,t){wf.m(e,t);var n=Df;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Nt(r)+`"][href="`+Nt(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Vf(e)}if(!xf.has(a)&&(e=m({rel:`modulepreload`,href:e},t),xf.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(Hf(a)))return}r=n.createElement(`link`),Vd(r,`link`,e),mt(r),n.head.appendChild(r)}}}function Nf(e,t,n){wf.S(e,t,n);var r=Df;if(r&&e){var i=pt(r).hoistableStyles,a=Lf(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Rf(a)))s.loading=5;else{e=m({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=xf.get(a))&&Gf(e,n);var c=o=r.createElement(`link`);mt(c),Vd(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Wf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Pf(e,t){wf.X(e,t);var n=Df;if(n&&e){var r=pt(n).hoistableScripts,i=Vf(e),a=r.get(i);a||(a=n.querySelector(Hf(i)),a||(e=m({src:e,async:!0},t),(t=xf.get(i))&&Kf(e,t),a=n.createElement(`script`),mt(a),Vd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Ff(e,t){wf.M(e,t);var n=Df;if(n&&e){var r=pt(n).hoistableScripts,i=Vf(e),a=r.get(i);a||(a=n.querySelector(Hf(i)),a||(e=m({src:e,async:!0,type:`module`},t),(t=xf.get(i))&&Kf(e,t),a=n.createElement(`script`),mt(a),Vd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function If(e,t,n,r){var a=(a=re.current)?Cf(a):null;if(!a)throw Error(i(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(t=Lf(n.href),n=pt(a).hoistableStyles,r=n.get(t),r||(r={type:`style`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=Lf(n.href);var o=pt(a).hoistableStyles,s=o.get(e);if(s||(a=a.ownerDocument||a,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=a.querySelector(Rf(e)))&&!o._p&&(s.instance=o,s.state.loading=5),xf.has(e)||(n={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},xf.set(e,n),o||Bf(a,e,n,s.state))),t&&r===null)throw Error(i(528,``));return s}if(t&&r!==null)throw Error(i(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(t=Vf(n),n=pt(a).hoistableScripts,r=n.get(t),r||(r={type:`script`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(i(444,e))}}function Lf(e){return`href="`+Nt(e)+`"`}function Rf(e){return`link[rel="stylesheet"][`+e+`]`}function zf(e){return m({},e,{"data-precedence":e.precedence,precedence:null})}function Bf(e,t,n,r){e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)?r.loading=1:(t=e.createElement(`link`),r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2}),Vd(t,`link`,n),mt(t),e.head.appendChild(t))}function Vf(e){return`[src="`+Nt(e)+`"]`}function Hf(e){return`script[async]`+e}function Uf(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Nt(n.href)+`"]`);if(r)return t.instance=r,mt(r),r;var a=m({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),mt(r),Vd(r,`style`,a),Wf(r,n.precedence,e),t.instance=r;case`stylesheet`:a=Lf(n.href);var o=e.querySelector(Rf(a));if(o)return t.state.loading|=4,t.instance=o,mt(o),o;r=zf(n),(a=xf.get(a))&&Gf(r,a),o=(e.ownerDocument||e).createElement(`link`),mt(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),Vd(o,`link`,r),t.state.loading|=4,Wf(o,n.precedence,e),t.instance=o;case`script`:return o=Vf(n.src),(a=e.querySelector(Hf(o)))?(t.instance=a,mt(a),a):(r=n,(a=xf.get(o))&&(r=m({},n),Kf(r,a)),e=e.ownerDocument||e,a=e.createElement(`script`),mt(a),Vd(a,`link`,r),e.head.appendChild(a),t.instance=a);case`void`:return null;default:throw Error(i(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Wf(r,n.precedence,e));return t.instance}function Wf(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function Xf(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Zf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Qf(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=Lf(r.href),a=t.querySelector(Rf(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=tp.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,mt(a);return}a=t.ownerDocument||t,r=zf(r),(i=xf.get(i))&&Gf(r,i),a=a.createElement(`link`),mt(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),Vd(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=tp.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var $f=0;function ep(e,t){return e.stylesheets&&e.count===0&&rp(e,e.stylesheets),0$f?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function tp(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)rp(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var np=null;function rp(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,np=new Map,t.forEach(ip,e),np=null,tp.call(e))}function ip(e,t){if(!(t.state.loading&4)){var n=np.get(e);if(n)var r=n.get(null);else{n=new Map,np.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=g()})),v=l(d(),1),y=_(),b=`modulepreload`,x=function(e){return`/`+e},S={},C=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=x(t,n),t=s(t),t in S)return;S[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:b,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},w=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,T=/^[\\/]{2}/;function E(e,t){return t+e.replace(/\\/g,`/`)}var D=`popstate`;function O(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function k(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return P(``,{pathname:r,search:i,hash:a},t.state&&t.state.usr||null,t.state&&t.state.key||`default`,n?{pathname:e.location.pathname,search:e.location.search,hash:e.location.hash}:void 0)}function n(e,t){return typeof t==`string`?t:F(t)}return L(t,n,null,e)}function A(e,t){if(e===!1||e==null)throw Error(t)}function j(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function M(){return Math.random().toString(36).substring(2,10)}function N(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function P(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?I(t):t,state:n,key:t&&t.key||r||M(),mask:i}}function F({pathname:e=`/`,search:t=``,hash:n=``}){return t&&t!==`?`&&(e+=t.charAt(0)===`?`?t:`?`+t),n&&n!==`#`&&(e+=n.charAt(0)===`#`?n:`#`+n),e}function I(e){let t={};if(e){let n=e.indexOf(`#`);n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf(`?`);r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function L(e,t,n,r={}){let{window:i=document.defaultView,v5Compat:a=!1}=r,o=i.history,s=`POP`,c=null,l=u();l??(l=0,o.replaceState({...o.state,idx:l},``));function u(){return(o.state||{idx:null}).idx}function d(){s=`POP`;let e=u(),t=e==null?null:e-l;l=e,c&&c({action:s,location:h.location,delta:t})}function f(e,t){s=`PUSH`;let r=O(e)?e:P(h.location,e,t);n&&n(r,e),l=u()+1;let d=N(r,l),f=h.createHref(r.mask||r);try{o.pushState(d,``,f)}catch(e){if(e instanceof DOMException&&e.name===`DataCloneError`)throw e;i.location.assign(f)}a&&c&&c({action:s,location:h.location,delta:1})}function p(e,t){s=`REPLACE`;let r=O(e)?e:P(h.location,e,t);n&&n(r,e),l=u();let i=N(r,l),d=h.createHref(r.mask||r);o.replaceState(i,``,d),a&&c&&c({action:s,location:h.location,delta:0})}function m(e){return R(i,e)}let h={get action(){return s},get location(){return e(i,o)},listen(e){if(c)throw Error(`A history only accepts one active listener`);return i.addEventListener(D,d),c=e,()=>{i.removeEventListener(D,d),c=null}},createHref(e){return t(i,e)},createURL:m,encodeLocation(e){let t=m(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:f,replace:p,go(e){return o.go(e)}};return h}function R(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),A(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:F(t);return i=i.replace(/ $/,`%20`),!n&&T.test(i)&&(i=r+i),new URL(i,r)}function z(e,t,n=`/`){return ee(e,t,n,!1)}function ee(e,t,n,r,i){let a=ge((typeof t==`string`?I(t):t).pathname||`/`,n);if(a==null)return null;let o=i??B(e),s=null,c=he(a);for(let e=0;s==null&&e{let c={relativePath:s===void 0?e.path||``:s,caseSensitive:e.caseSensitive===!0,childrenIndex:a,route:e};if(c.relativePath.startsWith(`/`)){if(!c.relativePath.startsWith(r)&&o)return;A(c.relativePath.startsWith(r),`Absolute route path "${c.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),c.relativePath=c.relativePath.slice(r.length)}let l=Ce([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(A(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),V(e.children,t,u,l,o)),!(e.path==null&&!e.index)&&t.push({path:l,score:le(l,e.index),routesMeta:u.map((e,t)=>{let[n,r]=me(e.relativePath,e.caseSensitive,t===u.length-1);return{...e,matcher:n,compiledParams:r}})})};return e.forEach((e,t)=>{if(e.path===``||!e.path?.includes(`?`))a(e,t);else for(let n of te(e.path))a(e,t,!0,n)}),t}function te(e){let t=e.split(`/`);if(t.length===0)return[];let[n,...r]=t,i=n.endsWith(`?`),a=n.replace(/\?$/,``);if(r.length===0)return i?[a,``]:[a];let o=te(r.join(`/`)),s=[];return s.push(...o.map(e=>e===``?a:[a,e].join(`/`))),i&&s.push(...o),s.map(t=>e.startsWith(`/`)&&t===``?`/`:t)}function H(e){e.sort((e,t)=>e.score===t.score?ue(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var ne=/^:[\w-]+$/,re=3,ie=2,ae=1,oe=10,se=-2,ce=e=>e===`*`;function le(e,t){let n=e.split(`/`),r=n.length;return n.some(ce)&&(r+=se),t&&(r+=ie),n.filter(e=>!ce(e)).reduce((e,t)=>e+(ne.test(t)?re:t===``?ae:oe),r)}function ue(e,t){return e.length===t.length&&e.slice(0,-1).every((e,n)=>e===t[n])?e[e.length-1]-t[t.length-1]:0}function de(e,t,n=!1){let{routesMeta:r}=e,i={},a=`/`,o=[];for(let e=0;e{if(t===`*`){let e=s[r]||``;o=a.slice(0,a.length-e.length).replace(/(.)\/+$/,`$1`)}let i=s[r];return e[t]=n&&!i?void 0:(i||``).replace(/%2F/g,`/`),e},{}),pathname:a,pathnameBase:o,pattern:e}}function me(e,t=!1,n=!0){j(e===`*`||!e.endsWith(`*`)||e.endsWith(`/*`),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,`/*`)}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,`/*`)}".`);let r=[],i=`^`+e.replace(/\/*\*?$/,``).replace(/^\/*/,`/`).replace(/[\\.*+^${}|()[\]]/g,`\\$&`).replace(/\/:([\w-]+)(\?)?/g,(e,t,n,i,a)=>{if(r.push({paramName:t,isOptional:n!=null}),n){let t=a.charAt(i+e.length);return t&&t!==`/`?`/([^\\/]*)`:`(?:/([^\\/]*))?`}return`/([^\\/]+)`}).replace(/\/([\w-]+)\?(\/|$)/g,`(/$1)?$2`);return e.endsWith(`*`)?(r.push({paramName:`*`}),i+=e===`*`||e===`/*`?`(.*)$`:`(?:\\/(.+)|\\/*)$`):n?i+=`\\/*$`:e!==``&&e!==`/`&&(i+=`(?:(?=\\/|$))`),[new RegExp(i,t?void 0:`i`),r]}function he(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return j(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function ge(e,t){if(t===`/`)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith(`/`)?t.length-1:t.length,r=e.charAt(n);return r&&r!==`/`?null:e.slice(n)||`/`}function _e(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?I(e):e,a;return n?(n=Se(n),a=n.startsWith(`/`)?ve(n.substring(1),`/`):ve(n,t)):a=t,{pathname:a,search:Ee(r),hash:De(i)}}function ve(e,t){let n=we(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function ye(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in and the router will parse it for you.`}function be(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function U(e){let t=be(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function xe(e,t,n,r=!1){let i;typeof e==`string`?i=I(e):(i={...e},A(!i.pathname||!i.pathname.includes(`?`),ye(`?`,`pathname`,`search`,i)),A(!i.pathname||!i.pathname.includes(`#`),ye(`#`,`pathname`,`hash`,i)),A(!i.search||!i.search.includes(`#`),ye(`#`,`search`,`hash`,i)));let a=e===``||i.pathname===``,o=a?`/`:i.pathname,s;if(o==null)s=n;else{let e=t.length-1;if(!r&&o.startsWith(`..`)){let t=o.split(`/`);for(;t[0]===`..`;)t.shift(),--e;i.pathname=t.join(`/`)}s=e>=0?t[e]:`/`}let c=_e(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var Se=e=>e.replace(/[\\/]{2,}/g,`/`),Ce=e=>Se(e.join(`/`)),we=e=>e.replace(/\/+$/,``),Te=e=>we(e).replace(/^\/*/,`/`),Ee=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,De=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,Oe=class{constructor(e,t,n,r=!1){this.status=e,this.statusText=t||``,this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function ke(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function Ae(e){return Ce(e.map(e=>e.route.path).filter(Boolean))||`/`}var je=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function Me(e,t){let n=e;if(typeof n!=`string`||!w.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(je)try{let e=new URL(window.location.href),r=T.test(n)?new URL(E(n,e.protocol)):new URL(n),a=ge(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{j(!1,` contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:i,to:n}}Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);var Ne=[`POST`,`PUT`,`PATCH`,`DELETE`];new Set(Ne);var Pe=[`GET`,...Ne];new Set(Pe);var Fe=[`about:`,`blob:`,`chrome:`,`chrome-untrusted:`,`content:`,`data:`,`devtools:`,`file:`,`filesystem:`,`javascript:`];function Ie(e){try{return Fe.includes(new URL(e).protocol)}catch{return!1}}var Le=v.createContext(null);Le.displayName=`DataRouter`;var Re=v.createContext(null);Re.displayName=`DataRouterState`;var ze=v.createContext(!1);function Be(){return v.useContext(ze)}var Ve=v.createContext({isTransitioning:!1});Ve.displayName=`ViewTransition`;var He=v.createContext(new Map);He.displayName=`Fetchers`;var Ue=v.createContext(null);Ue.displayName=`Await`;var We=v.createContext(null);We.displayName=`Navigation`;var Ge=v.createContext(null);Ge.displayName=`Location`;var Ke=v.createContext({outlet:null,matches:[],isDataRoute:!1});Ke.displayName=`Route`;var qe=v.createContext(null);qe.displayName=`RouteError`;var Je=`REACT_ROUTER_ERROR`,Ye=`REDIRECT`,Xe=`ROUTE_ERROR_RESPONSE`;function Ze(e){if(e.startsWith(`${Je}:${Ye}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`&&typeof t.location==`string`&&typeof t.reloadDocument==`boolean`&&typeof t.replace==`boolean`)return t}catch{}}function Qe(e){if(e.startsWith(`${Je}:${Xe}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new Oe(t.status,t.statusText,t.data)}catch{}}function $e(e,{relative:t}={}){A(et(),`useHref() may be used only in the context of a component.`);let{basename:n,navigator:r}=v.useContext(We),{hash:i,pathname:a,search:o}=ct(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:Ce([n,a])),r.createHref({pathname:s,search:o,hash:i})}function et(){return v.useContext(Ge)!=null}function tt(){return A(et(),`useLocation() may be used only in the context of a component.`),v.useContext(Ge).location}var nt=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function rt(e){v.useContext(We).static||v.useLayoutEffect(e)}function it(){let{isDataRoute:e}=v.useContext(Ke);return e?Tt():at()}function at(){A(et(),`useNavigate() may be used only in the context of a component.`);let e=v.useContext(Le),{basename:t,navigator:n}=v.useContext(We),{matches:r}=v.useContext(Ke),{pathname:i}=tt(),a=JSON.stringify(U(r)),o=v.useRef(!1);return rt(()=>{o.current=!0}),v.useCallback((r,s={})=>{if(j(o.current,nt),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=xe(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:Ce([t,c.pathname])),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}var ot=v.createContext(null);function st(e){let t=v.useContext(Ke).outlet;return v.useMemo(()=>t&&v.createElement(ot.Provider,{value:e},t),[t,e])}function ct(e,{relative:t}={}){let{matches:n}=v.useContext(Ke),{pathname:r}=tt(),i=JSON.stringify(U(n));return v.useMemo(()=>xe(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function lt(e,t){return ut(e,t)}function ut(e,t,n){A(et(),`useRoutes() may be used only in the context of a component.`);let{navigator:r}=v.useContext(We),{matches:i}=v.useContext(Ke),a=i[i.length-1],o=a?a.params:{},s=a?a.pathname:`/`,c=a?a.pathnameBase:`/`,l=a&&a.route;{let e=l&&l.path||``;Dt(s,!l||e.endsWith(`*`)||e.endsWith(`*?`),`You rendered descendant (or called \`useRoutes()\`) at "${s}" (under ) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render. -Please change the parent to .`)}let u=tt(),d;if(t){let e=typeof t==`string`?I(t):t;A(c===`/`||e.pathname?.startsWith(c),`When overriding the location using \`\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${c}" but pathname "${e.pathname}" was given in the \`location\` prop.`),d=e}else d=u;let f=d.pathname||`/`,p=f;if(c!==`/`){let e=c.replace(/^\//,``).split(`/`);p=`/`+f.replace(/^\//,``).split(`/`).slice(e.length).join(`/`)}let m=n&&n.state.matches.length?n.state.matches.map(e=>Object.assign(e,{route:n.manifest[e.route.id]||e.route})):z(e,{pathname:p});j(l||m!=null,`No routes matched location "${d.pathname}${d.search}${d.hash}" `),j(m==null||m[m.length-1].route.element!==void 0||m[m.length-1].route.Component!==void 0||m[m.length-1].route.lazy!==void 0,`Matched leaf route at location "${d.pathname}${d.search}${d.hash}" does not have an element or Component. This means it will render an with a null value by default resulting in an "empty" page.`);let h=_t(m&&m.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:Ce([c,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?c:Ce([c,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&h?v.createElement(Ge.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...d},navigationType:`POP`}},h):h}function dt(){let e=wt(),t=ke(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r=`rgba(200,200,200, 0.5)`,i={padding:`0.5rem`,backgroundColor:r},a={padding:`2px 4px`,backgroundColor:r},o=null;return console.error(`Error handled by React Router default ErrorBoundary:`,e),o=v.createElement(v.Fragment,null,v.createElement(`p`,null,`💿 Hey developer 👋`),v.createElement(`p`,null,`You can provide a way better UX than this when your app throws errors by providing your own `,v.createElement(`code`,{style:a},`ErrorBoundary`),` or`,` `,v.createElement(`code`,{style:a},`errorElement`),` prop on your route.`)),v.createElement(v.Fragment,null,v.createElement(`h2`,null,`Unexpected Application Error!`),v.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?v.createElement(`pre`,{style:i},n):null,o)}var ft=v.createElement(dt,null),pt=class extends v.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=Qe(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:v.createElement(Ke.Provider,{value:this.props.routeContext},v.createElement(qe.Provider,{value:e,children:this.props.component}));return this.context?v.createElement(ht,{error:e},t):t}};pt.contextType=ze;var mt=new WeakMap;function ht({children:e,error:t}){let{basename:n}=v.useContext(We);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=Ze(t.digest);if(e){let r=mt.get(t);if(r)throw r;let i=Me(e.location,n),a=i.absoluteURL||i.to;if(Ie(a))throw Error(`Invalid redirect location`);if(je&&!mt.get(t)){if(i.isExternal||e.reloadDocument)window.location.href=a;else{let n=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(i.to,{replace:e.replace}));throw mt.set(t,n),n}}return v.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${a}`})}}return e}function gt({routeContext:e,match:t,children:n}){let r=v.useContext(Le);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),v.createElement(Ke.Provider,{value:e},n)}function _t(e,t=[],n){let r=n?.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let i=e,a=r?.errors;if(a!=null){let e=i.findIndex(e=>e.route.id&&a?.[e.route.id]!==void 0);A(e>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(`,`)}`),i=i.slice(0,Math.min(i.length,e+1))}let o=!1,s=-1;if(n&&r){o=r.renderFallback;for(let e=0;e=0?i.slice(0,s+1):[i[0]];break}}}}let c=n?.onError,l=r&&c?(e,t)=>{c(e,{location:r.location,params:r.matches?.[0]?.params??{},pattern:Ae(r.matches),errorInfo:t})}:void 0;return i.reduceRight((e,n,c)=>{let u,d=!1,f=null,p=null;r&&(u=a&&n.route.id?a[n.route.id]:void 0,f=n.route.errorElement||ft,o&&(s<0&&c===0?(Dt(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),d=!0,p=null):s===c&&(d=!0,p=n.route.hydrateFallbackElement||null)));let m=t.concat(i.slice(0,c+1)),h=()=>{let t;return t=u?f:d?p:n.route.Component?v.createElement(n.route.Component,null):n.route.element?n.route.element:e,v.createElement(gt,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?v.createElement(pt,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function vt(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function yt(e){let t=v.useContext(Le);return A(t,vt(e)),t}function bt(e){let t=v.useContext(Re);return A(t,vt(e)),t}function xt(e){let t=v.useContext(Ke);return A(t,vt(e)),t}function St(e){let t=xt(e),n=t.matches[t.matches.length-1];return A(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function Ct(){return St(`useRouteId`)}function wt(){let e=v.useContext(qe),t=bt(`useRouteError`),n=St(`useRouteError`);return e===void 0?t.errors?.[n]:e}function Tt(){let{router:e}=yt(`useNavigate`),t=St(`useNavigate`),n=v.useRef(!1);return rt(()=>{n.current=!0}),v.useCallback(async(r,i={})=>{j(n.current,nt),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var Et={};function Dt(e,t,n){!t&&!Et[e]&&(Et[e]=!0,j(!1,n))}v.memo(Ot);function Ot({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return ut(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function kt({to:e,replace:t,state:n,relative:r}){A(et(),` may be used only in the context of a component.`);let{static:i}=v.useContext(We);j(!i,` must not be used on the initial render in a . This is a no-op, but you should modify your code so the is only ever rendered in response to some user interaction or state change.`);let{matches:a}=v.useContext(Ke),{pathname:o}=tt(),s=it(),c=xe(e,U(a),o,r===`path`),l=JSON.stringify(c);return v.useEffect(()=>{s(JSON.parse(l),{replace:t,state:n,relative:r})},[s,l,r,t,n]),null}function At(e){return st(e.context)}function jt(e){A(!1,`A is only ever to be used as the child of element, never rendered directly. Please wrap your in a .`)}function Mt({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){A(!et(),`You cannot render a inside another . You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=v.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=I(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=v.useMemo(()=>{let e=ge(l,s);return e==null?null:{location:{pathname:e,search:u,hash:d,state:f,key:p,mask:m},navigationType:r}},[s,l,u,d,f,p,r,m]);return j(h!=null,` is not able to match the URL "${l}${u}${d}" because it does not start with the basename, so the won't render anything.`),h==null?null:v.createElement(We.Provider,{value:c},v.createElement(Ge.Provider,{children:t,value:h}))}function Nt({children:e,location:t}){return lt(Pt(e),t)}v.Component;function Pt(e,t=[]){let n=[];return v.Children.forEach(e,(e,r)=>{if(!v.isValidElement(e))return;let i=[...t,r];if(e.type===v.Fragment){n.push.apply(n,Pt(e.props.children,i));return}A(e.type===jt,`[${typeof e.type==`string`?e.type:e.type.name}] is not a component. All component children of must be a or `),A(!e.props.index||!e.props.children,`An index route cannot have child routes.`);let a={id:e.props.id||i.join(`-`),caseSensitive:e.props.caseSensitive,element:e.props.element,Component:e.props.Component,index:e.props.index,path:e.props.path,middleware:e.props.middleware,loader:e.props.loader,action:e.props.action,hydrateFallbackElement:e.props.hydrateFallbackElement,HydrateFallback:e.props.HydrateFallback,errorElement:e.props.errorElement,ErrorBoundary:e.props.ErrorBoundary,hasErrorBoundary:e.props.hasErrorBoundary===!0||e.props.ErrorBoundary!=null||e.props.errorElement!=null,shouldRevalidate:e.props.shouldRevalidate,handle:e.props.handle,lazy:e.props.lazy};e.props.children&&(a.children=Pt(e.props.children,i)),n.push(a)}),n}var Ft=`get`,It=`application/x-www-form-urlencoded`;function Lt(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function Rt(e){return Lt(e)&&e.tagName.toLowerCase()===`button`}function zt(e){return Lt(e)&&e.tagName.toLowerCase()===`form`}function Bt(e){return Lt(e)&&e.tagName.toLowerCase()===`input`}function Vt(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Ht(e,t){return e.button===0&&(!t||t===`_self`)&&!Vt(e)}function Ut(e=``){return new URLSearchParams(typeof e==`string`||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(e=>[n,e]):[[n,r]])},[]))}function Wt(e,t){let n=Ut(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var Gt=null;function Kt(){if(Gt===null)try{new FormData(document.createElement(`form`),0),Gt=!1}catch{Gt=!0}return Gt}var qt=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function Jt(e){return e!=null&&!qt.has(e)?(j(!1,`"${e}" is not a valid \`encType\` for \`
\`/\`\` and will default to "${It}"`),null):e}function Yt(e,t){let n,r,i,a,o;if(zt(e)){let o=e.getAttribute(`action`);r=o?ge(o,t):null,n=e.getAttribute(`method`)||Ft,i=Jt(e.getAttribute(`enctype`))||It,a=new FormData(e)}else if(Rt(e)||Bt(e)&&(e.type===`submit`||e.type===`image`)){let o=e.form;if(o==null)throw Error(`Cannot submit a