1extern crate alloc;
9
10use alloc::string::String;
11use alloc::vec::Vec;
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum DynamicScriptAction {
15 EvalClassic { idx: usize, code: String },
17 EvalModule { idx: usize, specifier: String, code: String },
19 DispatchError { idx: usize },
21}
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct DynamicScriptFetchRequest {
25 pub idx: usize,
26 pub url: String,
27 pub host: String,
28 pub path: String,
29 pub is_https: bool,
30 pub is_module: bool,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
34struct PendingFetch {
35 idx: usize,
36 url: String,
37 host: String,
38 path: String,
39 is_module: bool,
40 ordered: bool,
41}
42
43#[derive(Debug, Default)]
44pub struct DynamicScriptManager {
45 pending_fetches: Vec<PendingFetch>,
46}
47
48impl DynamicScriptManager {
49 pub fn new() -> Self {
50 Self {
51 pending_fetches: Vec::new(),
52 }
53 }
54
55 pub fn has_pending(&self) -> bool {
56 !self.pending_fetches.is_empty()
57 }
58
59 pub fn clear(&mut self) {
60 self.pending_fetches.clear();
61 }
62
63 pub fn process_script<F>(
65 &mut self,
66 idx: usize,
67 src: Option<&str>,
68 ty: &str,
69 text: &str,
70 page_url: &str,
71 cache_reader: F,
72 ) -> (Vec<DynamicScriptAction>, Option<DynamicScriptFetchRequest>)
73 where
74 F: Fn(&str, &str) -> Option<Vec<u8>>,
75 {
76 self.process_script_with_async(idx, src, ty, text, page_url, true, cache_reader)
77 }
78
79 #[allow(clippy::too_many_arguments)]
81 pub fn process_script_with_async<F>(
82 &mut self,
83 idx: usize,
84 src: Option<&str>,
85 ty: &str,
86 text: &str,
87 page_url: &str,
88 is_async: bool,
89 cache_reader: F,
90 ) -> (Vec<DynamicScriptAction>, Option<DynamicScriptFetchRequest>)
91 where
92 F: Fn(&str, &str) -> Option<Vec<u8>>,
93 {
94 let ty_trimmed = ty.trim().to_ascii_lowercase();
95 let ty_essence = ty_trimmed.split(';').next().unwrap_or("").trim();
96 let is_module = ty_essence == "module";
97 let is_classic = ty_essence.is_empty()
98 || matches!(
99 ty_essence,
100 "text/javascript"
101 | "application/javascript"
102 | "application/x-javascript"
103 | "text/ecmascript"
104 | "application/ecmascript"
105 );
106
107 if !is_classic && !is_module {
108 return (Vec::new(), None);
109 }
110
111 match src {
112 Some(src_str) if !src_str.trim().is_empty() => {
113 let resolved = super::url_resolve::resolve_url(page_url, src_str.trim());
114 let (is_https, host, path) = super::url_resolve::split_target(
115 &resolved,
116 page_url.starts_with("https://"),
117 "",
118 );
119 let ordered = !is_async;
120 let has_preceding_ordered =
121 ordered && self.pending_fetches.iter().any(|p| p.ordered);
122
123 let cached = cache_reader(&host, &path);
125 if !has_preceding_ordered {
126 if let Some(cached_bytes) = cached {
127 let code = String::from_utf8(cached_bytes).unwrap_or_else(|e| {
128 String::from_utf8_lossy(&e.into_bytes()).into_owned()
129 });
130 let action = if is_module {
131 DynamicScriptAction::EvalModule {
132 idx,
133 specifier: resolved,
134 code,
135 }
136 } else {
137 DynamicScriptAction::EvalClassic { idx, code }
138 };
139 return (alloc::vec![action], None);
140 }
141 }
142 let fetch_req = if cached.is_some() {
143 None
144 } else {
145 Some(DynamicScriptFetchRequest {
146 idx,
147 url: resolved.clone(),
148 host: host.clone(),
149 path: path.clone(),
150 is_https,
151 is_module,
152 })
153 };
154 self.pending_fetches.push(PendingFetch {
155 idx,
156 url: resolved,
157 host,
158 path,
159 is_module,
160 ordered,
161 });
162 (Vec::new(), fetch_req)
163 }
164 _ => {
165 if text.trim().is_empty() {
167 (Vec::new(), None)
168 } else {
169 let action = if is_module {
170 DynamicScriptAction::EvalModule {
171 idx,
172 specifier: String::from("<inline-module>"),
173 code: String::from(text),
174 }
175 } else {
176 DynamicScriptAction::EvalClassic {
177 idx,
178 code: String::from(text),
179 }
180 };
181 (alloc::vec![action], None)
182 }
183 }
184 }
185 }
186
187 pub fn poll_pending<F>(&mut self, cache_reader: F) -> Vec<DynamicScriptAction>
191 where
192 F: Fn(&str, &str) -> Option<Vec<u8>>,
193 {
194 if self.pending_fetches.is_empty() {
195 return Vec::new();
196 }
197
198 let mut actions = Vec::new();
199 let mut remaining = Vec::new();
200 let mut ordered_blocked = false;
201
202 for pending in self.pending_fetches.drain(..) {
203 if pending.ordered && ordered_blocked {
204 remaining.push(pending);
205 continue;
206 }
207 if let Some(cached_bytes) = cache_reader(&pending.host, &pending.path) {
208 let code = String::from_utf8(cached_bytes)
209 .unwrap_or_else(|e| String::from_utf8_lossy(&e.into_bytes()).into_owned());
210 if pending.is_module {
211 actions.push(DynamicScriptAction::EvalModule {
212 idx: pending.idx,
213 specifier: pending.url,
214 code,
215 });
216 } else {
217 actions.push(DynamicScriptAction::EvalClassic {
218 idx: pending.idx,
219 code,
220 });
221 }
222 } else {
223 if pending.ordered {
224 ordered_blocked = true;
225 }
226 remaining.push(pending);
227 }
228 }
229
230 self.pending_fetches = remaining;
231 actions
232 }
233
234 pub fn take_failed<F>(&mut self, failed: F) -> Vec<DynamicScriptAction>
237 where
238 F: Fn(&str, &str) -> bool,
239 {
240 let mut actions = Vec::new();
241 self.pending_fetches.retain(|p| {
242 if failed(&p.host, &p.path) {
243 actions.push(DynamicScriptAction::DispatchError { idx: p.idx });
244 false
245 } else {
246 true
247 }
248 });
249 actions
250 }
251}