MCPcopy
hub / github.com/esm-dev/esm.sh / fetchImportMeta

Function fetchImportMeta

internal/importmap/meta.go:107–223  ·  view source on GitHub ↗

fetchImportMeta fetches the import metadata from the esm.sh CDN.

(cdnOrigin string, imp Import, target string)

Source from the content-addressed store, hash-verified

105
106// fetchImportMeta fetches the import metadata from the esm.sh CDN.
107func fetchImportMeta(cdnOrigin string, imp Import, target string) (meta ImportMeta, err error) {
108 asteriskPrefix := ""
109 version := ""
110 subPath := ""
111 if imp.External {
112 asteriskPrefix = "*"
113 }
114 if imp.Version != "" {
115 version = "@" + imp.Version
116 }
117 if imp.SubPath != "" {
118 subPath = "/" + imp.SubPath
119 }
120 url := fmt.Sprintf("%s/%s%s%s%s%s?meta", cdnOrigin, asteriskPrefix, imp.RegistryPrefix(), imp.Name, version, subPath)
121 if target != "" && target != "es2022" {
122 url += "&target=" + target
123 }
124
125 // check memory cache first
126 if v, ok := fetchCache.Load(url); ok {
127 meta, _ = v.(ImportMeta)
128 return
129 }
130
131 // only one fetch at a time for the same url
132 unlock := keyedMutex.Lock(url)
133 defer unlock()
134
135 // check memory cache again after acquiring the lock state
136 if v, ok := fetchCache.Load(url); ok {
137 meta, _ = v.(ImportMeta)
138 return
139 }
140
141 appDir, err := app_dir.GetAppDir()
142 if err != nil {
143 err = fmt.Errorf("could not get app directory: %s", err.Error())
144 return
145 }
146
147 sha := sha256.Sum256([]byte(url))
148 cachePath := filepath.Join(appDir, "meta", hex.EncodeToString(sha[:]))
149
150 // if the version is exact, check the cache on disk
151 if npm.IsExactVersion(imp.Version) {
152 f, err := os.Open(cachePath)
153 if err == nil {
154 defer f.Close()
155 err = json.NewDecoder(f).Decode(&meta)
156 if err == nil {
157 meta.SubPath = imp.SubPath
158 meta.Github = imp.Github
159 meta.Jsr = imp.Jsr
160 meta.External = imp.External
161 meta.Dev = imp.Dev
162 fetchCache.Store(url, meta)
163 return meta, nil
164 }

Callers 2

ParseImportMethod · 0.85
FetchImportMetaMethod · 0.85

Calls 7

GetAppDirFunction · 0.92
IsExactVersionFunction · 0.92
RegistryPrefixMethod · 0.80
ErrorMethod · 0.80
SpecifierMethod · 0.80
CloseMethod · 0.65
GetMethod · 0.65

Tested by

no test coverage detected