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};
45 if( ! open(F, $file) ) {
46 $logger->error("Error opening script file: $file");
50 my $js = $self->context;
51 $js->property_by_path("js.file", join( "\n", <F> ));
53 if( ! $js->eval("eval( js.file );") ) {
54 $logger->error("$file Eval failed: $@");
63 my( $self, $file ) = @_;
75 my( $self, $key, $fm ) = @_;
76 my $ctx = $self->context;
77 return undef unless ($ctx and $key and $fm);
78 my $o = $ctx->object_by_path($key);
80 for my $f ( $fm->properties ) {
81 $ctx->property_by_path("$key.$f", $fm->$f(),
84 my $k = _js_prop_name(shift());
89 my $k = _js_prop_name(shift());
99 my( $self, $key, $hash ) = @_;
100 my $ctx = $self->context;
101 return undef unless ($ctx and $key and $hash);
102 $ctx->object_by_path($key);
104 for my $k ( keys %$hash ) {
105 $ctx->property_by_path(
106 "$key.$k", $hash->{$k},
107 sub { $hash->{_js_prop_name(shift())} },
109 my( $key, $val ) = @_;
110 $hash->{_js_prop_name($key)} = $val; }