Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

refactor(notifications): share derived options before materialization

ldm0b766c582bfbb
diff --git a/moli-renderer-v8/src/context_bootstrap/notification_runtime.rs b/moli-renderer-v8/src/context_bootstrap/notification_runtime.rs
index 3fd03928d..98e87d3dc 100644
--- a/moli-renderer-v8/src/context_bootstrap/notification_runtime.rs
+++ b/moli-renderer-v8/src/context_bootstrap/notification_runtime.rs
@@ -253,24 +253,10 @@ pub(in crate::context_bootstrap) fn notification_constructor_callback<'s>(
);
return;
}
- if args.length() < 1 {
- throw_type_error(
- scope,
- "Failed to construct 'Notification': 1 argument required, but only 0 present.",
- );
- return;
- }
-
- let Some(title) = webidl::required_argument::<webidl::DomString>(
- scope,
- &args,
- 0,
- webidl::Context::argument("Notification", 1),
- "Failed to construct 'Notification': 1 argument required, but only 0 present.",
- ) else {
+ let Some(parsed) = webidl::parse_args::<NotificationArgs>(scope, &args) else {
return;
};
- let Some(options) = notification_options(scope, args.get(1)) else {
+ let Some(options) = notification_options(scope, parsed.options) else {
return;
};
@@ -278,7 +264,7 @@ pub(in crate::context_bootstrap) fn notification_constructor_callback<'s>(
initialize_notification_object(
scope,
notification,
- title.0,
+ parsed.title,
options.tag,
options.metadata,
options.data,
@@ -307,54 +293,138 @@ pub(in crate::context_bootstrap) fn finalize_notification_realm_bindings<'s>(
.map_err(|error| anyhow::anyhow!("failed to finalize Notification: {error}"))
}
+#[derive(webidl::WebIdlEnum)]
+#[webidl(name = "NotificationDirection")]
+enum NotificationDirection {
+ #[webidl(token = "auto")]
+ Auto,
+ #[webidl(token = "ltr")]
+ Ltr,
+ #[webidl(token = "rtl")]
+ Rtl,
+}
+
+struct VibrationPattern(Vec<u32>);
+
+impl<'s> webidl::WebIdlConverter<'s> for VibrationPattern {
+ type Options = ();
+ fn convert(
+ scope: &mut v8::PinScope<'s, '_>,
+ value: v8::Local<'s, v8::Value>,
+ context: webidl::Context,
+ _: &(),
+ ) -> Result<Self, webidl::WebIdlError> {
+ if let Some(values) = webidl::convert_optional_sequence::<webidl::UnsignedLong>(
+ scope,
+ value,
+ context,
+ &Default::default(),
+ )? {
+ return Ok(Self(values.0.into_iter().map(|value| value.0).collect()));
+ }
+ webidl::convert::<webidl::UnsignedLong>(scope, value, context)
+ .map(|value| Self(vec![value.0]))
+ }
+}
+
+#[derive(webidl::WebIdlDictionary)]
+#[webidl(prefix = "NotificationAction")]
+struct NotificationActionInit {
+ #[webidl(required)]
+ action: String,
+ #[webidl(default = "", converter = "usv_string")]
+ icon: String,
+ #[webidl(converter = "usv_string")]
+ navigate: Option<String>,
+ #[webidl(required)]
+ title: String,
+}
+
+#[derive(webidl::WebIdlArgs)]
+#[webidl(prefix = "Notification")]
+struct NotificationArgs<'s> {
+ #[webidl(required)]
+ title: String,
+ #[webidl(dictionary)]
+ options: NotificationOptionsInit<'s>,
+}
+
+#[derive(webidl::WebIdlDictionary)]
+#[webidl(prefix = "NotificationOptions")]
+struct NotificationOptionsInit<'s> {
+ #[webidl(sequence, converter = "raw", default = Vec::new())]
+ actions: Vec<webidl::Dictionary<NotificationActionInit>>,
+ #[webidl(default = "", converter = "usv_string")]
+ badge: String,
+ #[webidl(default = "")]
+ body: String,
+ #[webidl(converter = "raw")]
+ data: Option<v8::Local<'s, v8::Value>>,
+ #[webidl(default = NotificationDirection::Auto, converter = "enum")]
+ dir: NotificationDirection,
+ #[webidl(default = "", converter = "usv_string")]
+ icon: String,
+ #[webidl(default = "", converter = "usv_string")]
+ image: String,
+ #[webidl(default = "")]
+ lang: String,
+ #[webidl(default = false)]
+ renotify: bool,
+ #[webidl(default = false)]
+ require_interaction: bool,
+ #[webidl(nullable)]
+ silent: Option<bool>,
+ #[webidl(default = "")]
+ tag: String,
+ timestamp: Option<u64>,
+ #[webidl(default = VibrationPattern(Vec::new()), converter = "raw")]
+ vibrate: VibrationPattern,
+}
+
+impl NotificationOptionsInit<'_> {
+ fn into_metadata(self) -> ServiceWorkerNotificationMetadata {
+ ServiceWorkerNotificationMetadata {
+ dir: match self.dir {
+ NotificationDirection::Auto => "auto",
+ NotificationDirection::Ltr => "ltr",
+ NotificationDirection::Rtl => "rtl",
+ }
+ .to_owned(),
+ lang: self.lang,
+ body: self.body,
+ icon: self.icon,
+ image: self.image,
+ badge: self.badge,
+ vibrate: self.vibrate.0,
+ timestamp: self.timestamp,
+ renotify: self.renotify,
+ silent: self.silent,
+ require_interaction: self.require_interaction,
+ }
+ }
+}
+
fn notification_options<'s>(
scope: &mut v8::PinScope<'s, '_>,
- options: v8::Local<'s, v8::Value>,
+ mut options: NotificationOptionsInit<'s>,
) -> Option<NotificationObjectOptions<'s>> {
- let options =
- match webidl::dictionary_value(options, webidl::Context::argument("Notification", 2)) {
- Ok(Some(options)) => options,
- Ok(None) => {
- return Some(NotificationObjectOptions {
- data: v8::null(scope).into(),
- tag: String::new(),
- metadata: default_notification_metadata(),
- actions: Vec::new(),
- });
- }
- Err(error) => {
- webidl::throw_error(scope, &error);
- return None;
- }
- };
- let data = match webidl::property_result(
- scope,
- options,
- "data",
- webidl::Context::member("NotificationOptions", "data"),
- ) {
- Ok(Some(data)) if !data.is_undefined() => data,
- Ok(_) => {
- return Some(NotificationObjectOptions {
- data: v8::null(scope).into(),
- tag: notification_options_tag(scope, options, "NotificationOptions")?,
- metadata: notification_options_metadata(scope, options)?,
- actions: notification_constructor_actions(scope, options)?,
- });
- }
- Err(error) => {
- webidl::throw_error(scope, &error);
- return None;
- }
+ if !options.actions.is_empty() {
+ throw_type_error(
+ scope,
+ "Failed to construct 'Notification': non-persistent notifications do not support actions.",
+ );
+ return None;
+ }
+ let data = match options.data.take() {
+ Some(data) => structured_clone_value_for_storage(scope, data)?,
+ None => v8::null(scope).into(),
};
- let tag = notification_options_tag(scope, options, "NotificationOptions")?;
- let metadata = notification_options_metadata(scope, options)?;
- let actions = notification_constructor_actions(scope, options)?;
- structured_clone_value_for_storage(scope, data).map(|data| NotificationObjectOptions {
+ let tag = std::mem::take(&mut options.tag);
+ Some(NotificationObjectOptions {
data,
tag,
- metadata,
- actions,
+ metadata: options.into_metadata(),
+ actions: Vec::new(),
})
}
@@ -367,485 +437,63 @@ struct NotificationObjectOptions<'scope> {
pub(crate) fn notification_options_payload<'s>(
scope: &mut v8::PinScope<'s, '_>,
- options: v8::Local<'s, v8::Value>,
-) -> Option<NotificationOptionsPayload> {
- let options =
- match webidl::dictionary_value(options, webidl::Context::argument("Notification", 2)) {
- Ok(Some(options)) => options,
- Ok(None) => {
- let null_value: v8::Local<'_, v8::Value> = v8::null(scope).into();
- let data = crate::context_bootstrap::structured_serialize_value_for_storage(
- scope, null_value,
- )?;
- return Some(NotificationOptionsPayload {
- data,
- tag: String::new(),
- metadata: default_notification_metadata(),
- actions: Vec::new(),
- });
- }
- Err(error) => {
- webidl::throw_error(scope, &error);
- return None;
+ args: &v8::FunctionCallbackArguments<'s>,
+) -> Option<(String, NotificationOptionsPayload)> {
+ let parsed = webidl::parse_args::<NotificationArgs>(scope, args)?;
+ let mut options = parsed.options;
+ // The display limit is an algorithm step, after every sequence item and
+ // its dictionary have been converted, including entries beyond the limit.
+ let base_url = notification_base_url(scope);
+ let actions = std::mem::take(&mut options.actions)
+ .into_iter()
+ .take(NOTIFICATION_MAX_ACTIONS)
+ .map(|action| {
+ let action = action.0;
+ ServiceWorkerNotificationAction {
+ action: action.action,
+ title: action.title,
+ icon: action.icon,
+ navigate: action.navigate.and_then(|value| match &base_url {
+ Some(base) => base.join(&value).ok(),
+ None => Url::parse(&value).ok(),
+ }),
}
- };
- let tag = notification_options_tag(scope, options, "NotificationOptions")?;
- let metadata = notification_options_metadata(scope, options)?;
- let actions = notification_options_actions(scope, options)?;
- let data = match webidl::property_result(
- scope,
- options,
- "data",
- webidl::Context::member("NotificationOptions", "data"),
- ) {
- Ok(Some(data)) if !data.is_undefined() => data,
- Ok(_) => {
- let null_value: v8::Local<'_, v8::Value> = v8::null(scope).into();
- let data = crate::context_bootstrap::structured_serialize_value_for_storage(
- scope, null_value,
- )?;
- return Some(NotificationOptionsPayload {
- data,
- tag,
- metadata,
- actions,
- });
- }
- Err(error) => {
- webidl::throw_error(scope, &error);
- return None;
- }
- };
- crate::context_bootstrap::structured_serialize_value_for_storage(scope, data).map(|data| {
+ })
+ .collect();
+ let data = options
+ .data
+ .take()
+ .unwrap_or_else(|| v8::null(scope).into());
+ let data = crate::context_bootstrap::structured_serialize_value_for_storage(scope, data)?;
+ let tag = std::mem::take(&mut options.tag);
+ Some((
+ parsed.title,
NotificationOptionsPayload {
data,
tag,
- metadata,
+ metadata: options.into_metadata(),
actions,
- }
- })
-}
-
-pub(crate) fn notification_get_options_tag<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- options: v8::Local<'s, v8::Value>,
-) -> Option<Option<String>> {
- let options = match webidl::dictionary_value(
- options,
- webidl::Context::argument("ServiceWorkerRegistration.getNotifications", 1),
- ) {
- Ok(Some(options)) => options,
- Ok(None) => return Some(None),
- Err(error) => {
- webidl::throw_error(scope, &error);
- return None;
- }
- };
- let tag = notification_options_tag(scope, options, "GetNotificationOptions")?;
- if tag.is_empty() {
- Some(None)
- } else {
- Some(Some(tag))
- }
-}
-
-fn notification_options_tag<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- options: v8::Local<'s, v8::Object>,
- context_name: &'static str,
-) -> Option<String> {
- let tag = match webidl::property_result(
- scope,
- options,
- "tag",
- webidl::Context::member(context_name, "tag"),
- ) {
- Ok(Some(tag)) if !tag.is_undefined() => tag,
- Ok(_) => return Some(String::new()),
- Err(error) => {
- webidl::throw_error(scope, &error);
- return None;
- }
- };
- match webidl::convert::<webidl::DomString>(
- scope,
- tag,
- webidl::Context::member(context_name, "tag"),
- ) {
- Ok(tag) => Some(tag.0),
- Err(error) => {
- webidl::throw_error(scope, &error);
- None
- }
- }
-}
-
-fn default_notification_metadata() -> ServiceWorkerNotificationMetadata {
- ServiceWorkerNotificationMetadata {
- dir: "auto".to_owned(),
- ..ServiceWorkerNotificationMetadata::default()
- }
-}
-
-fn notification_options_metadata<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- options: v8::Local<'s, v8::Object>,
-) -> Option<ServiceWorkerNotificationMetadata> {
- Some(ServiceWorkerNotificationMetadata {
- dir: notification_options_dir(scope, options)?,
- lang: notification_options_string(scope, options, "lang")?,
- body: notification_options_string(scope, options, "body")?,
- icon: notification_options_string(scope, options, "icon")?,
- image: notification_options_string(scope, options, "image")?,
- badge: notification_options_string(scope, options, "badge")?,
- vibrate: notification_options_vibrate(scope, options)?,
- timestamp: notification_options_timestamp(scope, options)?,
- renotify: notification_options_bool(scope, options, "renotify")?,
- silent: notification_options_silent(scope, options)?,
- require_interaction: notification_options_bool(scope, options, "requireInteraction")?,
- })
-}
-
-fn notification_options_dir<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- options: v8::Local<'s, v8::Object>,
-) -> Option<String> {
- let dir = notification_options_string_with_default(scope, options, "dir", "auto")?;
- match dir.as_str() {
- "auto" | "ltr" | "rtl" => Some(dir),
- _ => {
- throw_type_error(
- scope,
- "Failed to read the 'dir' property from 'NotificationOptions': the provided value is not a valid enum value.",
- );
- None
- }
- }
-}
-
-fn notification_options_string<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- options: v8::Local<'s, v8::Object>,
- name: &'static str,
-) -> Option<String> {
- notification_options_string_with_default(scope, options, name, "")
-}
-
-fn notification_options_string_with_default<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- options: v8::Local<'s, v8::Object>,
- name: &'static str,
- default_value: &'static str,
-) -> Option<String> {
- let value = match webidl::property_result(
- scope,
- options,
- name,
- webidl::Context::member("NotificationOptions", name),
- ) {
- Ok(Some(value)) if !value.is_undefined() => value,
- Ok(_) => return Some(default_value.to_owned()),
- Err(error) => {
- webidl::throw_error(scope, &error);
- return None;
- }
- };
- match webidl::convert::<webidl::DomString>(
- scope,
- value,
- webidl::Context::member("NotificationOptions", name),
- ) {
- Ok(value) => Some(value.0),
- Err(error) => {
- webidl::throw_error(scope, &error);
- None
- }
- }
-}
-
-fn notification_options_bool<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- options: v8::Local<'s, v8::Object>,
- name: &'static str,
-) -> Option<bool> {
- let value = match webidl::property_result(
- scope,
- options,
- name,
- webidl::Context::member("NotificationOptions", name),
- ) {
- Ok(Some(value)) if !value.is_undefined() => value,
- Ok(_) => return Some(false),
- Err(error) => {
- webidl::throw_error(scope, &error);
- return None;
- }
- };
- match webidl::convert::<webidl::Boolean>(
- scope,
- value,
- webidl::Context::member("NotificationOptions", name),
- ) {
- Ok(value) => Some(value.0),
- Err(error) => {
- webidl::throw_error(scope, &error);
- None
- }
- }
-}
-
-fn notification_options_silent<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- options: v8::Local<'s, v8::Object>,
-) -> Option<Option<bool>> {
- let value = match webidl::property_result(
- scope,
- options,
- "silent",
- webidl::Context::member("NotificationOptions", "silent"),
- ) {
- Ok(Some(value)) if !value.is_undefined() && !value.is_null() => value,
- Ok(_) => return Some(None),
- Err(error) => {
- webidl::throw_error(scope, &error);
- return None;
- }
- };
- match webidl::convert::<webidl::Boolean>(
- scope,
- value,
- webidl::Context::member("NotificationOptions", "silent"),
- ) {
- Ok(value) => Some(Some(value.0)),
- Err(error) => {
- webidl::throw_error(scope, &error);
- None
- }
- }
-}
-
-fn notification_options_timestamp<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- options: v8::Local<'s, v8::Object>,
-) -> Option<Option<u64>> {
- let value = match webidl::property_result(
- scope,
- options,
- "timestamp",
- webidl::Context::member("NotificationOptions", "timestamp"),
- ) {
- Ok(Some(value)) if !value.is_undefined() => value,
- Ok(_) => return Some(None),
- Err(error) => {
- webidl::throw_error(scope, &error);
- return None;
- }
- };
- match webidl::convert::<webidl::UnsignedLongLong>(
- scope,
- value,
- webidl::Context::member("NotificationOptions", "timestamp"),
- ) {
- Ok(value) => Some(Some(value.0)),
- Err(error) => {
- webidl::throw_error(scope, &error);
- None
- }
- }
-}
-
-fn notification_options_vibrate<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- options: v8::Local<'s, v8::Object>,
-) -> Option<Vec<u32>> {
- let value = match webidl::property_result(
- scope,
- options,
- "vibrate",
- webidl::Context::member("NotificationOptions", "vibrate"),
- ) {
- Ok(Some(value)) if !value.is_undefined() && !value.is_null() => value,
- Ok(_) => return Some(Vec::new()),
- Err(error) => {
- webidl::throw_error(scope, &error);
- return None;
- }
- };
- if let Ok(array) = v8::Local::<v8::Array>::try_from(value) {
- let mut pattern = Vec::with_capacity(array.length() as usize);
- for index in 0..array.length() {
- let Some(item) = array.get_index(scope, index) else {
- continue;
- };
- let value = match webidl::convert::<webidl::UnsignedLong>(
- scope,
- item,
- webidl::Context::member("NotificationOptions", "vibrate"),
- ) {
- Ok(value) => value.0,
- Err(error) => {
- webidl::throw_error(scope, &error);
- return None;
- }
- };
- pattern.push(value);
- }
- return Some(pattern);
- }
- match webidl::convert::<webidl::UnsignedLong>(
- scope,
- value,
- webidl::Context::member("NotificationOptions", "vibrate"),
- ) {
- Ok(value) => Some(vec![value.0]),
- Err(error) => {
- webidl::throw_error(scope, &error);
- None
- }
- }
+ },
+ ))
}
-fn notification_constructor_actions<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- options: v8::Local<'s, v8::Object>,
-) -> Option<Vec<ServiceWorkerNotificationAction>> {
- let actions = match webidl::property_result(
- scope,
- options,
- "actions",
- webidl::Context::member("NotificationOptions", "actions"),
- ) {
- Ok(Some(actions)) if !actions.is_undefined() => actions,
- Ok(_) => return Some(Vec::new()),
- Err(error) => {
- webidl::throw_error(scope, &error);
- return None;
- }
- };
- if actions.is_null_or_undefined() {
- return Some(Vec::new());
- }
- throw_type_error(
- scope,
- "Failed to construct 'Notification': non-persistent notifications do not support actions.",
- );
- None
-}
-
-fn notification_options_actions<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- options: v8::Local<'s, v8::Object>,
-) -> Option<Vec<ServiceWorkerNotificationAction>> {
- let actions = match webidl::property_result(
- scope,
- options,
- "actions",
- webidl::Context::member("NotificationOptions", "actions"),
- ) {
- Ok(Some(actions)) if !actions.is_undefined() && !actions.is_null() => actions,
- Ok(_) => return Some(Vec::new()),
- Err(error) => {
- webidl::throw_error(scope, &error);
- return None;
- }
- };
- let Some(actions) = v8::Local::<v8::Array>::try_from(actions).ok() else {
- throw_type_error(
- scope,
- "Failed to read the 'actions' property from 'NotificationOptions': the provided value is not an array.",
- );
- return None;
- };
- let mut parsed = Vec::new();
- for index in 0..actions.length().min(NOTIFICATION_MAX_ACTIONS as u32) {
- let Some(action_value) = actions.get_index(scope, index) else {
- continue;
- };
- let Some(action_object) = v8::Local::<v8::Object>::try_from(action_value).ok() else {
- throw_type_error(
- scope,
- "Failed to read a NotificationAction entry: the provided value is not an object.",
- );
- return None;
- };
- parsed.push(notification_action_from_options(scope, action_object)?);
- }
- Some(parsed)
-}
-
-fn notification_action_from_options<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- action: v8::Local<'s, v8::Object>,
-) -> Option<ServiceWorkerNotificationAction> {
- Some(ServiceWorkerNotificationAction {
- action: required_notification_action_string(scope, action, "action")?,
- title: required_notification_action_string(scope, action, "title")?,
- icon: optional_notification_action_string(scope, action, "icon")?,
- navigate: optional_notification_action_navigate(scope, action)?,
- })
-}
-
-fn required_notification_action_string<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- action: v8::Local<'s, v8::Object>,
- name: &'static str,
-) -> Option<String> {
- let value = match webidl::property_result(
- scope,
- action,
- name,
- webidl::Context::member("NotificationAction", name),
- ) {
- Ok(Some(value)) if !value.is_undefined() => value,
- Ok(_) => {
- throw_type_error(
- scope,
- &format!("Failed to read a NotificationAction entry: '{name}' is required."),
- );
- return None;
- }
- Err(error) => {
- webidl::throw_error(scope, &error);
- return None;
- }
- };
- match webidl::convert::<webidl::DomString>(
- scope,
- value,
- webidl::Context::member("NotificationAction", name),
- ) {
- Ok(value) => Some(value.0),
- Err(error) => {
- webidl::throw_error(scope, &error);
- None
- }
- }
+#[derive(webidl::WebIdlDictionary)]
+#[webidl(prefix = "GetNotificationOptions")]
+struct GetNotificationOptions {
+ #[webidl(default = "")]
+ tag: String,
}
-fn optional_notification_action_string<'s>(
+pub(crate) fn notification_get_options_tag<'s>(
scope: &mut v8::PinScope<'s, '_>,
- action: v8::Local<'s, v8::Object>,
- name: &'static str,
-) -> Option<String> {
- let value = match webidl::property_result(
- scope,
- action,
- name,
- webidl::Context::member("NotificationAction", name),
- ) {
- Ok(Some(value)) if !value.is_undefined() => value,
- Ok(_) => return Some(String::new()),
- Err(error) => {
- webidl::throw_error(scope, &error);
- return None;
- }
- };
- match webidl::convert::<webidl::DomString>(
+ value: v8::Local<'s, v8::Value>,
+) -> Option<Option<String>> {
+ match webidl::convert::<webidl::Dictionary<GetNotificationOptions>>(
scope,
value,
- webidl::Context::member("NotificationAction", name),
+ webidl::Context::argument("ServiceWorkerRegistration.getNotifications", 1),
) {
- Ok(value) => Some(value.0),
+ Ok(parsed) => Some((!parsed.0.tag.is_empty()).then_some(parsed.0.tag)),
Err(error) => {
webidl::throw_error(scope, &error);
None
@@ -853,40 +501,6 @@ fn optional_notification_action_string<'s>(
}
}
-fn optional_notification_action_navigate<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- action: v8::Local<'s, v8::Object>,
-) -> Option<Option<Url>> {
- let value = match webidl::property_result(
- scope,
- action,
- "navigate",
- webidl::Context::member("NotificationAction", "navigate"),
- ) {
- Ok(Some(value)) if !value.is_undefined() => value,
- Ok(_) => return Some(None),
- Err(error) => {
- webidl::throw_error(scope, &error);
- return None;
- }
- };
- let value = match webidl::convert::<webidl::DomString>(
- scope,
- value,
- webidl::Context::member("NotificationAction", "navigate"),
- ) {
- Ok(value) => value.0,
- Err(error) => {
- webidl::throw_error(scope, &error);
- return None;
- }
- };
- let Some(base_url) = notification_base_url(scope) else {
- return Some(Url::parse(&value).ok());
- };
- Some(base_url.join(&value).ok())
-}
-
fn notification_base_url(scope: &mut v8::PinScope<'_, '_>) -> Option<Url> {
crate::worker::worker_current_script_url(scope).or_else(|| {
context_host_ptr_from_global_bridge(scope)
diff --git a/moli-renderer-v8/src/context_bootstrap/window_runtime/service_worker.rs b/moli-renderer-v8/src/context_bootstrap/window_runtime/service_worker.rs
index b54349bd7..a8952b9f3 100644
--- a/moli-renderer-v8/src/context_bootstrap/window_runtime/service_worker.rs
+++ b/moli-renderer-v8/src/context_bootstrap/window_runtime/service_worker.rs
@@ -70,6 +70,8 @@ struct ServiceWorkerRegistrationObjectDeclaration<'scope> {
#[webapi(
method = "showNotification",
+ returns_promise,
+ receiver = web_api_interfaces::ServiceWorkerRegistration::is_instance,
callback = service_worker_registration_show_notification_callback,
length = 1
)]
@@ -77,6 +79,8 @@ struct ServiceWorkerRegistrationObjectDeclaration<'scope> {
#[webapi(
method = "getNotifications",
+ returns_promise,
+ receiver = web_api_interfaces::ServiceWorkerRegistration::is_instance,
callback = service_worker_registration_get_notifications_callback,
length = 0
)]
@@ -1293,16 +1297,8 @@ fn service_worker_registration_show_notification_callback<'s>(
let promise = resolver.get_promise(scope);
rv.set(promise.into());
- let Some(title) = webidl::required_argument::<webidl::DomString>(
- scope,
- &args,
- 0,
- webidl::Context::argument("ServiceWorkerRegistration.showNotification", 1),
- "Failed to execute 'showNotification' on 'ServiceWorkerRegistration': 1 argument required, but only 0 present.",
- ) else {
- return;
- };
- let Some(options) = crate::context_bootstrap::notification_options_payload(scope, args.get(1))
+ let Some((title, options)) =
+ crate::context_bootstrap::notification_options_payload(scope, &args)
else {
return;
};
@@ -1333,7 +1329,7 @@ fn service_worker_registration_show_notification_callback<'s>(
}
if !host.show_service_worker_notification(
&scope_url,
- title.0,
+ title,
options.tag,
options.metadata,
options.actions,
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/service_worker_surface.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/service_worker_surface.rs
index dda829f46..ea354b841 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/service_worker_surface.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/service_worker_surface.rs
@@ -2267,6 +2267,20 @@ async fn navigator_service_worker_show_notification_records_clickable_notificati
)
.await;
+ vm.eval(&format!(
+ "globalThis.__notificationDictionaryResult='pending'; ({})(globalThis.__serviceWorkerShowRegistration).then(value=>__notificationDictionaryResult=value,error=>__notificationDictionaryResult=String(error.stack||error));",
+ include_str!("../../../../../../tests/fixtures/notification-persistent-dictionary.js"),
+ ))
+ .expect("notification dictionary fixture should start on a real Window registration");
+ drain_service_worker_test_until_eval_equals(
+ &mut vm,
+ &browser_context_runtime,
+ &loader,
+ "String(globalThis.__notificationDictionaryResult)",
+ "true",
+ )
+ .await;
+
vm.set_permission_overrides(&[crate::protocol_types::PermissionOverrideRegistration {
permission: serde_json::Value::String("notifications".to_owned()),
setting: "granted".to_owned(),
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs
index b10678926..1f43eaa15 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs
@@ -43,6 +43,7 @@ mod message_port_events;
mod message_port_lifecycle;
mod misc;
mod navigation;
+mod notification_init;
mod performance;
mod performance_memory;
mod platform_identity;
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/notification_init.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/notification_init.rs
new file mode 100644
index 000000000..e2b5380db
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/notification_init.rs
@@ -0,0 +1,13 @@
+use super::*;
+
+#[test]
+fn notification_constructor_converts_complete_options_before_materialization() {
+ let mut vm = new_storage_html_test_vm("https://notification-options.test/");
+ assert_eq!(
+ vm.eval(include_str!(
+ "../../../../tests/fixtures/notification-options-dictionary.js"
+ ))
+ .unwrap(),
+ "true"
+ );
+}
diff --git a/moli-renderer-v8/src/worker/global_scope/service_worker_api.rs b/moli-renderer-v8/src/worker/global_scope/service_worker_api.rs
index fb9874d93..34043bcb4 100644
--- a/moli-renderer-v8/src/worker/global_scope/service_worker_api.rs
+++ b/moli-renderer-v8/src/worker/global_scope/service_worker_api.rs
@@ -218,16 +218,8 @@ pub(super) fn service_worker_registration_show_notification_callback<'s>(
let promise = resolver.get_promise(scope);
rv.set(promise.into());
- let Some(title) = webidl::required_argument::<webidl::DomString>(
- scope,
- &args,
- 0,
- webidl::Context::argument("ServiceWorkerRegistration.showNotification", 1),
- "Failed to execute 'showNotification' on 'ServiceWorkerRegistration': 1 argument required, but only 0 present.",
- ) else {
- return;
- };
- let Some(options) = crate::context_bootstrap::notification_options_payload(scope, args.get(1))
+ let Some((title, options)) =
+ crate::context_bootstrap::notification_options_payload(scope, &args)
else {
return;
};
@@ -285,7 +277,7 @@ pub(super) fn service_worker_registration_show_notification_callback<'s>(
request_id,
registration_id,
version_id,
- title: title.0,
+ title,
tag: options.tag,
metadata: options.metadata,
actions: options.actions,
@@ -1905,6 +1897,8 @@ struct ServiceWorkerGlobalRegistrationDeclaration<'scope> {
#[webapi(
method = "showNotification",
+ returns_promise,
+ receiver = web_api_interfaces::ServiceWorkerRegistration::is_instance,
callback = service_worker_registration_show_notification_callback,
length = 1
)]
@@ -1912,6 +1906,8 @@ struct ServiceWorkerGlobalRegistrationDeclaration<'scope> {
#[webapi(
method = "getNotifications",
+ returns_promise,
+ receiver = web_api_interfaces::ServiceWorkerRegistration::is_instance,
callback = service_worker_registration_get_notifications_callback,
length = 0
)]
diff --git a/moli-renderer-v8/src/worker/thread/tests/mod.rs b/moli-renderer-v8/src/worker/thread/tests/mod.rs
index 053bc16c1..436b56ca0 100644
--- a/moli-renderer-v8/src/worker/thread/tests/mod.rs
+++ b/moli-renderer-v8/src/worker/thread/tests/mod.rs
@@ -2,6 +2,7 @@ mod abort_signal_events;
mod callback_execution;
mod error_reporting_guard;
mod event_target_prototype;
+mod notification_init;
mod request_init;
mod text_codecs;
use std::pin::pin;
diff --git a/moli-renderer-v8/src/worker/thread/tests/notification_init.rs b/moli-renderer-v8/src/worker/thread/tests/notification_init.rs
new file mode 100644
index 000000000..e290c786a
--- /dev/null
+++ b/moli-renderer-v8/src/worker/thread/tests/notification_init.rs
@@ -0,0 +1,43 @@
+use super::*;
+
+#[tokio::test]
+async fn service_worker_notification_options_reject_original_conversion_errors_before_dispatch() {
+ ensure_v8();
+ let source = format!(
+ "const verify = {}; self.addEventListener('message', event => event.waitUntil(verify(self.registration).then(value => {{if (value !== true) throw Error('notification fixture failed');}})));",
+ include_str!("../../../../tests/fixtures/notification-persistent-dictionary.js")
+ );
+ let mut handle = spawn_service_worker_for_test(&source);
+ let event_id = ServiceWorkerEventId::from_u64_for_worker(1);
+ handle.dispatch_service_worker_message_event(ServiceWorkerMessageEvent {
+ event_id,
+ owner: crate::service_worker_runtime::ServiceWorkerRunOwner::new(
+ ServiceWorkerVersionId::from_u64_for_test(1),
+ crate::runtime::RendererServiceWorkerRunIdentity::fresh(),
+ ),
+ source_client_id: None,
+ source_client_url: None,
+ source_client_snapshot: None,
+ source_worker: None,
+ source_origin: String::new(),
+ payload: serialize_test_string("verify"),
+ window_interaction_allowed: false,
+ });
+ let deadline = tokio::time::Instant::now() + TIMEOUT;
+ loop {
+ let message = tokio::time::timeout_at(deadline, handle.recv())
+ .await
+ .expect("notification conversion must settle without dispatch")
+ .expect("service worker must report its result");
+ match message {
+ WorkerToParentMessage::ServiceWorkerMessageCompleted(completion) => {
+ assert_eq!(completion.event_id, event_id);
+ assert_eq!(completion.result, Ok(()));
+ break;
+ }
+ WorkerToParentMessage::RuntimeInspectorMessages(_) => {}
+ other => panic!("conversion must fail before notification dispatch: {other:?}"),
+ }
+ }
+ handle.terminate_and_join();
+}
diff --git a/moli-renderer-v8/tests/fixtures/notification-options-dictionary.js b/moli-renderer-v8/tests/fixtures/notification-options-dictionary.js
new file mode 100644
index 000000000..a4e01bb8c
--- /dev/null
+++ b/moli-renderer-v8/tests/fixtures/notification-options-dictionary.js
@@ -0,0 +1,57 @@
+(() => {
+ const assert = (ok, label) => { if (!ok) throw Error(label); };
+ const members = ['actions','badge','body','data','dir','icon','image','lang',
+ 'renotify','requireInteraction','silent','tag','timestamp','vibrate'];
+ const trace = [], sentinel = {};
+ const options = {};
+ for (const key of members) Object.defineProperty(options, key, {
+ configurable: true, get() { trace.push(key); }
+ });
+ const notification = new Notification('audit', options);
+ notification.close();
+ assert(trace.join() === members.join(), 'NotificationOptions lexical order: ' + trace);
+ for (const stop of members) {
+ trace.length = 0;
+ const bad = Object.create(options);
+ Object.defineProperty(bad, stop, {get() { trace.push(stop); throw sentinel; }});
+ let error;
+ try { new Notification('audit', bad); } catch (caught) { error = caught; }
+ assert(error === sentinel, stop + ' original exception');
+ assert(trace.join() === members.slice(0, members.indexOf(stop) + 1).join(), stop + ' short circuit');
+ }
+ for (const value of [1, true, 'options', 1n, Symbol('options')]) {
+ let error;
+ try { new Notification('audit', value); } catch (caught) { error = caught; }
+ assert(error instanceof TypeError, 'primitive dictionary rejected');
+ }
+ let iterations = 0, nexts = 0;
+ const empty = {[Symbol.iterator]() {
+ iterations++;
+ return {next() { nexts++; return {done: true}; }};
+ }};
+ const emptyActions = new Notification('empty', {actions: empty});
+ emptyActions.close();
+ assert(iterations === 1 && nexts === 1, 'empty actions iterable must actually be consumed');
+ let index = 0, late = 0, error;
+ const actions = {[Symbol.iterator]() { return {next() {
+ if (index++ < 2) return {value: {action: 'a', title: 'A'}};
+ if (index === 3) return {value: {action: 'bad', get title() { throw sentinel; }}};
+ throw Error('must not read after failed item');
+ }}; }};
+ try { new Notification('bad', {actions, get badge() { late++; }}); } catch (caught) { error = caught; }
+ assert(error === sentinel && index === 3 && late === 0, 'convert every action before limits, stop at failing item');
+ for (const actions of [null, [{}], [{action: 'a'}]]) {
+ let error;
+ try { new Notification('bad', {actions}); } catch (caught) { error = caught; }
+ assert(error instanceof TypeError, 'actions sequence and required dictionary members');
+ }
+ const data = {value: 'before'};
+ const cloned = new Notification('clone', {data, get tag() { data.value = 'after'; return 'tag'; }});
+ assert(cloned.data !== data && cloned.data.value === 'after', 'clone data after complete dictionary conversion');
+ cloned.close();
+ const deferred = {get poison() { throw Error('clone must wait'); }};
+ error = undefined;
+ try { new Notification('clone', {data: deferred, get tag() { throw sentinel; }}); } catch (caught) { error = caught; }
+ assert(error === sentinel, 'later conversion error precedes data cloning');
+ return true;
+})()
diff --git a/moli-renderer-v8/tests/fixtures/notification-persistent-dictionary.js b/moli-renderer-v8/tests/fixtures/notification-persistent-dictionary.js
new file mode 100644
index 000000000..8f1015b1b
--- /dev/null
+++ b/moli-renderer-v8/tests/fixtures/notification-persistent-dictionary.js
@@ -0,0 +1,47 @@
+(async registration => {
+ const assert = (ok, label) => { if (!ok) throw Error(label); };
+ const members = ['actions','badge','body','data','dir','icon','image','lang',
+ 'renotify','requireInteraction','silent','tag','timestamp','vibrate'];
+ const rejection = async (operation, expected, label) => {
+ let promise;
+ try { promise = operation(); } catch (error) { throw Error(label + ' threw synchronously'); }
+ assert(promise instanceof Promise, label + ' Promise');
+ let rejected = false, error;
+ await promise.then(() => {}, caught => { rejected = true; error = caught; });
+ assert(rejected && Object.is(error, expected), label + ' original rejection');
+ };
+ for (const stop of members) for (const sentinel of [undefined, null, false, 0, 'sentinel', {}]) {
+ const trace = [];
+ const options = {};
+ for (const key of members) Object.defineProperty(options, key, {get() {
+ trace.push(key);
+ if (key === stop) throw sentinel;
+ }});
+ await rejection(() => registration.showNotification('audit', options), sentinel, stop);
+ assert(trace.join() === members.slice(0, members.indexOf(stop) + 1).join(), stop + ' short circuit: ' + trace);
+ }
+ const sentinel = {};
+ let index = 0, late = 0;
+ const actions = {[Symbol.iterator]() { return {next() {
+ if (index++ < 2) return {value: {action: 'a', title: 'A'}};
+ if (index === 3) return {value: {action: 'bad', get title() { throw sentinel; }}};
+ throw Error('must not read after failed item');
+ }}; }};
+ await rejection(() => registration.showNotification('audit', {actions, get data() { late++; }}), sentinel, 'third action');
+ assert(index === 3 && late === 0, 'validate actions beyond display limit before data');
+ await rejection(() => registration.getNotifications({get tag() { throw sentinel; }}), sentinel, 'getNotifications tag');
+ for (const value of [1, true, 'options', 1n, Symbol('options')]) {
+ for (const operation of [() => registration.showNotification('audit', value), () => registration.getNotifications(value)]) {
+ let promise;
+ try { promise = operation(); } catch (error) { throw Error('primitive options threw synchronously'); }
+ let error;
+ await promise.catch(caught => { error = caught; });
+ assert(error instanceof TypeError, 'primitive dictionary must reject TypeError');
+ }
+ }
+ let titleReads = 0;
+ const title = {toString() { titleReads++; throw sentinel; }};
+ await rejection(() => registration.showNotification(title, {get actions() { throw Error('late options'); }}), sentinel, 'title');
+ assert(titleReads === 1, 'title converted before options');
+ return true;
+})