script/dom/trustedtypes/
trustedscripturl.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::fmt;
6
7use dom_struct::dom_struct;
8
9use crate::dom::bindings::codegen::Bindings::TrustedScriptURLBinding::TrustedScriptURLMethods;
10use crate::dom::bindings::codegen::UnionTypes::TrustedScriptURLOrUSVString;
11use crate::dom::bindings::error::Fallible;
12use crate::dom::bindings::reflector::{Reflector, reflect_dom_object_with_cx};
13use crate::dom::bindings::root::DomRoot;
14use crate::dom::bindings::str::DOMString;
15use crate::dom::globalscope::GlobalScope;
16use crate::dom::trustedtypes::trustedtypepolicy::TrustedType;
17use crate::dom::trustedtypes::trustedtypepolicyfactory::{
18    DEFAULT_SCRIPT_SINK_GROUP, TrustedTypePolicyFactory,
19};
20
21#[dom_struct]
22pub struct TrustedScriptURL {
23    reflector_: Reflector,
24
25    data: DOMString,
26}
27
28impl TrustedScriptURL {
29    fn new_inherited(data: DOMString) -> Self {
30        Self {
31            reflector_: Reflector::new(),
32            data,
33        }
34    }
35
36    pub(crate) fn new(
37        cx: &mut js::context::JSContext,
38        data: DOMString,
39        global: &GlobalScope,
40    ) -> DomRoot<Self> {
41        reflect_dom_object_with_cx(Box::new(Self::new_inherited(data)), global, cx)
42    }
43
44    pub(crate) fn get_trusted_type_compliant_string(
45        cx: &mut js::context::JSContext,
46        global: &GlobalScope,
47        value: TrustedScriptURLOrUSVString,
48        sink: &str,
49    ) -> Fallible<DOMString> {
50        match value {
51            TrustedScriptURLOrUSVString::USVString(value) => {
52                TrustedTypePolicyFactory::get_trusted_type_compliant_string(
53                    cx,
54                    TrustedType::TrustedScriptURL,
55                    global,
56                    value.as_ref().into(),
57                    sink,
58                    DEFAULT_SCRIPT_SINK_GROUP,
59                )
60            },
61            TrustedScriptURLOrUSVString::TrustedScriptURL(trusted_script_url) => {
62                Ok(trusted_script_url.data.clone())
63            },
64        }
65    }
66
67    pub(crate) fn data(&self) -> &DOMString {
68        &self.data
69    }
70}
71
72impl fmt::Display for TrustedScriptURL {
73    #[inline]
74    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
75        f.write_str(&self.data.str())
76    }
77}
78
79impl TrustedScriptURLMethods<crate::DomTypeHolder> for TrustedScriptURL {
80    /// <https://www.w3.org/TR/trusted-types/#trustedscripturl-stringification-behavior>
81    fn Stringifier(&self) -> DOMString {
82        self.data.clone()
83    }
84
85    /// <https://www.w3.org/TR/trusted-types/#dom-trustedscripturl-tojson>
86    fn ToJSON(&self) -> DOMString {
87        self.data.clone()
88    }
89}