@@ -25,8 +25,13 @@ defmodule Wasmex.Components do
25
25
def start_link ( opts ) when is_list ( opts ) do
26
26
with { :ok , store } <- build_store ( opts ) ,
27
27
component_bytes <- Keyword . get ( opts , :bytes ) ,
28
+ imports <- Keyword . get ( opts , :imports , % { } ) ,
28
29
{ :ok , component } <- Wasmex.Components.Component . new ( store , component_bytes ) do
29
- GenServer . start_link ( __MODULE__ , % { store: store , component: component } , opts )
30
+ GenServer . start_link (
31
+ __MODULE__ ,
32
+ % { store: store , component: component , imports: imports } ,
33
+ opts
34
+ )
30
35
end
31
36
end
32
37
@@ -45,23 +50,45 @@ defmodule Wasmex.Components do
45
50
end
46
51
47
52
@ impl true
48
- def init ( % { store: store , component: component } = state ) do
49
- case Wasmex.Components.Instance . new ( store , component ) do
50
- { :ok , instance } -> { :ok , Map . merge ( state , % { instance: instance } ) }
51
- { :error , reason } -> { :error , reason }
53
+ def init ( % { store: store , component: component , imports: imports } = state ) do
54
+ case Wasmex.Components.Instance . new ( store , component , imports ) do
55
+ { :ok , instance } ->
56
+ { :ok , Map . merge ( state , % { instance: instance , component: component , imports: imports } ) }
57
+
58
+ { :error , reason } ->
59
+ { :error , reason }
52
60
end
53
61
end
54
62
55
63
@ impl true
56
64
def handle_call (
57
65
{ :call_function , name , params } ,
58
- _from ,
66
+ from ,
59
67
% { instance: instance } = state
60
68
) do
61
- case Wasmex.Components.Instance . call_function ( instance , name , params ) do
62
- { :ok , result } -> { :reply , { :ok , result } , state }
63
- { :error , error } -> { :reply , { :error , error } , state }
69
+ :ok = Wasmex.Components.Instance . call_function ( instance , name , params , from )
70
+ { :noreply , state }
71
+ end
72
+
73
+ @ impl true
74
+ def handle_info ( { :returned_function_call , result , from } , state ) do
75
+ case result do
76
+ { :raise , reason } -> raise ( reason )
77
+ valid_result -> GenServer . reply ( from , valid_result )
64
78
end
79
+
80
+ { :noreply , state }
81
+ end
82
+
83
+ @ impl true
84
+ def handle_info (
85
+ { :invoke_callback , name , token , params } ,
86
+ % { imports: imports , instance: _instance , component: component } = state
87
+ ) do
88
+ { :fn , function } = Map . get ( imports , name )
89
+ result = apply ( function , params )
90
+ :ok = Wasmex.Native . component_receive_callback_result ( component . resource , token , true , result )
91
+ { :noreply , state }
65
92
end
66
93
67
94
defp stringify ( s ) when is_binary ( s ) , do: s
0 commit comments