viewpoint-core 0.2.9

High-level browser automation API for Viewpoint
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! Clock mocking for controlling time in browser pages.
//!
//! The Clock API allows you to control time-related functions in JavaScript,
//! including Date, setTimeout, setInterval, requestAnimationFrame, and `performance.now()`.
//!
//! # Example
//!
//! ```
//! # #[cfg(feature = "integration")]
//! # tokio_test::block_on(async {
//! # use viewpoint_core::Browser;
//! use std::time::Duration;
//! # let browser = Browser::launch().headless(true).launch().await.unwrap();
//! # let context = browser.new_context().await.unwrap();
//! # let page = context.new_page().await.unwrap();
//! # page.goto("about:blank").goto().await.unwrap();
//!
//! // Install clock mocking
//! page.clock().install().await.unwrap();
//!
//! // Set a fixed time
//! page.clock().set_fixed_time("2024-01-01T00:00:00Z").await.unwrap();
//!
//! // Check that Date.now() returns the fixed time
//! use viewpoint_js::js;
//! let time: f64 = page.evaluate(js!{ Date.now() }).await.unwrap();
//!
//! // Advance time by 5 seconds, firing any scheduled timers
//! page.clock().run_for(Duration::from_secs(5)).await.unwrap();
//! # });
//! ```

use std::sync::Arc;
use std::time::Duration;

use tracing::{debug, instrument};
use viewpoint_cdp::CdpConnection;
use viewpoint_js::js;

use crate::error::PageError;

use super::clock_script::CLOCK_MOCK_SCRIPT;

/// Clock controller for mocking time in a browser page.
///
/// The Clock API allows you to control JavaScript's time-related functions
/// including Date, setTimeout, setInterval, requestAnimationFrame, and
/// `performance.now()`.
///
/// # Example
///
/// ```
/// # #[cfg(feature = "integration")]
/// # tokio_test::block_on(async {
/// # use viewpoint_core::Browser;
/// use std::time::Duration;
/// # let browser = Browser::launch().headless(true).launch().await.unwrap();
/// # let context = browser.new_context().await.unwrap();
/// # let page = context.new_page().await.unwrap();
/// # page.goto("about:blank").goto().await.unwrap();
///
/// // Install clock mocking
/// page.clock().install().await.unwrap();
///
/// // Freeze time at a specific moment
/// page.clock().set_fixed_time("2024-01-01T00:00:00Z").await.unwrap();
///
/// // Advance time and fire scheduled timers
/// page.clock().run_for(Duration::from_secs(5)).await.unwrap();
///
/// // Uninstall when done
/// page.clock().uninstall().await.unwrap();
/// # });
/// ```
#[derive(Debug)]
pub struct Clock<'a> {
    connection: &'a Arc<CdpConnection>,
    session_id: &'a str,
    installed: bool,
}

impl<'a> Clock<'a> {
    /// Create a new clock controller for a page.
    pub(crate) fn new(connection: &'a Arc<CdpConnection>, session_id: &'a str) -> Self {
        Self {
            connection,
            session_id,
            installed: false,
        }
    }

    /// Install clock mocking on the page.
    ///
    /// This replaces Date, setTimeout, setInterval, requestAnimationFrame,
    /// and `performance.now()` with mocked versions that can be controlled.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use viewpoint_core::Page;
    ///
    /// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
    /// page.clock().install().await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the clock cannot be installed.
    #[instrument(level = "debug", skip(self))]
    pub async fn install(&mut self) -> Result<(), PageError> {
        // First inject the clock library
        self.inject_clock_library().await?;

        // Then install it
        self.evaluate(js! { window.__viewpointClock.install() })
            .await?;
        self.installed = true;

        debug!("Clock installed");
        Ok(())
    }

    /// Uninstall clock mocking and restore original functions.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use viewpoint_core::Page;
    ///
    /// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
    /// page.clock().uninstall().await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the clock cannot be uninstalled.
    #[instrument(level = "debug", skip(self))]
    pub async fn uninstall(&mut self) -> Result<(), PageError> {
        self.evaluate(js! { window.__viewpointClock && window.__viewpointClock.uninstall() })
            .await?;
        self.installed = false;

        debug!("Clock uninstalled");
        Ok(())
    }

    /// Set a fixed time that doesn't advance.
    ///
    /// All calls to `Date.now()` and new `Date()` will return this time.
    /// Time remains frozen until you call `run_for`, `fast_forward`,
    /// `set_system_time`, or `resume`.
    ///
    /// # Arguments
    ///
    /// * `time` - The time to set, either as an ISO 8601 string (e.g., "2024-01-01T00:00:00Z")
    ///   or a Unix timestamp in milliseconds.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use viewpoint_core::Page;
    ///
    /// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
    /// // Using ISO string
    /// page.clock().set_fixed_time("2024-01-01T00:00:00Z").await?;
    ///
    /// // Using timestamp
    /// page.clock().set_fixed_time(1704067200000i64).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if setting the time fails.
    #[instrument(level = "debug", skip(self, time))]
    pub async fn set_fixed_time(&self, time: impl Into<TimeValue>) -> Result<(), PageError> {
        let time_value = time.into();
        match &time_value {
            TimeValue::Timestamp(ts) => {
                self.evaluate(&js! { window.__viewpointClock.setFixedTime(#{ts}) })
                    .await?;
            }
            TimeValue::IsoString(s) => {
                self.evaluate(&js! { window.__viewpointClock.setFixedTime(#{s}) })
                    .await?;
            }
        }
        debug!(time = ?time_value, "Fixed time set");
        Ok(())
    }

    /// Set the system time that flows normally.
    ///
    /// Time starts from the specified value and advances in real time.
    ///
    /// # Arguments
    ///
    /// * `time` - The starting time, either as an ISO 8601 string or Unix timestamp.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use viewpoint_core::Page;
    ///
    /// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
    /// page.clock().set_system_time("2024-01-01T00:00:00Z").await?;
    /// // Time will now flow from 2024-01-01
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if setting the time fails.
    #[instrument(level = "debug", skip(self, time))]
    pub async fn set_system_time(&self, time: impl Into<TimeValue>) -> Result<(), PageError> {
        let time_value = time.into();
        match &time_value {
            TimeValue::Timestamp(ts) => {
                self.evaluate(&js! { window.__viewpointClock.setSystemTime(#{ts}) })
                    .await?;
            }
            TimeValue::IsoString(s) => {
                self.evaluate(&js! { window.__viewpointClock.setSystemTime(#{s}) })
                    .await?;
            }
        }
        debug!(time = ?time_value, "System time set");
        Ok(())
    }

    /// Advance time by a duration, firing any scheduled timers.
    ///
    /// This advances the clock and executes any setTimeout/setInterval
    /// callbacks that were scheduled to fire during that period.
    ///
    /// # Arguments
    ///
    /// * `duration` - The amount of time to advance.
    ///
    /// # Returns
    ///
    /// The number of timers that were fired.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use viewpoint_core::Page;
    /// use std::time::Duration;
    ///
    /// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
    /// // Advance 5 seconds, firing any timers scheduled in that period
    /// let fired = page.clock().run_for(Duration::from_secs(5)).await?;
    /// println!("Fired {} timers", fired);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if advancing time fails.
    #[instrument(level = "debug", skip(self))]
    pub async fn run_for(&self, duration: Duration) -> Result<u32, PageError> {
        let ms = duration.as_millis();
        let result: f64 = self
            .evaluate_value(&js! { window.__viewpointClock.runFor(#{ms}) })
            .await?;
        debug!(
            duration_ms = ms,
            timers_fired = result as u32,
            "Time advanced"
        );
        Ok(result as u32)
    }

    /// Fast-forward time without firing timers.
    ///
    /// This advances the clock but does NOT execute scheduled timers.
    /// Use this when you want to jump ahead in time quickly.
    ///
    /// # Arguments
    ///
    /// * `duration` - The amount of time to skip.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use viewpoint_core::Page;
    /// use std::time::Duration;
    ///
    /// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
    /// // Skip ahead 1 hour without firing any timers
    /// page.clock().fast_forward(Duration::from_secs(3600)).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if fast-forwarding fails.
    #[instrument(level = "debug", skip(self))]
    pub async fn fast_forward(&self, duration: Duration) -> Result<(), PageError> {
        let ms = duration.as_millis();
        self.evaluate(&js! { window.__viewpointClock.fastForward(#{ms}) })
            .await?;
        debug!(duration_ms = ms, "Time fast-forwarded");
        Ok(())
    }

    /// Pause at a specific time.
    ///
    /// This sets the clock to the specified time and pauses it there.
    ///
    /// # Arguments
    ///
    /// * `time` - The time to pause at, as an ISO string or timestamp.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use viewpoint_core::Page;
    ///
    /// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
    /// // Pause at noon
    /// page.clock().pause_at("2024-01-01T12:00:00Z").await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if pausing fails.
    #[instrument(level = "debug", skip(self, time))]
    pub async fn pause_at(&self, time: impl Into<TimeValue>) -> Result<(), PageError> {
        let time_value = time.into();
        match &time_value {
            TimeValue::Timestamp(ts) => {
                self.evaluate(&js! { window.__viewpointClock.pauseAt(#{ts}) })
                    .await?;
            }
            TimeValue::IsoString(s) => {
                self.evaluate(&js! { window.__viewpointClock.pauseAt(#{s}) })
                    .await?;
            }
        }
        debug!(time = ?time_value, "Clock paused");
        Ok(())
    }

    /// Resume normal time flow.
    ///
    /// After calling this, time will advance normally from the current
    /// mocked time value.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use viewpoint_core::Page;
    ///
    /// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
    /// page.clock().resume().await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if resuming fails.
    #[instrument(level = "debug", skip(self))]
    pub async fn resume(&self) -> Result<(), PageError> {
        self.evaluate(js! { window.__viewpointClock.resume() })
            .await?;
        debug!("Clock resumed");
        Ok(())
    }

    /// Run all pending timers.
    ///
    /// This advances time to execute all scheduled setTimeout and setInterval
    /// callbacks, as well as requestAnimationFrame callbacks.
    ///
    /// # Returns
    ///
    /// The number of timers that were fired.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use viewpoint_core::Page;
    ///
    /// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
    /// let fired = page.clock().run_all_timers().await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if running timers fails.
    #[instrument(level = "debug", skip(self))]
    pub async fn run_all_timers(&self) -> Result<u32, PageError> {
        let result: f64 = self
            .evaluate_value(js! { window.__viewpointClock.runAllTimers() })
            .await?;
        debug!(timers_fired = result as u32, "All timers executed");
        Ok(result as u32)
    }

    /// Run to the last scheduled timer.
    ///
    /// This advances time to the last scheduled timer and executes all
    /// timers up to that point.
    ///
    /// # Returns
    ///
    /// The number of timers that were fired.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use viewpoint_core::Page;
    ///
    /// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
    /// let fired = page.clock().run_to_last().await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if running timers fails.
    #[instrument(level = "debug", skip(self))]
    pub async fn run_to_last(&self) -> Result<u32, PageError> {
        let result: f64 = self
            .evaluate_value(js! { window.__viewpointClock.runToLast() })
            .await?;
        debug!(timers_fired = result as u32, "Ran to last timer");
        Ok(result as u32)
    }

    /// Get the number of pending timers.
    ///
    /// This includes setTimeout, setInterval, and requestAnimationFrame callbacks.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use viewpoint_core::Page;
    ///
    /// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
    /// let count = page.clock().pending_timer_count().await?;
    /// println!("{} timers pending", count);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if getting the count fails.
    #[instrument(level = "debug", skip(self))]
    pub async fn pending_timer_count(&self) -> Result<u32, PageError> {
        let result: f64 = self
            .evaluate_value(js! { window.__viewpointClock.pendingTimerCount() })
            .await?;
        Ok(result as u32)
    }

    /// Check if clock mocking is installed.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use viewpoint_core::Page;
    ///
    /// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
    /// if page.clock().is_installed().await? {
    ///     println!("Clock is mocked");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the check fails.
    pub async fn is_installed(&self) -> Result<bool, PageError> {
        let result: bool = self
            .evaluate_value(
                js! { window.__viewpointClock && window.__viewpointClock.isInstalled() },
            )
            .await
            .unwrap_or(false);
        Ok(result)
    }

    /// Inject the clock mocking library into the page.
    async fn inject_clock_library(&self) -> Result<(), PageError> {
        self.evaluate(CLOCK_MOCK_SCRIPT).await?;
        Ok(())
    }

    /// Evaluate JavaScript and return nothing.
    async fn evaluate(&self, expression: &str) -> Result<(), PageError> {
        use viewpoint_cdp::protocol::runtime::EvaluateParams;

        let _: serde_json::Value = self
            .connection
            .send_command(
                "Runtime.evaluate",
                Some(EvaluateParams {
                    expression: expression.to_string(),
                    object_group: None,
                    include_command_line_api: None,
                    silent: None,
                    context_id: None,
                    return_by_value: Some(true),
                    await_promise: Some(false),
                }),
                Some(self.session_id),
            )
            .await?;

        Ok(())
    }

    /// Evaluate JavaScript and return a value.
    async fn evaluate_value<T: serde::de::DeserializeOwned>(
        &self,
        expression: &str,
    ) -> Result<T, PageError> {
        use viewpoint_cdp::protocol::runtime::EvaluateParams;

        #[derive(serde::Deserialize)]
        struct EvalResult {
            result: ResultValue,
        }

        #[derive(serde::Deserialize)]
        struct ResultValue {
            value: serde_json::Value,
        }

        let result: EvalResult = self
            .connection
            .send_command(
                "Runtime.evaluate",
                Some(EvaluateParams {
                    expression: expression.to_string(),
                    object_group: None,
                    include_command_line_api: None,
                    silent: None,
                    context_id: None,
                    return_by_value: Some(true),
                    await_promise: Some(false),
                }),
                Some(self.session_id),
            )
            .await?;

        serde_json::from_value(result.result.value)
            .map_err(|e| PageError::EvaluationFailed(format!("Failed to deserialize result: {e}")))
    }
}

/// A time value that can be either a timestamp or an ISO string.
#[derive(Debug, Clone)]
pub enum TimeValue {
    /// Unix timestamp in milliseconds.
    Timestamp(i64),
    /// ISO 8601 formatted string.
    IsoString(String),
}

impl From<i64> for TimeValue {
    fn from(ts: i64) -> Self {
        TimeValue::Timestamp(ts)
    }
}

impl From<u64> for TimeValue {
    fn from(ts: u64) -> Self {
        TimeValue::Timestamp(ts as i64)
    }
}

impl From<&str> for TimeValue {
    fn from(s: &str) -> Self {
        TimeValue::IsoString(s.to_string())
    }
}

impl From<String> for TimeValue {
    fn from(s: String) -> Self {
        TimeValue::IsoString(s)
    }
}