ParseEsmPath parses an import from a pathname or URL.
(pathnameOrUrl string)
| 224 | |
| 225 | // ParseEsmPath parses an import from a pathname or URL. |
| 226 | func ParseEsmPath(pathnameOrUrl string) (imp Import, err error) { |
| 227 | var pathname string |
| 228 | if strings.HasPrefix(pathnameOrUrl, "https://") || strings.HasPrefix(pathnameOrUrl, "http://") { |
| 229 | var u *url.URL |
| 230 | u, err = url.Parse(pathnameOrUrl) |
| 231 | if err != nil { |
| 232 | return |
| 233 | } |
| 234 | pathname = u.Path |
| 235 | } else if strings.HasPrefix(pathnameOrUrl, "/") { |
| 236 | var u *url.URL |
| 237 | u, err = url.Parse("https://esm.sh" + pathnameOrUrl) |
| 238 | if err != nil { |
| 239 | return |
| 240 | } |
| 241 | pathname = u.Path |
| 242 | } else { |
| 243 | err = fmt.Errorf("invalid pathname or url: %s", pathnameOrUrl) |
| 244 | return |
| 245 | } |
| 246 | if strings.HasPrefix(pathname, "/gh/") { |
| 247 | imp.Github = true |
| 248 | pathname = pathname[3:] |
| 249 | } else if strings.HasPrefix(pathname, "/jsr/") { |
| 250 | imp.Jsr = true |
| 251 | pathname = pathname[4:] |
| 252 | } |
| 253 | segs := strings.Split(utils.NormalizePathname(pathname)[1:], "/") |
| 254 | if len(segs) == 0 { |
| 255 | err = fmt.Errorf("invalid pathname: %s", pathname) |
| 256 | return |
| 257 | } |
| 258 | if strings.HasPrefix(segs[0], "@") { |
| 259 | if len(segs) == 1 || segs[1] == "" { |
| 260 | err = fmt.Errorf("invalid pathname: %s", pathname) |
| 261 | return |
| 262 | } |
| 263 | name, version := utils.SplitByLastByte(segs[1], '@') |
| 264 | imp.Name = segs[0] + "/" + name |
| 265 | imp.Version = version |
| 266 | segs = segs[2:] |
| 267 | } else { |
| 268 | imp.Name, imp.Version = utils.SplitByLastByte(segs[0], '@') |
| 269 | segs = segs[1:] |
| 270 | } |
| 271 | // remove the leading `*` from the package name if it is from esm.sh |
| 272 | imp.Name = strings.TrimPrefix(imp.Name, "*") |
| 273 | if len(segs) > 0 { |
| 274 | var hasTargetSegment bool |
| 275 | switch segs[0] { |
| 276 | case "es2015", "es2016", "es2017", "es2018", "es2019", "es2020", "es2021", "es2022", "es2023", "es2024", "esnext", "denonext", "deno", "node": |
| 277 | // remove the target segment of esm.sh |
| 278 | segs = segs[1:] |
| 279 | hasTargetSegment = true |
| 280 | } |
| 281 | if len(segs) > 0 { |
| 282 | if hasTargetSegment && strings.HasSuffix(pathname, ".mjs") { |
| 283 | subPath := strings.TrimSuffix(strings.Join(segs, "/"), ".mjs") |
no outgoing calls
no test coverage detected