:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(cli): delete CSS source maps after upload (#84034)
Manoel Aranda Neto90730d206846
diff --git a/cli/.sampo/changesets/dashing-lord-kullervo.md b/cli/.sampo/changesets/dashing-lord-kullervo.mdnew file mode 100644index 000000000000..e758c5e20920--- /dev/null+++ b/cli/.sampo/changesets/dashing-lord-kullervo.md@@ -0,0 +1,5 @@+---+cargo/posthog-cli: patch+---++Delete CSS source maps and remove their sourceMappingURL comments after uploaddiff --git a/cli/src/sourcemaps/content.rs b/cli/src/sourcemaps/content.rsindex 34de8a6c8011..04b5f729b362 100644--- a/cli/src/sourcemaps/content.rs+++ b/cli/src/sourcemaps/content.rs@@ -324,21 +324,39 @@ impl MinifiedSourceFile {}pub fn get_sourcemap_reference(&self) -> Result<Option<String>> {- let patterns = ["//# sourceMappingURL=", "//@ sourceMappingURL="];- let Some(found) = self.get_comment_value(&patterns) else {- return Ok(None);+ let found = if self.is_stylesheet() {+ css_sourcemap_reference(&self.inner.content)+ } else {+ self.inner.content.lines().rev().find_map(|line| {+ let line = line.trim();+ ["//# sourceMappingURL=", "//@ sourceMappingURL="]+ .iter()+ .find_map(|prefix| line.strip_prefix(prefix))+ })};- Ok(Some(urlencoding::decode(&found)?.into_owned()))++ Ok(found+ .map(|reference| urlencoding::decode(reference).map(|decoded| decoded.into_owned()))+ .transpose()?)}pub fn remove_sourcemap_reference(&mut self) -> bool {- let Some(range) = trailing_sourcemap_reference_range(&self.inner.content) else {+ let range = if self.is_stylesheet() {+ css_sourcemap_reference_removal_range(&self.inner.content)+ } else {+ trailing_sourcemap_reference_range(&self.inner.content)+ };+ let Some(range) = range else {return false;};self.inner.content.replace_range(range, "");true}+ fn is_stylesheet(&self) -> bool {+ self.inner.path.extension().is_some_and(|ext| ext == "css")+ }+fn get_comment_value(&self, patterns: &[&str]) -> Option<String> {for line in self.inner.content.lines().rev() {if let Some(val) = patterns@@ -406,6 +424,81 @@ impl MinifiedSourceFile {}}+const CSS_SOURCEMAP_REFERENCE_PREFIX: &str = "/*# sourceMappingURL=";++fn css_sourcemap_reference_range(line: &str) -> Option<std::ops::Range<usize>> {+ let bytes = line.as_bytes();+ let mut index = 0;+ let mut quote = None;+ let mut escaped = false;+ let mut found = None;++ while index < bytes.len() {+ if escaped {+ escaped = false;+ index += 1;+ continue;+ }++ if let Some(active_quote) = quote {+ if bytes[index] == b'\\' {+ escaped = true;+ } else if bytes[index] == active_quote {+ quote = None;+ }+ index += 1;+ continue;+ }++ if bytes[index] == b'\\' {+ escaped = true;+ index += 1;+ continue;+ }++ match bytes[index] {+ b'\'' | b'"' => {+ quote = Some(bytes[index]);+ index += 1;+ }+ b'/' if bytes.get(index + 1) == Some(&b'*') => {+ let comment_end = line[index + 2..].find("*/").map(|end| index + end + 4)?;+ if line[index..].starts_with(CSS_SOURCEMAP_REFERENCE_PREFIX) {+ found = Some(index..comment_end);+ }+ index = comment_end;+ }+ _ => index += 1,+ }+ }++ found+}++fn css_sourcemap_reference(content: &str) -> Option<&str> {+ let range = css_sourcemap_reference_range(content)?;+ let reference_start = range.start + CSS_SOURCEMAP_REFERENCE_PREFIX.len();+ Some(content[reference_start..range.end - 2].trim_end())+}++fn css_sourcemap_reference_removal_range(content: &str) -> Option<std::ops::Range<usize>> {+ let comment_range = css_sourcemap_reference_range(content)?;+ let line_start = content[..comment_range.start]+ .rfind('\n')+ .map_or(0, |index| index + 1);+ let line_end = content[comment_range.end..]+ .find('\n')+ .map_or(content.len(), |index| comment_range.end + index + 1);++ if content[line_start..comment_range.start].trim().is_empty()+ && content[comment_range.end..line_end].trim().is_empty()+ {+ Some(line_start..line_end)+ } else {+ Some(comment_range)+ }+}+fn trailing_sourcemap_reference_range(content: &str) -> Option<std::ops::Range<usize>> {let mut line_start = 0;let mut lines = Vec::new();@@ -468,12 +561,20 @@ mod tests {serde_json::from_value(value).expect("Failed to build SourceMapContent")}- fn minified_source(content: &str) -> MinifiedSourceFile {+ fn source_file(path: &str, content: &str) -> MinifiedSourceFile {MinifiedSourceFile {- inner: SourceFile::new(PathBuf::from("chunk.js"), content.to_string()),+ inner: SourceFile::new(PathBuf::from(path), content.to_string()),}}+ fn minified_source(content: &str) -> MinifiedSourceFile {+ source_file("chunk.js", content)+ }++ fn stylesheet_source(content: &str) -> MinifiedSourceFile {+ source_file("styles.css", content)+ }+#[test]fn build_code_snippet_json_encodes_ids() {let hostile = r#"a");window.x=1;("b"#;@@ -642,6 +743,104 @@ mod tests {assert_eq!(source.inner.content, "console.log(1);\r\n");}+ #[test]+ fn remove_sourcemap_reference_strips_css_comment() {+ let mut source =+ stylesheet_source(".app { color: black; }\n/*# sourceMappingURL=app.css.map*/\n");++ assert_eq!(+ source.get_sourcemap_reference().unwrap(),+ Some("app.css.map".to_string())+ );+ assert!(source.remove_sourcemap_reference());+ assert_eq!(source.inner.content, ".app { color: black; }\n");+ }++ #[test]+ fn remove_sourcemap_reference_strips_inline_css_comment() {+ let mut source = stylesheet_source(+ ".app{content:\"/* not a comment */\"}/*# sourceMappingURL=app.css.map */\n",+ );++ assert_eq!(+ source.get_sourcemap_reference().unwrap(),+ Some("app.css.map".to_string())+ );+ assert!(source.remove_sourcemap_reference());+ assert_eq!(+ source.inner.content,+ ".app{content:\"/* not a comment */\"}\n"+ );+ }++ #[test]+ fn remove_sourcemap_reference_ignores_css_string_contents() {+ let original = ".example::after{content:\"/*# sourceMappingURL=app.css.map*/\"}\n";+ let mut source = stylesheet_source(original);++ assert_eq!(source.get_sourcemap_reference().unwrap(), None);+ assert!(!source.remove_sourcemap_reference());+ assert_eq!(source.inner.content, original);+ }++ #[test]+ fn remove_sourcemap_reference_ignores_css_string_after_escaped_quote() {+ let original = ".foo\\'bar{content:\"x'/*# sourceMappingURL=victim.map*/\"}\n";+ let mut source = stylesheet_source(original);++ assert_eq!(source.get_sourcemap_reference().unwrap(), None);+ assert!(!source.remove_sourcemap_reference());+ assert_eq!(source.inner.content, original);+ }++ #[test]+ fn remove_sourcemap_reference_ignores_continued_css_string_contents() {+ let original =+ ".example::after{content:\"before\\\n/*# sourceMappingURL=app.css.map*/\"}\n";+ let mut source = stylesheet_source(original);++ assert_eq!(source.get_sourcemap_reference().unwrap(), None);+ assert!(!source.remove_sourcemap_reference());+ assert_eq!(source.inner.content, original);+ }++ #[test]+ fn remove_sourcemap_reference_ignores_javascript_template_contents() {+ let original = "const css = `body{}/*# sourceMappingURL=theme.css.map*/`;\n";+ let mut source = minified_source(original);++ assert_eq!(source.get_sourcemap_reference().unwrap(), None);+ assert!(!source.remove_sourcemap_reference());+ assert_eq!(source.inner.content, original);+ }++ #[test]+ fn remove_sourcemap_reference_preserves_adjacent_css_license() {+ let mut source =+ stylesheet_source(".a{}/*# sourceMappingURL=app.css.map*/ /* license */\n");++ assert_eq!(+ source.get_sourcemap_reference().unwrap(),+ Some("app.css.map".to_string())+ );+ assert!(source.remove_sourcemap_reference());+ assert_eq!(source.inner.content, ".a{} /* license */\n");+ }++ #[test]+ fn remove_sourcemap_reference_strips_css_comment_before_license() {+ let mut source = stylesheet_source(+ ".app{color:black}\n/*# sourceMappingURL=app.css.map */\n/* license */\n",+ );++ assert_eq!(+ source.get_sourcemap_reference().unwrap(),+ Some("app.css.map".to_string())+ );+ assert!(source.remove_sourcemap_reference());+ assert_eq!(source.inner.content, ".app{color:black}\n/* license */\n");+ }+#[test]fn remove_sourcemap_reference_strips_comment_with_injected_chunk_id() {let mut source = minified_source(diff --git a/cli/src/sourcemaps/plain/inject.rs b/cli/src/sourcemaps/plain/inject.rsindex 89416b112cda..a1c86b52f53e 100644--- a/cli/src/sourcemaps/plain/inject.rs+++ b/cli/src/sourcemaps/plain/inject.rs@@ -21,3 +21,7 @@ pub fn is_javascript_file(entry: &DirEntry) -> bool {.extension().is_some_and(|ext| ext == "js" || ext == "mjs" || ext == "cjs")}++pub fn is_stylesheet_file(entry: &DirEntry) -> bool {+ entry.file_type().is_file() && entry.path().extension().is_some_and(|ext| ext == "css")+}diff --git a/cli/src/sourcemaps/plain/upload.rs b/cli/src/sourcemaps/plain/upload.rsindex 9071ace0e738..ea63895dfe9c 100644--- a/cli/src/sourcemaps/plain/upload.rs+++ b/cli/src/sourcemaps/plain/upload.rs@@ -1,4 +1,7 @@-use std::{path::PathBuf, time::Instant};+use std::{+ path::{Path, PathBuf},+ time::Instant,+};use anyhow::{Context, Result};use rayon::iter::{IntoParallelIterator, ParallelIterator};@@ -24,7 +27,7 @@ use crate::{},content::MinifiedSourceFile,inject::get_release_for_maps,- plain::inject::is_javascript_file,+ plain::inject::{is_javascript_file, is_stylesheet_file},source_pairs::{read_pairs, SourcePair},},utils::files::{delete_files, FileSelection},@@ -90,7 +93,9 @@ pub fn upload(args: &Args, existing_release: Option<&Release>) -> Result<()> {);}- let selection = FileSelection::try_from(args.file_selection.clone())?;+ // Resolve stdin once so the JavaScript upload and CSS cleanup scan the same paths.+ let file_selection = args.file_selection.clone().resolve_stdin()?;+ let selection = FileSelection::try_from(file_selection.clone())?;let mut pairs = read_pairs(selection.into_iter().filter(is_javascript_file),@@ -200,9 +205,44 @@ pub fn upload(args: &Args, existing_release: Option<&Release>) -> Result<()> {upload_result?;if args.delete_after {- remove_sourcemap_references(source_paths)- .context("While stripping sourcemap references")?;- delete_files(sourcemap_paths).context("While deleting sourcemaps")?;+ let cleanup_roots = canonical_selection_roots(&file_selection.directory);+ let stylesheet_selection = FileSelection::try_from(file_selection)?;+ let stylesheet_pairs = read_pairs(+ stylesheet_selection.into_iter().filter(is_stylesheet_file),+ &args.public_path_prefix,+ );+ let (stylesheet_pairs, unsafe_stylesheet_pairs): (Vec<_>, Vec<_>) = stylesheet_pairs+ .into_iter()+ .partition(|pair| path_is_within_roots(&pair.sourcemap.inner.path, &cleanup_roots));+ for pair in unsafe_stylesheet_pairs {+ warn!(+ "Skipping CSS sourcemap cleanup for {} because it resolves outside the selected paths",+ pair.sourcemap.inner.path.display()+ );+ }+ let stylesheet_source_paths = stylesheet_pairs+ .iter()+ .map(|pair| pair.source.inner.path.clone())+ .collect::<Vec<_>>();+ let stylesheet_sourcemap_paths = stylesheet_pairs+ .iter()+ .map(|pair| pair.sourcemap.inner.path.clone())+ .collect::<Vec<_>>();++ remove_sourcemap_references(+ source_paths+ .into_iter()+ .chain(stylesheet_source_paths)+ .collect(),+ )+ .context("While stripping sourcemap references")?;+ delete_files(+ sourcemap_paths+ .into_iter()+ .chain(stylesheet_sourcemap_paths)+ .collect(),+ )+ .context("While deleting sourcemaps")?;}Ok(())@@ -225,6 +265,25 @@ fn prepare_uploads(Ok(dedup_uploads_by_chunk_id(uploads))}+fn canonical_selection_roots(paths: &[PathBuf]) -> Vec<PathBuf> {+ paths+ .iter()+ .filter_map(|path| path.canonicalize().ok())+ .filter_map(|path| {+ if path.is_dir() {+ Some(path)+ } else {+ path.parent().map(Path::to_path_buf)+ }+ })+ .collect()+}++fn path_is_within_roots(path: &Path, roots: &[PathBuf]) -> bool {+ path.canonicalize()+ .is_ok_and(|path| roots.iter().any(|root| path.starts_with(root)))+}+fn remove_sourcemap_references(paths: Vec<PathBuf>) -> Result<()> {for path in paths {let mut source = MinifiedSourceFile::load(&path)@@ -243,6 +302,47 @@ mod tests {use super::*;use crate::{sourcemaps::inject::inject_pairs, utils::files::FileSelection};+ #[test]+ fn stylesheet_cleanup_only_accepts_maps_inside_selected_roots() {+ let dir = tempfile::tempdir().expect("Failed to create temp dir");+ let output = dir.path().join("output");+ std::fs::create_dir(&output).expect("Failed to create output directory");+ let selected_source = output.join("app.css");+ let selected_map = output.join("app.css.map");+ let outside_map = dir.path().join("outside.css.map");+ std::fs::write(&selected_source, "").expect("Failed to write selected source");+ std::fs::write(&selected_map, "{}").expect("Failed to write selected map");+ std::fs::write(&outside_map, "{}").expect("Failed to write outside map");++ let directory_roots = canonical_selection_roots(std::slice::from_ref(&output));+ let file_roots = canonical_selection_roots(std::slice::from_ref(&selected_source));++ assert!(path_is_within_roots(&selected_map, &directory_roots));+ assert!(path_is_within_roots(&selected_map, &file_roots));+ assert!(!path_is_within_roots(&outside_map, &directory_roots));+ assert!(!path_is_within_roots(+ &output.join("..").join("outside.css.map"),+ &directory_roots+ ));+ }++ #[cfg(unix)]+ #[test]+ fn stylesheet_cleanup_rejects_symlinks_outside_selected_roots() {+ let dir = tempfile::tempdir().expect("Failed to create temp dir");+ let output = dir.path().join("output");+ std::fs::create_dir(&output).expect("Failed to create output directory");+ let outside_map = dir.path().join("outside.css.map");+ let symlinked_map = output.join("app.css.map");+ std::fs::write(&outside_map, "{}").expect("Failed to write outside map");+ std::os::unix::fs::symlink(&outside_map, &symlinked_map)+ .expect("Failed to create sourcemap symlink");++ let roots = canonical_selection_roots(std::slice::from_ref(&output));++ assert!(!path_is_within_roots(&symlinked_map, &roots));+ }+#[test]fn event_mode_uploads_one_payload_per_chunk_id() {// The hashless copy keeps the original's sourceMappingURL, so both files are identical.diff --git a/cli/tests/sourcemap.rs b/cli/tests/sourcemap.rsindex 20513d23d749..45b5ffa4fe3b 100644--- a/cli/tests/sourcemap.rs+++ b/cli/tests/sourcemap.rs@@ -3,7 +3,7 @@ use posthog_cli::{args::ReleaseMode,content::SourceMapContent,inject::{inject_pairs, inject_pairs_legacy},- plain::inject::is_javascript_file,+ plain::inject::{is_javascript_file, is_stylesheet_file},source_pairs::SourcePair,},utils::files::FileSelection,@@ -66,6 +66,38 @@ fn test_search_without_multiple_files() {assert_eq!(pairs.len(), 2);}+#[test]+fn test_stylesheet_pair_is_discoverable_for_cleanup() {+ let dir = tempfile::tempdir().expect("Failed to create stylesheet fixture directory");+ let stylesheet_path = dir.path().join("app.css");+ fs::write(+ &stylesheet_path,+ ".app { color: black; }\n/*# sourceMappingURL=app.css.map*/\n",+ )+ .expect("Failed to write stylesheet fixture");+ fs::write(+ dir.path().join("app.css.map"),+ r#"{"version":3,"sources":[],"names":[],"mappings":""}"#,+ )+ .expect("Failed to write stylesheet sourcemap fixture");++ let selection = FileSelection::from_roots(vec![dir.path().to_path_buf()])+ .include(vec![])+ .expect("Failed to select stylesheet fixture");+ let pairs = posthog_cli::sourcemaps::source_pairs::read_pairs(+ selection.into_iter().filter(is_stylesheet_file),+ &None,+ );++ assert_eq!(pairs.len(), 1);+ assert_eq!(+ pairs[0].source.inner.path,+ stylesheet_path+ .canonicalize()+ .expect("Failed to canonicalize stylesheet fixture")+ );+}+#[test]fn test_search_without_prefix() {let pairs = read_pairs(vec![get_case_path("search")], vec![], vec![], &None)