summaryrefslogtreecommitdiffstats
path: root/internal/builder/importmap.go
blob: 844541191a3e4bd6f369a0a72b35afbd2ebe8f9d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package builder

import (
	"encoding/json"
	"os"
	"path/filepath"
	"strings"
)

// ImportMap represents a browser importmap.
type ImportMap struct {
	Imports map[string]string `json:"imports"`
}

// GenerateImportMap scans libDir for .js files and produces an importmap JSON string.
//
// Naming rules:
//   - lib/chart.js          → "chart"
//   - lib/icons/index.js    → "icons"
//   - lib/utils/helpers.js  → "utils/helpers"
func GenerateImportMap(libDir string) (string, error) {
	imports := make(map[string]string)

	if _, err := os.Stat(libDir); os.IsNotExist(err) {
		b, _ := json.MarshalIndent(ImportMap{Imports: imports}, "", "  ")
		return string(b), nil
	}

	err := filepath.WalkDir(libDir, func(path string, d os.DirEntry, err error) error {
		if err != nil || d.IsDir() || !strings.HasSuffix(path, ".js") {
			return err
		}
		rel, _ := filepath.Rel(libDir, path)
		rel = filepath.ToSlash(rel)

		dir := filepath.ToSlash(filepath.Dir(rel))
		base := strings.TrimSuffix(filepath.Base(rel), ".js")

		var importName string
		switch {
		case dir == ".":
			importName = base
		case base == "index":
			importName = dir
		default:
			importName = dir + "/" + base
		}

		imports[importName] = "/lib/" + rel
		return nil
	})
	if err != nil {
		return "", err
	}

	b, err := json.MarshalIndent(ImportMap{Imports: imports}, "", "  ")
	return string(b), err
}