Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions crates/trusted-server-core/src/tsjs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,105 @@ pub fn tsjs_deferred_script_tags(module_ids: &[&str]) -> String {
.map(|id| tsjs_deferred_script_tag(id))
.collect::<String>()
}

#[cfg(test)]
mod tests {
use super::*;

const UNIFIED_SCRIPT_PREFIX: &str = "/static/tsjs=tsjs-unified.min.js?v=";

fn assert_sha256_hex(hash: &str) {
assert_eq!(hash.len(), 64, "should include a SHA-256 hex hash");
assert!(
hash.chars()
.all(|character| matches!(character, '0'..='9' | 'a'..='f')),
"should include only lowercase hex characters"
);
}

#[test]
fn tsjs_script_src_includes_stable_cache_busting_hash() {
let module_ids = ["core", "lockr", "permutive"];

let src = tsjs_script_src(&module_ids);
let hash = src
.strip_prefix(UNIFIED_SCRIPT_PREFIX)
.expect("should include unified script URL prefix");

assert_sha256_hex(hash);
assert_eq!(
src,
tsjs_script_src(&module_ids),
"should produce a stable URL for identical module IDs"
);
}

#[test]
fn tsjs_script_tag_uses_generated_src_and_trusted_server_id() {
let module_ids = ["core", "lockr"];
let src = tsjs_script_src(&module_ids);
let tag = tsjs_script_tag(&module_ids);

assert_eq!(
tag.matches("<script").count(),
1,
"should emit one opening script tag"
);
assert_eq!(
tag.matches("</script>").count(),
1,
"should emit one closing script tag"
);
assert!(
tag.contains(r#"id="trustedserver-js""#),
"should include trusted server script ID"
);
assert_eq!(
tag,
format!(r#"<script src="{src}" id="trustedserver-js"></script>"#),
"should use generated script source"
);
}

#[test]
fn tsjs_deferred_script_src_includes_module_cache_busting_hash() {
let src = tsjs_deferred_script_src("prebid");
let hash = src
.strip_prefix("/static/tsjs=tsjs-prebid.min.js?v=")
.expect("should include deferred script URL prefix");

assert_sha256_hex(hash);
}

#[test]
fn tsjs_deferred_script_tag_uses_generated_src_and_defer() {
let src = tsjs_deferred_script_src("prebid");
let tag = tsjs_deferred_script_tag("prebid");

assert_eq!(
tag,
format!(r#"<script src="{src}" defer></script>"#),
"should use generated deferred script source"
);
}

#[test]
fn tsjs_deferred_script_tags_concatenates_tags_in_order() {
let module_ids = ["prebid", "lockr"];

assert_eq!(
tsjs_deferred_script_tags(&module_ids),
format!(
"{}{}",
tsjs_deferred_script_tag("prebid"),
tsjs_deferred_script_tag("lockr")
),
"should concatenate deferred script tags in module order"
);
assert_eq!(
tsjs_deferred_script_tags(&[]),
"",
"should return empty output for no deferred modules"
);
}
}
Loading