first commit

This commit is contained in:
Artem Anufrij
2026-10-07 18:56:27 +02:00
commit 2a8a60b725
7768 changed files with 1550851 additions and 0 deletions
+180
View File
@@ -0,0 +1,180 @@
/**
Check if the current environment is Windows Subsystem for Linux (WSL).
*/
export const isWsl: boolean;
/**
Get the PowerShell executable path in WSL environment.
*/
export function powerShellPathFromWsl(): Promise<string>;
/**
Get the PowerShell executable path for the current environment.
Returns WSL path if in WSL, otherwise returns Windows path.
*/
export function powerShellPath(): Promise<string>;
/**
Check if PowerShell is accessible in the current environment.
This is useful to determine whether Windows integration features can be used. In sandboxed WSL environments or systems where PowerShell is not accessible, this will return `false`.
@returns A promise that resolves to `true` if PowerShell is accessible, `false` otherwise.
@example
```
import {canAccessPowerShell} from 'wsl-utils';
if (await canAccessPowerShell()) {
// Use Windows integration features
console.log('PowerShell is accessible');
} else {
// Fall back to Linux-native behavior
console.log('PowerShell is not accessible');
}
```
*/
export function canAccessPowerShell(): Promise<boolean>;
/**
Get the default browser in WSL.
@returns A promise that resolves to the [ProgID](https://setuserfta.com/guide-to-understanding-progids-and-file-type-associations/) of the default browser (e.g., `'ChromeHTML'`, `'FirefoxURL'`).
@example
```
import {wslDefaultBrowser} from 'wsl-utils';
const progId = await wslDefaultBrowser();
//=> 'ChromeHTML'
```
*/
export function wslDefaultBrowser(): Promise<string>;
/**
Get the mount point for fixed drives in WSL.
*/
export function wslDrivesMountPoint(): Promise<string>;
/**
Convert a WSL Linux path to a Windows-accessible path.
URLs (strings starting with a protocol like `https://`) are returned unchanged.
@param path - The WSL path to convert (e.g., `/home/user/file.html`).
@returns The Windows-accessible path (e.g., `\\wsl.localhost\Ubuntu\home\user\file.html`) or the original path if conversion fails.
@example
```
import {convertWslPathToWindows} from 'wsl-utils';
// Convert a Linux path
const windowsPath = await convertWslPathToWindows('/home/user/file.html');
//=> '\\wsl.localhost\Ubuntu\home\user\file.html'
// URLs are not converted
const url = await convertWslPathToWindows('https://example.com');
//=> 'https://example.com'
```
*/
export function convertWslPathToWindows(path: string): Promise<string>;
/**
Convert multiple WSL Linux paths to Windows-accessible paths.
URLs (strings starting with a protocol like `https://`) are returned unchanged.
@param paths - The WSL paths to convert.
@returns The Windows-accessible paths in the same order, or the original paths if conversion fails.
@example
```
import {convertWslPathToWindows} from 'wsl-utils';
const windowsPaths = await convertWslPathToWindows([
'/home/user/file.html',
'/mnt/c/Users/file.txt',
'https://example.com'
]);
//=> ['\\wsl.localhost\Ubuntu\home\user\file.html', 'C:\Users\file.txt', 'https://example.com']
```
*/
export function convertWslPathToWindows(paths: string[]): Promise<string[]>;
/**
Check if a Windows path is a UNC path (e.g., `\\wsl.localhost\...` or `\\wsl$\...`).
UNC paths indicate the file resides on the WSL Linux filesystem rather than a Windows drive.
@param path - The Windows path to check.
@returns `true` if the path is a UNC path, `false` otherwise.
@example
```
import {isUncPath} from 'wsl-utils';
isUncPath('\\\\wsl.localhost\\Ubuntu\\home\\user');
//=> true
isUncPath('C:\\Users\\file.txt');
//=> false
```
*/
export function isUncPath(path: string): boolean;
/**
Check if a WSL path maps to the Windows filesystem.
This converts the path and checks if it's on a Windows drive (e.g., `/mnt/c/...` → `C:\...`) rather than the Linux filesystem (e.g., `/home/...` → `\\wsl$\...`).
@param path - The WSL path to check.
@returns `true` if the path is on a Windows drive, `false` if it's on the Linux filesystem.
@example
```
import {isPathOnWindowsFilesystem} from 'wsl-utils';
await isPathOnWindowsFilesystem('/mnt/c/Users/file.txt');
//=> true
await isPathOnWindowsFilesystem('/home/user/file.txt');
//=> false
```
*/
export function isPathOnWindowsFilesystem(path: string): Promise<boolean>;
/**
Convert a Windows path to a WSL Linux path.
@param path - The Windows path to convert (e.g., `C:\Users\file.txt`).
@returns The WSL path (e.g., `/mnt/c/Users/file.txt`) or the original path if conversion fails.
@example
```
import {convertWindowsPathToWsl} from 'wsl-utils';
const wslPath = await convertWindowsPathToWsl('C:\\Users\\file.txt');
//=> '/mnt/c/Users/file.txt'
```
*/
export function convertWindowsPathToWsl(path: string): Promise<string>;
/**
Convert multiple Windows paths to WSL Linux paths.
@param paths - The Windows paths to convert.
@returns The WSL paths in the same order, or the original paths if conversion fails.
@example
```
import {convertWindowsPathToWsl} from 'wsl-utils';
const wslPaths = await convertWindowsPathToWsl([
'C:\\Users\\file.txt',
'D:\\Projects\\app'
]);
//=> ['/mnt/c/Users/file.txt', '/mnt/d/Projects/app']
```
*/
export function convertWindowsPathToWsl(paths: string[]): Promise<string[]>;
+126
View File
@@ -0,0 +1,126 @@
import path from 'node:path';
import {promisify} from 'node:util';
import childProcess from 'node:child_process';
import fs, {constants as fsConstants} from 'node:fs/promises';
import isWsl from 'is-wsl';
import {powerShellPath as windowsPowerShellPath, executePowerShell} from 'powershell-utils';
import {parseMountPointFromConfig} from './utilities.js';
const execFile = promisify(childProcess.execFile);
export const wslDrivesMountPoint = (() => {
// Default value for "root" param
// according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config
const defaultMountPoint = '/mnt/';
let mountPoint;
return async function () {
if (mountPoint) {
// Return memoized mount point value
return mountPoint;
}
const configFilePath = '/etc/wsl.conf';
let isConfigFileExists = false;
try {
await fs.access(configFilePath, fsConstants.F_OK);
isConfigFileExists = true;
} catch {}
if (!isConfigFileExists) {
return defaultMountPoint;
}
const configContent = await fs.readFile(configFilePath, {encoding: 'utf8'});
const parsedMountPoint = parseMountPointFromConfig(configContent);
if (parsedMountPoint === undefined) {
return defaultMountPoint;
}
mountPoint = parsedMountPoint;
mountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`;
return mountPoint;
};
})();
export const powerShellPathFromWsl = async () => {
const mountPoint = await wslDrivesMountPoint();
return `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
};
export const powerShellPath = isWsl ? powerShellPathFromWsl : windowsPowerShellPath;
// Cache for PowerShell accessibility check
let canAccessPowerShellPromise;
export const canAccessPowerShell = async () => {
canAccessPowerShellPromise ??= (async () => {
try {
const psPath = await powerShellPath();
await fs.access(psPath, fsConstants.X_OK);
return true;
} catch {
// PowerShell is not accessible (either doesn't exist, no execute permission, or other error)
return false;
}
})();
return canAccessPowerShellPromise;
};
export const wslDefaultBrowser = async () => {
const psPath = await powerShellPath();
const command = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
// The spawned Windows process inherits the Linux working directory, which WSL exposes to Windows as a `\\wsl.localhost\…` UNC path served by the distro's default user, so a directory that user cannot traverse makes the launch fail. PowerShell's own directory is on the Windows drive, so it always resolves to a plain `C:\…` path.
const {stdout} = await executePowerShell(command, {
powerShellPath: psPath,
cwd: path.dirname(psPath),
});
return stdout.trim();
};
const isUrl = path => /^[a-z]+:\/\//i.test(path);
// `wslpath` only accepts a single path, so each path needs its own call.
const convertPath = async (flag, path) => {
// `--` stops `wslpath` from reading a leading `-` as an option. Only pass it when needed, as it is only confirmed for WSL 2.5 and later.
const wslpathArguments = path.startsWith('-') ? [flag, '--', path] : [flag, path];
try {
const {stdout} = await execFile('wslpath', wslpathArguments, {encoding: 'utf8'});
return stdout.replace(/\r?\n$/, '') || path;
} catch {
// If wslpath fails, keep original path
return path;
}
};
export const convertWslPathToWindows = async paths => {
const isBatch = Array.isArray(paths);
const pathArray = isBatch ? paths : [paths];
// URLs stay as-is
const results = await Promise.all(pathArray.map(path => isUrl(path) ? path : convertPath('-aw', path)));
return isBatch ? results : results[0];
};
export const isUncPath = path => /^\\\\/u.test(path);
export const isPathOnWindowsFilesystem = async path => {
const windowsPath = await convertWslPathToWindows(path);
return !isUncPath(windowsPath);
};
export const convertWindowsPathToWsl = async paths => {
const isBatch = Array.isArray(paths);
const pathArray = isBatch ? paths : [paths];
const results = await Promise.all(pathArray.map(path => convertPath('-u', path)));
return isBatch ? results : results[0];
};
export {default as isWsl} from 'is-wsl';
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+48
View File
@@ -0,0 +1,48 @@
{
"name": "wsl-utils",
"version": "1.0.1",
"description": "Utilities for working with Windows Subsystem for Linux (WSL)",
"license": "MIT",
"repository": "sindresorhus/wsl-utils",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"type": "module",
"exports": {
"types": "./index.d.ts",
"default": "./index.js"
},
"sideEffects": false,
"engines": {
"node": ">=20"
},
"scripts": {
"test": "xo && ava && tsc index.d.ts --skipLibCheck"
},
"files": [
"index.js",
"index.d.ts",
"utilities.js"
],
"keywords": [
"wsl",
"windows",
"subsystem",
"linux",
"powershell",
"mount",
"utilities"
],
"dependencies": {
"is-wsl": "^3.1.0",
"powershell-utils": "^0.2.0"
},
"devDependencies": {
"ava": "^6.4.1",
"typescript": "^5.9.3",
"xo": "^1.2.3"
}
}
+223
View File
@@ -0,0 +1,223 @@
# wsl-utils
> Utilities for working with [Windows Subsystem for Linux (WSL)](https://en.wikipedia.org/wiki/Windows_Subsystem_for_Linux)
## Install
```sh
npm install wsl-utils
```
## Usage
```js
import {isWsl, powerShellPathFromWsl} from 'wsl-utils';
// Check if running in WSL
console.log('Is WSL:', isWsl);
// Get PowerShell path from WSL
console.log('PowerShell path:', await powerShellPathFromWsl());
//=> '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe'
```
## API
### isWsl
Type: `boolean`
Check if the current environment is Windows Subsystem for Linux (WSL).
### powerShellPathFromWsl()
Returns: `Promise<string>`
Get the PowerShell executable path in WSL environment.
### powerShellPath()
Returns: `Promise<string>`
Get the PowerShell executable path for the current environment.
Returns WSL path if in WSL, otherwise returns Windows path.
### canAccessPowerShell()
Returns: `Promise<boolean>`
Check if PowerShell is accessible in the current environment.
This is useful to determine whether Windows integration features can be used. In sandboxed WSL environments or systems where PowerShell is not accessible, this will return `false`.
```js
import {canAccessPowerShell} from 'wsl-utils';
if (await canAccessPowerShell()) {
// Use Windows integration features
console.log('PowerShell is accessible');
} else {
// Fall back to Linux-native behavior
console.log('PowerShell is not accessible');
}
```
### wslDefaultBrowser()
Returns: `Promise<string>`
Get the default browser in WSL.
Returns a promise that resolves to the [ProgID](https://setuserfta.com/guide-to-understanding-progids-and-file-type-associations/) of the default browser (e.g., `'ChromeHTML'`, `'FirefoxURL'`).
```js
import {wslDefaultBrowser} from 'wsl-utils';
const progId = await wslDefaultBrowser();
//=> 'ChromeHTML'
```
### wslDrivesMountPoint()
Returns: `Promise<string>`
Get the mount point for fixed drives in WSL.
### convertWslPathToWindows(path)
Returns: `Promise<string>`
Convert a WSL Linux path to a Windows-accessible path.
URLs (strings starting with a protocol like `https://`) are returned unchanged.
```js
import {convertWslPathToWindows} from 'wsl-utils';
// Convert a Linux path
const windowsPath = await convertWslPathToWindows('/home/user/file.html');
//=> '\\wsl.localhost\Ubuntu\home\user\file.html'
// URLs are not converted
const url = await convertWslPathToWindows('https://example.com');
//=> 'https://example.com'
```
#### path
Type: `string`
The WSL path to convert (e.g., `/home/user/file.html`).
### convertWslPathToWindows(paths)
Returns: `Promise<string[]>`
Convert multiple WSL Linux paths to Windows-accessible paths.
```js
import {convertWslPathToWindows} from 'wsl-utils';
const windowsPaths = await convertWslPathToWindows([
'/home/user/file.html',
'/mnt/c/Users/file.txt',
'https://example.com'
]);
//=> ['\\wsl.localhost\Ubuntu\home\user\file.html', 'C:\Users\file.txt', 'https://example.com']
```
#### paths
Type: `string[]`
The WSL paths to convert.
### isUncPath(path)
Returns: `boolean`
Check if a Windows path is a UNC path (e.g., `\\wsl.localhost\...` or `\\wsl$\...`).
UNC paths indicate the file resides on the WSL Linux filesystem rather than a Windows drive.
```js
import {isUncPath} from 'wsl-utils';
isUncPath('\\\\wsl.localhost\\Ubuntu\\home\\user');
//=> true
isUncPath('C:\\Users\\file.txt');
//=> false
```
#### path
Type: `string`
The Windows path to check.
### isPathOnWindowsFilesystem(path)
Returns: `Promise<boolean>`
Check if a WSL path maps to the Windows filesystem.
This converts the path and checks if it's on a Windows drive (e.g., `/mnt/c/...` → `C:\...`) rather than the Linux filesystem (e.g., `/home/...` → `\\wsl$\...`).
```js
import {isPathOnWindowsFilesystem} from 'wsl-utils';
await isPathOnWindowsFilesystem('/mnt/c/Users/file.txt');
//=> true
await isPathOnWindowsFilesystem('/home/user/file.txt');
//=> false
```
#### path
Type: `string`
The WSL path to check.
### convertWindowsPathToWsl(path)
Returns: `Promise<string>`
Convert a Windows path to a WSL Linux path.
```js
import {convertWindowsPathToWsl} from 'wsl-utils';
const wslPath = await convertWindowsPathToWsl('C:\\Users\\file.txt');
//=> '/mnt/c/Users/file.txt'
```
#### path
Type: `string`
The Windows path to convert.
### convertWindowsPathToWsl(paths)
Returns: `Promise<string[]>`
Convert multiple Windows paths to WSL Linux paths.
```js
import {convertWindowsPathToWsl} from 'wsl-utils';
const wslPaths = await convertWindowsPathToWsl([
'C:\\Users\\file.txt',
'D:\\Projects\\app'
]);
//=> ['/mnt/c/Users/file.txt', '/mnt/d/Projects/app']
```
#### paths
Type: `string[]`
The Windows paths to convert.
+19
View File
@@ -0,0 +1,19 @@
export function parseMountPointFromConfig(content) {
for (const line of content.split('\n')) {
// Skip comment lines
if (/^\s*#/.test(line)) {
continue;
}
// Match root at start of line (after optional whitespace)
const match = /^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(line);
if (!match) {
continue;
}
return match.groups.mountPoint
.trim()
// Strip surrounding quotes
.replaceAll(/^["']|["']$/g, '');
}
}