Commit 40dea036 authored by Mickaël Desfrênes's avatar Mickaël Desfrênes
Browse files

fix css imports

parent 1be643f4
Loading
Loading
Loading
Loading
+38 −3
Changes for freeze.go: 38 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -20,6 +20,7 @@ import (
)

var cssURLRegexp = regexp.MustCompile(`url\(\s*['"]?([^'")]+)['"]?\s*\)`)
var cssImportRegexp = regexp.MustCompile(`@import\s+(?:url\(\s*)?['"]?([^'")\s;]+)['"]?\s*\)?`)

// Freeze runs against an isolated transient server so the crawl observes the
// same BaseX routes as start, without depending on any already running service.
@@ -159,6 +160,14 @@ func freezeSite(startURL, output string) error {
		if r.StatusCode < 200 || r.StatusCode >= 300 {
			return
		}
		if isCSSContentType(r.Headers.Get("Content-Type"), r.Request.URL.Path) {
			for _, ref := range cssImportRefs(r.Body) {
				u := r.Request.AbsoluteURL(ref)
				if u != "" {
					_ = r.Request.Visit(u)
				}
			}
		}
		if err := saveMirroredResponse(r.Request.URL, r.Body, r.Headers.Get("Content-Type"), output); err != nil {
			setErr(err)
		}
@@ -321,10 +330,22 @@ func rewriteHTMLLinksToRelative(body []byte, currentURL *url.URL, contentType, o
	return []byte(htmlText), nil
}

// This intentionally handles simple url(...) references only; complex CSS
// parsing would be heavier than the static assets MaX bundles currently use.
// This intentionally handles simple @import and url(...) references only;
// complex CSS parsing would be heavier than the static assets MaX bundles use.
func rewriteCSSLinksToRelative(body []byte, currentURL *url.URL, contentType, outputDir string) ([]byte, error) {
	cssText := cssURLRegexp.ReplaceAllStringFunc(string(body), func(match string) string {
	cssText := cssImportRegexp.ReplaceAllStringFunc(string(body), func(match string) string {
		sub := cssImportRegexp.FindStringSubmatch(match)
		if len(sub) < 2 {
			return match
		}
		ref := sub[1]
		rewritten, err := relativeMirroredRef(currentURL, contentType, ref, "text/css", outputDir)
		if err != nil {
			return match
		}
		return strings.Replace(match, ref, rewritten, 1)
	})
	cssText = cssURLRegexp.ReplaceAllStringFunc(cssText, func(match string) string {
		sub := cssURLRegexp.FindStringSubmatch(match)
		if len(sub) < 2 {
			return match
@@ -339,6 +360,20 @@ func rewriteCSSLinksToRelative(body []byte, currentURL *url.URL, contentType, ou
	return []byte(cssText), nil
}

// Imported stylesheets are fetch dependencies, not just text to rewrite; without
// visiting them the frozen tree keeps valid @import lines that point to files not
// present in the copy.
func cssImportRefs(body []byte) []string {
	matches := cssImportRegexp.FindAllSubmatch(body, -1)
	refs := make([]string, 0, len(matches))
	for _, match := range matches {
		if len(match) >= 2 {
			refs = append(refs, string(match[1]))
		}
	}
	return refs
}

// External links and non-fetching schemes stay untouched; only links that map
// into the mirrored output tree are converted to relative filesystem paths.
func relativeMirroredRef(currentURL *url.URL, currentContentType, rawRef, guessType, outputDir string) (string, error) {
+1 −1
Changes for main.go: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -10,7 +10,7 @@ import (
//go:embed max_releases.json
var fallbackReleases []byte

const version = "0.4.5"
const version = "0.4.6"

const maxConfigFile = "config.xml"
const minSupportedMaxVersion = "0.0.5"
+76
Changes for main_test.go: 76 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -8,6 +8,7 @@ import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"path/filepath"
@@ -70,6 +71,81 @@ func TestRewriteCSSLinksToRelative(t *testing.T) {
	}
}

func TestRewriteCSSImportsToRelative(t *testing.T) {
	currentURL, err := url.Parse("http://localhost:8080/css/main.css")
	if err != nil {
		t.Fatal(err)
	}

	input := []byte(`@charset "UTF-8";
@import "/shared/reset.css";
@import url('./nested/theme.css');
body{background:url('/images/bg.png')}`)
	out, err := rewriteCSSLinksToRelative(input, currentURL, "text/css", "/tmp/freeze")
	if err != nil {
		t.Fatal(err)
	}
	text := string(out)
	for _, expected := range []string{
		`@import "../shared/reset.css"`,
		`@import url(nested/theme.css)`,
		`url(../images/bg.png)`,
	} {
		if !strings.Contains(text, expected) {
			t.Fatalf("expected %q in rewritten css, got: %s", expected, text)
		}
	}
}

func TestCSSImportRefs(t *testing.T) {
	input := []byte(`@charset "UTF-8";
@import "./0.config/0.layers.css";
@import url("./0.config/fonts.css");
@import url(./3.utilities/text.css) screen;
body{background:url("./not-an-import.png")}`)
	got := cssImportRefs(input)
	want := []string{
		"./0.config/0.layers.css",
		"./0.config/fonts.css",
		"./3.utilities/text.css",
	}
	if strings.Join(got, ",") != strings.Join(want, ",") {
		t.Fatalf("unexpected import refs: want %v, got %v", want, got)
	}
}

func TestFreezeSiteCrawlsCSSImports(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Path {
		case "/":
			w.Header().Set("Content-Type", "text/html")
			_, _ = w.Write([]byte(`<link rel="stylesheet" href="/css/main.css">`))
		case "/css/main.css":
			w.Header().Set("Content-Type", "text/css")
			_, _ = w.Write([]byte(`@import "./nested.css"; body{color:black}`))
		case "/css/nested.css":
			w.Header().Set("Content-Type", "text/css")
			_, _ = w.Write([]byte(`body{background:white}`))
		default:
			http.NotFound(w, r)
		}
	}))
	defer server.Close()

	output := t.TempDir()
	if err := freezeSite(server.URL+"/", output); err != nil {
		t.Fatal(err)
	}
	for _, path := range []string{
		filepath.Join(output, "css", "main.css"),
		filepath.Join(output, "css", "nested.css"),
	} {
		if !fileExists(path) {
			t.Fatalf("expected frozen css file to exist: %s", path)
		}
	}
}

func TestProjectsJSONStorageLifecycle(t *testing.T) {
	tmpHome := t.TempDir()
	prevHome := userMaxDir