11const std = @import ("std" );
22
3+ const jsruntime = @import ("jsruntime" );
4+
35const server = @import ("../server.zig" );
46const Ctx = server .Cmd ;
57const cdp = @import ("cdp.zig" );
@@ -108,11 +110,14 @@ fn runIfWaitingForDebugger(
108110
109111fn evaluate (
110112 alloc : std.mem.Allocator ,
111- _ : u64 ,
113+ id : u64 ,
112114 scanner : * std.json.Scanner ,
113- _ : * Ctx ,
115+ ctx : * Ctx ,
114116) ! []const u8 {
115117
118+ // ensure a page has been previously created
119+ if (ctx .browser .currentSession ().page == null ) return error .CDPNoPage ;
120+
116121 // input
117122 const Params = struct {
118123 expression : []const u8 ,
@@ -123,7 +128,45 @@ fn evaluate(
123128 const sessionID = input .sessionID ;
124129 std .debug .assert (sessionID != null );
125130
126- std .log .debug ("expr: len {d}" , .{input .params .expression .len });
127-
128- return error .CDPNormal ;
131+ // save script in file at debug mode
132+ std .log .debug ("script {d} length: {d}" , .{ id , input .params .expression .len });
133+ if (std .log .defaultLogEnabled (.debug )) {
134+ const name = try std .fmt .allocPrint (alloc , "id_{d}.js" , .{id });
135+ defer alloc .free (name );
136+ const dir = try std .fs .cwd ().makeOpenPath ("zig-cache/tmp" , .{});
137+ const f = try dir .createFile (name , .{});
138+ defer f .close ();
139+ const nb = try f .write (input .params .expression );
140+ std .debug .assert (nb == input .params .expression .len );
141+ const p = try dir .realpathAlloc (alloc , name );
142+ defer alloc .free (p );
143+ std .log .debug ("Script {d} saved at {s}" , .{ id , p });
144+ }
145+
146+ // evaluate the script in the context of the current page
147+ // TODO: should we use instead the allocator of the page?
148+ // the following code does not work
149+ // const page_alloc = ctx.browser.currentSession().page.?.arena.allocator();
150+ const session_alloc = ctx .browser .currentSession ().alloc ;
151+ var res = jsruntime.JSResult {};
152+ try ctx .browser .currentSession ().env .run (session_alloc , input .params .expression , "cdp" , & res , null );
153+ defer res .deinit (session_alloc );
154+
155+ if (! res .success ) {
156+ std .log .err ("script {d} result: {s}" , .{ id , res .result });
157+ if (res .stack ) | stack | {
158+ std .log .err ("script {d} stack: {s}" , .{ id , stack });
159+ }
160+ return error .CDPRuntimeEvaluate ;
161+ }
162+ std .log .debug ("script {d} result: {s}" , .{ id , res .result });
163+
164+ // TODO: Resp should depends on JS result returned by the JS engine
165+ const Resp = struct {
166+ type : []const u8 = "object" ,
167+ className : []const u8 = "UtilityScript" ,
168+ description : []const u8 = "UtilityScript" ,
169+ objectId : []const u8 = "7481631759780215274.3.2" ,
170+ };
171+ return result (alloc , id , Resp , Resp {}, sessionID );
129172}
0 commit comments