Initial commit

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
dinlo
2026-05-31 18:44:04 +08:00
commit 436a9631fc
8616 changed files with 1389957 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
Copyright (c) Felix Rieseberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+262
View File
@@ -0,0 +1,262 @@
# @electron/windows-sign [![npm][npm_img]][npm_url]
Codesign your app for Windows. Made for [Electron][electron] but really supports any folder with binary files. `electron-windows-sign` scans a folder for [signable files](#file-types) and codesigns them with both SHA-1 and SHA-256. It can be highly customized and used either programmatically or on the command line.
This tool is particularly useful if you want to code sign Electron or other Windows binaries with an EV certificate or an HSM setup (like DigiCert KeyLocker, AWS CloudHSM, Azure Key Vault HSM, Google Cloud Key Management Service HSM, and other similar services). For more details on how you'd exactly do that, please see [Use with Cloud HSM Providers](#use-with-cloud-hsm-providers) below.
# Requirements
By default, this module spawns `signtool.exe` and needs to run on Windows. If you're building an Electron app and care enough to codesign them, I would heavily recommend that you build and test your apps on the platforms you're building for.
# Usage
Most developers of Electron apps will likely not use this module directly - and instead use it indirectly
instead. If you are one of those developers who is using a module like `@electron/forge` or `@electron/packager`, you can configure this module with global environment variables. If that describes
you, you can skip ahead to your use case:
- [With a certificate file and password](#with-a-certificate-file-and-password)
- [With a custom binary or custom parameters](#with-a-custom-signtoolexe-or-custom-parameters)
- [With a completely custom hook](#with-a-custom-hook-function)
## Direct Usage
`@electron/windows-codesign` is built to both esm and cjs and can be used both as a module as well as directly from the command line.
```ts
import { sign } from "@electron/windows-sign"
// or const { sign } = require("@electron/windows-sign")
await sign(signOptions)
```
```ps1
electron-windows-sign $PATH_TO_APP_DIRECTORY [options ...]
```
## With a certificate file and password
This is the "traditional" way to codesign Electron apps on Windows. You pass in a certificate file
(like a .pfx) and a password, which will then be passed to a built-in version of `signtool.exe` taken
directly from the Windows SDK.
```ts
await sign({
appDirectory: "C:\\Path\\To\\App",
// or process.env.WINDOWS_CERTIFICATE_FILE
certificateFile: "C:\\Cert.pfx",
// or process.env.WINDOWS_CERTIFICATE_PASSWORD
certificatePassword: "hunter99"
})
```
```ps1
electron-windows-sign $PATH_TO_APP_DIRECTORY --certificate-file=$PATH_TO_CERT --certificate-password=$CERT-PASSWORD
```
### Full configuration
```ts
// Path to a timestamp server. Defaults to http://timestamp.digicert.com
// Can also be passed as process.env.WINDOWS_TIMESTAMP_SERVER
timestampServer = "http://timestamp.digicert.com"
// Description of the signed content. Will be passed to signtool.exe as /d
// Can also be passed as process.env.WINDOWS_SIGN_DESCRIPTION
description = "My content"
// URL of the signed content. Will be passed to signtool.exe as /du
// Can also be passed as process.env.WINDOWS_SIGN_WEBSITE
website = "https://mywebsite.com"
// If enabled, attempt to sign .js JavaScript files. Disabled by default
signJavaScript = true
// If unspecified, both sha1 and sha256 signatures will be appended. Will be passed to signtool.exe as the /fd option.
hashes = ["sha256"]
```
## With a custom signtool.exe or custom parameters
Sometimes, you need to specify specific signing parameters or use a different version
of `signtool.exe`. In this mode, `@electron/windows-sign` will call the provided binary
with the provided parameters for each file to sign.
If you only provide `signToolPath`, the default parameters will be used.
If you only provide `signWithParams`, the default `signtool.exe` will be used.
All the [additional configuration](#additional-configuration) mentioned above is also
available here, but only used if you do not provide your own parameters.
```ts
await sign({
appDirectory: "C:\\Path\\To\\App",
// or process.env.WINDOWS_CERTIFICATE_FILE
certificateFile: "C:\\Cert.pfx",
// or process.env.WINDOWS_CERTIFICATE_PASSWORD
certificatePassword: "hunter99",
// or process.env.WINDOWS_SIGNTOOL_PATH
signToolPath: "C:\\Path\\To\\my-custom-tool.exe",
// or process.env.WINDOWS_SIGN_WITH_PARAMS
signWithParams: "--my=custom --parameters"
})
```
```ps1
electron-windows-sign $PATH_TO_APP_DIRECTORY --sign-tool-path=$PATH_TO_TOOL --sign-with-params="--my=custom --parameters"
```
## With a custom hook function
Sometimes, you just want all modules depending on `@electron/windows-sign` to call
your completely custom logic. You can either specify a `hookFunction` (if you're calling
this module yourself) or a `hookModulePath`, which this module will attempt to require.
Using the `hookModulePath` has the benefit that you can override how any other users
of this module (like `@electron/packager`) codesign your app.
```ts
await sign({
// A function with the following signature:
// (fileToSign: string) => void | Promise<void>
//
// This function will be called sequentially for each file that
// @electron/windows-sign wants to sign.
hookFunction: myHookFunction
// Path to a hook module.
hookModulePath: "C:\\Path\\To\\my-hook-module.js",
})
```
Your hook module should either directly export a function or
export a `default` function.
```js
// Good:
module.exports = function (filePath) {
console.log(`Path to file to sign: ${filePath}`)
}
// Good:
module.exports = async function (filePath) {
console.log(`Path to file to sign: ${filePath}`)
}
// Good:
export default async function (filePath) {
console.log(`Path to file to sign: ${filePath}`)
}
// Bad:
module.exports = {
myCustomHookName: function (filePath) {
console.log(`Path to file to sign: ${filePath}`)
}
}
// Bad:
export async function myCustomHookName(filePath) {
console.log(`Path to file to sign: ${filePath}`)
}
```
```
SYNOPSIS
electron-windows-sign app [options ...]
DESCRIPTION
app
Path to the application to sign. It must be a directory.
certificate-file
Path to the certificate file (.pfx) to use for signing. Uses
environment variable WINDOWS_CERTIFICATE_FILE if not provided.
certificate-password
Password to use for the certificate. Uses environment variable
WINDOWS_CERTIFICATE_PASSWORD if not provided.
sign-tool-path
Path to the signtool.exe binary. If not specified, the tool will attempt
use a built-in version.
timestamp-server
URL of the timestamp server to use. If not specified, the tool will
attempt to use a built-in server (http://timestamp.digicert.com)
description
Description to use for the signed files. Passed as /d to signtool.exe.
website
URL of the website to use for the signed files. Passed as /du to
signtool.exe.
sign-with-params
Additional parameters to pass to signtool.exe. This can be used to
specify additional certificates to use for cross-signing.
automatically-select-certificate
Automatically select the best certificate to use for signing. On by default.
help
Print this usage information.
debug
Print additional debug information.
```
# File Types
This tool will aggressively attempt to sign all files that _can_
be signed, excluding scripts.
- [Portable executable files][pe] (.exe, .dll, .sys, .efi, .scr, .node)
- Microsoft installers (.msi)
- APPX/MSIX packages (.appx, .appxbundle, .msix, .msixbundle)
- Catalog files (.cat)
- Cabinet files (.cab)
- Silverlight applications (.xap)
- Scripts (.vbs, .wsf, .ps1)
If you do want to sign JavaScript, please enable it with the `signJavaScript`
parameter. As far as we are aware, there are no benefits to signing
JavaScript files, so we do not by default.
# Use with Cloud HSM Providers
Since 2023, Microsoft requires that Windows software be signed with an extended validation (EV) certificate in order to avoid a Windows Defender popup. This presents a challenge for developers who are used to building and signing in the cloud or some continuous integration setup like GitHub Actions, CircleCI, Travis CI, or AppVeyor because EV certificates require a Hardware Security Module (HSM). Or, in simpler words: If you want to code sign your Windows software so that your customers don't see a scary Windows Defender dialog, you need to code sign on a computer with a USB device plugged in.
The industry has an answer to this problem: Services like DigiCert KeyLocker, AWS CloudHSM, Azure Key Vault HSM, or Google Cloud Key Management Service HSM allow code signing binaries with an Extended Validation (EV) certificate from the cloud. `@electron/windows-sign` is compatible with all of these services.
## Custom signtool parameters
Most services allow signing your code with Microsoft's `signtool.exe`. Let's take DigiCert KeyLocker as an example. [DigiCert's documentation](https://docs.digicert.com/en/digicert-keylocker/signing-tools/sign-authenticode-files-with-signtool-on-windows.html) explains the steps necessary to setup your signing machine. Once done, you can sign with the following call:
```
signtool.exe sign /csp "DigiCert Signing Manager KSP" /kc <keypair_alias> /f <certificate_file> /tr http://timestamp.digicert.com /td SHA256 /fd SHA256 <file_to_be_signed>
```
To sign with `@electron/windows-sign` using those instructions, you would take the parameters and add them to `signWithParams`:
```js
await sign({
signWithParams: "/csp \"DigiCert Signing Manager KSP\" /kc <keypair_alias> /f <certificate_file> /tr http://timestamp.digicert.com /td SHA256 /fd SHA256"
})
```
Both Google's and Amazon's solutions similarly allow you to sign with Microsoft's SignTool. Documentation for [Google can be found here](https://cloud.google.com/kms/docs/reference/cng-signtool), [Amazon's lives here](https://docs.aws.amazon.com/cloudhsm/latest/userguide/signtool.html).
## Custom signtool.exe
Some providers provide drop-in replacements for `signtool.exe`. If that's the case, simply pass the path to that replacement:
```ts
await sign({
// or process.env.WINDOWS_SIGNTOOL_PATH
signToolPath: "C:\\Path\\To\\my-custom-tool.exe",
})
```
## Fully custom process
If your HSM provider has a more complex setup, you might have to call a custom file with custom parameters. If that's the case, use a hook function or hook module, which allows you to completely customize what to do with each file that `@electron/windows-sign` wants to sign. More documentation about this option can be found in the ["Signing with a custom hook function" section above](#with-a-custom-hook-function).
# License
BSD 2-Clause "Simplified". Please see LICENSE for details.
[electron]: https://github.com/electron/electron
[npm_img]: https://img.shields.io/npm/v/@electron/windows-sign.svg
[npm_url]: https://npmjs.org/package/@electron/windows-sign
[pe]: https://en.wikipedia.org/wiki/Portable_Executable
@@ -0,0 +1,43 @@
NAME
electron-windows-sign -- code signing for Electron apps on Windows.
SYNOPSIS
electron-windows-sign app [options ...]
DESCRIPTION
app
Path to the application to sign. It must be a directory.
certificate-file
Path to the certificate file (.pfx) to use for signing.
certificate-password
Password to use for the certificate.
sign-tool-path
Path to the signtool.exe binary. If not specified, the tool will attempt
use a built-in version.
timestamp-server
URL of the timestamp server to use. If not specified, the tool will
attempt to use a built-in server (http://timestamp.digicert.com)
description
Description to use for the signed files. Passed as /d to signtool.exe.
website
URL of the website to use for the signed files. Passed as /du to
signtool.exe.
sign-with-params
Additional parameters to pass to signtool.exe. This can be used to
specify additional certificates to use for cross-signing.
automatically-select-certificate
Automatically select the best certificate to use for signing. On by default.
help
Print this usage information.
debug
Print additional debug information.
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const args = require('minimist')(process.argv.slice(2), {
string: [
'certificate-file',
'certificate-password',
'sign-tool-path',
'timestamp-server',
'description',
'website',
'sign-with-params'
],
boolean: [
'help',
'debug'
],
default: {
'automatically-select-certificate': true
}
});
const usage = fs.readFileSync(path.join(__dirname, 'electron-windows-sign-usage.txt')).toString();
const sign = require('../').sign;
args.app = args._.shift();
if (!args.app || args.help) {
console.log(usage);
process.exit(0);
}
// Remove excess arguments
delete args._;
delete args.help;
sign(args, function done(err) {
if (err) {
console.error('Sign failed:');
if (err.message) console.error(err.message);
else if (err.stack) console.error(err.stack);
else console.log(err);
process.exit(1);
}
console.log('Application signed:', args.app);
process.exit(0);
});
+16
View File
@@ -0,0 +1,16 @@
import { SignOptions } from './types';
/**
* Recursively goes through an entire directory and returns an array
* of full paths for files ot sign.
*
* - Portable executable files (.exe, .dll, .sys, .efi, .scr, .node)
* - Microsoft installers (.msi)
* - APPX/MSIX packages (.appx, .appxbundle, .msix, .msixbundle)
* - Catalog files (.cat)
* - Cabinet files (.cab)
* - Silverlight applications (.xap)
* - Scripts (.vbs, .wsf, .ps1)
* If configured:
* - JavaScript files (.js)
*/
export declare function getFilesToSign(options: SignOptions, dir?: string): Array<string>;
+66
View File
@@ -0,0 +1,66 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFilesToSign = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const IS_PE_REGEX = /\.(exe|dll|sys|efi|scr|node)$/i;
const IS_MSI_REGEX = /\.msi$/i;
const IS_PACKAGE_REGEX = /\.(appx|appxbundle|msix|msixbundle)$/i;
const IS_CATCAB_REGEX = /\.(cat|cab)$/i;
const IS_SILVERLIGHT_REGEX = /\.xap$/i;
const IS_SCRIPT_REGEX = /\.(vbs|wsf|ps1)$/i;
const IS_JS_REGEX = /\.js$/i;
/**
* Recursively goes through an entire directory and returns an array
* of full paths for files ot sign.
*
* - Portable executable files (.exe, .dll, .sys, .efi, .scr, .node)
* - Microsoft installers (.msi)
* - APPX/MSIX packages (.appx, .appxbundle, .msix, .msixbundle)
* - Catalog files (.cat)
* - Cabinet files (.cab)
* - Silverlight applications (.xap)
* - Scripts (.vbs, .wsf, .ps1)
* If configured:
* - JavaScript files (.js)
*/
function getFilesToSign(options, dir) {
if (isSignOptionsForFiles(options)) {
return options.files;
}
dir = dir || options.appDirectory;
// Array of file paths to sign
const result = [];
// Iterate over the app directory, looking for files to sign
const files = fs_extra_1.default.readdirSync(dir);
const regexes = [
IS_PE_REGEX,
IS_MSI_REGEX,
IS_PACKAGE_REGEX,
IS_CATCAB_REGEX,
IS_SILVERLIGHT_REGEX,
IS_SCRIPT_REGEX
];
if (options.signJavaScript) {
regexes.push(IS_JS_REGEX);
}
for (const file of files) {
const fullPath = path_1.default.resolve(dir, file);
if (fs_extra_1.default.statSync(fullPath).isDirectory()) {
// If it's a directory, recurse
result.push(...getFilesToSign(options, fullPath));
}
else if (regexes.some((regex) => regex.test(file))) {
// If it's a match, add it to the list
result.push(fullPath);
}
}
return result;
}
exports.getFilesToSign = getFilesToSign;
function isSignOptionsForFiles(input) {
return !!input.files;
}
+4
View File
@@ -0,0 +1,4 @@
import { sign } from './sign';
import { createSeaSignTool, SeaOptions, InternalSeaOptions } from './sea';
import { HookFunction, OptionalHookOptions, OptionalSignToolOptions, SignOptions, SignToolOptions, SignOptionsForDirectory, SignOptionsForFiles } from './types';
export { sign, SignOptions, SignToolOptions, HookFunction, OptionalSignToolOptions, OptionalHookOptions, createSeaSignTool, SeaOptions, InternalSeaOptions, SignOptionsForDirectory, SignOptionsForFiles };
+7
View File
@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSeaSignTool = exports.sign = void 0;
const sign_1 = require("./sign");
Object.defineProperty(exports, "sign", { enumerable: true, get: function () { return sign_1.sign; } });
const sea_1 = require("./sea");
Object.defineProperty(exports, "createSeaSignTool", { enumerable: true, get: function () { return sea_1.createSeaSignTool; } });
+61
View File
@@ -0,0 +1,61 @@
import { SignToolOptions } from './types';
/**
* Options for signing with a Node.js single executable application.
*
* @category Single executable applications
*/
export interface SeaOptions {
/**
* Full path to the Node.js single executable application. Needs to end with `.exe`.
*/
path: string;
/**
* A binary to use. Will use the current executable (process.execPath) by default.
*
* @defaultValue The Node.js {@link https://nodejs.org/api/process.html#processexecpath | `process.execPath`}
*/
bin?: string;
/**
* Options to pass to SignTool.
*/
windowsSign: SignToolOptions;
}
/**
* This interface represents {@link SeaOptions} with all optional properties
* inferred by `@electron/windows-sign` if not passed in by the user.
*
* @category Single executable applications
*/
export interface InternalSeaOptions extends Required<SeaOptions> {
/**
* Directory of the Node.js single executable application.
*/
dir: string;
/**
* File name of the Node.js single executable application.
*/
filename: string;
}
/**
* cross-dir uses new Error() stacks
* to figure out our directory in a way
* that's somewhat cross-compatible.
*
* We can't just use __dirname because it's
* undefined in ESM - and we can't use import.meta.url
* because TypeScript won't allow usage unless you're
* _only_ compiling for ESM.
*/
export declare const DIRNAME: string;
/**
* Uses Node's "Single Executable App" functionality
* to create a Node-driven signtool.exe that calls this
* module.
*
* This is useful with other tooling that _always_ calls
* a signtool.exe to sign. Some of those tools cannot be
* easily configured, but we _can_ override their signtool.exe.
*
* @category Single executable applications
*/
export declare function createSeaSignTool(options?: Partial<SeaOptions>): Promise<InternalSeaOptions>;
+220
View File
@@ -0,0 +1,220 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSeaSignTool = exports.DIRNAME = void 0;
const cross_dirname_1 = require("cross-dirname");
const path_1 = __importDefault(require("path"));
const os_1 = __importDefault(require("os"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const postject_1 = __importDefault(require("postject"));
const spawn_1 = require("./spawn");
const log_1 = require("./utils/log");
/**
* cross-dir uses new Error() stacks
* to figure out our directory in a way
* that's somewhat cross-compatible.
*
* We can't just use __dirname because it's
* undefined in ESM - and we can't use import.meta.url
* because TypeScript won't allow usage unless you're
* _only_ compiling for ESM.
*/
exports.DIRNAME = (0, cross_dirname_1.getDirname)();
const FILENAMES = {
SEA_CONFIG: 'sea-config.json',
SEA_MAIN: 'sea.js',
SEA_BLOB: 'sea.blob',
SEA_RECEIVER: 'receiver.mjs'
};
const SEA_MAIN_SCRIPT = `
const bin = "%PATH_TO_BIN%";
const script = "%PATH_TO_SCRIPT%";
const options = %WINDOWS_SIGN_OPTIONS%
const { spawnSync } = require('child_process');
function main() {
console.log("@electron/windows-sign sea");
console.log({ bin, script });
try {
const spawn = spawnSync(
bin,
[ script, JSON.stringify(options), JSON.stringify(process.argv.slice(1)) ],
{ stdio: ['inherit', 'inherit', 'pipe'] }
);
if (spawn.status !== 0) {
throw new Error(\`Spawn failed with code: \${spawn.status}. Stderr: \${spawn.stderr}\`);
}
} catch (error) {
// Do not rethrow the error or write it to stdout/stderr. Then the process won't terminate.
// See: https://github.com/electron/windows-sign/pull/48
process.exit(1);
}
}
main();
`;
const SEA_RECEIVER_SCRIPT = `
import { sign } from '@electron/windows-sign';
import fs from 'fs-extra';
import path from 'path';
const logPath = path.join('electron-windows-sign.log');
const options = JSON.parse(process.argv[2]);
const signArgv = JSON.parse(process.argv[3]);
const files = signArgv.slice(-1);
try {
fs.appendFileSync(logPath, \`\\nCalled with: \${JSON.stringify(process.argv, null, 2)}\`);
sign({ ...options, files })
.then((result) => {
fs.appendFileSync(logPath, \`\\nSuccessfully signed with result: \${result}\`);
})
.catch((error) => {
fs.appendFileSync(logPath, \`\\nError from sign: \${error}\`);
throw new Error(error);
});
} catch (error) {
fs.appendFileSync(logPath, \`\\Error invoking sign: \${error}\`);
throw new Error(error);
}
`;
/**
* Uses Node's "Single Executable App" functionality
* to create a Node-driven signtool.exe that calls this
* module.
*
* This is useful with other tooling that _always_ calls
* a signtool.exe to sign. Some of those tools cannot be
* easily configured, but we _can_ override their signtool.exe.
*
* @category Single executable applications
*/
async function createSeaSignTool(options = {}) {
checkCompatibility();
const requiredOptions = await getOptions(options);
await createFiles(requiredOptions);
await createBlob(requiredOptions);
await createBinary(requiredOptions);
await createSeaReceiver(requiredOptions);
await cleanup(requiredOptions);
return requiredOptions;
}
exports.createSeaSignTool = createSeaSignTool;
async function createSeaReceiver(options) {
const receiverPath = path_1.default.join(options.dir, FILENAMES.SEA_RECEIVER);
await fs_extra_1.default.ensureFile(receiverPath);
await fs_extra_1.default.writeFile(receiverPath, SEA_RECEIVER_SCRIPT);
}
async function createFiles(options) {
const { dir, bin } = options;
const receiverPath = path_1.default.join(options.dir, FILENAMES.SEA_RECEIVER);
// sea-config.json
await fs_extra_1.default.outputJSON(path_1.default.join(dir, FILENAMES.SEA_CONFIG), {
main: FILENAMES.SEA_MAIN,
output: FILENAMES.SEA_BLOB,
disableExperimentalSEAWarning: true
}, {
spaces: 2
});
// signtool.js
const binPath = bin || process.execPath;
const script = SEA_MAIN_SCRIPT
.replace('%PATH_TO_BIN%', escapeMaybe(binPath))
.replace('%PATH_TO_SCRIPT%', escapeMaybe(receiverPath))
.replace('%WINDOWS_SIGN_OPTIONS%', JSON.stringify(options.windowsSign));
await fs_extra_1.default.outputFile(path_1.default.join(dir, FILENAMES.SEA_MAIN), script);
}
async function createBlob(options) {
const args = ['--experimental-sea-config', 'sea-config.json'];
const bin = process.execPath;
const cwd = options.dir;
(0, log_1.log)(`Calling ${bin} with options:`, args);
const { stderr, stdout } = await (0, spawn_1.spawnPromise)(bin, args, {
cwd
});
(0, log_1.log)('stdout:', stdout);
(0, log_1.log)('stderr:', stderr);
}
async function createBinary(options) {
const { dir, filename } = options;
(0, log_1.log)(`Creating ${filename} in ${dir}`);
// Copy Node over
const seaPath = path_1.default.join(dir, filename);
await fs_extra_1.default.copyFile(process.execPath, seaPath);
// Remove the Node signature
const signtool = path_1.default.join(exports.DIRNAME, '../../vendor/signtool.exe');
await (0, spawn_1.spawnPromise)(signtool, [
'remove',
'/s',
seaPath
]);
// Inject the blob
const blob = await fs_extra_1.default.readFile(path_1.default.join(dir, FILENAMES.SEA_BLOB));
await postject_1.default.inject(seaPath, 'NODE_SEA_BLOB', blob, {
sentinelFuse: 'NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2'
});
}
async function cleanup(options) {
const { dir } = options;
const toRemove = [
FILENAMES.SEA_BLOB,
FILENAMES.SEA_MAIN,
FILENAMES.SEA_CONFIG
];
for (const file of toRemove) {
try {
await fs_extra_1.default.remove(path_1.default.join(dir, file));
}
catch (error) {
console.warn(`Tried and failed to remove ${file}. Continuing.`, error);
}
}
}
async function getOptions(options) {
const cloned = { ...options };
if (!cloned.path) {
cloned.path = path_1.default.join(os_1.default.homedir(), '.electron', 'windows-sign', 'sea.exe');
await fs_extra_1.default.ensureFile(cloned.path);
}
if (!cloned.bin) {
cloned.bin = process.execPath;
}
if (!cloned.windowsSign) {
throw new Error('Did not find windowsSign options, which are required');
}
return {
path: cloned.path,
dir: path_1.default.dirname(cloned.path),
filename: path_1.default.basename(cloned.path),
bin: cloned.bin,
windowsSign: cloned.windowsSign
};
}
/**
* Ensures that the current Node.js version supports SEA app generation and errors if not.
*/
function checkCompatibility() {
const version = process.versions.node;
const split = version.split('.');
const major = parseInt(split[0], 10);
if (major >= 20) {
return true;
}
throw new Error(`Your Node.js version (${process.version}) does not support Single Executable Applications. Please upgrade your version of Node.js.`);
}
/** Make sure that the input string has escaped backwards slashes
* - but never double-escaped backwards slashes.
*/
function escapeMaybe(input) {
const result = input.split(path_1.default.sep).join('\\\\');
if (result.includes('\\\\\\\\')) {
throw new Error(`Your passed input ${input} contains escaped slashes. Please do not escape them`);
}
return result;
}
+8
View File
@@ -0,0 +1,8 @@
import { InternalSignOptions } from './types';
/**
* Sign with a hook function, basically letting everyone
* write completely custom sign logic
*
* @param {InternalSignOptions} options
*/
export declare function signWithHook(options: InternalSignOptions): Promise<void>;
+45
View File
@@ -0,0 +1,45 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.signWithHook = void 0;
const path_1 = __importDefault(require("path"));
const log_1 = require("./utils/log");
let hookFunction;
function getHookFunction(options) {
if (options.hookFunction) {
return options.hookFunction;
}
if (options.hookModulePath) {
const module = require(path_1.default.resolve(options.hookModulePath));
if (module.default) {
return module.default;
}
if (typeof module === 'function') {
return module;
}
}
if (!hookFunction) {
throw new Error('No hook function found. Signing will not be possible. Please see the documentation for how to pass a hook function to @electron/windows-sign');
}
return hookFunction;
}
/**
* Sign with a hook function, basically letting everyone
* write completely custom sign logic
*
* @param {InternalSignOptions} options
*/
async function signWithHook(options) {
hookFunction = getHookFunction(options);
for (const file of options.files) {
try {
await hookFunction(file);
}
catch (error) {
(0, log_1.log)(`Error signing ${file}`, error);
}
}
}
exports.signWithHook = signWithHook;
+2
View File
@@ -0,0 +1,2 @@
import { InternalSignOptions } from './types';
export declare function signWithSignTool(options: InternalSignOptions): Promise<void>;
+118
View File
@@ -0,0 +1,118 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.signWithSignTool = void 0;
const path_1 = __importDefault(require("path"));
const log_1 = require("./utils/log");
const spawn_1 = require("./spawn");
const cross_dirname_1 = require("cross-dirname");
const DIRNAME = (0, cross_dirname_1.getDirname)();
function getSigntoolArgs(options) {
// See the following url for docs
// https://learn.microsoft.com/en-us/dotnet/framework/tools/signtool-exe
const { certificateFile, certificatePassword, hash, timestampServer } = options;
const args = ['sign'];
// Automatically select cert
if (options.automaticallySelectCertificate) {
args.push('/a');
}
// Dual-sign
if (options.appendSignature) {
args.push('/as');
}
// Timestamp
if (hash === "sha256" /* HASHES.sha256 */) {
args.push('/tr', timestampServer);
args.push('/td', hash);
}
else {
args.push('/t', timestampServer);
}
// Certificate file
if (certificateFile) {
args.push('/f', path_1.default.resolve(certificateFile));
}
// Certificate password
if (certificatePassword) {
args.push('/p', certificatePassword);
}
// Hash
args.push('/fd', hash);
// Description
if (options.description) {
args.push('/d', options.description);
}
// Website
if (options.website) {
args.push('/du', options.website);
}
// Debug
if (options.debug) {
args.push('/debug');
}
if (options.signWithParams) {
const extraArgs = [];
if (Array.isArray(options.signWithParams)) {
extraArgs.push(...options.signWithParams);
}
else {
// Split up at spaces and doublequotes
extraArgs.push(...options.signWithParams.match(/(?:[^\s"]+|"[^"]*")+/g));
}
(0, log_1.log)('Parsed signWithParams as:', extraArgs);
args.push(...extraArgs);
}
return args;
}
async function execute(options) {
const { signToolPath, files } = options;
const args = getSigntoolArgs(options);
(0, log_1.log)('Executing signtool with args', { args, files });
const { code, stderr, stdout } = await (0, spawn_1.spawnPromise)(signToolPath, [...args, ...files], {
env: process.env,
cwd: process.cwd()
});
if (code !== 0) {
throw new Error(`Signtool exited with code ${code}. Stderr: ${stderr}. Stdout: ${stdout}`);
}
}
async function signWithSignTool(options) {
const certificatePassword = options.certificatePassword || process.env.WINDOWS_CERTIFICATE_PASSWORD;
const certificateFile = options.certificateFile || process.env.WINDOWS_CERTIFICATE_FILE;
const signWithParams = options.signWithParams || process.env.WINDOWS_SIGN_WITH_PARAMS;
const timestampServer = options.timestampServer || process.env.WINDOWS_TIMESTAMP_SERVER || 'http://timestamp.digicert.com';
const signToolPath = options.signToolPath || process.env.WINDOWS_SIGNTOOL_PATH || path_1.default.join(DIRNAME, '../../vendor/signtool.exe');
const description = options.description || process.env.WINDOWS_SIGN_DESCRIPTION;
const website = options.website || process.env.WINDOWS_SIGN_WEBSITE;
if (!certificateFile && !(signWithParams || signToolPath)) {
throw new Error('You must provide a certificateFile and a signToolPath or signing parameters');
}
if (!signToolPath && !signWithParams && !certificatePassword) {
throw new Error('You must provide a certificatePassword or signing parameters');
}
const internalOptions = {
appendSignature: false,
...options,
certificateFile,
certificatePassword,
signWithParams,
signToolPath,
description,
timestampServer,
website
};
const hashes = options.hashes == null || options.hashes.length === 0
? ["sha1" /* HASHES.sha1 */, "sha256" /* HASHES.sha256 */]
: options.hashes;
if (hashes.includes("sha1" /* HASHES.sha1 */)) {
await execute({ ...internalOptions, hash: "sha1" /* HASHES.sha1 */ });
// If we signed with SHA1, we need to append the SHA256 signature:
internalOptions.appendSignature = true;
}
if (hashes.includes("sha256" /* HASHES.sha256 */)) {
await execute({ ...internalOptions, hash: "sha256" /* HASHES.sha256 */ });
}
}
exports.signWithSignTool = signWithSignTool;
+13
View File
@@ -0,0 +1,13 @@
import { SignOptions } from './types';
/**
* This is the main function exported from this module. It'll
* look at your options, determine the best way to sign a file,
* and then return one of our internal functions to do the actual
* signing.
*
* @param options
* @returns {Promise<void>}
*
* @category Sign
*/
export declare function sign(options: SignOptions): Promise<void>;
+45
View File
@@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sign = void 0;
const files_1 = require("./files");
const sign_with_hook_1 = require("./sign-with-hook");
const sign_with_signtool_1 = require("./sign-with-signtool");
const log_1 = require("./utils/log");
const parse_env_1 = require("./utils/parse-env");
/**
* This is the main function exported from this module. It'll
* look at your options, determine the best way to sign a file,
* and then return one of our internal functions to do the actual
* signing.
*
* @param options
* @returns {Promise<void>}
*
* @category Sign
*/
async function sign(options) {
const signJavaScript = options.signJavaScript || (0, parse_env_1.booleanFromEnv)('WINDOWS_SIGN_JAVASCRIPT');
const hookModulePath = options.hookModulePath || process.env.WINDOWS_SIGN_HOOK_MODULE_PATH;
if (options.debug) {
(0, log_1.enableDebugging)();
}
(0, log_1.log)('Called with options', { options });
const files = (0, files_1.getFilesToSign)(options);
const internalOptions = {
...options,
signJavaScript,
hookModulePath,
files
};
// If a hook is provides, sign with the hook
if (internalOptions.hookFunction || internalOptions.hookModulePath) {
(0, log_1.log)('Signing with hook');
return (0, sign_with_hook_1.signWithHook)(internalOptions);
}
// If we're going with the defaults, we're signing
// with signtool. Custom signing tools are also
// handled here.
(0, log_1.log)('Signing with signtool');
return (0, sign_with_signtool_1.signWithSignTool)(internalOptions);
}
exports.sign = sign;
+16
View File
@@ -0,0 +1,16 @@
/// <reference types="node" />
import { SpawnOptions } from 'child_process';
export interface SpawnPromiseResult {
stdout: string;
stderr: string;
code: number;
}
/**
* Spawn a process as a promise
*
* @param {string} name
* @param {Array<string>} args
* @param {SpawnOptions} [options]
* @returns {Promise<SpawnPromiseResult>}
*/
export declare function spawnPromise(name: string, args: Array<string>, options?: SpawnOptions): Promise<SpawnPromiseResult>;
+34
View File
@@ -0,0 +1,34 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.spawnPromise = void 0;
const log_1 = require("./utils/log");
/**
* Spawn a process as a promise
*
* @param {string} name
* @param {Array<string>} args
* @param {SpawnOptions} [options]
* @returns {Promise<SpawnPromiseResult>}
*/
function spawnPromise(name, args, options) {
return new Promise((resolve) => {
const { spawn } = require('child_process');
const fork = spawn(name, args, options);
(0, log_1.log)(`Spawning ${name} with ${args}`);
let stdout = '';
let stderr = '';
fork.stdout.on('data', (data) => {
(0, log_1.log)(`Spawn ${name} stdout: ${data}`);
stdout += data;
});
fork.stderr.on('data', (data) => {
(0, log_1.log)(`Spawn ${name} stderr: ${data}`);
stderr += data;
});
fork.on('close', (code) => {
(0, log_1.log)(`Spawn ${name}: Child process exited with code ${code}`);
resolve({ stdout, stderr, code });
});
});
}
exports.spawnPromise = spawnPromise;
+143
View File
@@ -0,0 +1,143 @@
/**
* SHA-1 has been deprecated on Windows since 2016. We'll still dualsign.
* https://social.technet.microsoft.com/wiki/contents/articles/32288.windows-enforcement-of-sha1-certificates.aspx#Post-February_TwentySeventeen_Plan
*/
export declare const enum HASHES {
sha1 = "sha1",
sha256 = "sha256"
}
/**
* Signing can be either by specifying a directory of files to sign.
*
* @category Sign
*/
export type SignOptions = SignOptionsForDirectory | SignOptionsForFiles;
/**
* Options for signing by passing a path to a directory to be codesigned.
*
* @category Sign
*/
export interface SignOptionsForDirectory extends SignToolOptions {
/**
* Path to the application directory. We will scan this
* directory for any `.dll`, `.exe`, `.msi`, or `.node` files and
* codesign them with `signtool.exe`.
*/
appDirectory: string;
}
/**
* Options for signing by passing an array of files to be codesigned.
*
* @category Sign
*/
export interface SignOptionsForFiles extends SignToolOptions {
/**
* Array of paths to files to be codesigned with `signtool.exe`.
*/
files: Array<string>;
}
/**
* @category Utility
*/
export interface SignToolOptions extends OptionalSignToolOptions, OptionalHookOptions {
}
export interface InternalSignOptions extends SignOptionsForFiles {
}
export interface InternalSignToolOptions extends OptionalSignToolOptions, OptionalHookOptions {
signToolPath: string;
timestampServer: string;
files: Array<string>;
hash: HASHES;
appendSignature?: boolean;
}
/**
* @category Utility
*/
export interface OptionalSignToolOptions {
/**
* Path to a `.pfx` code signing certificate.
* Will use `process.env.WINDOWS_CERTIFICATE_FILE` if this option is not provided.
*/
certificateFile?: string;
/**
* Password to {@link certificateFile}. If you don't provide this,
* you need to provide the {@link signWithParams} option.
* Will use `process.env.WINDOWS_CERTIFICATE_PASSWORD` if this option is not provided.
*/
certificatePassword?: string;
/**
* Path to a timestamp server.
* Will use `process.env.WINDOWS_TIMESTAMP_SERVER` if this option is not provided.
*
* @defaultValue http://timestamp.digicert.com
*/
timestampServer?: string;
/**
* Description of the signed content. Will be passed to `signtool.exe` as `/d`.
*/
description?: string;
/**
* URL for the expanded description of the signed content. Will be passed to `signtool.exe` as `/du`.
*/
website?: string;
/**
* Path to the `signtool.exe` used to sign. Will use `vendor/signtool.exe` if not provided.
*/
signToolPath?: string;
/**
* Additional parameters to pass to `signtool.exe`.
*
* @see Microsoft's {@link https://learn.microsoft.com/en-us/dotnet/framework/tools/signtool-exe SignTool.exe documentation}
*/
signWithParams?: string | Array<string>;
/**
* Enables debug logging.
*
* @defaultValue false
*/
debug?: boolean;
/**
* Automatically selects the best signing certificate according to SignTool. Will be passed to `signtool.exe` as `/a`.
*
* @defaultValue true
*/
automaticallySelectCertificate?: boolean;
/**
* Whether or not to sign JavaScript files.
*
* @defaultValue false
*/
signJavaScript?: boolean;
/**
* Hash algorithms to use for signing.
*/
hashes?: HASHES[];
}
/**
* Custom function that is called sequentially for each file that needs to be signed.
*
* @param fileToSign Absolute path to the file to sign
*
* @category Utility
*/
export type HookFunction = (fileToSign: string) => void | Promise<void>;
/**
* @category Utility
*/
export interface OptionalHookOptions {
/**
* A hook function called for each file that needs to be signed.
* Use this for full control over your app's signing logic.
* `@electron/windows-sign` will not attempt to sign with SignTool if a custom hook is detected.
*/
hookFunction?: HookFunction;
/**
* A path to a JavaScript file, exporting a single function that will be called for each file that needs to be signed.
* Use this for full control over your app's signing logic.
* `@electron/windows-sign` will not attempt to sign with SignTool if a custom hook is detected.
*/
hookModulePath?: string;
}
export interface InternalHookOptions extends OptionalHookOptions {
files: Array<string>;
}
+2
View File
@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
+2
View File
@@ -0,0 +1,2 @@
export declare function enableDebugging(): void;
export declare const log: import("debug").Debugger;
+9
View File
@@ -0,0 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.log = exports.enableDebugging = void 0;
const debug_1 = require("debug");
function enableDebugging() {
debug_1.debug.enable('electron-windows-sign');
}
exports.enableDebugging = enableDebugging;
exports.log = (0, debug_1.debug)('electron-windows-sign');
+11
View File
@@ -0,0 +1,11 @@
/**
* Tries to parse an process.env string to a boolean.
* Will understand undefined as the default value
* Will understand "false", "False", "fAlse", or "0" as `false`
* Will understand everything else as true
*
* @export
* @param {string} name
* @return {*} {boolean}
*/
export declare function booleanFromEnv(name: string): boolean | undefined;
+24
View File
@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.booleanFromEnv = void 0;
/**
* Tries to parse an process.env string to a boolean.
* Will understand undefined as the default value
* Will understand "false", "False", "fAlse", or "0" as `false`
* Will understand everything else as true
*
* @export
* @param {string} name
* @return {*} {boolean}
*/
function booleanFromEnv(name) {
const value = process.env[name];
if (value === undefined) {
return undefined;
}
if (value.toLowerCase() === 'false' || value === '0') {
return false;
}
return !!value;
}
exports.booleanFromEnv = booleanFromEnv;
+16
View File
@@ -0,0 +1,16 @@
import { SignOptions } from './types';
/**
* Recursively goes through an entire directory and returns an array
* of full paths for files ot sign.
*
* - Portable executable files (.exe, .dll, .sys, .efi, .scr, .node)
* - Microsoft installers (.msi)
* - APPX/MSIX packages (.appx, .appxbundle, .msix, .msixbundle)
* - Catalog files (.cat)
* - Cabinet files (.cab)
* - Silverlight applications (.xap)
* - Scripts (.vbs, .wsf, .ps1)
* If configured:
* - JavaScript files (.js)
*/
export declare function getFilesToSign(options: SignOptions, dir?: string): Array<string>;
+59
View File
@@ -0,0 +1,59 @@
import path from 'path';
import fs from 'fs-extra';
const IS_PE_REGEX = /\.(exe|dll|sys|efi|scr|node)$/i;
const IS_MSI_REGEX = /\.msi$/i;
const IS_PACKAGE_REGEX = /\.(appx|appxbundle|msix|msixbundle)$/i;
const IS_CATCAB_REGEX = /\.(cat|cab)$/i;
const IS_SILVERLIGHT_REGEX = /\.xap$/i;
const IS_SCRIPT_REGEX = /\.(vbs|wsf|ps1)$/i;
const IS_JS_REGEX = /\.js$/i;
/**
* Recursively goes through an entire directory and returns an array
* of full paths for files ot sign.
*
* - Portable executable files (.exe, .dll, .sys, .efi, .scr, .node)
* - Microsoft installers (.msi)
* - APPX/MSIX packages (.appx, .appxbundle, .msix, .msixbundle)
* - Catalog files (.cat)
* - Cabinet files (.cab)
* - Silverlight applications (.xap)
* - Scripts (.vbs, .wsf, .ps1)
* If configured:
* - JavaScript files (.js)
*/
export function getFilesToSign(options, dir) {
if (isSignOptionsForFiles(options)) {
return options.files;
}
dir = dir || options.appDirectory;
// Array of file paths to sign
const result = [];
// Iterate over the app directory, looking for files to sign
const files = fs.readdirSync(dir);
const regexes = [
IS_PE_REGEX,
IS_MSI_REGEX,
IS_PACKAGE_REGEX,
IS_CATCAB_REGEX,
IS_SILVERLIGHT_REGEX,
IS_SCRIPT_REGEX
];
if (options.signJavaScript) {
regexes.push(IS_JS_REGEX);
}
for (const file of files) {
const fullPath = path.resolve(dir, file);
if (fs.statSync(fullPath).isDirectory()) {
// If it's a directory, recurse
result.push(...getFilesToSign(options, fullPath));
}
else if (regexes.some((regex) => regex.test(file))) {
// If it's a match, add it to the list
result.push(fullPath);
}
}
return result;
}
function isSignOptionsForFiles(input) {
return !!input.files;
}
+4
View File
@@ -0,0 +1,4 @@
import { sign } from './sign';
import { createSeaSignTool, SeaOptions, InternalSeaOptions } from './sea';
import { HookFunction, OptionalHookOptions, OptionalSignToolOptions, SignOptions, SignToolOptions, SignOptionsForDirectory, SignOptionsForFiles } from './types';
export { sign, SignOptions, SignToolOptions, HookFunction, OptionalSignToolOptions, OptionalHookOptions, createSeaSignTool, SeaOptions, InternalSeaOptions, SignOptionsForDirectory, SignOptionsForFiles };
+3
View File
@@ -0,0 +1,3 @@
import { sign } from './sign';
import { createSeaSignTool } from './sea';
export { sign, createSeaSignTool };
+61
View File
@@ -0,0 +1,61 @@
import { SignToolOptions } from './types';
/**
* Options for signing with a Node.js single executable application.
*
* @category Single executable applications
*/
export interface SeaOptions {
/**
* Full path to the Node.js single executable application. Needs to end with `.exe`.
*/
path: string;
/**
* A binary to use. Will use the current executable (process.execPath) by default.
*
* @defaultValue The Node.js {@link https://nodejs.org/api/process.html#processexecpath | `process.execPath`}
*/
bin?: string;
/**
* Options to pass to SignTool.
*/
windowsSign: SignToolOptions;
}
/**
* This interface represents {@link SeaOptions} with all optional properties
* inferred by `@electron/windows-sign` if not passed in by the user.
*
* @category Single executable applications
*/
export interface InternalSeaOptions extends Required<SeaOptions> {
/**
* Directory of the Node.js single executable application.
*/
dir: string;
/**
* File name of the Node.js single executable application.
*/
filename: string;
}
/**
* cross-dir uses new Error() stacks
* to figure out our directory in a way
* that's somewhat cross-compatible.
*
* We can't just use __dirname because it's
* undefined in ESM - and we can't use import.meta.url
* because TypeScript won't allow usage unless you're
* _only_ compiling for ESM.
*/
export declare const DIRNAME: string;
/**
* Uses Node's "Single Executable App" functionality
* to create a Node-driven signtool.exe that calls this
* module.
*
* This is useful with other tooling that _always_ calls
* a signtool.exe to sign. Some of those tools cannot be
* easily configured, but we _can_ override their signtool.exe.
*
* @category Single executable applications
*/
export declare function createSeaSignTool(options?: Partial<SeaOptions>): Promise<InternalSeaOptions>;
+213
View File
@@ -0,0 +1,213 @@
import { getDirname } from 'cross-dirname';
import path from 'path';
import os from 'os';
import fs from 'fs-extra';
import postject from 'postject';
import { spawnPromise } from './spawn';
import { log } from './utils/log';
/**
* cross-dir uses new Error() stacks
* to figure out our directory in a way
* that's somewhat cross-compatible.
*
* We can't just use __dirname because it's
* undefined in ESM - and we can't use import.meta.url
* because TypeScript won't allow usage unless you're
* _only_ compiling for ESM.
*/
export const DIRNAME = getDirname();
const FILENAMES = {
SEA_CONFIG: 'sea-config.json',
SEA_MAIN: 'sea.js',
SEA_BLOB: 'sea.blob',
SEA_RECEIVER: 'receiver.mjs'
};
const SEA_MAIN_SCRIPT = `
const bin = "%PATH_TO_BIN%";
const script = "%PATH_TO_SCRIPT%";
const options = %WINDOWS_SIGN_OPTIONS%
const { spawnSync } = require('child_process');
function main() {
console.log("@electron/windows-sign sea");
console.log({ bin, script });
try {
const spawn = spawnSync(
bin,
[ script, JSON.stringify(options), JSON.stringify(process.argv.slice(1)) ],
{ stdio: ['inherit', 'inherit', 'pipe'] }
);
if (spawn.status !== 0) {
throw new Error(\`Spawn failed with code: \${spawn.status}. Stderr: \${spawn.stderr}\`);
}
} catch (error) {
// Do not rethrow the error or write it to stdout/stderr. Then the process won't terminate.
// See: https://github.com/electron/windows-sign/pull/48
process.exit(1);
}
}
main();
`;
const SEA_RECEIVER_SCRIPT = `
import { sign } from '@electron/windows-sign';
import fs from 'fs-extra';
import path from 'path';
const logPath = path.join('electron-windows-sign.log');
const options = JSON.parse(process.argv[2]);
const signArgv = JSON.parse(process.argv[3]);
const files = signArgv.slice(-1);
try {
fs.appendFileSync(logPath, \`\\nCalled with: \${JSON.stringify(process.argv, null, 2)}\`);
sign({ ...options, files })
.then((result) => {
fs.appendFileSync(logPath, \`\\nSuccessfully signed with result: \${result}\`);
})
.catch((error) => {
fs.appendFileSync(logPath, \`\\nError from sign: \${error}\`);
throw new Error(error);
});
} catch (error) {
fs.appendFileSync(logPath, \`\\Error invoking sign: \${error}\`);
throw new Error(error);
}
`;
/**
* Uses Node's "Single Executable App" functionality
* to create a Node-driven signtool.exe that calls this
* module.
*
* This is useful with other tooling that _always_ calls
* a signtool.exe to sign. Some of those tools cannot be
* easily configured, but we _can_ override their signtool.exe.
*
* @category Single executable applications
*/
export async function createSeaSignTool(options = {}) {
checkCompatibility();
const requiredOptions = await getOptions(options);
await createFiles(requiredOptions);
await createBlob(requiredOptions);
await createBinary(requiredOptions);
await createSeaReceiver(requiredOptions);
await cleanup(requiredOptions);
return requiredOptions;
}
async function createSeaReceiver(options) {
const receiverPath = path.join(options.dir, FILENAMES.SEA_RECEIVER);
await fs.ensureFile(receiverPath);
await fs.writeFile(receiverPath, SEA_RECEIVER_SCRIPT);
}
async function createFiles(options) {
const { dir, bin } = options;
const receiverPath = path.join(options.dir, FILENAMES.SEA_RECEIVER);
// sea-config.json
await fs.outputJSON(path.join(dir, FILENAMES.SEA_CONFIG), {
main: FILENAMES.SEA_MAIN,
output: FILENAMES.SEA_BLOB,
disableExperimentalSEAWarning: true
}, {
spaces: 2
});
// signtool.js
const binPath = bin || process.execPath;
const script = SEA_MAIN_SCRIPT
.replace('%PATH_TO_BIN%', escapeMaybe(binPath))
.replace('%PATH_TO_SCRIPT%', escapeMaybe(receiverPath))
.replace('%WINDOWS_SIGN_OPTIONS%', JSON.stringify(options.windowsSign));
await fs.outputFile(path.join(dir, FILENAMES.SEA_MAIN), script);
}
async function createBlob(options) {
const args = ['--experimental-sea-config', 'sea-config.json'];
const bin = process.execPath;
const cwd = options.dir;
log(`Calling ${bin} with options:`, args);
const { stderr, stdout } = await spawnPromise(bin, args, {
cwd
});
log('stdout:', stdout);
log('stderr:', stderr);
}
async function createBinary(options) {
const { dir, filename } = options;
log(`Creating ${filename} in ${dir}`);
// Copy Node over
const seaPath = path.join(dir, filename);
await fs.copyFile(process.execPath, seaPath);
// Remove the Node signature
const signtool = path.join(DIRNAME, '../../vendor/signtool.exe');
await spawnPromise(signtool, [
'remove',
'/s',
seaPath
]);
// Inject the blob
const blob = await fs.readFile(path.join(dir, FILENAMES.SEA_BLOB));
await postject.inject(seaPath, 'NODE_SEA_BLOB', blob, {
sentinelFuse: 'NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2'
});
}
async function cleanup(options) {
const { dir } = options;
const toRemove = [
FILENAMES.SEA_BLOB,
FILENAMES.SEA_MAIN,
FILENAMES.SEA_CONFIG
];
for (const file of toRemove) {
try {
await fs.remove(path.join(dir, file));
}
catch (error) {
console.warn(`Tried and failed to remove ${file}. Continuing.`, error);
}
}
}
async function getOptions(options) {
const cloned = { ...options };
if (!cloned.path) {
cloned.path = path.join(os.homedir(), '.electron', 'windows-sign', 'sea.exe');
await fs.ensureFile(cloned.path);
}
if (!cloned.bin) {
cloned.bin = process.execPath;
}
if (!cloned.windowsSign) {
throw new Error('Did not find windowsSign options, which are required');
}
return {
path: cloned.path,
dir: path.dirname(cloned.path),
filename: path.basename(cloned.path),
bin: cloned.bin,
windowsSign: cloned.windowsSign
};
}
/**
* Ensures that the current Node.js version supports SEA app generation and errors if not.
*/
function checkCompatibility() {
const version = process.versions.node;
const split = version.split('.');
const major = parseInt(split[0], 10);
if (major >= 20) {
return true;
}
throw new Error(`Your Node.js version (${process.version}) does not support Single Executable Applications. Please upgrade your version of Node.js.`);
}
/** Make sure that the input string has escaped backwards slashes
* - but never double-escaped backwards slashes.
*/
function escapeMaybe(input) {
const result = input.split(path.sep).join('\\\\');
if (result.includes('\\\\\\\\')) {
throw new Error(`Your passed input ${input} contains escaped slashes. Please do not escape them`);
}
return result;
}
+8
View File
@@ -0,0 +1,8 @@
import { InternalSignOptions } from './types';
/**
* Sign with a hook function, basically letting everyone
* write completely custom sign logic
*
* @param {InternalSignOptions} options
*/
export declare function signWithHook(options: InternalSignOptions): Promise<void>;
+38
View File
@@ -0,0 +1,38 @@
import path from 'path';
import { log } from './utils/log';
let hookFunction;
function getHookFunction(options) {
if (options.hookFunction) {
return options.hookFunction;
}
if (options.hookModulePath) {
const module = require(path.resolve(options.hookModulePath));
if (module.default) {
return module.default;
}
if (typeof module === 'function') {
return module;
}
}
if (!hookFunction) {
throw new Error('No hook function found. Signing will not be possible. Please see the documentation for how to pass a hook function to @electron/windows-sign');
}
return hookFunction;
}
/**
* Sign with a hook function, basically letting everyone
* write completely custom sign logic
*
* @param {InternalSignOptions} options
*/
export async function signWithHook(options) {
hookFunction = getHookFunction(options);
for (const file of options.files) {
try {
await hookFunction(file);
}
catch (error) {
log(`Error signing ${file}`, error);
}
}
}
+2
View File
@@ -0,0 +1,2 @@
import { InternalSignOptions } from './types';
export declare function signWithSignTool(options: InternalSignOptions): Promise<void>;
+111
View File
@@ -0,0 +1,111 @@
import path from 'path';
import { log } from './utils/log';
import { spawnPromise } from './spawn';
import { getDirname } from 'cross-dirname';
const DIRNAME = getDirname();
function getSigntoolArgs(options) {
// See the following url for docs
// https://learn.microsoft.com/en-us/dotnet/framework/tools/signtool-exe
const { certificateFile, certificatePassword, hash, timestampServer } = options;
const args = ['sign'];
// Automatically select cert
if (options.automaticallySelectCertificate) {
args.push('/a');
}
// Dual-sign
if (options.appendSignature) {
args.push('/as');
}
// Timestamp
if (hash === "sha256" /* HASHES.sha256 */) {
args.push('/tr', timestampServer);
args.push('/td', hash);
}
else {
args.push('/t', timestampServer);
}
// Certificate file
if (certificateFile) {
args.push('/f', path.resolve(certificateFile));
}
// Certificate password
if (certificatePassword) {
args.push('/p', certificatePassword);
}
// Hash
args.push('/fd', hash);
// Description
if (options.description) {
args.push('/d', options.description);
}
// Website
if (options.website) {
args.push('/du', options.website);
}
// Debug
if (options.debug) {
args.push('/debug');
}
if (options.signWithParams) {
const extraArgs = [];
if (Array.isArray(options.signWithParams)) {
extraArgs.push(...options.signWithParams);
}
else {
// Split up at spaces and doublequotes
extraArgs.push(...options.signWithParams.match(/(?:[^\s"]+|"[^"]*")+/g));
}
log('Parsed signWithParams as:', extraArgs);
args.push(...extraArgs);
}
return args;
}
async function execute(options) {
const { signToolPath, files } = options;
const args = getSigntoolArgs(options);
log('Executing signtool with args', { args, files });
const { code, stderr, stdout } = await spawnPromise(signToolPath, [...args, ...files], {
env: process.env,
cwd: process.cwd()
});
if (code !== 0) {
throw new Error(`Signtool exited with code ${code}. Stderr: ${stderr}. Stdout: ${stdout}`);
}
}
export async function signWithSignTool(options) {
const certificatePassword = options.certificatePassword || process.env.WINDOWS_CERTIFICATE_PASSWORD;
const certificateFile = options.certificateFile || process.env.WINDOWS_CERTIFICATE_FILE;
const signWithParams = options.signWithParams || process.env.WINDOWS_SIGN_WITH_PARAMS;
const timestampServer = options.timestampServer || process.env.WINDOWS_TIMESTAMP_SERVER || 'http://timestamp.digicert.com';
const signToolPath = options.signToolPath || process.env.WINDOWS_SIGNTOOL_PATH || path.join(DIRNAME, '../../vendor/signtool.exe');
const description = options.description || process.env.WINDOWS_SIGN_DESCRIPTION;
const website = options.website || process.env.WINDOWS_SIGN_WEBSITE;
if (!certificateFile && !(signWithParams || signToolPath)) {
throw new Error('You must provide a certificateFile and a signToolPath or signing parameters');
}
if (!signToolPath && !signWithParams && !certificatePassword) {
throw new Error('You must provide a certificatePassword or signing parameters');
}
const internalOptions = {
appendSignature: false,
...options,
certificateFile,
certificatePassword,
signWithParams,
signToolPath,
description,
timestampServer,
website
};
const hashes = options.hashes == null || options.hashes.length === 0
? ["sha1" /* HASHES.sha1 */, "sha256" /* HASHES.sha256 */]
: options.hashes;
if (hashes.includes("sha1" /* HASHES.sha1 */)) {
await execute({ ...internalOptions, hash: "sha1" /* HASHES.sha1 */ });
// If we signed with SHA1, we need to append the SHA256 signature:
internalOptions.appendSignature = true;
}
if (hashes.includes("sha256" /* HASHES.sha256 */)) {
await execute({ ...internalOptions, hash: "sha256" /* HASHES.sha256 */ });
}
}
+13
View File
@@ -0,0 +1,13 @@
import { SignOptions } from './types';
/**
* This is the main function exported from this module. It'll
* look at your options, determine the best way to sign a file,
* and then return one of our internal functions to do the actual
* signing.
*
* @param options
* @returns {Promise<void>}
*
* @category Sign
*/
export declare function sign(options: SignOptions): Promise<void>;
+41
View File
@@ -0,0 +1,41 @@
import { getFilesToSign } from './files';
import { signWithHook } from './sign-with-hook';
import { signWithSignTool } from './sign-with-signtool';
import { enableDebugging, log } from './utils/log';
import { booleanFromEnv } from './utils/parse-env';
/**
* This is the main function exported from this module. It'll
* look at your options, determine the best way to sign a file,
* and then return one of our internal functions to do the actual
* signing.
*
* @param options
* @returns {Promise<void>}
*
* @category Sign
*/
export async function sign(options) {
const signJavaScript = options.signJavaScript || booleanFromEnv('WINDOWS_SIGN_JAVASCRIPT');
const hookModulePath = options.hookModulePath || process.env.WINDOWS_SIGN_HOOK_MODULE_PATH;
if (options.debug) {
enableDebugging();
}
log('Called with options', { options });
const files = getFilesToSign(options);
const internalOptions = {
...options,
signJavaScript,
hookModulePath,
files
};
// If a hook is provides, sign with the hook
if (internalOptions.hookFunction || internalOptions.hookModulePath) {
log('Signing with hook');
return signWithHook(internalOptions);
}
// If we're going with the defaults, we're signing
// with signtool. Custom signing tools are also
// handled here.
log('Signing with signtool');
return signWithSignTool(internalOptions);
}
+16
View File
@@ -0,0 +1,16 @@
/// <reference types="node" />
import { SpawnOptions } from 'child_process';
export interface SpawnPromiseResult {
stdout: string;
stderr: string;
code: number;
}
/**
* Spawn a process as a promise
*
* @param {string} name
* @param {Array<string>} args
* @param {SpawnOptions} [options]
* @returns {Promise<SpawnPromiseResult>}
*/
export declare function spawnPromise(name: string, args: Array<string>, options?: SpawnOptions): Promise<SpawnPromiseResult>;
+30
View File
@@ -0,0 +1,30 @@
import { log } from './utils/log';
/**
* Spawn a process as a promise
*
* @param {string} name
* @param {Array<string>} args
* @param {SpawnOptions} [options]
* @returns {Promise<SpawnPromiseResult>}
*/
export function spawnPromise(name, args, options) {
return new Promise((resolve) => {
const { spawn } = require('child_process');
const fork = spawn(name, args, options);
log(`Spawning ${name} with ${args}`);
let stdout = '';
let stderr = '';
fork.stdout.on('data', (data) => {
log(`Spawn ${name} stdout: ${data}`);
stdout += data;
});
fork.stderr.on('data', (data) => {
log(`Spawn ${name} stderr: ${data}`);
stderr += data;
});
fork.on('close', (code) => {
log(`Spawn ${name}: Child process exited with code ${code}`);
resolve({ stdout, stderr, code });
});
});
}
+143
View File
@@ -0,0 +1,143 @@
/**
* SHA-1 has been deprecated on Windows since 2016. We'll still dualsign.
* https://social.technet.microsoft.com/wiki/contents/articles/32288.windows-enforcement-of-sha1-certificates.aspx#Post-February_TwentySeventeen_Plan
*/
export declare const enum HASHES {
sha1 = "sha1",
sha256 = "sha256"
}
/**
* Signing can be either by specifying a directory of files to sign.
*
* @category Sign
*/
export type SignOptions = SignOptionsForDirectory | SignOptionsForFiles;
/**
* Options for signing by passing a path to a directory to be codesigned.
*
* @category Sign
*/
export interface SignOptionsForDirectory extends SignToolOptions {
/**
* Path to the application directory. We will scan this
* directory for any `.dll`, `.exe`, `.msi`, or `.node` files and
* codesign them with `signtool.exe`.
*/
appDirectory: string;
}
/**
* Options for signing by passing an array of files to be codesigned.
*
* @category Sign
*/
export interface SignOptionsForFiles extends SignToolOptions {
/**
* Array of paths to files to be codesigned with `signtool.exe`.
*/
files: Array<string>;
}
/**
* @category Utility
*/
export interface SignToolOptions extends OptionalSignToolOptions, OptionalHookOptions {
}
export interface InternalSignOptions extends SignOptionsForFiles {
}
export interface InternalSignToolOptions extends OptionalSignToolOptions, OptionalHookOptions {
signToolPath: string;
timestampServer: string;
files: Array<string>;
hash: HASHES;
appendSignature?: boolean;
}
/**
* @category Utility
*/
export interface OptionalSignToolOptions {
/**
* Path to a `.pfx` code signing certificate.
* Will use `process.env.WINDOWS_CERTIFICATE_FILE` if this option is not provided.
*/
certificateFile?: string;
/**
* Password to {@link certificateFile}. If you don't provide this,
* you need to provide the {@link signWithParams} option.
* Will use `process.env.WINDOWS_CERTIFICATE_PASSWORD` if this option is not provided.
*/
certificatePassword?: string;
/**
* Path to a timestamp server.
* Will use `process.env.WINDOWS_TIMESTAMP_SERVER` if this option is not provided.
*
* @defaultValue http://timestamp.digicert.com
*/
timestampServer?: string;
/**
* Description of the signed content. Will be passed to `signtool.exe` as `/d`.
*/
description?: string;
/**
* URL for the expanded description of the signed content. Will be passed to `signtool.exe` as `/du`.
*/
website?: string;
/**
* Path to the `signtool.exe` used to sign. Will use `vendor/signtool.exe` if not provided.
*/
signToolPath?: string;
/**
* Additional parameters to pass to `signtool.exe`.
*
* @see Microsoft's {@link https://learn.microsoft.com/en-us/dotnet/framework/tools/signtool-exe SignTool.exe documentation}
*/
signWithParams?: string | Array<string>;
/**
* Enables debug logging.
*
* @defaultValue false
*/
debug?: boolean;
/**
* Automatically selects the best signing certificate according to SignTool. Will be passed to `signtool.exe` as `/a`.
*
* @defaultValue true
*/
automaticallySelectCertificate?: boolean;
/**
* Whether or not to sign JavaScript files.
*
* @defaultValue false
*/
signJavaScript?: boolean;
/**
* Hash algorithms to use for signing.
*/
hashes?: HASHES[];
}
/**
* Custom function that is called sequentially for each file that needs to be signed.
*
* @param fileToSign Absolute path to the file to sign
*
* @category Utility
*/
export type HookFunction = (fileToSign: string) => void | Promise<void>;
/**
* @category Utility
*/
export interface OptionalHookOptions {
/**
* A hook function called for each file that needs to be signed.
* Use this for full control over your app's signing logic.
* `@electron/windows-sign` will not attempt to sign with SignTool if a custom hook is detected.
*/
hookFunction?: HookFunction;
/**
* A path to a JavaScript file, exporting a single function that will be called for each file that needs to be signed.
* Use this for full control over your app's signing logic.
* `@electron/windows-sign` will not attempt to sign with SignTool if a custom hook is detected.
*/
hookModulePath?: string;
}
export interface InternalHookOptions extends OptionalHookOptions {
files: Array<string>;
}
+1
View File
@@ -0,0 +1 @@
export {};
+2
View File
@@ -0,0 +1,2 @@
export declare function enableDebugging(): void;
export declare const log: import("debug").Debugger;
+5
View File
@@ -0,0 +1,5 @@
import { debug as debugModule } from 'debug';
export function enableDebugging() {
debugModule.enable('electron-windows-sign');
}
export const log = debugModule('electron-windows-sign');
+11
View File
@@ -0,0 +1,11 @@
/**
* Tries to parse an process.env string to a boolean.
* Will understand undefined as the default value
* Will understand "false", "False", "fAlse", or "0" as `false`
* Will understand everything else as true
*
* @export
* @param {string} name
* @return {*} {boolean}
*/
export declare function booleanFromEnv(name: string): boolean | undefined;
+20
View File
@@ -0,0 +1,20 @@
/**
* Tries to parse an process.env string to a boolean.
* Will understand undefined as the default value
* Will understand "false", "False", "fAlse", or "0" as `false`
* Will understand everything else as true
*
* @export
* @param {string} name
* @return {*} {boolean}
*/
export function booleanFromEnv(name) {
const value = process.env[name];
if (value === undefined) {
return undefined;
}
if (value.toLowerCase() === 'false' || value === '0') {
return false;
}
return !!value;
}
+15
View File
@@ -0,0 +1,15 @@
(The MIT License)
Copyright (c) 2011-2024 JP Richardson
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.
+294
View File
@@ -0,0 +1,294 @@
Node.js: fs-extra
=================
`fs-extra` adds file system methods that aren't included in the native `fs` module and adds promise support to the `fs` methods. It also uses [`graceful-fs`](https://github.com/isaacs/node-graceful-fs) to prevent `EMFILE` errors. It should be a drop in replacement for `fs`.
[![npm Package](https://img.shields.io/npm/v/fs-extra.svg)](https://www.npmjs.org/package/fs-extra)
[![License](https://img.shields.io/npm/l/fs-extra.svg)](https://github.com/jprichardson/node-fs-extra/blob/master/LICENSE)
[![build status](https://img.shields.io/github/actions/workflow/status/jprichardson/node-fs-extra/ci.yml?branch=master)](https://github.com/jprichardson/node-fs-extra/actions/workflows/ci.yml?query=branch%3Amaster)
[![downloads per month](http://img.shields.io/npm/dm/fs-extra.svg)](https://www.npmjs.org/package/fs-extra)
[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)
Why?
----
I got tired of including `mkdirp`, `rimraf`, and `ncp` in most of my projects.
Installation
------------
npm install fs-extra
Usage
-----
### CommonJS
`fs-extra` is a drop in replacement for native `fs`. All methods in `fs` are attached to `fs-extra`. All `fs` methods return promises if the callback isn't passed.
You don't ever need to include the original `fs` module again:
```js
const fs = require('fs') // this is no longer necessary
```
you can now do this:
```js
const fs = require('fs-extra')
```
or if you prefer to make it clear that you're using `fs-extra` and not `fs`, you may want
to name your `fs` variable `fse` like so:
```js
const fse = require('fs-extra')
```
you can also keep both, but it's redundant:
```js
const fs = require('fs')
const fse = require('fs-extra')
```
**NOTE:** The deprecated constants `fs.F_OK`, `fs.R_OK`, `fs.W_OK`, & `fs.X_OK` are not exported on Node.js v24.0.0+; please use their `fs.constants` equivalents.
### ESM
There is also an `fs-extra/esm` import, that supports both default and named exports. However, note that `fs` methods are not included in `fs-extra/esm`; you still need to import `fs` and/or `fs/promises` seperately:
```js
import { readFileSync } from 'fs'
import { readFile } from 'fs/promises'
import { outputFile, outputFileSync } from 'fs-extra/esm'
```
Default exports are supported:
```js
import fs from 'fs'
import fse from 'fs-extra/esm'
// fse.readFileSync is not a function; must use fs.readFileSync
```
but you probably want to just use regular `fs-extra` instead of `fs-extra/esm` for default exports:
```js
import fs from 'fs-extra'
// both fs and fs-extra methods are defined
```
Sync vs Async vs Async/Await
-------------
Most methods are async by default. All async methods will return a promise if the callback isn't passed.
Sync methods on the other hand will throw if an error occurs.
Also Async/Await will throw an error if one occurs.
Example:
```js
const fs = require('fs-extra')
// Async with promises:
fs.copy('/tmp/myfile', '/tmp/mynewfile')
.then(() => console.log('success!'))
.catch(err => console.error(err))
// Async with callbacks:
fs.copy('/tmp/myfile', '/tmp/mynewfile', err => {
if (err) return console.error(err)
console.log('success!')
})
// Sync:
try {
fs.copySync('/tmp/myfile', '/tmp/mynewfile')
console.log('success!')
} catch (err) {
console.error(err)
}
// Async/Await:
async function copyFiles () {
try {
await fs.copy('/tmp/myfile', '/tmp/mynewfile')
console.log('success!')
} catch (err) {
console.error(err)
}
}
copyFiles()
```
Methods
-------
### Async
- [copy](docs/copy.md)
- [emptyDir](docs/emptyDir.md)
- [ensureFile](docs/ensureFile.md)
- [ensureDir](docs/ensureDir.md)
- [ensureLink](docs/ensureLink.md)
- [ensureSymlink](docs/ensureSymlink.md)
- [mkdirp](docs/ensureDir.md)
- [mkdirs](docs/ensureDir.md)
- [move](docs/move.md)
- [outputFile](docs/outputFile.md)
- [outputJson](docs/outputJson.md)
- [pathExists](docs/pathExists.md)
- [readJson](docs/readJson.md)
- [remove](docs/remove.md)
- [writeJson](docs/writeJson.md)
### Sync
- [copySync](docs/copy-sync.md)
- [emptyDirSync](docs/emptyDir-sync.md)
- [ensureFileSync](docs/ensureFile-sync.md)
- [ensureDirSync](docs/ensureDir-sync.md)
- [ensureLinkSync](docs/ensureLink-sync.md)
- [ensureSymlinkSync](docs/ensureSymlink-sync.md)
- [mkdirpSync](docs/ensureDir-sync.md)
- [mkdirsSync](docs/ensureDir-sync.md)
- [moveSync](docs/move-sync.md)
- [outputFileSync](docs/outputFile-sync.md)
- [outputJsonSync](docs/outputJson-sync.md)
- [pathExistsSync](docs/pathExists-sync.md)
- [readJsonSync](docs/readJson-sync.md)
- [removeSync](docs/remove-sync.md)
- [writeJsonSync](docs/writeJson-sync.md)
**NOTE:** You can still use the native Node.js methods. They are promisified and copied over to `fs-extra`. See [notes on `fs.read()`, `fs.write()`, & `fs.writev()`](docs/fs-read-write-writev.md)
### What happened to `walk()` and `walkSync()`?
They were removed from `fs-extra` in v2.0.0. If you need the functionality, `walk` and `walkSync` are available as separate packages, [`klaw`](https://github.com/jprichardson/node-klaw) and [`klaw-sync`](https://github.com/manidlou/node-klaw-sync).
Third Party
-----------
### CLI
[fse-cli](https://www.npmjs.com/package/@atao60/fse-cli) allows you to run `fs-extra` from a console or from [npm](https://www.npmjs.com) scripts.
### TypeScript
If you like TypeScript, you can use `fs-extra` with it: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/fs-extra
### File / Directory Watching
If you want to watch for changes to files or directories, then you should use [chokidar](https://github.com/paulmillr/chokidar).
### Obtain Filesystem (Devices, Partitions) Information
[fs-filesystem](https://github.com/arthurintelligence/node-fs-filesystem) allows you to read the state of the filesystem of the host on which it is run. It returns information about both the devices and the partitions (volumes) of the system.
### Misc.
- [fs-extra-debug](https://github.com/jdxcode/fs-extra-debug) - Send your fs-extra calls to [debug](https://npmjs.org/package/debug).
- [mfs](https://github.com/cadorn/mfs) - Monitor your fs-extra calls.
Hacking on fs-extra
-------------------
Wanna hack on `fs-extra`? Great! Your help is needed! [fs-extra is one of the most depended upon Node.js packages](http://nodei.co/npm/fs-extra.png?downloads=true&downloadRank=true&stars=true). This project
uses [JavaScript Standard Style](https://github.com/feross/standard) - if the name or style choices bother you,
you're gonna have to get over it :) If `standard` is good enough for `npm`, it's good enough for `fs-extra`.
[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
What's needed?
- First, take a look at existing issues. Those are probably going to be where the priority lies.
- More tests for edge cases. Specifically on different platforms. There can never be enough tests.
- Improve test coverage.
Note: If you make any big changes, **you should definitely file an issue for discussion first.**
### Running the Test Suite
fs-extra contains hundreds of tests.
- `npm run lint`: runs the linter ([standard](http://standardjs.com/))
- `npm run unit`: runs the unit tests
- `npm run unit-esm`: runs tests for `fs-extra/esm` exports
- `npm test`: runs the linter and all tests
When running unit tests, set the environment variable `CROSS_DEVICE_PATH` to the absolute path of an empty directory on another device (like a thumb drive) to enable cross-device move tests.
### Windows
If you run the tests on the Windows and receive a lot of symbolic link `EPERM` permission errors, it's
because on Windows you need elevated privilege to create symbolic links. You can add this to your Windows's
account by following the instructions here: http://superuser.com/questions/104845/permission-to-make-symbolic-links-in-windows-7
However, I didn't have much luck doing this.
Since I develop on Mac OS X, I use VMWare Fusion for Windows testing. I create a shared folder that I map to a drive on Windows.
I open the `Node.js command prompt` and run as `Administrator`. I then map the network drive running the following command:
net use z: "\\vmware-host\Shared Folders"
I can then navigate to my `fs-extra` directory and run the tests.
Naming
------
I put a lot of thought into the naming of these functions. Inspired by @coolaj86's request. So he deserves much of the credit for raising the issue. See discussion(s) here:
* https://github.com/jprichardson/node-fs-extra/issues/2
* https://github.com/flatiron/utile/issues/11
* https://github.com/ryanmcgrath/wrench-js/issues/29
* https://github.com/substack/node-mkdirp/issues/17
First, I believe that in as many cases as possible, the [Node.js naming schemes](http://nodejs.org/api/fs.html) should be chosen. However, there are problems with the Node.js own naming schemes.
For example, `fs.readFile()` and `fs.readdir()`: the **F** is capitalized in *File* and the **d** is not capitalized in *dir*. Perhaps a bit pedantic, but they should still be consistent. Also, Node.js has chosen a lot of POSIX naming schemes, which I believe is great. See: `fs.mkdir()`, `fs.rmdir()`, `fs.chown()`, etc.
We have a dilemma though. How do you consistently name methods that perform the following POSIX commands: `cp`, `cp -r`, `mkdir -p`, and `rm -rf`?
My perspective: when in doubt, err on the side of simplicity. A directory is just a hierarchical grouping of directories and files. Consider that for a moment. So when you want to copy it or remove it, in most cases you'll want to copy or remove all of its contents. When you want to create a directory, if the directory that it's suppose to be contained in does not exist, then in most cases you'll want to create that too.
So, if you want to remove a file or a directory regardless of whether it has contents, just call `fs.remove(path)`. If you want to copy a file or a directory whether it has contents, just call `fs.copy(source, destination)`. If you want to create a directory regardless of whether its parent directories exist, just call `fs.mkdirs(path)` or `fs.mkdirp(path)`.
Credit
------
`fs-extra` wouldn't be possible without using the modules from the following authors:
- [Isaac Shlueter](https://github.com/isaacs)
- [Charlie McConnel](https://github.com/avianflu)
- [James Halliday](https://github.com/substack)
- [Andrew Kelley](https://github.com/andrewrk)
License
-------
Licensed under MIT
Copyright (c) 2011-2024 [JP Richardson](https://github.com/jprichardson)
[1]: http://nodejs.org/docs/latest/api/fs.html
[jsonfile]: https://github.com/jprichardson/node-jsonfile
@@ -0,0 +1,176 @@
'use strict'
const fs = require('graceful-fs')
const path = require('path')
const mkdirsSync = require('../mkdirs').mkdirsSync
const utimesMillisSync = require('../util/utimes').utimesMillisSync
const stat = require('../util/stat')
function copySync (src, dest, opts) {
if (typeof opts === 'function') {
opts = { filter: opts }
}
opts = opts || {}
opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now
opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber
// Warn about using preserveTimestamps on 32-bit node
if (opts.preserveTimestamps && process.arch === 'ia32') {
process.emitWarning(
'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' +
'\tsee https://github.com/jprichardson/node-fs-extra/issues/269',
'Warning', 'fs-extra-WARN0002'
)
}
const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy', opts)
stat.checkParentPathsSync(src, srcStat, dest, 'copy')
if (opts.filter && !opts.filter(src, dest)) return
const destParent = path.dirname(dest)
if (!fs.existsSync(destParent)) mkdirsSync(destParent)
return getStats(destStat, src, dest, opts)
}
function getStats (destStat, src, dest, opts) {
const statSync = opts.dereference ? fs.statSync : fs.lstatSync
const srcStat = statSync(src)
if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts)
else if (srcStat.isFile() ||
srcStat.isCharacterDevice() ||
srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts)
else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts)
else if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`)
else if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`)
throw new Error(`Unknown file: ${src}`)
}
function onFile (srcStat, destStat, src, dest, opts) {
if (!destStat) return copyFile(srcStat, src, dest, opts)
return mayCopyFile(srcStat, src, dest, opts)
}
function mayCopyFile (srcStat, src, dest, opts) {
if (opts.overwrite) {
fs.unlinkSync(dest)
return copyFile(srcStat, src, dest, opts)
} else if (opts.errorOnExist) {
throw new Error(`'${dest}' already exists`)
}
}
function copyFile (srcStat, src, dest, opts) {
fs.copyFileSync(src, dest)
if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest)
return setDestMode(dest, srcStat.mode)
}
function handleTimestamps (srcMode, src, dest) {
// Make sure the file is writable before setting the timestamp
// otherwise open fails with EPERM when invoked with 'r+'
// (through utimes call)
if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode)
return setDestTimestamps(src, dest)
}
function fileIsNotWritable (srcMode) {
return (srcMode & 0o200) === 0
}
function makeFileWritable (dest, srcMode) {
return setDestMode(dest, srcMode | 0o200)
}
function setDestMode (dest, srcMode) {
return fs.chmodSync(dest, srcMode)
}
function setDestTimestamps (src, dest) {
// The initial srcStat.atime cannot be trusted
// because it is modified by the read(2) system call
// (See https://nodejs.org/api/fs.html#fs_stat_time_values)
const updatedSrcStat = fs.statSync(src)
return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime)
}
function onDir (srcStat, destStat, src, dest, opts) {
if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts)
return copyDir(src, dest, opts)
}
function mkDirAndCopy (srcMode, src, dest, opts) {
fs.mkdirSync(dest)
copyDir(src, dest, opts)
return setDestMode(dest, srcMode)
}
function copyDir (src, dest, opts) {
const dir = fs.opendirSync(src)
try {
let dirent
while ((dirent = dir.readSync()) !== null) {
copyDirItem(dirent.name, src, dest, opts)
}
} finally {
dir.closeSync()
}
}
function copyDirItem (item, src, dest, opts) {
const srcItem = path.join(src, item)
const destItem = path.join(dest, item)
if (opts.filter && !opts.filter(srcItem, destItem)) return
const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy', opts)
return getStats(destStat, srcItem, destItem, opts)
}
function onLink (destStat, src, dest, opts) {
let resolvedSrc = fs.readlinkSync(src)
if (opts.dereference) {
resolvedSrc = path.resolve(process.cwd(), resolvedSrc)
}
if (!destStat) {
return fs.symlinkSync(resolvedSrc, dest)
} else {
let resolvedDest
try {
resolvedDest = fs.readlinkSync(dest)
} catch (err) {
// dest exists and is a regular file or directory,
// Windows may throw UNKNOWN error. If dest already exists,
// fs throws error anyway, so no need to guard against it here.
if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest)
throw err
}
if (opts.dereference) {
resolvedDest = path.resolve(process.cwd(), resolvedDest)
}
// If both symlinks resolve to the same target, they are still distinct symlinks
// that can be copied/overwritten. Only check subdirectory constraints when
// the resolved paths are different.
if (resolvedSrc !== resolvedDest) {
if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {
throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)
}
// prevent copy if src is a subdir of dest since unlinking
// dest in this case would result in removing src contents
// and therefore a broken symlink would be created.
if (stat.isSrcSubdir(resolvedDest, resolvedSrc)) {
throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)
}
}
return copyLink(resolvedSrc, dest)
}
}
function copyLink (resolvedSrc, dest) {
fs.unlinkSync(dest)
return fs.symlinkSync(resolvedSrc, dest)
}
module.exports = copySync
@@ -0,0 +1,180 @@
'use strict'
const fs = require('../fs')
const path = require('path')
const { mkdirs } = require('../mkdirs')
const { pathExists } = require('../path-exists')
const { utimesMillis } = require('../util/utimes')
const stat = require('../util/stat')
const { asyncIteratorConcurrentProcess } = require('../util/async')
async function copy (src, dest, opts = {}) {
if (typeof opts === 'function') {
opts = { filter: opts }
}
opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now
opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber
// Warn about using preserveTimestamps on 32-bit node
if (opts.preserveTimestamps && process.arch === 'ia32') {
process.emitWarning(
'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' +
'\tsee https://github.com/jprichardson/node-fs-extra/issues/269',
'Warning', 'fs-extra-WARN0001'
)
}
const { srcStat, destStat } = await stat.checkPaths(src, dest, 'copy', opts)
await stat.checkParentPaths(src, srcStat, dest, 'copy')
const include = await runFilter(src, dest, opts)
if (!include) return
// check if the parent of dest exists, and create it if it doesn't exist
const destParent = path.dirname(dest)
const dirExists = await pathExists(destParent)
if (!dirExists) {
await mkdirs(destParent)
}
await getStatsAndPerformCopy(destStat, src, dest, opts)
}
async function runFilter (src, dest, opts) {
if (!opts.filter) return true
return opts.filter(src, dest)
}
async function getStatsAndPerformCopy (destStat, src, dest, opts) {
const statFn = opts.dereference ? fs.stat : fs.lstat
const srcStat = await statFn(src)
if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts)
if (
srcStat.isFile() ||
srcStat.isCharacterDevice() ||
srcStat.isBlockDevice()
) return onFile(srcStat, destStat, src, dest, opts)
if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts)
if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`)
if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`)
throw new Error(`Unknown file: ${src}`)
}
async function onFile (srcStat, destStat, src, dest, opts) {
if (!destStat) return copyFile(srcStat, src, dest, opts)
if (opts.overwrite) {
await fs.unlink(dest)
return copyFile(srcStat, src, dest, opts)
}
if (opts.errorOnExist) {
throw new Error(`'${dest}' already exists`)
}
}
async function copyFile (srcStat, src, dest, opts) {
await fs.copyFile(src, dest)
if (opts.preserveTimestamps) {
// Make sure the file is writable before setting the timestamp
// otherwise open fails with EPERM when invoked with 'r+'
// (through utimes call)
if (fileIsNotWritable(srcStat.mode)) {
await makeFileWritable(dest, srcStat.mode)
}
// Set timestamps and mode correspondingly
// Note that The initial srcStat.atime cannot be trusted
// because it is modified by the read(2) system call
// (See https://nodejs.org/api/fs.html#fs_stat_time_values)
const updatedSrcStat = await fs.stat(src)
await utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime)
}
return fs.chmod(dest, srcStat.mode)
}
function fileIsNotWritable (srcMode) {
return (srcMode & 0o200) === 0
}
function makeFileWritable (dest, srcMode) {
return fs.chmod(dest, srcMode | 0o200)
}
async function onDir (srcStat, destStat, src, dest, opts) {
// the dest directory might not exist, create it
if (!destStat) {
await fs.mkdir(dest)
}
// iterate through the files in the current directory to copy everything
await asyncIteratorConcurrentProcess(await fs.opendir(src), async (item) => {
const srcItem = path.join(src, item.name)
const destItem = path.join(dest, item.name)
const include = await runFilter(srcItem, destItem, opts)
// only copy the item if it matches the filter function
if (include) {
const { destStat } = await stat.checkPaths(srcItem, destItem, 'copy', opts)
// If the item is a copyable file, `getStatsAndPerformCopy` will copy it
// If the item is a directory, `getStatsAndPerformCopy` will call `onDir` recursively
await getStatsAndPerformCopy(destStat, srcItem, destItem, opts)
}
})
if (!destStat) {
await fs.chmod(dest, srcStat.mode)
}
}
async function onLink (destStat, src, dest, opts) {
let resolvedSrc = await fs.readlink(src)
if (opts.dereference) {
resolvedSrc = path.resolve(process.cwd(), resolvedSrc)
}
if (!destStat) {
return fs.symlink(resolvedSrc, dest)
}
let resolvedDest = null
try {
resolvedDest = await fs.readlink(dest)
} catch (e) {
// dest exists and is a regular file or directory,
// Windows may throw UNKNOWN error. If dest already exists,
// fs throws error anyway, so no need to guard against it here.
if (e.code === 'EINVAL' || e.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest)
throw e
}
if (opts.dereference) {
resolvedDest = path.resolve(process.cwd(), resolvedDest)
}
// If both symlinks resolve to the same target, they are still distinct symlinks
// that can be copied/overwritten. Only check subdirectory constraints when
// the resolved paths are different.
if (resolvedSrc !== resolvedDest) {
if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {
throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)
}
// do not copy if src is a subdir of dest since unlinking
// dest in this case would result in removing src contents
// and therefore a broken symlink would be created.
if (stat.isSrcSubdir(resolvedDest, resolvedSrc)) {
throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)
}
}
// copy the link
await fs.unlink(dest)
return fs.symlink(resolvedSrc, dest)
}
module.exports = copy
@@ -0,0 +1,7 @@
'use strict'
const u = require('universalify').fromPromise
module.exports = {
copy: u(require('./copy')),
copySync: require('./copy-sync')
}
@@ -0,0 +1,39 @@
'use strict'
const u = require('universalify').fromPromise
const fs = require('../fs')
const path = require('path')
const mkdir = require('../mkdirs')
const remove = require('../remove')
const emptyDir = u(async function emptyDir (dir) {
let items
try {
items = await fs.readdir(dir)
} catch {
return mkdir.mkdirs(dir)
}
return Promise.all(items.map(item => remove.remove(path.join(dir, item))))
})
function emptyDirSync (dir) {
let items
try {
items = fs.readdirSync(dir)
} catch {
return mkdir.mkdirsSync(dir)
}
items.forEach(item => {
item = path.join(dir, item)
remove.removeSync(item)
})
}
module.exports = {
emptyDirSync,
emptydirSync: emptyDirSync,
emptyDir,
emptydir: emptyDir
}
@@ -0,0 +1,66 @@
'use strict'
const u = require('universalify').fromPromise
const path = require('path')
const fs = require('../fs')
const mkdir = require('../mkdirs')
async function createFile (file) {
let stats
try {
stats = await fs.stat(file)
} catch { }
if (stats && stats.isFile()) return
const dir = path.dirname(file)
let dirStats = null
try {
dirStats = await fs.stat(dir)
} catch (err) {
// if the directory doesn't exist, make it
if (err.code === 'ENOENT') {
await mkdir.mkdirs(dir)
await fs.writeFile(file, '')
return
} else {
throw err
}
}
if (dirStats.isDirectory()) {
await fs.writeFile(file, '')
} else {
// parent is not a directory
// This is just to cause an internal ENOTDIR error to be thrown
await fs.readdir(dir)
}
}
function createFileSync (file) {
let stats
try {
stats = fs.statSync(file)
} catch { }
if (stats && stats.isFile()) return
const dir = path.dirname(file)
try {
if (!fs.statSync(dir).isDirectory()) {
// parent is not a directory
// This is just to cause an internal ENOTDIR error to be thrown
fs.readdirSync(dir)
}
} catch (err) {
// If the stat call above failed because the directory doesn't exist, create it
if (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir)
else throw err
}
fs.writeFileSync(file, '')
}
module.exports = {
createFile: u(createFile),
createFileSync
}
@@ -0,0 +1,23 @@
'use strict'
const { createFile, createFileSync } = require('./file')
const { createLink, createLinkSync } = require('./link')
const { createSymlink, createSymlinkSync } = require('./symlink')
module.exports = {
// file
createFile,
createFileSync,
ensureFile: createFile,
ensureFileSync: createFileSync,
// link
createLink,
createLinkSync,
ensureLink: createLink,
ensureLinkSync: createLinkSync,
// symlink
createSymlink,
createSymlinkSync,
ensureSymlink: createSymlink,
ensureSymlinkSync: createSymlinkSync
}
@@ -0,0 +1,64 @@
'use strict'
const u = require('universalify').fromPromise
const path = require('path')
const fs = require('../fs')
const mkdir = require('../mkdirs')
const { pathExists } = require('../path-exists')
const { areIdentical } = require('../util/stat')
async function createLink (srcpath, dstpath) {
let dstStat
try {
dstStat = await fs.lstat(dstpath)
} catch {
// ignore error
}
let srcStat
try {
srcStat = await fs.lstat(srcpath)
} catch (err) {
err.message = err.message.replace('lstat', 'ensureLink')
throw err
}
if (dstStat && areIdentical(srcStat, dstStat)) return
const dir = path.dirname(dstpath)
const dirExists = await pathExists(dir)
if (!dirExists) {
await mkdir.mkdirs(dir)
}
await fs.link(srcpath, dstpath)
}
function createLinkSync (srcpath, dstpath) {
let dstStat
try {
dstStat = fs.lstatSync(dstpath)
} catch {}
try {
const srcStat = fs.lstatSync(srcpath)
if (dstStat && areIdentical(srcStat, dstStat)) return
} catch (err) {
err.message = err.message.replace('lstat', 'ensureLink')
throw err
}
const dir = path.dirname(dstpath)
const dirExists = fs.existsSync(dir)
if (dirExists) return fs.linkSync(srcpath, dstpath)
mkdir.mkdirsSync(dir)
return fs.linkSync(srcpath, dstpath)
}
module.exports = {
createLink: u(createLink),
createLinkSync
}
@@ -0,0 +1,101 @@
'use strict'
const path = require('path')
const fs = require('../fs')
const { pathExists } = require('../path-exists')
const u = require('universalify').fromPromise
/**
* Function that returns two types of paths, one relative to symlink, and one
* relative to the current working directory. Checks if path is absolute or
* relative. If the path is relative, this function checks if the path is
* relative to symlink or relative to current working directory. This is an
* initiative to find a smarter `srcpath` to supply when building symlinks.
* This allows you to determine which path to use out of one of three possible
* types of source paths. The first is an absolute path. This is detected by
* `path.isAbsolute()`. When an absolute path is provided, it is checked to
* see if it exists. If it does it's used, if not an error is returned
* (callback)/ thrown (sync). The other two options for `srcpath` are a
* relative url. By default Node's `fs.symlink` works by creating a symlink
* using `dstpath` and expects the `srcpath` to be relative to the newly
* created symlink. If you provide a `srcpath` that does not exist on the file
* system it results in a broken symlink. To minimize this, the function
* checks to see if the 'relative to symlink' source file exists, and if it
* does it will use it. If it does not, it checks if there's a file that
* exists that is relative to the current working directory, if does its used.
* This preserves the expectations of the original fs.symlink spec and adds
* the ability to pass in `relative to current working direcotry` paths.
*/
async function symlinkPaths (srcpath, dstpath) {
if (path.isAbsolute(srcpath)) {
try {
await fs.lstat(srcpath)
} catch (err) {
err.message = err.message.replace('lstat', 'ensureSymlink')
throw err
}
return {
toCwd: srcpath,
toDst: srcpath
}
}
const dstdir = path.dirname(dstpath)
const relativeToDst = path.join(dstdir, srcpath)
const exists = await pathExists(relativeToDst)
if (exists) {
return {
toCwd: relativeToDst,
toDst: srcpath
}
}
try {
await fs.lstat(srcpath)
} catch (err) {
err.message = err.message.replace('lstat', 'ensureSymlink')
throw err
}
return {
toCwd: srcpath,
toDst: path.relative(dstdir, srcpath)
}
}
function symlinkPathsSync (srcpath, dstpath) {
if (path.isAbsolute(srcpath)) {
const exists = fs.existsSync(srcpath)
if (!exists) throw new Error('absolute srcpath does not exist')
return {
toCwd: srcpath,
toDst: srcpath
}
}
const dstdir = path.dirname(dstpath)
const relativeToDst = path.join(dstdir, srcpath)
const exists = fs.existsSync(relativeToDst)
if (exists) {
return {
toCwd: relativeToDst,
toDst: srcpath
}
}
const srcExists = fs.existsSync(srcpath)
if (!srcExists) throw new Error('relative srcpath does not exist')
return {
toCwd: srcpath,
toDst: path.relative(dstdir, srcpath)
}
}
module.exports = {
symlinkPaths: u(symlinkPaths),
symlinkPathsSync
}
@@ -0,0 +1,34 @@
'use strict'
const fs = require('../fs')
const u = require('universalify').fromPromise
async function symlinkType (srcpath, type) {
if (type) return type
let stats
try {
stats = await fs.lstat(srcpath)
} catch {
return 'file'
}
return (stats && stats.isDirectory()) ? 'dir' : 'file'
}
function symlinkTypeSync (srcpath, type) {
if (type) return type
let stats
try {
stats = fs.lstatSync(srcpath)
} catch {
return 'file'
}
return (stats && stats.isDirectory()) ? 'dir' : 'file'
}
module.exports = {
symlinkType: u(symlinkType),
symlinkTypeSync
}
@@ -0,0 +1,92 @@
'use strict'
const u = require('universalify').fromPromise
const path = require('path')
const fs = require('../fs')
const { mkdirs, mkdirsSync } = require('../mkdirs')
const { symlinkPaths, symlinkPathsSync } = require('./symlink-paths')
const { symlinkType, symlinkTypeSync } = require('./symlink-type')
const { pathExists } = require('../path-exists')
const { areIdentical } = require('../util/stat')
async function createSymlink (srcpath, dstpath, type) {
let stats
try {
stats = await fs.lstat(dstpath)
} catch { }
if (stats && stats.isSymbolicLink()) {
// When srcpath is relative, resolve it relative to dstpath's directory
// (standard symlink behavior) or fall back to cwd if that doesn't exist
let srcStat
if (path.isAbsolute(srcpath)) {
srcStat = await fs.stat(srcpath)
} else {
const dstdir = path.dirname(dstpath)
const relativeToDst = path.join(dstdir, srcpath)
try {
srcStat = await fs.stat(relativeToDst)
} catch {
srcStat = await fs.stat(srcpath)
}
}
const dstStat = await fs.stat(dstpath)
if (areIdentical(srcStat, dstStat)) return
}
const relative = await symlinkPaths(srcpath, dstpath)
srcpath = relative.toDst
const toType = await symlinkType(relative.toCwd, type)
const dir = path.dirname(dstpath)
if (!(await pathExists(dir))) {
await mkdirs(dir)
}
return fs.symlink(srcpath, dstpath, toType)
}
function createSymlinkSync (srcpath, dstpath, type) {
let stats
try {
stats = fs.lstatSync(dstpath)
} catch { }
if (stats && stats.isSymbolicLink()) {
// When srcpath is relative, resolve it relative to dstpath's directory
// (standard symlink behavior) or fall back to cwd if that doesn't exist
let srcStat
if (path.isAbsolute(srcpath)) {
srcStat = fs.statSync(srcpath)
} else {
const dstdir = path.dirname(dstpath)
const relativeToDst = path.join(dstdir, srcpath)
try {
srcStat = fs.statSync(relativeToDst)
} catch {
srcStat = fs.statSync(srcpath)
}
}
const dstStat = fs.statSync(dstpath)
if (areIdentical(srcStat, dstStat)) return
}
const relative = symlinkPathsSync(srcpath, dstpath)
srcpath = relative.toDst
type = symlinkTypeSync(relative.toCwd, type)
const dir = path.dirname(dstpath)
const exists = fs.existsSync(dir)
if (exists) return fs.symlinkSync(srcpath, dstpath, type)
mkdirsSync(dir)
return fs.symlinkSync(srcpath, dstpath, type)
}
module.exports = {
createSymlink: u(createSymlink),
createSymlinkSync
}
+68
View File
@@ -0,0 +1,68 @@
import _copy from './copy/index.js'
import _empty from './empty/index.js'
import _ensure from './ensure/index.js'
import _json from './json/index.js'
import _mkdirs from './mkdirs/index.js'
import _move from './move/index.js'
import _outputFile from './output-file/index.js'
import _pathExists from './path-exists/index.js'
import _remove from './remove/index.js'
// NOTE: Only exports fs-extra's functions; fs functions must be imported from "node:fs" or "node:fs/promises"
export const copy = _copy.copy
export const copySync = _copy.copySync
export const emptyDirSync = _empty.emptyDirSync
export const emptydirSync = _empty.emptydirSync
export const emptyDir = _empty.emptyDir
export const emptydir = _empty.emptydir
export const createFile = _ensure.createFile
export const createFileSync = _ensure.createFileSync
export const ensureFile = _ensure.ensureFile
export const ensureFileSync = _ensure.ensureFileSync
export const createLink = _ensure.createLink
export const createLinkSync = _ensure.createLinkSync
export const ensureLink = _ensure.ensureLink
export const ensureLinkSync = _ensure.ensureLinkSync
export const createSymlink = _ensure.createSymlink
export const createSymlinkSync = _ensure.createSymlinkSync
export const ensureSymlink = _ensure.ensureSymlink
export const ensureSymlinkSync = _ensure.ensureSymlinkSync
export const readJson = _json.readJson
export const readJSON = _json.readJSON
export const readJsonSync = _json.readJsonSync
export const readJSONSync = _json.readJSONSync
export const writeJson = _json.writeJson
export const writeJSON = _json.writeJSON
export const writeJsonSync = _json.writeJsonSync
export const writeJSONSync = _json.writeJSONSync
export const outputJson = _json.outputJson
export const outputJSON = _json.outputJSON
export const outputJsonSync = _json.outputJsonSync
export const outputJSONSync = _json.outputJSONSync
export const mkdirs = _mkdirs.mkdirs
export const mkdirsSync = _mkdirs.mkdirsSync
export const mkdirp = _mkdirs.mkdirp
export const mkdirpSync = _mkdirs.mkdirpSync
export const ensureDir = _mkdirs.ensureDir
export const ensureDirSync = _mkdirs.ensureDirSync
export const move = _move.move
export const moveSync = _move.moveSync
export const outputFile = _outputFile.outputFile
export const outputFileSync = _outputFile.outputFileSync
export const pathExists = _pathExists.pathExists
export const pathExistsSync = _pathExists.pathExistsSync
export const remove = _remove.remove
export const removeSync = _remove.removeSync
export default {
..._copy,
..._empty,
..._ensure,
..._json,
..._mkdirs,
..._move,
..._outputFile,
..._pathExists,
..._remove
}
@@ -0,0 +1,146 @@
'use strict'
// This is adapted from https://github.com/normalize/mz
// Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors
const u = require('universalify').fromCallback
const fs = require('graceful-fs')
const api = [
'access',
'appendFile',
'chmod',
'chown',
'close',
'copyFile',
'cp',
'fchmod',
'fchown',
'fdatasync',
'fstat',
'fsync',
'ftruncate',
'futimes',
'glob',
'lchmod',
'lchown',
'lutimes',
'link',
'lstat',
'mkdir',
'mkdtemp',
'open',
'opendir',
'readdir',
'readFile',
'readlink',
'realpath',
'rename',
'rm',
'rmdir',
'stat',
'statfs',
'symlink',
'truncate',
'unlink',
'utimes',
'writeFile'
].filter(key => {
// Some commands are not available on some systems. Ex:
// fs.cp was added in Node.js v16.7.0
// fs.statfs was added in Node v19.6.0, v18.15.0
// fs.glob was added in Node.js v22.0.0
// fs.lchown is not available on at least some Linux
return typeof fs[key] === 'function'
})
// Export cloned fs:
Object.assign(exports, fs)
// Universalify async methods:
api.forEach(method => {
exports[method] = u(fs[method])
})
// We differ from mz/fs in that we still ship the old, broken, fs.exists()
// since we are a drop-in replacement for the native module
exports.exists = function (filename, callback) {
if (typeof callback === 'function') {
return fs.exists(filename, callback)
}
return new Promise(resolve => {
return fs.exists(filename, resolve)
})
}
// fs.read(), fs.write(), fs.readv(), & fs.writev() need special treatment due to multiple callback args
exports.read = function (fd, buffer, offset, length, position, callback) {
if (typeof callback === 'function') {
return fs.read(fd, buffer, offset, length, position, callback)
}
return new Promise((resolve, reject) => {
fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => {
if (err) return reject(err)
resolve({ bytesRead, buffer })
})
})
}
// Function signature can be
// fs.write(fd, buffer[, offset[, length[, position]]], callback)
// OR
// fs.write(fd, string[, position[, encoding]], callback)
// We need to handle both cases, so we use ...args
exports.write = function (fd, buffer, ...args) {
if (typeof args[args.length - 1] === 'function') {
return fs.write(fd, buffer, ...args)
}
return new Promise((resolve, reject) => {
fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => {
if (err) return reject(err)
resolve({ bytesWritten, buffer })
})
})
}
// Function signature is
// s.readv(fd, buffers[, position], callback)
// We need to handle the optional arg, so we use ...args
exports.readv = function (fd, buffers, ...args) {
if (typeof args[args.length - 1] === 'function') {
return fs.readv(fd, buffers, ...args)
}
return new Promise((resolve, reject) => {
fs.readv(fd, buffers, ...args, (err, bytesRead, buffers) => {
if (err) return reject(err)
resolve({ bytesRead, buffers })
})
})
}
// Function signature is
// s.writev(fd, buffers[, position], callback)
// We need to handle the optional arg, so we use ...args
exports.writev = function (fd, buffers, ...args) {
if (typeof args[args.length - 1] === 'function') {
return fs.writev(fd, buffers, ...args)
}
return new Promise((resolve, reject) => {
fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => {
if (err) return reject(err)
resolve({ bytesWritten, buffers })
})
})
}
// fs.realpath.native sometimes not available if fs is monkey-patched
if (typeof fs.realpath.native === 'function') {
exports.realpath.native = u(fs.realpath.native)
} else {
process.emitWarning(
'fs.realpath.native is not a function. Is fs being monkey-patched?',
'Warning', 'fs-extra-WARN0003'
)
}
+16
View File
@@ -0,0 +1,16 @@
'use strict'
module.exports = {
// Export promiseified graceful-fs:
...require('./fs'),
// Export extra methods:
...require('./copy'),
...require('./empty'),
...require('./ensure'),
...require('./json'),
...require('./mkdirs'),
...require('./move'),
...require('./output-file'),
...require('./path-exists'),
...require('./remove')
}
@@ -0,0 +1,16 @@
'use strict'
const u = require('universalify').fromPromise
const jsonFile = require('./jsonfile')
jsonFile.outputJson = u(require('./output-json'))
jsonFile.outputJsonSync = require('./output-json-sync')
// aliases
jsonFile.outputJSON = jsonFile.outputJson
jsonFile.outputJSONSync = jsonFile.outputJsonSync
jsonFile.writeJSON = jsonFile.writeJson
jsonFile.writeJSONSync = jsonFile.writeJsonSync
jsonFile.readJSON = jsonFile.readJson
jsonFile.readJSONSync = jsonFile.readJsonSync
module.exports = jsonFile
@@ -0,0 +1,11 @@
'use strict'
const jsonFile = require('jsonfile')
module.exports = {
// jsonfile exports
readJson: jsonFile.readFile,
readJsonSync: jsonFile.readFileSync,
writeJson: jsonFile.writeFile,
writeJsonSync: jsonFile.writeFileSync
}
@@ -0,0 +1,12 @@
'use strict'
const { stringify } = require('jsonfile/utils')
const { outputFileSync } = require('../output-file')
function outputJsonSync (file, data, options) {
const str = stringify(data, options)
outputFileSync(file, str, options)
}
module.exports = outputJsonSync
@@ -0,0 +1,12 @@
'use strict'
const { stringify } = require('jsonfile/utils')
const { outputFile } = require('../output-file')
async function outputJson (file, data, options = {}) {
const str = stringify(data, options)
await outputFile(file, str, options)
}
module.exports = outputJson
@@ -0,0 +1,14 @@
'use strict'
const u = require('universalify').fromPromise
const { makeDir: _makeDir, makeDirSync } = require('./make-dir')
const makeDir = u(_makeDir)
module.exports = {
mkdirs: makeDir,
mkdirsSync: makeDirSync,
// alias
mkdirp: makeDir,
mkdirpSync: makeDirSync,
ensureDir: makeDir,
ensureDirSync: makeDirSync
}
@@ -0,0 +1,27 @@
'use strict'
const fs = require('../fs')
const { checkPath } = require('./utils')
const getMode = options => {
const defaults = { mode: 0o777 }
if (typeof options === 'number') return options
return ({ ...defaults, ...options }).mode
}
module.exports.makeDir = async (dir, options) => {
checkPath(dir)
return fs.mkdir(dir, {
mode: getMode(options),
recursive: true
})
}
module.exports.makeDirSync = (dir, options) => {
checkPath(dir)
return fs.mkdirSync(dir, {
mode: getMode(options),
recursive: true
})
}
@@ -0,0 +1,21 @@
// Adapted from https://github.com/sindresorhus/make-dir
// Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (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.
'use strict'
const path = require('path')
// https://github.com/nodejs/node/issues/8987
// https://github.com/libuv/libuv/pull/1088
module.exports.checkPath = function checkPath (pth) {
if (process.platform === 'win32') {
const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, ''))
if (pathHasInvalidWinCharacters) {
const error = new Error(`Path contains invalid characters: ${pth}`)
error.code = 'EINVAL'
throw error
}
}
}
@@ -0,0 +1,7 @@
'use strict'
const u = require('universalify').fromPromise
module.exports = {
move: u(require('./move')),
moveSync: require('./move-sync')
}
@@ -0,0 +1,55 @@
'use strict'
const fs = require('graceful-fs')
const path = require('path')
const copySync = require('../copy').copySync
const removeSync = require('../remove').removeSync
const mkdirpSync = require('../mkdirs').mkdirpSync
const stat = require('../util/stat')
function moveSync (src, dest, opts) {
opts = opts || {}
const overwrite = opts.overwrite || opts.clobber || false
const { srcStat, isChangingCase = false } = stat.checkPathsSync(src, dest, 'move', opts)
stat.checkParentPathsSync(src, srcStat, dest, 'move')
if (!isParentRoot(dest)) mkdirpSync(path.dirname(dest))
return doRename(src, dest, overwrite, isChangingCase)
}
function isParentRoot (dest) {
const parent = path.dirname(dest)
const parsedPath = path.parse(parent)
return parsedPath.root === parent
}
function doRename (src, dest, overwrite, isChangingCase) {
if (isChangingCase) return rename(src, dest, overwrite)
if (overwrite) {
removeSync(dest)
return rename(src, dest, overwrite)
}
if (fs.existsSync(dest)) throw new Error('dest already exists.')
return rename(src, dest, overwrite)
}
function rename (src, dest, overwrite) {
try {
fs.renameSync(src, dest)
} catch (err) {
if (err.code !== 'EXDEV') throw err
return moveAcrossDevice(src, dest, overwrite)
}
}
function moveAcrossDevice (src, dest, overwrite) {
const opts = {
overwrite,
errorOnExist: true,
preserveTimestamps: true
}
copySync(src, dest, opts)
return removeSync(src)
}
module.exports = moveSync
@@ -0,0 +1,59 @@
'use strict'
const fs = require('../fs')
const path = require('path')
const { copy } = require('../copy')
const { remove } = require('../remove')
const { mkdirp } = require('../mkdirs')
const { pathExists } = require('../path-exists')
const stat = require('../util/stat')
async function move (src, dest, opts = {}) {
const overwrite = opts.overwrite || opts.clobber || false
const { srcStat, isChangingCase = false } = await stat.checkPaths(src, dest, 'move', opts)
await stat.checkParentPaths(src, srcStat, dest, 'move')
// If the parent of dest is not root, make sure it exists before proceeding
const destParent = path.dirname(dest)
const parsedParentPath = path.parse(destParent)
if (parsedParentPath.root !== destParent) {
await mkdirp(destParent)
}
return doRename(src, dest, overwrite, isChangingCase)
}
async function doRename (src, dest, overwrite, isChangingCase) {
if (!isChangingCase) {
if (overwrite) {
await remove(dest)
} else if (await pathExists(dest)) {
throw new Error('dest already exists.')
}
}
try {
// Try w/ rename first, and try copy + remove if EXDEV
await fs.rename(src, dest)
} catch (err) {
if (err.code !== 'EXDEV') {
throw err
}
await moveAcrossDevice(src, dest, overwrite)
}
}
async function moveAcrossDevice (src, dest, overwrite) {
const opts = {
overwrite,
errorOnExist: true,
preserveTimestamps: true
}
await copy(src, dest, opts)
return remove(src)
}
module.exports = move
@@ -0,0 +1,31 @@
'use strict'
const u = require('universalify').fromPromise
const fs = require('../fs')
const path = require('path')
const mkdir = require('../mkdirs')
const pathExists = require('../path-exists').pathExists
async function outputFile (file, data, encoding = 'utf-8') {
const dir = path.dirname(file)
if (!(await pathExists(dir))) {
await mkdir.mkdirs(dir)
}
return fs.writeFile(file, data, encoding)
}
function outputFileSync (file, ...args) {
const dir = path.dirname(file)
if (!fs.existsSync(dir)) {
mkdir.mkdirsSync(dir)
}
fs.writeFileSync(file, ...args)
}
module.exports = {
outputFile: u(outputFile),
outputFileSync
}
@@ -0,0 +1,12 @@
'use strict'
const u = require('universalify').fromPromise
const fs = require('../fs')
function pathExists (path) {
return fs.access(path).then(() => true).catch(() => false)
}
module.exports = {
pathExists: u(pathExists),
pathExistsSync: fs.existsSync
}
@@ -0,0 +1,17 @@
'use strict'
const fs = require('graceful-fs')
const u = require('universalify').fromCallback
function remove (path, callback) {
fs.rm(path, { recursive: true, force: true }, callback)
}
function removeSync (path) {
fs.rmSync(path, { recursive: true, force: true })
}
module.exports = {
remove: u(remove),
removeSync
}
@@ -0,0 +1,29 @@
'use strict'
// https://github.com/jprichardson/node-fs-extra/issues/1056
// Performing parallel operations on each item of an async iterator is
// surprisingly hard; you need to have handlers in place to avoid getting an
// UnhandledPromiseRejectionWarning.
// NOTE: This function does not presently handle return values, only errors
async function asyncIteratorConcurrentProcess (iterator, fn) {
const promises = []
for await (const item of iterator) {
promises.push(
fn(item).then(
() => null,
(err) => err ?? new Error('unknown error')
)
)
}
await Promise.all(
promises.map((promise) =>
promise.then((possibleErr) => {
if (possibleErr !== null) throw possibleErr
})
)
)
}
module.exports = {
asyncIteratorConcurrentProcess
}
@@ -0,0 +1,159 @@
'use strict'
const fs = require('../fs')
const path = require('path')
const u = require('universalify').fromPromise
function getStats (src, dest, opts) {
const statFunc = opts.dereference
? (file) => fs.stat(file, { bigint: true })
: (file) => fs.lstat(file, { bigint: true })
return Promise.all([
statFunc(src),
statFunc(dest).catch(err => {
if (err.code === 'ENOENT') return null
throw err
})
]).then(([srcStat, destStat]) => ({ srcStat, destStat }))
}
function getStatsSync (src, dest, opts) {
let destStat
const statFunc = opts.dereference
? (file) => fs.statSync(file, { bigint: true })
: (file) => fs.lstatSync(file, { bigint: true })
const srcStat = statFunc(src)
try {
destStat = statFunc(dest)
} catch (err) {
if (err.code === 'ENOENT') return { srcStat, destStat: null }
throw err
}
return { srcStat, destStat }
}
async function checkPaths (src, dest, funcName, opts) {
const { srcStat, destStat } = await getStats(src, dest, opts)
if (destStat) {
if (areIdentical(srcStat, destStat)) {
const srcBaseName = path.basename(src)
const destBaseName = path.basename(dest)
if (funcName === 'move' &&
srcBaseName !== destBaseName &&
srcBaseName.toLowerCase() === destBaseName.toLowerCase()) {
return { srcStat, destStat, isChangingCase: true }
}
throw new Error('Source and destination must not be the same.')
}
if (srcStat.isDirectory() && !destStat.isDirectory()) {
throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)
}
if (!srcStat.isDirectory() && destStat.isDirectory()) {
throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)
}
}
if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
throw new Error(errMsg(src, dest, funcName))
}
return { srcStat, destStat }
}
function checkPathsSync (src, dest, funcName, opts) {
const { srcStat, destStat } = getStatsSync(src, dest, opts)
if (destStat) {
if (areIdentical(srcStat, destStat)) {
const srcBaseName = path.basename(src)
const destBaseName = path.basename(dest)
if (funcName === 'move' &&
srcBaseName !== destBaseName &&
srcBaseName.toLowerCase() === destBaseName.toLowerCase()) {
return { srcStat, destStat, isChangingCase: true }
}
throw new Error('Source and destination must not be the same.')
}
if (srcStat.isDirectory() && !destStat.isDirectory()) {
throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)
}
if (!srcStat.isDirectory() && destStat.isDirectory()) {
throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)
}
}
if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
throw new Error(errMsg(src, dest, funcName))
}
return { srcStat, destStat }
}
// recursively check if dest parent is a subdirectory of src.
// It works for all file types including symlinks since it
// checks the src and dest inodes. It starts from the deepest
// parent and stops once it reaches the src parent or the root path.
async function checkParentPaths (src, srcStat, dest, funcName) {
const srcParent = path.resolve(path.dirname(src))
const destParent = path.resolve(path.dirname(dest))
if (destParent === srcParent || destParent === path.parse(destParent).root) return
let destStat
try {
destStat = await fs.stat(destParent, { bigint: true })
} catch (err) {
if (err.code === 'ENOENT') return
throw err
}
if (areIdentical(srcStat, destStat)) {
throw new Error(errMsg(src, dest, funcName))
}
return checkParentPaths(src, srcStat, destParent, funcName)
}
function checkParentPathsSync (src, srcStat, dest, funcName) {
const srcParent = path.resolve(path.dirname(src))
const destParent = path.resolve(path.dirname(dest))
if (destParent === srcParent || destParent === path.parse(destParent).root) return
let destStat
try {
destStat = fs.statSync(destParent, { bigint: true })
} catch (err) {
if (err.code === 'ENOENT') return
throw err
}
if (areIdentical(srcStat, destStat)) {
throw new Error(errMsg(src, dest, funcName))
}
return checkParentPathsSync(src, srcStat, destParent, funcName)
}
function areIdentical (srcStat, destStat) {
// stat.dev can be 0n on windows when node version >= 22.x.x
return destStat.ino !== undefined && destStat.dev !== undefined && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev
}
// return true if dest is a subdir of src, otherwise false.
// It only checks the path strings.
function isSrcSubdir (src, dest) {
const srcArr = path.resolve(src).split(path.sep).filter(i => i)
const destArr = path.resolve(dest).split(path.sep).filter(i => i)
return srcArr.every((cur, i) => destArr[i] === cur)
}
function errMsg (src, dest, funcName) {
return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`
}
module.exports = {
// checkPaths
checkPaths: u(checkPaths),
checkPathsSync,
// checkParent
checkParentPaths: u(checkParentPaths),
checkParentPathsSync,
// Misc
isSrcSubdir,
areIdentical
}
@@ -0,0 +1,36 @@
'use strict'
const fs = require('../fs')
const u = require('universalify').fromPromise
async function utimesMillis (path, atime, mtime) {
// if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback)
const fd = await fs.open(path, 'r+')
let closeErr = null
try {
await fs.futimes(fd, atime, mtime)
} finally {
try {
await fs.close(fd)
} catch (e) {
closeErr = e
}
}
if (closeErr) {
throw closeErr
}
}
function utimesMillisSync (path, atime, mtime) {
const fd = fs.openSync(path, 'r+')
fs.futimesSync(fd, atime, mtime)
return fs.closeSync(fd)
}
module.exports = {
utimesMillis: u(utimesMillis),
utimesMillisSync
}
+71
View File
@@ -0,0 +1,71 @@
{
"name": "fs-extra",
"version": "11.3.4",
"description": "fs-extra contains methods that aren't included in the vanilla Node.js fs package. Such as recursive mkdir, copy, and remove.",
"engines": {
"node": ">=14.14"
},
"homepage": "https://github.com/jprichardson/node-fs-extra",
"repository": {
"type": "git",
"url": "git+https://github.com/jprichardson/node-fs-extra.git"
},
"keywords": [
"fs",
"file",
"file system",
"copy",
"directory",
"extra",
"mkdirp",
"mkdir",
"mkdirs",
"recursive",
"json",
"read",
"write",
"extra",
"delete",
"remove",
"touch",
"create",
"text",
"output",
"move",
"promise"
],
"author": "JP Richardson <jprichardson@gmail.com>",
"license": "MIT",
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^6.0.1",
"universalify": "^2.0.0"
},
"devDependencies": {
"klaw": "^2.1.1",
"klaw-sync": "^3.0.2",
"minimist": "^1.1.1",
"mocha": "^10.1.0",
"nyc": "^15.0.0",
"proxyquire": "^2.0.1",
"read-dir-files": "^0.1.1",
"standard": "^17.0.0"
},
"main": "./lib/index.js",
"exports": {
".": "./lib/index.js",
"./esm": "./lib/esm.mjs"
},
"files": [
"lib/",
"!lib/**/__tests__/"
],
"scripts": {
"lint": "standard",
"test-find": "find ./lib/**/__tests__ -name *.test.js | xargs mocha",
"test": "npm run lint && npm run unit && npm run unit-esm",
"unit": "nyc node test.js",
"unit-esm": "node test.mjs"
},
"sideEffects": false
}
+15
View File
@@ -0,0 +1,15 @@
(The MIT License)
Copyright (c) 2012-2015, JP Richardson <jprichardson@gmail.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.
+230
View File
@@ -0,0 +1,230 @@
Node.js - jsonfile
================
Easily read/write JSON files in Node.js. _Note: this module cannot be used in the browser._
[![npm Package](https://img.shields.io/npm/v/jsonfile.svg?style=flat-square)](https://www.npmjs.org/package/jsonfile)
[![linux build status](https://img.shields.io/github/actions/workflow/status/jprichardson/node-jsonfile/ci.yml?branch=master)](https://github.com/jprichardson/node-jsonfile/actions?query=branch%3Amaster)
[![windows Build status](https://img.shields.io/appveyor/ci/jprichardson/node-jsonfile/master.svg?label=windows%20build)](https://ci.appveyor.com/project/jprichardson/node-jsonfile/branch/master)
<a href="https://github.com/feross/standard"><img src="https://cdn.rawgit.com/feross/standard/master/sticker.svg" alt="Standard JavaScript" width="100"></a>
Why?
----
Writing `JSON.stringify()` and then `fs.writeFile()` and `JSON.parse()` with `fs.readFile()` enclosed in `try/catch` blocks became annoying.
Installation
------------
npm install --save jsonfile
API
---
* [`readFile(filename, [options], callback)`](#readfilefilename-options-callback)
* [`readFileSync(filename, [options])`](#readfilesyncfilename-options)
* [`writeFile(filename, obj, [options], callback)`](#writefilefilename-obj-options-callback)
* [`writeFileSync(filename, obj, [options])`](#writefilesyncfilename-obj-options)
----
### readFile(filename, [options], callback)
`options` (`object`, default `undefined`): Pass in any [`fs.readFile`](https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback) options or set `reviver` for a [JSON reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).
- `throws` (`boolean`, default: `true`). If `JSON.parse` throws an error, pass this error to the callback.
If `false`, returns `null` for the object.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
jsonfile.readFile(file, function (err, obj) {
if (err) console.error(err)
console.dir(obj)
})
```
You can also use this method with promises. The `readFile` method will return a promise if you do not pass a callback function.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
jsonfile.readFile(file)
.then(obj => console.dir(obj))
.catch(error => console.error(error))
```
----
### readFileSync(filename, [options])
`options` (`object`, default `undefined`): Pass in any [`fs.readFileSync`](https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options) options or set `reviver` for a [JSON reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).
- `throws` (`boolean`, default: `true`). If an error is encountered reading or parsing the file, throw the error. If `false`, returns `null` for the object.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
console.dir(jsonfile.readFileSync(file))
```
----
### writeFile(filename, obj, [options], callback)
`options`: Pass in any [`fs.writeFile`](https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback) options or set `replacer` for a [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). Can also pass in `spaces`, or override `EOL` string or set `finalEOL` flag as `false` to not save the file with `EOL` at the end.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj, function (err) {
if (err) console.error(err)
})
```
Or use with promises as follows:
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj)
.then(res => {
console.log('Write complete')
})
.catch(error => console.error(error))
```
**formatting with spaces:**
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj, { spaces: 2 }, function (err) {
if (err) console.error(err)
})
```
**overriding EOL:**
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj, { spaces: 2, EOL: '\r\n' }, function (err) {
if (err) console.error(err)
})
```
**disabling the EOL at the end of file:**
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj, { spaces: 2, finalEOL: false }, function (err) {
if (err) console.log(err)
})
```
**appending to an existing JSON file:**
You can use `fs.writeFile` option `{ flag: 'a' }` to achieve this.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/mayAlreadyExistedData.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj, { flag: 'a' }, function (err) {
if (err) console.error(err)
})
```
----
### writeFileSync(filename, obj, [options])
`options`: Pass in any [`fs.writeFileSync`](https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options) options or set `replacer` for a [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). Can also pass in `spaces`, or override `EOL` string or set `finalEOL` flag as `false` to not save the file with `EOL` at the end.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFileSync(file, obj)
```
**formatting with spaces:**
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFileSync(file, obj, { spaces: 2 })
```
**overriding EOL:**
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFileSync(file, obj, { spaces: 2, EOL: '\r\n' })
```
**disabling the EOL at the end of file:**
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFileSync(file, obj, { spaces: 2, finalEOL: false })
```
**appending to an existing JSON file:**
You can use `fs.writeFileSync` option `{ flag: 'a' }` to achieve this.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/mayAlreadyExistedData.json'
const obj = { name: 'JP' }
jsonfile.writeFileSync(file, obj, { flag: 'a' })
```
License
-------
(MIT License)
Copyright 2012-2016, JP Richardson <jprichardson@gmail.com>
+88
View File
@@ -0,0 +1,88 @@
let _fs
try {
_fs = require('graceful-fs')
} catch (_) {
_fs = require('fs')
}
const universalify = require('universalify')
const { stringify, stripBom } = require('./utils')
async function _readFile (file, options = {}) {
if (typeof options === 'string') {
options = { encoding: options }
}
const fs = options.fs || _fs
const shouldThrow = 'throws' in options ? options.throws : true
let data = await universalify.fromCallback(fs.readFile)(file, options)
data = stripBom(data)
let obj
try {
obj = JSON.parse(data, options ? options.reviver : null)
} catch (err) {
if (shouldThrow) {
err.message = `${file}: ${err.message}`
throw err
} else {
return null
}
}
return obj
}
const readFile = universalify.fromPromise(_readFile)
function readFileSync (file, options = {}) {
if (typeof options === 'string') {
options = { encoding: options }
}
const fs = options.fs || _fs
const shouldThrow = 'throws' in options ? options.throws : true
try {
let content = fs.readFileSync(file, options)
content = stripBom(content)
return JSON.parse(content, options.reviver)
} catch (err) {
if (shouldThrow) {
err.message = `${file}: ${err.message}`
throw err
} else {
return null
}
}
}
async function _writeFile (file, obj, options = {}) {
const fs = options.fs || _fs
const str = stringify(obj, options)
await universalify.fromCallback(fs.writeFile)(file, str, options)
}
const writeFile = universalify.fromPromise(_writeFile)
function writeFileSync (file, obj, options = {}) {
const fs = options.fs || _fs
const str = stringify(obj, options)
// not sure if fs.writeFileSync returns anything, but just in case
return fs.writeFileSync(file, str, options)
}
// NOTE: do not change this export format; required for ESM compat
// see https://github.com/jprichardson/node-jsonfile/pull/162 for details
module.exports = {
readFile,
readFileSync,
writeFile,
writeFileSync
}
+40
View File
@@ -0,0 +1,40 @@
{
"name": "jsonfile",
"version": "6.2.0",
"description": "Easily read/write JSON files.",
"repository": {
"type": "git",
"url": "git@github.com:jprichardson/node-jsonfile.git"
},
"keywords": [
"read",
"write",
"file",
"json",
"fs",
"fs-extra"
],
"author": "JP Richardson <jprichardson@gmail.com>",
"license": "MIT",
"dependencies": {
"universalify": "^2.0.0"
},
"optionalDependencies": {
"graceful-fs": "^4.1.6"
},
"devDependencies": {
"mocha": "^8.2.0",
"rimraf": "^2.4.0",
"standard": "^16.0.1"
},
"main": "index.js",
"files": [
"index.js",
"utils.js"
],
"scripts": {
"lint": "standard",
"test": "npm run lint && npm run unit",
"unit": "mocha"
}
}
+14
View File
@@ -0,0 +1,14 @@
function stringify (obj, { EOL = '\n', finalEOL = true, replacer = null, spaces } = {}) {
const EOF = finalEOL ? EOL : ''
const str = JSON.stringify(obj, replacer, spaces)
return str.replace(/\n/g, EOL) + EOF
}
function stripBom (content) {
// we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified
if (Buffer.isBuffer(content)) content = content.toString('utf8')
return content.replace(/^\uFEFF/, '')
}
module.exports = { stringify, stripBom }
+20
View File
@@ -0,0 +1,20 @@
(The MIT License)
Copyright (c) 2017, Ryan Zimmerman <opensrc@ryanzim.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.
@@ -0,0 +1,76 @@
# universalify
![GitHub Workflow Status (branch)](https://img.shields.io/github/actions/workflow/status/RyanZim/universalify/ci.yml?branch=master)
![Coveralls github branch](https://img.shields.io/coveralls/github/RyanZim/universalify/master.svg)
![npm](https://img.shields.io/npm/dm/universalify.svg)
![npm](https://img.shields.io/npm/l/universalify.svg)
Make a callback- or promise-based function support both promises and callbacks.
Uses the native promise implementation.
## Installation
```bash
npm install universalify
```
## API
### `universalify.fromCallback(fn)`
Takes a callback-based function to universalify, and returns the universalified function.
Function must take a callback as the last parameter that will be called with the signature `(error, result)`. `universalify` does not support calling the callback with three or more arguments, and does not ensure that the callback is only called once.
```js
function callbackFn (n, cb) {
setTimeout(() => cb(null, n), 15)
}
const fn = universalify.fromCallback(callbackFn)
// Works with Promises:
fn('Hello World!')
.then(result => console.log(result)) // -> Hello World!
.catch(error => console.error(error))
// Works with Callbacks:
fn('Hi!', (error, result) => {
if (error) return console.error(error)
console.log(result)
// -> Hi!
})
```
### `universalify.fromPromise(fn)`
Takes a promise-based function to universalify, and returns the universalified function.
Function must return a valid JS promise. `universalify` does not ensure that a valid promise is returned.
```js
function promiseFn (n) {
return new Promise(resolve => {
setTimeout(() => resolve(n), 15)
})
}
const fn = universalify.fromPromise(promiseFn)
// Works with Promises:
fn('Hello World!')
.then(result => console.log(result)) // -> Hello World!
.catch(error => console.error(error))
// Works with Callbacks:
fn('Hi!', (error, result) => {
if (error) return console.error(error)
console.log(result)
// -> Hi!
})
```
## License
MIT
+24
View File
@@ -0,0 +1,24 @@
'use strict'
exports.fromCallback = function (fn) {
return Object.defineProperty(function (...args) {
if (typeof args[args.length - 1] === 'function') fn.apply(this, args)
else {
return new Promise((resolve, reject) => {
args.push((err, res) => (err != null) ? reject(err) : resolve(res))
fn.apply(this, args)
})
}
}, 'name', { value: fn.name })
}
exports.fromPromise = function (fn) {
return Object.defineProperty(function (...args) {
const cb = args[args.length - 1]
if (typeof cb !== 'function') return fn.apply(this, args)
else {
args.pop()
fn.apply(this, args).then(r => cb(null, r), cb)
}
}, 'name', { value: fn.name })
}
@@ -0,0 +1,34 @@
{
"name": "universalify",
"version": "2.0.1",
"description": "Make a callback- or promise-based function support both promises and callbacks.",
"keywords": [
"callback",
"native",
"promise"
],
"homepage": "https://github.com/RyanZim/universalify#readme",
"bugs": "https://github.com/RyanZim/universalify/issues",
"license": "MIT",
"author": "Ryan Zimmerman <opensrc@ryanzim.com>",
"files": [
"index.js"
],
"repository": {
"type": "git",
"url": "git+https://github.com/RyanZim/universalify.git"
},
"scripts": {
"test": "standard && nyc --reporter text --reporter lcovonly tape test/*.js | colortape"
},
"devDependencies": {
"colortape": "^0.1.2",
"coveralls": "^3.0.1",
"nyc": "^15.0.0",
"standard": "^14.3.1",
"tape": "^5.0.1"
},
"engines": {
"node": ">= 10.0.0"
}
}
+70
View File
@@ -0,0 +1,70 @@
{
"name": "@electron/windows-sign",
"version": "1.2.2",
"description": "Codesign Electron Windows apps",
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"files": [
"dist",
"entitlements",
"README.md",
"LICENSE",
"bin",
"vendor"
],
"bin": {
"electron-windows-sign": "bin/electron-windows-sign.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/electron/windows-sign.git"
},
"author": {
"name": "Felix Rieseberg",
"email": "felix@felixrieseberg.com"
},
"license": "BSD-2-Clause",
"bugs": {
"url": "https://github.com/electron/windows-sign/issues"
},
"homepage": "https://github.com/electron/windows-sign",
"publishConfig": {
"provenance": true
},
"dependencies": {
"cross-dirname": "^0.1.0",
"debug": "^4.3.4",
"fs-extra": "^11.1.1",
"minimist": "^1.2.8",
"postject": "^1.0.0-alpha.6"
},
"devDependencies": {
"@types/debug": "^4.1.10",
"@types/fs-extra": "^11.0.3",
"@types/node": "^18.18.7",
"@typescript-eslint/eslint-plugin": "^5.62.0",
"@typescript-eslint/parser": "^5.62.0",
"eslint": "^8.52.0",
"eslint-config-eslint": "^9.0.0",
"eslint-config-standard": "^17.1.0",
"eslint-plugin-import": "^2.29.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^6.1.1",
"globstar": "^1.0.0",
"standard": "^17.1.0",
"tsx": "^3.14.0",
"typedoc": "~0.25.13",
"typescript": "^5.2.2"
},
"scripts": {
"build": "tsc && tsc -p tsconfig.esm.json",
"docs": "npx typedoc",
"lint": "eslint --ext .ts,.js src bin test",
"test:loader": "globstar -- node --loader tsx --test \"test/**/*.spec.ts\"",
"test": "globstar -- node --import tsx --test \"test/**/*.spec.ts\"",
"prepublishOnly": "yarn build"
},
"engines": {
"node": ">=14.14"
}
}
Binary file not shown.