Files
Calcium-Ion 0c1be7b1a9 refactor(plugins): 把插件 API v1 拆成独立模块 pluginkit (#8475)
插件 API v1 的元数据校验、utils、moejs 执行层和任务钩子的结果解析搬到
嵌套模块 github.com/QuantumNous/new-api/pluginkit,按 pluginkit/vX.Y.Z
打标签发布,其他宿主可以直接引用同一份实现。

- pkg/jsplugin 只留注册表、路由和 CLI,现有导出名通过别名保留,行为不变
- 文档 v1.md、v1.d.ts、v1.schema.json 移到 pluginkit/,schema 和类型由模块内嵌
- 请求处理钩子新增宿主专有的 ctx.client、ctx.session,new-api 不提供
- 导出 MaxPluginKeyLength、NewAPIReservedKeys 和 CallPathJSONInto
- CI、Makefile、Dockerfile 和 AGENTS.md 按 relaykit 的方式加上 pluginkit
2026-11-27 19:12:59 +08:00

122 lines
4.2 KiB
Go

package pluginkit
import (
"context"
"encoding/json"
"fmt"
"reflect"
"strings"
"time"
)
// Fixture describes deterministic calls into a plugin. Arguments and expected
// values stay as JSON so fixtures remain portable across engine implementations.
type Fixture struct {
UnixNow *int64 `json:"unixNow"`
Cases []FixtureCase `json:"cases"`
}
type FixtureCase struct {
Name string `json:"name"`
Hook string `json:"hook"`
Member string `json:"member,omitempty"`
Path []string `json:"path,omitempty"`
Args []json.RawMessage `json:"args"`
Expected json.RawMessage `json:"expected"`
ExpectedError string `json:"expectedError,omitempty"`
}
type FixtureReport struct {
Total int
Passed int
}
// ReplayFixture compiles a plugin and runs every fixture case in declaration
// order. unixNow is fixed by the fixture to keep signing and timestamp hooks
// reproducible.
func ReplayFixture(ctx context.Context, source string, data []byte) (FixtureReport, error) {
return ReplayFixtureWith(ctx, CompilePlugin, source, data)
}
// ReplayFixtureWith is ReplayFixture with the host's own admission: compile
// loads the plugin, for example CompilePlugin followed by the host's route
// checks.
func ReplayFixtureWith(ctx context.Context, compile func(source string, options Options) (*LoadedPlugin, error), source string, data []byte) (FixtureReport, error) {
var fixture Fixture
if err := unmarshalJSON(data, &fixture); err != nil {
return FixtureReport{}, fmt.Errorf("decode fixture: %w", err)
}
if len(fixture.Cases) == 0 {
return FixtureReport{}, fmt.Errorf("fixture must contain at least one case")
}
options := Options{Key: "fixture", Version: "fixture"}
if fixture.UnixNow != nil {
fixed := time.Unix(*fixture.UnixNow, 0)
options.Now = func() time.Time { return fixed }
}
plugin, err := compile(source, options)
if err != nil {
return FixtureReport{}, fmt.Errorf("compile plugin: %w", err)
}
report := FixtureReport{Total: len(fixture.Cases)}
for index, testCase := range fixture.Cases {
caseName := strings.TrimSpace(testCase.Name)
if caseName == "" {
caseName = fmt.Sprintf("case %d", index+1)
}
if strings.TrimSpace(testCase.Hook) == "" {
return report, fmt.Errorf("%s: hook is required", caseName)
}
args := make([]any, len(testCase.Args))
for argumentIndex, raw := range testCase.Args {
if err = unmarshalJSON(raw, &args[argumentIndex]); err != nil {
return report, fmt.Errorf("%s: decode argument %d: %w", caseName, argumentIndex+1, err)
}
}
var result any
if testCase.Member != "" && len(testCase.Path) > 0 {
return report, fmt.Errorf("%s: member and path are mutually exclusive", caseName)
}
if len(testCase.Path) > 0 {
result, err = plugin.Engine.CallPath(ctx, testCase.Hook, testCase.Path, args...)
} else if testCase.Member == "" {
result, err = plugin.Engine.Call(ctx, testCase.Hook, args...)
} else {
result, err = plugin.Engine.CallMember(ctx, testCase.Hook, testCase.Member, args...)
}
if testCase.ExpectedError != "" {
if err == nil || !strings.Contains(err.Error(), testCase.ExpectedError) {
return report, fmt.Errorf("%s: expected error containing %q, got %v", caseName, testCase.ExpectedError, err)
}
report.Passed++
continue
}
if err != nil {
return report, fmt.Errorf("%s: %w", caseName, err)
}
if len(testCase.Expected) == 0 {
return report, fmt.Errorf("%s: expected is required when expectedError is empty", caseName)
}
var expected any
if err = unmarshalJSON(testCase.Expected, &expected); err != nil {
return report, fmt.Errorf("%s: decode expected value: %w", caseName, err)
}
actualData, marshalErr := marshalJSON(result)
if marshalErr != nil {
return report, fmt.Errorf("%s: encode actual value: %w", caseName, marshalErr)
}
var actual any
if err = unmarshalJSON(actualData, &actual); err != nil {
return report, fmt.Errorf("%s: normalize actual value: %w", caseName, err)
}
if !reflect.DeepEqual(expected, actual) {
return report, fmt.Errorf("%s: result mismatch: expected %s, got %s", caseName, testCase.Expected, actualData)
}
report.Passed++
}
return report, nil
}