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

fix js imports

parent 40dea036
Loading
Loading
Loading
Loading
+71
Changes for freeze.go: 71 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -21,6 +21,7 @@ import (

var cssURLRegexp = regexp.MustCompile(`url\(\s*['"]?([^'")]+)['"]?\s*\)`)
var cssImportRegexp = regexp.MustCompile(`@import\s+(?:url\(\s*)?['"]?([^'")\s;]+)['"]?\s*\)?`)
var jsImportRegexp = regexp.MustCompile(`(?m)(?:\bimport\s+(?:[^'";]*?\s+from\s+)?|\bexport\s+[^'";]*?\s+from\s+|\bimport\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.
@@ -168,6 +169,14 @@ func freezeSite(startURL, output string) error {
				}
			}
		}
		if isJSContentType(r.Headers.Get("Content-Type"), r.Request.URL.Path) {
			for _, ref := range jsImportRefs(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)
		}
@@ -240,6 +249,12 @@ func saveMirroredResponse(u *url.URL, body []byte, contentType, outputDir string
			return err
		}
		content = rewritten
	} else if isJSContentType(contentType, u.Path) {
		rewritten, err := rewriteJSImportsToRelative(body, u, contentType, outputDir)
		if err != nil {
			return err
		}
		content = rewritten
	}

	if err := os.MkdirAll(filepath.Dir(localPath), 0o755); err != nil {
@@ -296,6 +311,15 @@ func isCSSContentType(contentType, reqPath string) bool {
	return strings.Contains(ct, "text/css") || strings.HasSuffix(rp, ".css")
}

func isJSContentType(contentType, reqPath string) bool {
	ct := strings.ToLower(contentType)
	rp := strings.ToLower(reqPath)
	return strings.Contains(ct, "javascript") ||
		strings.Contains(ct, "ecmascript") ||
		strings.HasSuffix(rp, ".js") ||
		strings.HasSuffix(rp, ".mjs")
}

func rewriteHTMLLinksToRelative(body []byte, currentURL *url.URL, contentType, outputDir string) ([]byte, error) {
	doc, err := goquery.NewDocumentFromReader(bytes.NewReader(body))
	if err != nil {
@@ -374,6 +398,53 @@ func cssImportRefs(body []byte) []string {
	return refs
}

// JavaScript module specifiers are fetch dependencies when they are local URLs;
// bare package names are left alone because they cannot be mirrored from MaX.
func jsImportRefs(body []byte) []string {
	matches := jsImportRegexp.FindAllSubmatch(body, -1)
	refs := make([]string, 0, len(matches))
	for _, match := range matches {
		if len(match) < 2 {
			continue
		}
		ref := string(match[1])
		if isLocalImportSpecifier(ref) {
			refs = append(refs, ref)
		}
	}
	return refs
}

// Keep JavaScript rewriting limited to literal module specifiers. Computed
// dynamic imports and bare packages are preserved because changing them would be
// more likely to break application code than to make the frozen copy complete.
func rewriteJSImportsToRelative(body []byte, currentURL *url.URL, contentType, outputDir string) ([]byte, error) {
	jsText := jsImportRegexp.ReplaceAllStringFunc(string(body), func(match string) string {
		sub := jsImportRegexp.FindStringSubmatch(match)
		if len(sub) < 2 {
			return match
		}
		ref := sub[1]
		if !isLocalImportSpecifier(ref) {
			return match
		}
		rewritten, err := relativeMirroredRef(currentURL, contentType, ref, "application/javascript", outputDir)
		if err != nil {
			return match
		}
		return strings.Replace(match, ref, rewritten, 1)
	})
	return []byte(jsText), nil
}

func isLocalImportSpecifier(ref string) bool {
	trimmed := strings.TrimSpace(ref)
	if trimmed == "" {
		return false
	}
	return strings.HasPrefix(trimmed, ".") || strings.HasPrefix(trimmed, "/")
}

// 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.6"
const version = "0.4.7"

const maxConfigFile = "config.xml"
const minSupportedMaxVersion = "0.0.5"
+84
Changes for main_test.go: 84 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -146,6 +146,90 @@ func TestFreezeSiteCrawlsCSSImports(t *testing.T) {
	}
}

func TestRewriteJSImportsToRelative(t *testing.T) {
	currentURL, err := url.Parse("http://localhost:8080/static/js/app.js")
	if err != nil {
		t.Fatal(err)
	}

	input := []byte(`import "./local.js";
import thing from "/vendor/thing.js";
export { value } from "./reexport.js";
const lazy = import("./lazy.js");
import "bare-package";`)
	out, err := rewriteJSImportsToRelative(input, currentURL, "application/javascript", "/tmp/freeze")
	if err != nil {
		t.Fatal(err)
	}
	text := string(out)
	for _, expected := range []string{
		`import "local.js"`,
		`from "../../vendor/thing.js"`,
		`from "reexport.js"`,
		`import("lazy.js")`,
		`import "bare-package"`,
	} {
		if !strings.Contains(text, expected) {
			t.Fatalf("expected %q in rewritten js, got: %s", expected, text)
		}
	}
}

func TestJSImportRefs(t *testing.T) {
	input := []byte(`import "./local.js";
import thing from "/vendor/thing.js";
export { value } from "./reexport.js";
const lazy = import("./lazy.js");
const ignored = import(name);
import "bare-package";`)
	got := jsImportRefs(input)
	want := []string{
		"./local.js",
		"/vendor/thing.js",
		"./reexport.js",
		"./lazy.js",
	}
	if strings.Join(got, ",") != strings.Join(want, ",") {
		t.Fatalf("unexpected import refs: want %v, got %v", want, got)
	}
}

func TestFreezeSiteCrawlsJSImports(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(`<script type="module" src="/js/app.js"></script>`))
		case "/js/app.js":
			w.Header().Set("Content-Type", "application/javascript")
			_, _ = w.Write([]byte(`import "./module.js"; const lazy = import("./lazy.js");`))
		case "/js/module.js":
			w.Header().Set("Content-Type", "application/javascript")
			_, _ = w.Write([]byte(`export const value = 1;`))
		case "/js/lazy.js":
			w.Header().Set("Content-Type", "application/javascript")
			_, _ = w.Write([]byte(`export const lazy = true;`))
		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, "js", "app.js"),
		filepath.Join(output, "js", "module.js"),
		filepath.Join(output, "js", "lazy.js"),
	} {
		if !fileExists(path) {
			t.Fatalf("expected frozen js file to exist: %s", path)
		}
	}
}

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