wip rename

This commit is contained in:
2026-01-28 14:22:35 -05:00
parent 604178341d
commit a613283539
11 changed files with 112 additions and 158 deletions

View File

@@ -0,0 +1,170 @@
package functions
import (
"fmt"
"reflect"
"strings"
"sync"
)
type typeCollector struct {
mu sync.Mutex
types map[string]string
paramTypes map[string]bool
}
func newTypeCollector() *typeCollector {
return &typeCollector{
types: make(map[string]string),
paramTypes: make(map[string]bool),
}
}
func (tc *typeCollector) collectTypes(argsType reflect.Type, fnType reflect.Type) []string {
tc.mu.Lock()
defer tc.mu.Unlock()
tc.types = make(map[string]string)
tc.paramTypes = make(map[string]bool)
var result []string
tc.collectStruct(argsType, argsType.Name())
for i := 0; i < argsType.NumField(); i++ {
field := argsType.Field(i)
if field.Type.Kind() == reflect.Pointer || strings.Contains(field.Tag.Get("json"), ",omitempty") {
tc.collectParamType(field.Type)
}
}
if fnType.Kind() == reflect.Func && fnType.NumOut() > 0 {
lastIndex := fnType.NumOut() - 1
lastType := fnType.Out(lastIndex)
if lastType.Implements(reflect.TypeOf((*error)(nil)).Elem()) {
if fnType.NumOut() > 1 {
tc.collectType(fnType.Out(0))
}
} else {
tc.collectType(lastType)
}
}
for _, t := range tc.types {
result = append(result, t)
}
return result
}
func (tc *typeCollector) collectParamType(t reflect.Type) {
if t.Kind() == reflect.Pointer {
tc.collectParamType(t.Elem())
return
}
if t.Kind() == reflect.Struct && t.Name() != "" {
tc.paramTypes[t.Name()+" | null"] = true
}
}
func (tc *typeCollector) getParamTypes() map[string]bool {
return tc.paramTypes
}
func (tc *typeCollector) collectType(t reflect.Type) {
if t.Kind() == reflect.Pointer {
tc.collectType(t.Elem())
return
}
if t.Kind() == reflect.Struct {
name := t.Name()
if _, exists := tc.types[name]; !exists {
tc.collectStruct(t, name)
}
}
}
func (tc *typeCollector) collectStruct(t reflect.Type, name string) {
if t.Kind() != reflect.Struct {
return
}
var fields []string
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if field.Anonymous || !field.IsExported() {
continue
}
fieldName := getFieldName(field)
var tsType string
var isOptional bool
isPointer := field.Type.Kind() == reflect.Pointer
if isPointer {
isOptional = true
tsType = goTypeToTSType(field.Type, false)
} else {
isOptional = strings.Contains(field.Tag.Get("json"), ",omitempty")
tsType = goTypeToTSType(field.Type, false)
}
if isOptional {
fieldName += "?"
}
fields = append(fields, fmt.Sprintf("%s: %s", fieldName, tsType))
tc.collectType(field.Type)
}
tc.types[name] = fmt.Sprintf("interface %s {%s}", name, strings.Join(fields, "; "))
}
func goTypeToTSType(t reflect.Type, isPointer bool) string {
if t.Kind() == reflect.Pointer {
return goTypeToTSType(t.Elem(), true)
}
baseType := ""
switch t.Kind() {
case reflect.String:
baseType = "string"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
baseType = "number"
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
baseType = "number"
case reflect.Float32, reflect.Float64:
baseType = "number"
case reflect.Bool:
baseType = "boolean"
case reflect.Interface:
baseType = "any"
case reflect.Slice:
baseType = fmt.Sprintf("%s[]", goTypeToTSType(t.Elem(), false))
case reflect.Map:
if t.Key().Kind() == reflect.String && t.Elem().Kind() == reflect.Interface {
baseType = "Record<string, any>"
} else {
baseType = "Record<string, any>"
}
case reflect.Struct:
name := t.Name()
if name == "" {
baseType = "{}"
} else {
baseType = name
}
default:
baseType = "any"
}
if isPointer {
baseType += " | null"
}
return baseType
}

View File

@@ -0,0 +1,95 @@
package functions
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"modernc.org/quickjs"
)
type TestArgs struct {
Field1 string `json:"field1"`
}
func (t TestArgs) Validate() error {
return nil
}
func TestAsyncFunction(t *testing.T) {
RegisterAsyncFunction("testAsync", func(_ context.Context, args TestArgs) (string, error) {
return "result: " + args.Field1, nil
})
registryMutex.RLock()
fn, ok := functionRegistry["testAsync"]
registryMutex.RUnlock()
require.True(t, ok, "testAsync should be registered")
assert.Contains(t, fn.Definition(), "Promise<string>", "definition should include Promise<string>")
}
func TestAsyncFunctionResolution(t *testing.T) {
RegisterAsyncFunction("resolveTest", func(_ context.Context, args TestArgs) (string, error) {
return "test-result", nil
})
vm, err := quickjs.NewVM()
require.NoError(t, err)
defer func() {
_ = vm.Close()
}()
vm.SetCanBlock(true)
RegisterFunctions(context.Background(), vm)
result, err := vm.Eval(`resolveTest("hello")`, quickjs.EvalGlobal)
require.NoError(t, err)
assert.NotNil(t, result)
}
func TestAsyncFunctionRejection(t *testing.T) {
RegisterAsyncFunction("rejectTest", func(_ context.Context, args TestArgs) (string, error) {
return "", assert.AnError
})
vm, err := quickjs.NewVM()
require.NoError(t, err)
defer func() {
_ = vm.Close()
}()
vm.SetCanBlock(true)
RegisterFunctions(context.Background(), vm)
result, err := vm.Eval(`rejectTest({field1: "hello"})`, quickjs.EvalGlobal)
require.NoError(t, err)
assert.NotNil(t, result)
}
func TestNonPromise(t *testing.T) {
RegisterFunction("nonPromiseTest", func(_ context.Context, args TestArgs) (string, error) {
return "sync-result", nil
})
vm, err := quickjs.NewVM()
require.NoError(t, err)
defer func() {
_ = vm.Close()
}()
vm.SetCanBlock(true)
RegisterFunctions(context.Background(), vm)
result, err := vm.Eval(`nonPromiseTest({field1: "hello"})`, quickjs.EvalGlobal)
require.NoError(t, err)
if obj, ok := result.(*quickjs.Object); ok {
var arr []any
if err := obj.Into(&arr); err == nil && len(arr) > 0 {
assert.Equal(t, "sync-result", arr[0])
}
}
}

View File

@@ -0,0 +1,78 @@
package functions
import (
"fmt"
"reflect"
"strings"
"sync"
)
var (
functionRegistry = make(map[string]Function)
registryMutex sync.RWMutex
collector *typeCollector
)
func registerFunction[A Args, R any](name string, isAsync bool, fn RawFunc[A, R]) {
registryMutex.Lock()
defer registryMutex.Unlock()
if collector == nil {
collector = newTypeCollector()
}
tType := reflect.TypeFor[A]()
if tType.Kind() != reflect.Struct {
panic(fmt.Sprintf("function %s: argument must be a struct type, got %v", name, tType))
}
fnType := reflect.TypeOf(fn)
types := collector.collectTypes(tType, fnType)
paramTypes := collector.getParamTypes()
functionRegistry[name] = &functionImpl[A, R]{
name: name,
fn: fn,
types: types,
definition: generateTypeScriptDefinition(name, tType, fnType, isAsync, paramTypes),
}
}
func GetFunctionDeclarations() string {
registryMutex.RLock()
defer registryMutex.RUnlock()
typeDefinitions := make(map[string]bool)
var typeDefs []string
var functionDecls []string
for _, fn := range functionRegistry {
for _, t := range fn.Types() {
if !typeDefinitions[t] {
typeDefinitions[t] = true
typeDefs = append(typeDefs, t)
}
}
functionDecls = append(functionDecls, fn.Definition())
}
result := strings.Join(typeDefs, "\n\n")
if len(result) > 0 && len(functionDecls) > 0 {
result += "\n\n"
}
result += strings.Join(functionDecls, "\n")
return result
}
func GetRegisteredFunctions() map[string]Function {
return functionRegistry
}
func RegisterFunction[T Args, R any](name string, fn RawFunc[T, R]) {
registerFunction(name, false, fn)
}
func RegisterAsyncFunction[T Args, R any](name string, fn RawFunc[T, R]) {
registerFunction(name, true, fn)
}

View File

@@ -0,0 +1,76 @@
package functions
import (
"context"
"errors"
"reflect"
)
type Function interface {
Name() string
Types() []string
Definition() string
WrapFn(context.Context) func(...any) (any, error)
}
type RawFunc[A Args, R any] func(context.Context, A) (R, error)
type Args interface {
Validate() error
}
type functionImpl[A Args, R any] struct {
name string
fn RawFunc[A, R]
definition string
types []string
}
func (b *functionImpl[A, R]) Name() string {
return b.name
}
func (b *functionImpl[A, R]) Types() []string {
return b.types
}
func (b *functionImpl[A, R]) Definition() string {
return b.definition
}
func (b *functionImpl[A, R]) WrapFn(ctx context.Context) func(...any) (any, error) {
return func(allArgs ...any) (any, error) {
// Populate Arguments
var fnArgs A
aVal := reflect.ValueOf(&fnArgs).Elem()
// Populate Fields
for i := range min(aVal.NumField(), len(allArgs)) {
field := aVal.Field(i)
if !field.CanSet() {
return nil, errors.New("cannot set field")
}
argVal := reflect.ValueOf(allArgs[i])
if !argVal.Type().AssignableTo(field.Type()) {
return nil, errors.New("cannot assign field")
}
field.Set(argVal)
}
// Validate
if err := fnArgs.Validate(); err != nil {
return nil, errors.New("cannot validate args")
}
// Call Function
resp, err := b.fn(ctx, fnArgs)
if err != nil {
return nil, err
}
return resp, nil
}
}

View File

@@ -0,0 +1,73 @@
package functions
import (
"fmt"
"reflect"
"strings"
)
func getFieldName(field reflect.StructField) string {
jsonTag := field.Tag.Get("json")
if jsonTag != "" && jsonTag != "-" {
name, _, _ := strings.Cut(jsonTag, ",")
return name
}
return field.Name
}
func generateTypeScriptDefinition(name string, argsType reflect.Type, fnType reflect.Type, isPromise bool, paramTypes map[string]bool) string {
if argsType.Kind() != reflect.Struct {
return ""
}
var params []string
for i := 0; i < argsType.NumField(); i++ {
field := argsType.Field(i)
fieldName := getFieldName(field)
goType := field.Type
var tsType string
var isOptional bool
isPointer := goType.Kind() == reflect.Pointer
if isPointer {
isOptional = true
tsType = goTypeToTSType(goType, true)
if !strings.Contains(tsType, " | null") {
tsType += " | null"
}
} else {
isOptional = strings.Contains(field.Tag.Get("json"), ",omitempty")
tsType = goTypeToTSType(goType, false)
if isOptional && paramTypes[tsType+" | null"] {
tsType += " | null"
}
}
if isOptional {
fieldName += "?"
}
params = append(params, fmt.Sprintf("%s: %s", fieldName, tsType))
}
returnSignature := "any"
if fnType.Kind() == reflect.Func && fnType.NumOut() > 0 {
lastIndex := fnType.NumOut() - 1
lastType := fnType.Out(lastIndex)
if lastType.Implements(reflect.TypeOf((*error)(nil)).Elem()) {
if fnType.NumOut() > 1 {
returnType := fnType.Out(0)
returnSignature = goTypeToTSType(returnType, returnType.Kind() == reflect.Pointer)
}
} else {
returnSignature = goTypeToTSType(lastType, lastType.Kind() == reflect.Pointer)
}
}
if isPromise {
returnSignature = fmt.Sprintf("Promise<%s>", returnSignature)
}
return fmt.Sprintf("declare function %s(%s): %s;", name, strings.Join(params, ", "), returnSignature)
}

View File

@@ -0,0 +1,273 @@
package functions
import (
"context"
"reflect"
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
type TestBasicArgs struct {
Name string `json:"name"`
Age int `json:"age"`
}
func (t TestBasicArgs) Validate() error { return nil }
func TestBasicType(t *testing.T) {
resetRegistry()
RegisterFunction[TestBasicArgs, string]("basic", func(ctx context.Context, args TestBasicArgs) (string, error) {
return args.Name, nil
})
defs := GetFunctionDeclarations()
assert.Contains(t, defs, "declare function basic(name: string, age: number): string;")
assert.Contains(t, defs, "interface TestBasicArgs")
}
func resetRegistry() {
registryLock.Lock()
defer registryLock.Unlock()
functionRegistry = make(map[string]Function)
}
var (
registryLock sync.Mutex
)
type TestComplexArgs struct {
Items []int `json:"items"`
Data map[string]any `json:"data"`
Flag bool `json:"flag"`
}
func (t TestComplexArgs) Validate() error { return nil }
func TestComplexTypes(t *testing.T) {
resetRegistry()
RegisterFunction[TestComplexArgs, bool]("complex", func(ctx context.Context, args TestComplexArgs) (bool, error) {
return args.Flag, nil
})
defs := GetFunctionDeclarations()
assert.Contains(t, defs, "declare function complex(items: number[], data: Record<string, any>, flag: boolean): boolean;")
}
type TestNestedArgs struct {
User struct {
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
} `json:"user"`
}
func (t TestNestedArgs) Validate() error { return nil }
func TestNestedStruct(t *testing.T) {
resetRegistry()
RegisterFunction[TestNestedArgs, string]("nested", func(ctx context.Context, args TestNestedArgs) (string, error) {
return args.User.FirstName, nil
})
defs := GetFunctionDeclarations()
assert.Contains(t, defs, "declare function nested(user: {}): string;")
}
type TestOptionalArgs struct {
Name string `json:"name"`
Age *int `json:"age,omitempty"`
Score *int `json:"score"`
}
func (t TestOptionalArgs) Validate() error { return nil }
func TestOptionalFields(t *testing.T) {
resetRegistry()
RegisterFunction[TestOptionalArgs, string]("optional", func(ctx context.Context, args TestOptionalArgs) (string, error) {
return args.Name, nil
})
defs := GetFunctionDeclarations()
assert.Contains(t, defs, "declare function optional(name: string, age?: number | null, score?: number | null): string;")
}
type TestResult struct {
ID int `json:"id"`
Data []byte `json:"data"`
}
type TestResultArgs struct {
Input string `json:"input"`
}
func (t TestResultArgs) Validate() error { return nil }
func TestResultStruct(t *testing.T) {
resetRegistry()
RegisterFunction[TestResultArgs, TestResult]("result", func(ctx context.Context, args TestResultArgs) (TestResult, error) {
return TestResult{ID: 1}, nil
})
defs := GetFunctionDeclarations()
assert.Contains(t, defs, "declare function result(input: string): TestResult;")
assert.Contains(t, defs, "interface TestResult {id: number; data: number[]}")
}
type TestAsyncArgs struct {
URL string `json:"url"`
}
func (t TestAsyncArgs) Validate() error { return nil }
type TestAsyncResult struct {
Status int `json:"status"`
}
func TestAsyncPromise(t *testing.T) {
resetRegistry()
RegisterAsyncFunction[TestAsyncArgs, *TestAsyncStatus]("async", func(ctx context.Context, args TestAsyncArgs) (*TestAsyncStatus, error) {
return &TestAsyncStatus{Code: 200}, nil
})
defs := GetFunctionDeclarations()
assert.Contains(t, defs, "declare function async(url: string): Promise<TestAsyncStatus | null>;")
assert.Contains(t, defs, "interface TestAsyncStatus")
}
type TestAsyncStatus struct {
Code int `json:"code"`
}
type TestNestedPointerResult struct {
Value string `json:"value"`
}
type TestNestedPointerArgs struct {
ID int `json:"id"`
}
func (t TestNestedPointerArgs) Validate() error { return nil }
func TestNestedPointerInResult(t *testing.T) {
resetRegistry()
RegisterFunction[TestNestedPointerArgs, *TestNestedPointerResult]("pointerResult", func(ctx context.Context, args TestNestedPointerArgs) (*TestNestedPointerResult, error) {
return &TestNestedPointerResult{Value: "test"}, nil
})
defs := GetFunctionDeclarations()
assert.Contains(t, defs, "declare function pointerResult(id: number): TestNestedPointerResult | null;")
}
type TestUintArgs struct {
Value uint `json:"value"`
}
func (t TestUintArgs) Validate() error { return nil }
func TestUintType(t *testing.T) {
resetRegistry()
RegisterFunction[TestUintArgs, uint]("uint", func(ctx context.Context, args TestUintArgs) (uint, error) {
return args.Value, nil
})
defs := GetFunctionDeclarations()
assert.Contains(t, defs, "declare function uint(value: number): number;")
}
type TestFloatArgs struct {
Amount float64 `json:"amount"`
}
func (t TestFloatArgs) Validate() error { return nil }
func TestFloatType(t *testing.T) {
resetRegistry()
RegisterFunction[TestFloatArgs, float32]("float", func(ctx context.Context, args TestFloatArgs) (float32, error) {
return float32(args.Amount), nil
})
defs := GetFunctionDeclarations()
assert.Contains(t, defs, "declare function float(amount: number): number;")
}
type TestPointerInArgs struct {
User *struct {
Name string `json:"name"`
} `json:"user"`
}
func (t TestPointerInArgs) Validate() error { return nil }
func TestNestedPointerStruct(t *testing.T) {
resetRegistry()
RegisterFunction[TestPointerInArgs, string]("nestedPointer", func(ctx context.Context, args TestPointerInArgs) (string, error) {
return "test", nil
})
defs := GetFunctionDeclarations()
assert.Contains(t, defs, "declare function nestedPointer(user?: {} | null): string;")
}
type TestErrorOnlyArgs struct {
Input string `json:"input"`
}
func (t TestErrorOnlyArgs) Validate() error { return nil }
func TestErrorOnlyReturn(t *testing.T) {
resetRegistry()
RegisterFunction[TestErrorOnlyArgs, struct{}]("errorOnly", func(ctx context.Context, args TestErrorOnlyArgs) (struct{}, error) {
return struct{}{}, nil
})
defs := GetFunctionDeclarations()
assert.Contains(t, defs, "declare function errorOnly(input: string): {};")
}
func TestGoTypeToTSTypeBasic(t *testing.T) {
tests := []struct {
input reflect.Type
inputPtr bool
expected string
}{
{reflect.TypeOf(""), false, "string"},
{reflect.TypeOf(0), false, "number"},
{reflect.TypeOf(int64(0)), false, "number"},
{reflect.TypeOf(uint(0)), false, "number"},
{reflect.TypeOf(3.14), false, "number"},
{reflect.TypeOf(float32(0.0)), false, "number"},
{reflect.TypeOf(true), false, "boolean"},
{reflect.TypeOf([]string{}), false, "string[]"},
{reflect.TypeOf([]int{}), false, "number[]"},
{reflect.TypeOf(map[string]any{}), false, "Record<string, any>"},
{reflect.TypeOf(map[string]int{}), false, "Record<string, any>"},
}
for _, tt := range tests {
t.Run(tt.expected, func(t *testing.T) {
result := goTypeToTSType(tt.input, tt.inputPtr)
assert.Equal(t, tt.expected, result)
})
}
}
type TestNestedStructField struct {
Inner struct {
Name string `json:"name"`
} `json:"inner"`
}
func TestGoTypeToTSTypeNestedStruct(t *testing.T) {
result := goTypeToTSType(reflect.TypeOf(TestNestedStructField{}), false)
assert.Equal(t, "TestNestedStructField", result)
}
type TestArrayField struct {
Items []string `json:"items"`
}
func TestGoTypeToTSTypeArray(t *testing.T) {
result := goTypeToTSType(reflect.TypeOf(TestArrayField{}), false)
assert.Equal(t, "TestArrayField", result)
}