1 package OpenILS::Utils::SpiderMonkey;
2 use strict; use warnings;
3 use OpenSRF::Utils::Logger qw(:logger);
4 use OpenILS::Utils::ScriptRunner;
5 use base 'OpenILS::Utils::ScriptRunner';
6 use JavaScript::SpiderMonkey;
9 my ( $class, $file ) = @_;
10 $class = ref($class) || $class;
11 my $self = { file => $file };
12 return bless( $self, $class );
16 my( $self, $context ) = @_;
17 $self->{ctx} = $context if $context;
23 my $js = JavaScript::SpiderMonkey->new();
25 $js->function_set("perl_print", sub { print "@_\n"; } );
26 $js->function_set("log_error", sub { $logger->error(@_); return 1;} );
27 $js->function_set("log_warn", sub { $logger->warn(@_); return 1;} );
28 $js->function_set("log_info", sub { $logger->info(@_); return 1;} );
29 $js->function_set("log_debug", sub { $logger->debug(@_); return 1;} );
30 $js->function_set("log_internal", sub { $logger->internal(@_); return 1;} );
37 my( $self, $filename ) = @_;
38 $self->{file} = $filename;
43 my $file = shift() || $self->{file};
44 my $js = $self->context;
46 if( ! open(F, $file) ) {
47 $logger->error("Error opening script file: $file");
51 if( ! $js->eval(join("\n", <F>)) ) {
52 $logger->error("$file Eval failed: $@");
61 my( $self, $file ) = @_;
73 my( $self, $key, $fm ) = @_;
74 my $ctx = $self->context;
75 return undef unless ($ctx and $key and $fm);
76 my $o = $ctx->object_by_path($key);
78 for my $f ( $fm->properties ) {
79 $ctx->property_by_path("$key.$f", $fm->$f(),
82 my $k = _js_prop_name(shift());
87 my $k = _js_prop_name(shift());
97 my( $self, $key, $hash ) = @_;
98 my $ctx = $self->context;
99 return undef unless ($ctx and $key and $hash);
100 $ctx->object_by_path($key);
102 for my $k ( keys %$hash ) {
103 $ctx->property_by_path(
104 "$key.$k", $hash->{$k},
105 sub { $hash->{_js_prop_name(shift())} },
107 my( $key, $val ) = @_;
108 $hash->{_js_prop_name($key)} = $val; }