fetchImportMeta fetches the import metadata from the esm.sh CDN.
(cdnOrigin string, imp Import, target string)
| 105 | |
| 106 | // fetchImportMeta fetches the import metadata from the esm.sh CDN. |
| 107 | func 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 | } |
no test coverage detected