types
This commit is contained in:
@@ -6,12 +6,14 @@ type RuntimeOption func(*Runtime)
|
||||
|
||||
func WithStdout(stdout io.Writer) RuntimeOption {
|
||||
return func(r *Runtime) {
|
||||
// Set Stdout
|
||||
r.opts.Stdout = stdout
|
||||
}
|
||||
}
|
||||
|
||||
func WithStderr(stderr io.Writer) RuntimeOption {
|
||||
return func(r *Runtime) {
|
||||
// Set Stderr
|
||||
r.opts.Stderr = stderr
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,8 +14,10 @@ import (
|
||||
)
|
||||
|
||||
type Runtime struct {
|
||||
ctx *qjs.Context
|
||||
opts qjs.Option
|
||||
ctx *qjs.Context
|
||||
opts qjs.Option
|
||||
funcs map[string]functions.Function
|
||||
typeDecls map[string]string
|
||||
}
|
||||
|
||||
func New(ctx context.Context, opts ...RuntimeOption) (*Runtime, error) {
|
||||
@@ -41,8 +43,21 @@ func New(ctx context.Context, opts ...RuntimeOption) (*Runtime, error) {
|
||||
}
|
||||
|
||||
func (r *Runtime) populateGlobals() error {
|
||||
for name, fn := range functions.GetRegisteredFunctions() {
|
||||
// Register Main Function
|
||||
// Initialize Maps
|
||||
r.funcs = make(map[string]functions.Function)
|
||||
r.typeDecls = make(map[string]string)
|
||||
|
||||
// Load Requested Functions
|
||||
allFuncs := functions.GetRegisteredFunctions()
|
||||
for name, fn := range allFuncs {
|
||||
r.funcs[name] = fn
|
||||
if err := r.addFunctionTypes(fn); err != nil {
|
||||
return fmt.Errorf("failed to add types for function %s: %w", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Register Functions with QuickJS
|
||||
for name, fn := range r.funcs {
|
||||
if fn.IsAsync() {
|
||||
r.ctx.SetAsyncFunc(name, func(this *qjs.This) {
|
||||
qjsVal, err := callFunc(this, fn)
|
||||
@@ -62,6 +77,37 @@ func (r *Runtime) populateGlobals() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// addFunctionTypes adds types from a function to the runtime's type declarations.
|
||||
// Returns an error if there's a type conflict (same name, different definition).
|
||||
func (r *Runtime) addFunctionTypes(fn functions.Function) error {
|
||||
for name, def := range fn.Types() {
|
||||
if existing, ok := r.typeDecls[name]; ok && existing != def {
|
||||
return fmt.Errorf("type conflict: %s has conflicting definitions (existing: %s, new: %s)",
|
||||
name, existing, def)
|
||||
}
|
||||
r.typeDecls[name] = def
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetTypeDeclarations returns all TypeScript type declarations for this runtime.
|
||||
// Includes both type definitions and function declarations.
|
||||
func (r *Runtime) GetTypeDeclarations() string {
|
||||
var decls []string
|
||||
|
||||
// Add Type Definitions
|
||||
for _, def := range r.typeDecls {
|
||||
decls = append(decls, def)
|
||||
}
|
||||
|
||||
// Add Function Declarations
|
||||
for _, fn := range r.funcs {
|
||||
decls = append(decls, fn.Definition())
|
||||
}
|
||||
|
||||
return strings.Join(decls, "\n\n")
|
||||
}
|
||||
|
||||
func (r *Runtime) RunFile(filePath string) error {
|
||||
tsFileContent, err := os.ReadFile(filePath)
|
||||
if err != nil {
|
||||
@@ -86,9 +132,9 @@ func (r *Runtime) RunCode(tsCode string) error {
|
||||
|
||||
func (r *Runtime) transformCode(tsCode string) ([]byte, error) {
|
||||
result := api.Transform(tsCode, api.TransformOptions{
|
||||
Loader: api.LoaderTS,
|
||||
Target: api.ES2022,
|
||||
// Format: api.FormatIIFE,
|
||||
Loader: api.LoaderTS,
|
||||
Target: api.ES2022,
|
||||
Format: api.FormatIIFE,
|
||||
Sourcemap: api.SourceMapNone,
|
||||
TreeShaking: api.TreeShakingFalse,
|
||||
})
|
||||
|
||||
@@ -23,11 +23,14 @@ func (t TestArgs) Validate() error {
|
||||
}
|
||||
|
||||
func TestExecuteTypeScript(t *testing.T) {
|
||||
// Create Buffers
|
||||
var stdout, stderr bytes.Buffer
|
||||
|
||||
// Create Runtime
|
||||
rt, err := New(context.Background(), WithStderr(&stderr), WithStdout(&stdout))
|
||||
assert.NoError(t, err, "Expected no error")
|
||||
|
||||
// Create TypeScript Code
|
||||
tsCode := `interface Person {
|
||||
name: string;
|
||||
age: number;
|
||||
@@ -54,73 +57,107 @@ function calculateSum(a: number, b: number): number {
|
||||
console.log("Sum of 5 and 10 is: " + calculateSum(5, 10));
|
||||
`
|
||||
|
||||
// Create Temp File
|
||||
tmpFile, err := os.CreateTemp("", "*.ts")
|
||||
assert.NoError(t, err, "Failed to create temp file")
|
||||
t.Cleanup(func() {
|
||||
_ = os.Remove(tmpFile.Name())
|
||||
})
|
||||
|
||||
// Write Code to File
|
||||
_, err = tmpFile.WriteString(tsCode)
|
||||
assert.NoError(t, err, "Failed to write to temp file")
|
||||
err = tmpFile.Close()
|
||||
assert.NoError(t, err, "Failed to close temp file")
|
||||
|
||||
// Run File
|
||||
err = rt.RunFile(tmpFile.Name())
|
||||
|
||||
// Verify Execution
|
||||
assert.NoError(t, err, "Expected no error")
|
||||
assert.Empty(t, stderr.String(), "Expected no error output")
|
||||
|
||||
// Verify Output
|
||||
output := stdout.String()
|
||||
|
||||
assert.Contains(t, output, "Hello, Alice!", "Should greet Alice")
|
||||
assert.Contains(t, output, "You are 30 years old", "Should show age")
|
||||
assert.Contains(t, output, "Email: alice@example.com", "Should show email")
|
||||
assert.Contains(t, output, "Sum of 5 and 10 is: 15", "Should calculate sum correctly")
|
||||
|
||||
// Verify Line Count
|
||||
lines := strings.Split(strings.TrimSpace(output), "\n")
|
||||
assert.GreaterOrEqual(t, len(lines), 3, "Should have at least 3 output lines")
|
||||
}
|
||||
|
||||
func TestAsyncFunctionResolution(t *testing.T) {
|
||||
// Register Async Function
|
||||
functions.RegisterAsyncFunction("resolveTest", func(_ context.Context, args TestArgs) (string, error) {
|
||||
return "test-result", nil
|
||||
})
|
||||
|
||||
// Create Runtime
|
||||
r, err := New(context.Background())
|
||||
require.NoError(t, err)
|
||||
|
||||
// Async functions need to be awaited in an async context
|
||||
// Execute Async Function - Must be awaited in async context
|
||||
result, err := r.ctx.Eval("test.js", qjs.Code(`async function run() { return await resolveTest("hello"); }; run()`))
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
defer result.Free()
|
||||
|
||||
// Verify Result
|
||||
assert.Equal(t, "test-result", result.String())
|
||||
}
|
||||
|
||||
func TestAsyncFunctionRejection(t *testing.T) {
|
||||
// Register Async Function that Returns Error
|
||||
functions.RegisterAsyncFunction("rejectTest", func(_ context.Context, args TestArgs) (string, error) {
|
||||
return "", assert.AnError
|
||||
})
|
||||
|
||||
// Create Runtime
|
||||
r, err := New(context.Background())
|
||||
require.NoError(t, err)
|
||||
|
||||
// Rejected promises throw when awaited
|
||||
// Execute Async Function - Rejected Promises Throw When Awaited
|
||||
_, err = r.ctx.Eval("test.js", qjs.Code(`async function run() { return await rejectTest("hello"); }; run()`))
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestNonPromise(t *testing.T) {
|
||||
// Register Sync Function
|
||||
functions.RegisterFunction("nonPromiseTest", func(_ context.Context, args TestArgs) (string, error) {
|
||||
return "sync-result", nil
|
||||
})
|
||||
|
||||
// Create Runtime
|
||||
r, err := New(context.Background())
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Execute Sync Function
|
||||
result, err := r.ctx.Eval("test.js", qjs.Code(`nonPromiseTest("hello")`))
|
||||
assert.NoError(t, err)
|
||||
defer result.Free()
|
||||
|
||||
// Verify Result
|
||||
assert.Equal(t, "sync-result", result.String())
|
||||
}
|
||||
|
||||
func TestGetTypeDeclarations(t *testing.T) {
|
||||
// Register Function
|
||||
functions.RegisterFunction("testFunc", func(_ context.Context, args TestArgs) (string, error) {
|
||||
return "result", nil
|
||||
})
|
||||
|
||||
// Create Runtime
|
||||
r, err := New(context.Background())
|
||||
require.NoError(t, err)
|
||||
|
||||
// Get Type Declarations
|
||||
decls := r.GetTypeDeclarations()
|
||||
|
||||
// Verify Declarations
|
||||
assert.Contains(t, decls, "interface TestArgs")
|
||||
assert.Contains(t, decls, "declare function testFunc")
|
||||
assert.Contains(t, decls, "field1: string")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user