url-or-path
Advanced tools
+15
-35
| import {fileURLToPath, pathToFileURL} from 'node:url' | ||
| const FILE_PATH_INVALID_ERROR_MESSAGE = 'File path should be a string or URL.' | ||
| const NONE_FILE_URL_ERROR_MESSAGE = "Only 'file:' URLs are supported." | ||
| const FILE_PROTOCOL = 'file:' | ||
| const isString = (value) => typeof value === 'string' | ||
| const isStringStartsWithFileProtocol = (string) => | ||
| string.startsWith(`${FILE_PROTOCOL}//`) | ||
| const isUrlInstance = (urlOrPath) => urlOrPath instanceof URL | ||
| const isUrlString = (urlOrPath) => | ||
| typeof urlOrPath === 'string' && urlOrPath.startsWith('file://') | ||
| function assertFileUrl(url) { | ||
| if (!(url instanceof URL)) { | ||
| throw new TypeError(FILE_PATH_INVALID_ERROR_MESSAGE) | ||
| const isUrl = (urlOrPath) => isUrlInstance(urlOrPath) || isUrlString(urlOrPath) | ||
| const toUrl = (urlOrPath) => { | ||
| if (isUrlInstance(urlOrPath)) { | ||
| return urlOrPath | ||
| } | ||
| if (url.protocol !== FILE_PROTOCOL) { | ||
| throw new TypeError(NONE_FILE_URL_ERROR_MESSAGE) | ||
| if (isUrlString(urlOrPath)) { | ||
| return new URL(urlOrPath) | ||
| } | ||
| return pathToFileURL(urlOrPath) | ||
| } | ||
| const toPath = (urlOrPath) => | ||
| isUrl(urlOrPath) ? fileURLToPath(urlOrPath) : urlOrPath | ||
| const addSlash = (url) => | ||
@@ -25,26 +29,2 @@ url.href.endsWith('/') ? url : new URL(`${url.href}/`) | ||
| function toUrl(urlOrPath) { | ||
| if (isString(urlOrPath)) { | ||
| return isStringStartsWithFileProtocol(urlOrPath) | ||
| ? new URL(urlOrPath) | ||
| : pathToFileURL(urlOrPath) | ||
| } | ||
| assertFileUrl(urlOrPath) | ||
| return urlOrPath | ||
| } | ||
| function toPath(urlOrPath) { | ||
| if (isString(urlOrPath)) { | ||
| return isStringStartsWithFileProtocol(urlOrPath) | ||
| ? fileURLToPath(urlOrPath) | ||
| : urlOrPath | ||
| } | ||
| assertFileUrl(urlOrPath) | ||
| return fileURLToPath(urlOrPath) | ||
| } | ||
| export {toDirectory, toUrl, toUrl as toURL, toPath} |
+6
-6
| { | ||
| "name": "url-or-path", | ||
| "version": "1.1.0", | ||
| "version": "2.0.0", | ||
| "description": "Convert between file URL and path.", | ||
@@ -53,7 +53,7 @@ "homepage": "https://github.com/fisker/url-or-path#readme", | ||
| "devDependencies": { | ||
| "@fisker/eslint-config": "10.0.10", | ||
| "@fisker/eslint-config-ava": "2.0.4", | ||
| "@fisker/husky-config": "4.1.1", | ||
| "@fisker/eslint-config": "10.0.12", | ||
| "@fisker/eslint-config-ava": "2.0.5", | ||
| "@fisker/husky-config": "4.1.2", | ||
| "@fisker/lint-staged-config": "3.1.4", | ||
| "@fisker/prettier-config": "5.0.4", | ||
| "@fisker/prettier-config": "5.0.5", | ||
| "ava": "4.0.1", | ||
@@ -65,3 +65,3 @@ "c8": "7.11.0", | ||
| "lint-staged": "12.3.3", | ||
| "markdownlint-cli": "0.31.0", | ||
| "markdownlint-cli": "0.31.1", | ||
| "npm-run-all": "4.1.5", | ||
@@ -68,0 +68,0 @@ "prettier": "2.5.1", |
5626
-7.83%20
-45.95%