Skip to main content

blitz_script/
native_document.rs

1use std::fmt::Debug;
2use std::marker::PhantomData;
3use std::sync::Arc;
4use std::task::Context;
5
6use blitz_dom::{BaseDocument, DocGuard, DocGuardMut, Document, DocumentConfig, NodeId};
7use blitz_html::HtmlDocument;
8use blitz_traits::events::{BlitzPointerEvent, DomEvent, UiEvent};
9use url::Url;
10
11use crate::document_scripts::{DocumentScript, ScriptKind, document_scripts};
12use crate::fetch::{DefaultScriptFetcher, ScriptFetcher};
13use crate::native_host::{NativeGuest, NativeHost};
14use crate::{NativeHostDocumentBackend, ScriptDocumentBackend};
15
16/// A real native guest capable of running source and operating on a Blitz DOM.
17///
18/// Implementations provide the engine and host intrinsics. This adapter does
19/// not manufacture a guest, evaluate source, or emulate DOM operations.
20pub trait TypedNativeGuest: NativeGuest<Error: Debug> + 'static {
21    /// Whether the guest implements the Intl APIs required by this runtime.
22    fn supports_intl(&self) -> bool {
23        false
24    }
25
26    /// Whether the guest can install and apply import maps.
27    fn supports_import_maps(&self) -> bool {
28        false
29    }
30
31    /// Whether the guest can execute ECMAScript modules.
32    fn supports_modules(&self) -> bool {
33        false
34    }
35
36    /// Install a parsed document and its host bindings into this guest.
37    fn install_document(&mut self, document: &mut BaseDocument) -> Result<(), Self::Error>;
38
39    /// Execute source through this guest. Implementations must return an error
40    /// when the selected script kind is unsupported.
41    fn execute_source(
42        &mut self,
43        document: &mut BaseDocument,
44        source: &str,
45        source_url: Option<&Url>,
46        kind: &ScriptKind,
47    ) -> Result<(), Self::Error>;
48
49    /// Install an import map using the guest's native import-map machinery.
50    fn install_import_map(
51        &mut self,
52        source: &str,
53        base_url: Option<&Url>,
54    ) -> Result<(), Self::Error>;
55
56    /// Dispatch an input event through this guest's DOM event implementation.
57    fn dispatch_ui_event(
58        &mut self,
59        document: &mut BaseDocument,
60        event: UiEvent,
61    ) -> Result<(), Self::Error>;
62
63    /// Poll guest jobs and host work associated with this document.
64    fn poll(
65        &mut self,
66        document: &mut BaseDocument,
67        context: Option<Context>,
68    ) -> Result<bool, Self::Error>;
69
70    /// Drain immediately runnable work according to the document settle policy.
71    fn poll_for_settle(
72        &mut self,
73        document: &mut BaseDocument,
74        context: Option<Context>,
75        run_timers: bool,
76    ) -> Result<bool, Self::Error>;
77
78    /// Notify the guest that this document is preparing for teardown.
79    fn prepare_teardown(&mut self, document: &mut BaseDocument) -> Result<(), Self::Error>;
80
81    /// Notify the guest that this document is being disposed.
82    fn dispose_document(&mut self, document: &mut BaseDocument) -> Result<(), Self::Error>;
83
84    /// Complete ready-state transitions and loading events after script bootstrap.
85    fn finish_loading(&mut self, document: &mut BaseDocument) -> Result<(), Self::Error>;
86
87    /// Forward visibility and page lifecycle changes to the guest.
88    fn set_page_visible(
89        &mut self,
90        document: &mut BaseDocument,
91        visible: bool,
92    ) -> Result<(), Self::Error>;
93
94    fn freeze(&mut self, document: &mut BaseDocument) -> Result<(), Self::Error>;
95
96    fn finish_restore(&mut self, document: &mut BaseDocument) -> Result<(), Self::Error>;
97
98    fn resume(&mut self, document: &mut BaseDocument) -> Result<(), Self::Error>;
99
100    /// Access the guest's native storage without stringifying guest values.
101    fn storage_get(&mut self, key: &str) -> Result<Option<Self::Value>, Self::Error>;
102    fn storage_set(&mut self, key: &str, value: Self::Value) -> Result<(), Self::Error>;
103    fn storage_remove(&mut self, key: &str) -> Result<(), Self::Error>;
104    fn storage_clear(&mut self) -> Result<(), Self::Error>;
105}
106
107/// Required runtime operations supplied by a native guest.
108///
109/// Basic document guests implement only `TypedNativeGuest`; executable
110/// application hosts additionally implement these runtime operations.
111pub trait NativeDocumentRuntime: TypedNativeGuest {
112    fn eval_named(
113        &mut self,
114        document: &mut BaseDocument,
115        source: &str,
116        name: &str,
117    ) -> Result<(), Self::Error>;
118
119    fn eval_json(
120        &mut self,
121        document: &mut BaseDocument,
122        source: &str,
123    ) -> Result<serde_json::Value, Self::Error>;
124
125    fn has_pending_jobs(&self) -> bool;
126
127    fn pending_task_count(&self) -> u64;
128
129    fn diagnostic_batch(
130        &self,
131        console_after: u64,
132        errors_after: u64,
133        limit: usize,
134    ) -> Result<crate::DiagnosticBatch, Self::Error>;
135
136    fn dispatch_dom_event(
137        &mut self,
138        document: &mut BaseDocument,
139        event: DomEvent,
140    ) -> Result<(), Self::Error>;
141
142    fn handle_pointer_move_to_node(
143        &mut self,
144        document: &mut BaseDocument,
145        event: BlitzPointerEvent,
146        node: NodeId,
147    ) -> Result<(), Self::Error>;
148
149    fn handle_ui_event_to_node(
150        &mut self,
151        document: &mut BaseDocument,
152        event: UiEvent,
153        node: NodeId,
154    ) -> Result<(), Self::Error>;
155
156    fn dispatch_node_event(
157        &mut self,
158        document: &mut BaseDocument,
159        node: NodeId,
160        name: &str,
161    ) -> Result<bool, Self::Error>;
162
163    fn set_ipc_handler(&mut self, handler: Box<dyn Fn(String)>) -> Result<(), Self::Error>;
164}
165
166/// Work invoked by a backend during its document poll, on the document thread.
167pub type DocumentPollHook =
168    Box<dyn FnMut(&mut dyn Document, Option<&Context<'_>>) -> bool + 'static>;
169
170/// The installed host extension owns a concrete native host, which in turn
171/// owns the guest used for all execution and document operations.
172pub struct DocumentHostExtension<G: TypedNativeGuest> {
173    host: Box<dyn NativeHost<Guest = G>>,
174    teardown_started: bool,
175    disposed: bool,
176}
177
178impl<G: TypedNativeGuest> DocumentHostExtension<G> {
179    fn new<H>(host: H) -> Self
180    where
181        H: NativeHost<Guest = G> + 'static,
182    {
183        Self {
184            host: Box::new(host),
185            teardown_started: false,
186            disposed: false,
187        }
188    }
189
190    fn install(&mut self, document: &mut BaseDocument) -> Result<(), String> {
191        self.host
192            .guest_mut()
193            .install_document(document)
194            .map_err(|error| format!("failed to install native document: {error:?}"))?;
195        Ok(())
196    }
197
198    fn guest(&self) -> &G {
199        self.host.guest()
200    }
201
202    fn guest_mut(&mut self) -> &mut G {
203        self.host.guest_mut()
204    }
205
206    fn prepare_teardown(&mut self, document: &mut BaseDocument) -> Result<(), String> {
207        if self.teardown_started {
208            return Ok(());
209        }
210        self.teardown_started = true;
211        self.guest_mut()
212            .prepare_teardown(document)
213            .map_err(|error| format!("native guest teardown preparation failed: {error:?}"))
214    }
215
216    fn dispose(&mut self, document: &mut BaseDocument) -> Result<(), String> {
217        if self.disposed {
218            return Ok(());
219        }
220        self.disposed = true;
221        self.guest_mut()
222            .dispose_document(document)
223            .map_err(|error| format!("native guest disposal failed: {error:?}"))
224    }
225}
226
227/// A script document backed by an actual guest and host supplied by its caller.
228///
229/// `H` is retained as the host's concrete type for API clarity. The host is
230/// owned behind the engine-neutral NativeHost boundary once attached.
231pub struct BoundScriptDocument<G, H>
232where
233    G: TypedNativeGuest,
234    H: NativeHost<Guest = G> + 'static,
235{
236    document: BaseDocument,
237    scripts: Vec<DocumentScript>,
238    base_url: Option<Url>,
239    fetcher: Box<dyn ScriptFetcher>,
240    extension: Option<DocumentHostExtension<G>>,
241    last_error: Option<String>,
242    execution: Option<Result<(), String>>,
243    poll_hooks: Vec<DocumentPollHook>,
244    retired: bool,
245    _host: PhantomData<fn() -> H>,
246}
247
248impl<G, H> BoundScriptDocument<G, H>
249where
250    G: TypedNativeGuest,
251    H: NativeHost<Guest = G> + 'static,
252{
253    /// Parse HTML and bind a real host before returning an executable document.
254    pub fn new_bound(html: Arc<str>, config: DocumentConfig, host: H) -> Result<Self, String> {
255        Self::new_bound_with_fetcher(html, config, host, DefaultScriptFetcher)
256    }
257
258    /// Variant of new_bound with an embedder-provided external script fetcher.
259    pub fn new_bound_with_fetcher<F>(
260        html: Arc<str>,
261        config: DocumentConfig,
262        host: H,
263        fetcher: F,
264    ) -> Result<Self, String>
265    where
266        F: ScriptFetcher,
267    {
268        let mut document = Self::parse(html, config, Box::new(fetcher))?;
269        document.attach_native_host(host)?;
270        Ok(document)
271    }
272
273    /// Return the most recent error from a Document callback, if any.
274    pub fn last_error(&self) -> Option<&str> {
275        self.last_error.as_deref()
276    }
277
278    /// Drain a callback failure so an application can publish it once.
279    pub fn take_last_error(&mut self) -> Option<String> {
280        self.last_error.take()
281    }
282
283    /// Add a poll hook without replacing hooks already registered.
284    pub fn add_poll_hook(&mut self, hook: DocumentPollHook) -> Result<(), String> {
285        self.ensure_live()?;
286        self.poll_hooks.push(hook);
287        Ok(())
288    }
289
290    /// Borrow the native guest while the document is live and attached.
291    pub fn guest(&self) -> Option<&G> {
292        if self.ensure_live().is_err() {
293            return None;
294        }
295        self.extension.as_ref().map(DocumentHostExtension::guest)
296    }
297
298    /// Mutably borrow the native guest while the document is live and attached.
299    pub fn guest_mut(&mut self) -> Option<&mut G> {
300        if self.ensure_live().is_err() {
301            return None;
302        }
303        self.extension
304            .as_mut()
305            .map(DocumentHostExtension::guest_mut)
306    }
307
308    /// Run a callback with mutable access to the guest and its document.
309    pub fn with_guest_mut<R>(
310        &mut self,
311        callback: impl FnOnce(&mut G, &mut BaseDocument) -> R,
312    ) -> Result<R, String> {
313        self.ensure_live()?;
314        let extension = self
315            .extension
316            .as_mut()
317            .ok_or_else(|| String::from("native host is not attached"))?;
318        Ok(callback(extension.guest_mut(), &mut self.document))
319    }
320
321    /// Read a native guest storage value.
322    pub fn storage_get(&mut self, key: &str) -> Result<Option<G::Value>, String> {
323        self.ensure_live()?;
324        self.extension
325            .as_mut()
326            .ok_or_else(|| String::from("native host is not attached"))?
327            .guest_mut()
328            .storage_get(key)
329            .map_err(|error| format!("native storage read failed: {error:?}"))
330    }
331
332    /// Write a native guest storage value.
333    pub fn storage_set(&mut self, key: &str, value: G::Value) -> Result<(), String> {
334        self.ensure_live()?;
335        self.extension
336            .as_mut()
337            .ok_or_else(|| String::from("native host is not attached"))?
338            .guest_mut()
339            .storage_set(key, value)
340            .map_err(|error| format!("native storage write failed: {error:?}"))
341    }
342
343    pub fn storage_remove(&mut self, key: &str) -> Result<(), String> {
344        self.ensure_live()?;
345        self.extension
346            .as_mut()
347            .ok_or_else(|| String::from("native host is not attached"))?
348            .guest_mut()
349            .storage_remove(key)
350            .map_err(|error| format!("native storage removal failed: {error:?}"))
351    }
352
353    pub fn storage_clear(&mut self) -> Result<(), String> {
354        self.ensure_live()?;
355        self.extension
356            .as_mut()
357            .ok_or_else(|| String::from("native host is not attached"))?
358            .guest_mut()
359            .storage_clear()
360            .map_err(|error| format!("native storage clear failed: {error:?}"))
361    }
362
363    fn parse(
364        html: Arc<str>,
365        config: DocumentConfig,
366        fetcher: Box<dyn ScriptFetcher>,
367    ) -> Result<Self, String> {
368        let base_url = config
369            .base_url
370            .as_deref()
371            .map(Url::parse)
372            .transpose()
373            .map_err(|error| format!("invalid document base URL: {error}"))?;
374        let parsed = HtmlDocument::from_html(&html, config);
375        let document = parsed.into_inner();
376        let scripts = document_scripts(&document);
377        Ok(Self {
378            document,
379            scripts,
380            base_url,
381            fetcher,
382            extension: None,
383            last_error: None,
384            execution: None,
385            poll_hooks: Vec::new(),
386            retired: false,
387            _host: PhantomData,
388        })
389    }
390
391    fn execute_all_scripts(&mut self) -> Result<(), String> {
392        let extension = self.extension.as_mut().ok_or_else(|| {
393            String::from("cannot execute scripts before a native host is attached")
394        })?;
395
396        #[cfg(feature = "intl")]
397        if !extension.guest_mut().supports_intl() {
398            return Err(String::from(
399                "the attached native guest does not provide Intl support",
400            ));
401        }
402
403        for script in &self.scripts {
404            let source_url = script
405                .src
406                .as_deref()
407                .map(|src| resolve_script_url(self.base_url.as_ref(), src))
408                .transpose()?;
409            let source = match (script.src.as_deref(), source_url.as_ref()) {
410                (Some(_), Some(url)) => self
411                    .fetcher
412                    .fetch_for_document(url, self.base_url.as_ref())
413                    .map_err(|error| format!("failed to fetch script {url}: {error}"))?,
414                _ => script.source.clone(),
415            };
416
417            if matches!(&script.kind, ScriptKind::ImportMap) {
418                let guest = extension.guest_mut();
419                if !guest.supports_import_maps() {
420                    return Err(String::from(
421                        "the attached native guest does not support import maps",
422                    ));
423                }
424                guest
425                    .install_import_map(&source, source_url.as_ref().or(self.base_url.as_ref()))
426                    .map_err(|error| format!("failed to install import map: {error:?}"))?;
427                continue;
428            }
429
430            if matches!(&script.kind, ScriptKind::Module) {
431                let guest = extension.guest_mut();
432                if !guest.supports_modules() {
433                    return Err(String::from(
434                        "the attached native guest does not support modules",
435                    ));
436                }
437            }
438
439            extension
440                .guest_mut()
441                .execute_source(
442                    &mut self.document,
443                    &source,
444                    source_url.as_ref().or(self.base_url.as_ref()),
445                    &script.kind,
446                )
447                .map_err(|error| format!("native script execution failed: {error:?}"))?;
448        }
449        extension
450            .guest_mut()
451            .finish_loading(&mut self.document)
452            .map_err(|error| format!("native loading completion failed: {error:?}"))
453    }
454
455    fn ensure_live(&self) -> Result<(), String> {
456        if self.retired || self.document.page_retiring {
457            Err(String::from("native document has been retired"))
458        } else {
459            Ok(())
460        }
461    }
462
463    fn run_guest_callback(
464        &mut self,
465        callback: impl FnOnce(&mut G, &mut BaseDocument) -> Result<(), G::Error>,
466    ) {
467        if self.ensure_live().is_err() {
468            return;
469        }
470        let Some(extension) = self.extension.as_mut() else {
471            return;
472        };
473        if let Err(error) = callback(extension.guest_mut(), &mut self.document) {
474            self.last_error = Some(format!("native document callback failed: {error:?}"));
475        }
476    }
477
478    fn run_poll_hooks(&mut self, context: Option<&Context<'_>>) -> bool {
479        if self.ensure_live().is_err() {
480            return false;
481        }
482        let mut hooks = std::mem::take(&mut self.poll_hooks);
483        let mut work_remains = false;
484        for hook in &mut hooks {
485            if self.document.page_frozen {
486                break;
487            }
488            work_remains |= hook(self, context);
489            if self.ensure_live().is_err() {
490                self.poll_hooks.clear();
491                return false;
492            }
493        }
494        hooks.append(&mut self.poll_hooks);
495        self.poll_hooks = hooks;
496        work_remains
497    }
498}
499
500impl<G, H> BoundScriptDocument<G, H>
501where
502    G: NativeDocumentRuntime,
503    H: NativeHost<Guest = G> + 'static,
504{
505    /// Evaluate source through the bound native guest.
506    pub fn eval(&mut self, source: &str) -> Result<(), String> {
507        self.eval_named(source, "<eval>")
508    }
509
510    /// Evaluate named source through the bound native guest.
511    pub fn eval_named(&mut self, source: &str, name: &str) -> Result<(), String> {
512        self.ensure_live()?;
513        let extension = self
514            .extension
515            .as_mut()
516            .ok_or_else(|| String::from("native host is not attached"))?;
517        extension
518            .guest_mut()
519            .eval_named(&mut self.document, source, name)
520            .map_err(|error| format!("native source evaluation failed: {error:?}"))
521    }
522
523    /// Evaluate source and return its JSON-compatible result.
524    pub fn eval_json(&mut self, source: &str) -> Result<serde_json::Value, String> {
525        self.ensure_live()?;
526        let extension = self
527            .extension
528            .as_mut()
529            .ok_or_else(|| String::from("native host is not attached"))?;
530        extension
531            .guest_mut()
532            .eval_json(&mut self.document, source)
533            .map_err(|error| format!("native JSON evaluation failed: {error:?}"))
534    }
535
536    /// Whether the live guest reports pending jobs for this document.
537    pub fn has_pending_jobs(&self) -> bool {
538        self.ensure_live().is_ok()
539            && self
540                .extension
541                .as_ref()
542                .is_some_and(|extension| extension.guest().has_pending_jobs())
543    }
544
545    /// Return the live guest's pending task count.
546    pub fn pending_task_count(&self) -> u64 {
547        if self.ensure_live().is_err() {
548            return 0;
549        }
550        self.extension
551            .as_ref()
552            .map_or(0, |extension| extension.guest().pending_task_count())
553    }
554
555    /// Return a bounded batch of diagnostics from the bound guest.
556    pub fn diagnostic_batch(
557        &self,
558        console_after: u64,
559        errors_after: u64,
560        limit: usize,
561    ) -> Result<crate::DiagnosticBatch, String> {
562        self.ensure_live()?;
563        let extension = self
564            .extension
565            .as_ref()
566            .ok_or_else(|| String::from("native host is not attached"))?;
567        extension
568            .guest()
569            .diagnostic_batch(console_after, errors_after, limit)
570            .map_err(|error| format!("native diagnostic read failed: {error:?}"))
571    }
572
573    /// Dispatch a DOM event through the bound native guest.
574    pub fn dispatch_dom_event(&mut self, event: DomEvent) -> Result<(), String> {
575        self.ensure_live()?;
576        let extension = self
577            .extension
578            .as_mut()
579            .ok_or_else(|| String::from("native host is not attached"))?;
580        extension
581            .guest_mut()
582            .dispatch_dom_event(&mut self.document, event)
583            .map_err(|error| format!("native DOM event dispatch failed: {error:?}"))
584    }
585
586    /// Move pointer state to a caller-resolved node through the bound guest.
587    pub fn handle_pointer_move_to_node(
588        &mut self,
589        event: BlitzPointerEvent,
590        node: NodeId,
591    ) -> Result<(), String> {
592        self.ensure_live()?;
593        let extension = self
594            .extension
595            .as_mut()
596            .ok_or_else(|| String::from("native host is not attached"))?;
597        extension
598            .guest_mut()
599            .handle_pointer_move_to_node(&mut self.document, event, node)
600            .map_err(|error| format!("native pointer dispatch failed: {error:?}"))
601    }
602
603    /// Dispatch UI input to a caller-resolved node through the bound guest.
604    pub fn handle_ui_event_to_node(&mut self, event: UiEvent, node: NodeId) -> Result<(), String> {
605        self.ensure_live()?;
606        let extension = self
607            .extension
608            .as_mut()
609            .ok_or_else(|| String::from("native host is not attached"))?;
610        extension
611            .guest_mut()
612            .handle_ui_event_to_node(&mut self.document, event, node)
613            .map_err(|error| format!("native UI event dispatch failed: {error:?}"))
614    }
615
616    /// Dispatch a named event at a node through the bound guest.
617    pub fn dispatch_node_event(&mut self, node: NodeId, name: &str) -> Result<bool, String> {
618        self.ensure_live()?;
619        let extension = self
620            .extension
621            .as_mut()
622            .ok_or_else(|| String::from("native host is not attached"))?;
623        extension
624            .guest_mut()
625            .dispatch_node_event(&mut self.document, node, name)
626            .map_err(|error| format!("native node event dispatch failed: {error:?}"))
627    }
628
629    /// Install an IPC handler through the bound native guest.
630    pub fn set_ipc_handler(&mut self, handler: Box<dyn Fn(String)>) -> Result<(), String> {
631        self.ensure_live()?;
632        let extension = self
633            .extension
634            .as_mut()
635            .ok_or_else(|| String::from("native host is not attached"))?;
636        extension
637            .guest_mut()
638            .set_ipc_handler(handler)
639            .map_err(|error| format!("native IPC handler installation failed: {error:?}"))
640    }
641}
642
643fn resolve_script_url(base_url: Option<&Url>, source: &str) -> Result<Url, String> {
644    if let Some(base_url) = base_url {
645        base_url
646            .join(source)
647            .map_err(|error| format!("invalid script URL {source}: {error}"))
648    } else {
649        Url::parse(source)
650            .map_err(|error| format!("relative script URL has no document base URL: {error}"))
651    }
652}
653
654impl<G, H> ScriptDocumentBackend for BoundScriptDocument<G, H>
655where
656    G: TypedNativeGuest,
657    H: NativeHost<Guest = G> + 'static,
658{
659    fn from_html(html: Arc<str>, config: DocumentConfig) -> Result<Self, String> {
660        Self::parse(html, config, Box::new(DefaultScriptFetcher))
661    }
662
663    fn execute_scripts(&mut self) -> Result<(), String> {
664        self.ensure_live()?;
665        if self.extension.is_none() {
666            return Err(String::from(
667                "cannot execute scripts before a native host is attached",
668            ));
669        }
670        if let Some(result) = &self.execution {
671            return result.clone();
672        }
673        let result = self.execute_all_scripts();
674        self.execution = Some(result.clone());
675        result
676    }
677}
678
679impl<G, H> NativeHostDocumentBackend for BoundScriptDocument<G, H>
680where
681    G: TypedNativeGuest,
682    H: NativeHost<Guest = G> + 'static,
683{
684    type Host = H;
685
686    fn attach_native_host(&mut self, host: Self::Host) -> Result<(), String> {
687        self.ensure_live()?;
688        if self.extension.is_some() {
689            return Err(String::from("a native host is already attached"));
690        }
691        let mut extension = DocumentHostExtension::new(host);
692        if let Err(error) = extension.install(&mut self.document) {
693            let _ = extension.prepare_teardown(&mut self.document);
694            let _ = extension.dispose(&mut self.document);
695            return Err(error);
696        }
697        self.extension = Some(extension);
698        Ok(())
699    }
700}
701
702impl<G, H> Document for BoundScriptDocument<G, H>
703where
704    G: TypedNativeGuest,
705    H: NativeHost<Guest = G> + 'static,
706{
707    fn inner(&self) -> DocGuard<'_> {
708        self.document.inner()
709    }
710
711    fn inner_mut(&mut self) -> DocGuardMut<'_> {
712        self.document.inner_mut()
713    }
714
715    fn handle_ui_event(&mut self, event: UiEvent) {
716        if self.document.page_frozen || self.document.page_input_blocked {
717            return;
718        }
719        self.run_guest_callback(|guest, document| guest.dispatch_ui_event(document, event));
720    }
721
722    fn poll(&mut self, context: Option<Context>) -> bool {
723        if self.ensure_live().is_err() || self.document.page_frozen {
724            return false;
725        }
726        let guest_work = if let Some(extension) = self.extension.as_mut() {
727            let guest_context = context.as_ref().map(|ctx| Context::from_waker(ctx.waker()));
728            match extension
729                .guest_mut()
730                .poll(&mut self.document, guest_context)
731            {
732                Ok(work_remains) => work_remains,
733                Err(error) => {
734                    self.last_error = Some(format!("native document poll failed: {error:?}"));
735                    false
736                }
737            }
738        } else {
739            return false;
740        };
741        let hook_work = self.run_poll_hooks(context.as_ref());
742        self.ensure_live().is_ok() && (hook_work | guest_work)
743    }
744
745    fn poll_for_settle(&mut self, context: Option<Context>, run_timers: bool) -> bool {
746        if self.ensure_live().is_err() || self.document.page_frozen {
747            return false;
748        }
749        let guest_work = if let Some(extension) = self.extension.as_mut() {
750            match extension.guest_mut().poll_for_settle(
751                &mut self.document,
752                context.as_ref().map(|ctx| Context::from_waker(ctx.waker())),
753                run_timers,
754            ) {
755                Ok(work_remains) => work_remains,
756                Err(error) => {
757                    self.last_error = Some(format!("native settle poll failed: {error:?}"));
758                    false
759                }
760            }
761        } else {
762            return false;
763        };
764        let hook_work = self.run_poll_hooks(context.as_ref());
765        self.ensure_live().is_ok() && (hook_work | guest_work)
766    }
767
768    fn prepare_teardown(&mut self) {
769        self.retired = true;
770        self.poll_hooks.clear();
771        if let Some(extension) = self.extension.as_mut() {
772            if let Err(error) = extension.prepare_teardown(&mut self.document) {
773                self.last_error = Some(error);
774            }
775        }
776        self.document.prepare_teardown();
777    }
778
779    fn dispose(mut self: Box<Self>) -> Arc<blitz_dom::release::Teardown> {
780        self.prepare_teardown();
781        if let Some(extension) = self.extension.as_mut() {
782            if let Err(error) = extension.dispose(&mut self.document) {
783                self.last_error = Some(error);
784            }
785        }
786        let receipt = Arc::clone(&self.document.inner().teardown);
787        drop(self);
788        receipt
789    }
790
791    fn set_page_visible(&mut self, visible: bool) {
792        self.document.set_page_visible(visible);
793        self.run_guest_callback(|guest, document| guest.set_page_visible(document, visible));
794    }
795
796    fn freeze(&mut self) {
797        self.document.freeze();
798        self.run_guest_callback(|guest, document| guest.freeze(document));
799    }
800
801    fn finish_restore(&mut self) {
802        self.document.finish_restore();
803        self.run_guest_callback(|guest, document| guest.finish_restore(document));
804    }
805
806    fn resume(&mut self) {
807        self.document.resume();
808        self.run_guest_callback(|guest, document| guest.resume(document));
809    }
810}
811
812impl<G, H> Drop for BoundScriptDocument<G, H>
813where
814    G: TypedNativeGuest,
815    H: NativeHost<Guest = G> + 'static,
816{
817    fn drop(&mut self) {
818        self.prepare_teardown();
819        if let Some(extension) = self.extension.as_mut() {
820            let _ = extension.dispose(&mut self.document);
821        }
822    }
823}