Initial commit

This commit is contained in:
2025-03-07 19:22:02 +01:00
commit 4a98255d83
55743 changed files with 5280367 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
# Set the default behavior, in case people don't have core.autocrlf set.
* text=auto
# Declare files that will always have specific line endings on checkout.
*.sh text eol=lf
cli.js text eol=lf
*.ps1 text eol=CRLF
+11
View File
@@ -0,0 +1,11 @@
office-addin-dev-certs v0.0.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
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.
+81
View File
@@ -0,0 +1,81 @@
# Office-Addin-dev-certs
This package can be used to manage certificates for development server using https://localhost.
## Installation
```
npm install office-addin-dev-certs
```
Upon installation a development CA certicate and localhost key and
certificate will be generated inside `<userhome>/.office-addin-dev-certs`.
The certificate is valid for 30 days by default.
#
## Command-Line Interface
* [install](#install)
* [verify](#verify)
* [uninstall](#uninstall)
#
### install
Creates an SSL certificate for "localhost" signed by a developer CA certificate and installs the developer CA certificate so that the certificates are trusted. If the certificates were installed but are no longer valid, they will be replaced with valid certificates.
Syntax:
`office-addin-dev-certs install [options]`
Options:
`--machine`
Install the CA certificate for all users. You must be an Administrator.
`--days <days>`
Specifies the number of days until the CA certificate expires. Default: 30 days.
#
### verify
Verify the certificate.
Syntax:
`office-addin-dev-certs verify`
#
### uninstall
Uninstall the certificate.
Syntax:
`office-addin-dev-certs uninstall [options]`
Options:
`--machine`
Uninstall the CA certificate for all users. You must be an Administrator.
#
## API Usage
```js
var https = require('https')
var devCerts = require("office-addin-dev-certs");
var options = await devCerts.getHttpsServerOptions();
var server = https.createServer(options, function (req, res) {
res.end('This is servered over HTTPS')
})
server.listen(443, function () {
console.log('The server is running on https://localhost:443')
})
```
Generated Vendored Executable
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env node
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
//
// If the package.json bin config specifies a file in the lib folder, it will cause an
// error during "npm install" if the lib folder doesn't exist (because the package hasn't been built yet).
// It specifies this file instead which then calls into the file in the lib folder.
require("./lib/cli.js");
+14
View File
@@ -0,0 +1,14 @@
import officeAddins from "eslint-plugin-office-addins";
import tsParser from "@typescript-eslint/parser";
export default [
...officeAddins.configs.recommended,
{
plugins: {
"office-addins": officeAddins,
},
languageOptions: {
parser: tsParser,
},
},
];
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env node
export {};
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env node
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const commander_1 = require("commander");
const office_addin_usage_data_1 = require("office-addin-usage-data");
const commands = __importStar(require("./commands"));
const defaults = __importStar(require("./defaults"));
/* global process */
const commander = new commander_1.Command();
commander.name("office-addin-dev-certs");
commander.version(process.env.npm_package_version || "(version not available)");
commander
.command("install")
.option("--machine", "Install the CA certificate for all users. You must be an Administrator.")
.option("--days <days>", `Specifies the validity of CA certificate in days. Default: ${defaults.daysUntilCertificateExpires}`)
.option("--domains <domains>", `List of IP address and domains separated by commas. Default: ${defaults.domain.join(",")}`)
.description(`Generate an SSL certificate for "localhost" issued by a CA certificate which is installed.`)
.action(commands.install);
commander.command("verify").description(`Verify the CA certificate.`).action(commands.verify);
commander
.command("uninstall")
.option("--machine", "Uninstall the CA certificate for all users. You must be an Administrator.")
.description(`Uninstall the certificate.`)
.action(commands.uninstall);
// if the command is not known, display an error
commander.on("command:*", function () {
(0, office_addin_usage_data_1.logErrorMessage)(`The command syntax is not valid.\n`);
process.exitCode = 1;
commander.help();
});
if (process.argv.length > 2) {
commander.parse(process.argv);
}
else {
commander.help();
}
//# sourceMappingURL=cli.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";;AAEA,4DAA4D;AAC5D,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;AAElC,yCAAoC;AACpC,qEAA0D;AAC1D,qDAAuC;AACvC,qDAAuC;AAEvC,oBAAoB;AAEpB,MAAM,SAAS,GAAG,IAAI,mBAAO,EAAE,CAAC;AAEhC,SAAS,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC;AACzC,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,yBAAyB,CAAC,CAAC;AAEhF,SAAS;KACN,OAAO,CAAC,SAAS,CAAC;KAClB,MAAM,CAAC,WAAW,EAAE,yEAAyE,CAAC;KAC9F,MAAM,CACL,eAAe,EACf,8DAA8D,QAAQ,CAAC,2BAA2B,EAAE,CACrG;KACA,MAAM,CACL,qBAAqB,EACrB,gEAAgE,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAC5F;KACA,WAAW,CACV,4FAA4F,CAC7F;KACA,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AAE5B,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,WAAW,CAAC,4BAA4B,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AAE9F,SAAS;KACN,OAAO,CAAC,WAAW,CAAC;KACpB,MAAM,CAAC,WAAW,EAAE,2EAA2E,CAAC;KAChG,WAAW,CAAC,4BAA4B,CAAC;KACzC,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;AAE9B,gDAAgD;AAChD,SAAS,CAAC,EAAE,CAAC,WAAW,EAAE;IACxB,IAAA,yCAAe,EAAC,oCAAoC,CAAC,CAAC;IACtD,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACrB,SAAS,CAAC,IAAI,EAAE,CAAC;AACnB,CAAC,CAAC,CAAC;AAEH,IAAI,OAAO,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE;IAC3B,SAAS,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/B;KAAM;IACL,SAAS,CAAC,IAAI,EAAE,CAAC;CAClB"}
+4
View File
@@ -0,0 +1,4 @@
import { OptionValues } from "commander";
export declare function install(options: OptionValues): Promise<void>;
export declare function uninstall(options: OptionValues): Promise<void>;
export declare function verify(options: OptionValues): Promise<void>;
+124
View File
@@ -0,0 +1,124 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.verify = exports.uninstall = exports.install = void 0;
const office_addin_cli_1 = require("office-addin-cli");
const office_addin_usage_data_1 = require("office-addin-usage-data");
const defaults = __importStar(require("./defaults"));
const install_1 = require("./install");
const uninstall_1 = require("./uninstall");
const verify_1 = require("./verify");
const defaults_1 = require("./defaults");
const office_addin_usage_data_2 = require("office-addin-usage-data");
/* global console */
function install(options) {
return __awaiter(this, void 0, void 0, function* () {
try {
const days = parseDays(options.days);
const domains = parseDomains(options.domains);
yield (0, install_1.ensureCertificatesAreInstalled)(days, domains, options.machine);
defaults_1.usageDataObject.reportSuccess("install");
}
catch (err) {
defaults_1.usageDataObject.reportException("install", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.install = install;
function parseDays(optionValue) {
const days = (0, office_addin_cli_1.parseNumber)(optionValue, "--days should specify a number.");
if (days !== undefined) {
if (!Number.isInteger(days)) {
throw new office_addin_usage_data_2.ExpectedError("--days should be integer.");
}
if (days <= 0) {
throw new office_addin_usage_data_2.ExpectedError("--days should be greater than zero.");
}
}
return days;
}
function parseDomains(optionValue) {
switch (typeof optionValue) {
case "string": {
try {
return optionValue.split(",");
}
catch (_a) {
throw new Error("string value not in the correct format");
}
}
case "undefined": {
return undefined;
}
default: {
throw new Error("--domains value should be a string.");
}
}
}
function uninstall(options) {
return __awaiter(this, void 0, void 0, function* () {
try {
yield (0, uninstall_1.uninstallCaCertificate)(options.machine);
(0, uninstall_1.deleteCertificateFiles)(defaults.certificateDirectory);
defaults_1.usageDataObject.reportSuccess("uninstall");
}
catch (err) {
defaults_1.usageDataObject.reportException("uninstall", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.uninstall = uninstall;
function verify(options /* eslint-disable-line @typescript-eslint/no-unused-vars */) {
return __awaiter(this, void 0, void 0, function* () {
try {
if (yield (0, verify_1.verifyCertificates)()) {
console.log(`You have trusted access to https://localhost.\nCertificate: ${defaults.localhostCertificatePath}\nKey: ${defaults.localhostKeyPath}`);
}
else {
console.log(`You need to install certificates for trusted access to https://localhost.`);
}
defaults_1.usageDataObject.reportSuccess("verify");
}
catch (err) {
defaults_1.usageDataObject.reportException("verify", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.verify = verify;
//# sourceMappingURL=commands.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"commands.js","sourceRoot":"","sources":["../src/commands.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGlC,uDAA+C;AAC/C,qEAA0D;AAC1D,qDAAuC;AACvC,uCAA2D;AAC3D,2CAA6E;AAC7E,qCAA8C;AAC9C,yCAA6C;AAC7C,qEAAwD;AAExD,oBAAoB;AAEpB,SAAsB,OAAO,CAAC,OAAqB;;QACjD,IAAI;YACF,MAAM,IAAI,GAAG,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;YACrC,MAAM,OAAO,GAAG,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;YAE9C,MAAM,IAAA,wCAA8B,EAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;YACrE,0BAAe,CAAC,aAAa,CAAC,SAAS,CAAC,CAAC;SAC1C;QAAC,OAAO,GAAQ,EAAE;YACjB,0BAAe,CAAC,eAAe,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;YAChD,IAAA,yCAAe,EAAC,GAAG,CAAC,CAAC;SACtB;IACH,CAAC;CAAA;AAXD,0BAWC;AAED,SAAS,SAAS,CAAC,WAAgB;IACjC,MAAM,IAAI,GAAG,IAAA,8BAAW,EAAC,WAAW,EAAE,iCAAiC,CAAC,CAAC;IAEzE,IAAI,IAAI,KAAK,SAAS,EAAE;QACtB,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE;YAC3B,MAAM,IAAI,uCAAa,CAAC,2BAA2B,CAAC,CAAC;SACtD;QACD,IAAI,IAAI,IAAI,CAAC,EAAE;YACb,MAAM,IAAI,uCAAa,CAAC,qCAAqC,CAAC,CAAC;SAChE;KACF;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,YAAY,CAAC,WAAgB;IACpC,QAAQ,OAAO,WAAW,EAAE;QAC1B,KAAK,QAAQ,CAAC,CAAC;YACb,IAAI;gBACF,OAAO,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;aAC/B;YAAC,WAAM;gBACN,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;aAC3D;SACF;QACD,KAAK,WAAW,CAAC,CAAC;YAChB,OAAO,SAAS,CAAC;SAClB;QACD,OAAO,CAAC,CAAC;YACP,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;SACxD;KACF;AACH,CAAC;AAED,SAAsB,SAAS,CAAC,OAAqB;;QACnD,IAAI;YACF,MAAM,IAAA,kCAAsB,EAAC,OAAO,CAAC,OAAO,CAAC,CAAC;YAC9C,IAAA,kCAAsB,EAAC,QAAQ,CAAC,oBAAoB,CAAC,CAAC;YACtD,0BAAe,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;SAC5C;QAAC,OAAO,GAAQ,EAAE;YACjB,0BAAe,CAAC,eAAe,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC;YAClD,IAAA,yCAAe,EAAC,GAAG,CAAC,CAAC;SACtB;IACH,CAAC;CAAA;AATD,8BASC;AAED,SAAsB,MAAM,CAC1B,OAAqB,CAAC,2DAA2D;;QAEjF,IAAI;YACF,IAAI,MAAM,IAAA,2BAAkB,GAAE,EAAE;gBAC9B,OAAO,CAAC,GAAG,CACT,+DAA+D,QAAQ,CAAC,wBAAwB,UAAU,QAAQ,CAAC,gBAAgB,EAAE,CACtI,CAAC;aACH;iBAAM;gBACL,OAAO,CAAC,GAAG,CAAC,2EAA2E,CAAC,CAAC;aAC1F;YACD,0BAAe,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;SACzC;QAAC,OAAO,GAAQ,EAAE;YACjB,0BAAe,CAAC,eAAe,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;YAC/C,IAAA,yCAAe,EAAC,GAAG,CAAC,CAAC;SACtB;IACH,CAAC;CAAA;AAhBD,wBAgBC"}
+16
View File
@@ -0,0 +1,16 @@
import { OfficeAddinUsageData } from "office-addin-usage-data";
export declare const certificateDirectoryName = ".office-addin-dev-certs";
export declare const certificateDirectory: string;
export declare const caCertificateFileName = "ca.crt";
export declare const caCertificatePath: string;
export declare const localhostCertificateFileName = "localhost.crt";
export declare const localhostCertificatePath: string;
export declare const localhostKeyFileName = "localhost.key";
export declare const localhostKeyPath: string;
export declare const certificateName = "Developer CA for Microsoft Office Add-ins";
export declare const countryCode = "US";
export declare const daysUntilCertificateExpires = 30;
export declare const domain: string[];
export declare const locality = "Redmond";
export declare const state = "WA";
export declare const usageDataObject: OfficeAddinUsageData;
+34
View File
@@ -0,0 +1,34 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.usageDataObject = exports.state = exports.locality = exports.domain = exports.daysUntilCertificateExpires = exports.countryCode = exports.certificateName = exports.localhostKeyPath = exports.localhostKeyFileName = exports.localhostCertificatePath = exports.localhostCertificateFileName = exports.caCertificatePath = exports.caCertificateFileName = exports.certificateDirectory = exports.certificateDirectoryName = void 0;
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
const office_addin_usage_data_1 = require("office-addin-usage-data");
// Default certificate names
exports.certificateDirectoryName = ".office-addin-dev-certs";
exports.certificateDirectory = path_1.default.join(os_1.default.homedir(), exports.certificateDirectoryName);
exports.caCertificateFileName = "ca.crt";
exports.caCertificatePath = path_1.default.join(exports.certificateDirectory, exports.caCertificateFileName);
exports.localhostCertificateFileName = "localhost.crt";
exports.localhostCertificatePath = path_1.default.join(exports.certificateDirectory, exports.localhostCertificateFileName);
exports.localhostKeyFileName = "localhost.key";
exports.localhostKeyPath = path_1.default.join(exports.certificateDirectory, exports.localhostKeyFileName);
// Default certificate details
exports.certificateName = "Developer CA for Microsoft Office Add-ins";
exports.countryCode = "US";
exports.daysUntilCertificateExpires = 30;
exports.domain = ["127.0.0.1", "localhost"];
exports.locality = "Redmond";
exports.state = "WA";
// Usage data defaults
exports.usageDataObject = new office_addin_usage_data_1.OfficeAddinUsageData({
projectName: "office-addin-dev-certs",
instrumentationKey: office_addin_usage_data_1.instrumentationKeyForOfficeAddinCLITools,
raisePrompt: false,
});
//# sourceMappingURL=defaults.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"defaults.js","sourceRoot":"","sources":["../src/defaults.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;;;AAElC,4CAAoB;AACpB,gDAAwB;AACxB,qEAGiC;AAEjC,4BAA4B;AACf,QAAA,wBAAwB,GAAG,yBAAyB,CAAC;AACrD,QAAA,oBAAoB,GAAG,cAAI,CAAC,IAAI,CAAC,YAAE,CAAC,OAAO,EAAE,EAAE,gCAAwB,CAAC,CAAC;AACzE,QAAA,qBAAqB,GAAG,QAAQ,CAAC;AACjC,QAAA,iBAAiB,GAAG,cAAI,CAAC,IAAI,CAAC,4BAAoB,EAAE,6BAAqB,CAAC,CAAC;AAC3E,QAAA,4BAA4B,GAAG,eAAe,CAAC;AAC/C,QAAA,wBAAwB,GAAG,cAAI,CAAC,IAAI,CAC/C,4BAAoB,EACpB,oCAA4B,CAC7B,CAAC;AACW,QAAA,oBAAoB,GAAG,eAAe,CAAC;AACvC,QAAA,gBAAgB,GAAG,cAAI,CAAC,IAAI,CAAC,4BAAoB,EAAE,4BAAoB,CAAC,CAAC;AAEtF,8BAA8B;AACjB,QAAA,eAAe,GAAG,2CAA2C,CAAC;AAC9D,QAAA,WAAW,GAAG,IAAI,CAAC;AACnB,QAAA,2BAA2B,GAAG,EAAE,CAAC;AACjC,QAAA,MAAM,GAAG,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;AACpC,QAAA,QAAQ,GAAG,SAAS,CAAC;AACrB,QAAA,KAAK,GAAG,IAAI,CAAC;AAE1B,sBAAsB;AACT,QAAA,eAAe,GAAyB,IAAI,8CAAoB,CAAC;IAC5E,WAAW,EAAE,wBAAwB;IACrC,kBAAkB,EAAE,kEAAwC;IAC5D,WAAW,EAAE,KAAK;CACnB,CAAC,CAAC"}
+1
View File
@@ -0,0 +1 @@
export declare function generateCertificates(caCertificatePath?: string, localhostCertificatePath?: string, localhostKeyPath?: string, daysUntilCertificateExpires?: number, domains?: string[]): Promise<void>;
+106
View File
@@ -0,0 +1,106 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateCertificates = void 0;
const fs_1 = __importDefault(require("fs"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const mkcert = __importStar(require("mkcert"));
const path_1 = __importDefault(require("path"));
const defaults = __importStar(require("./defaults"));
/* global console */
/* Generate operation will check if there is already valid certificate installed.
if yes, then this operation will be no op.
else, new certificates are generated and installed if --install was provided.
*/
function generateCertificates(caCertificatePath = defaults.caCertificatePath, localhostCertificatePath = defaults.localhostCertificatePath, localhostKeyPath = defaults.localhostKeyPath, daysUntilCertificateExpires = defaults.daysUntilCertificateExpires, domains = defaults.domain) {
return __awaiter(this, void 0, void 0, function* () {
try {
fs_extra_1.default.ensureDirSync(path_1.default.dirname(caCertificatePath));
fs_extra_1.default.ensureDirSync(path_1.default.dirname(localhostCertificatePath));
fs_extra_1.default.ensureDirSync(path_1.default.dirname(localhostKeyPath));
}
catch (err) {
throw new Error(`Unable to create the directory.\n${err}`);
}
const cACertificateInfo = {
countryCode: defaults.countryCode,
locality: defaults.locality,
organization: defaults.certificateName,
state: defaults.state,
validity: daysUntilCertificateExpires,
};
let caCertificate;
try {
caCertificate = yield mkcert.createCA(cACertificateInfo);
}
catch (err) {
throw new Error(`Unable to generate the CA certificate.\n${err}`);
}
const localhostCertificateInfo = {
ca: caCertificate,
domains,
validity: daysUntilCertificateExpires,
};
let localhostCertificate;
try {
localhostCertificate = yield mkcert.createCert(localhostCertificateInfo);
}
catch (err) {
throw new Error(`Unable to generate the localhost certificate.\n${err}`);
}
try {
if (!fs_1.default.existsSync(caCertificatePath)) {
fs_1.default.writeFileSync(`${caCertificatePath}`, caCertificate.cert);
fs_1.default.writeFileSync(`${localhostCertificatePath}`, localhostCertificate.cert);
fs_1.default.writeFileSync(`${localhostKeyPath}`, localhostCertificate.key);
}
}
catch (err) {
throw new Error(`Unable to write generated certificates.\n${err}`);
}
if (caCertificatePath === defaults.caCertificatePath) {
console.log("The developer certificates have been generated in " + defaults.certificateDirectory);
}
else {
console.log("The developer certificates have been generated.");
}
});
}
exports.generateCertificates = generateCertificates;
//# sourceMappingURL=generate.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"generate.js","sourceRoot":"","sources":["../src/generate.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAElC,4CAAoB;AACpB,wDAA+B;AAC/B,+CAAiC;AACjC,gDAAwB;AACxB,qDAAuC;AAEvC,oBAAoB;AAEpB;;;EAGE;AACF,SAAsB,oBAAoB,CACxC,oBAA4B,QAAQ,CAAC,iBAAiB,EACtD,2BAAmC,QAAQ,CAAC,wBAAwB,EACpE,mBAA2B,QAAQ,CAAC,gBAAgB,EACpD,8BAAsC,QAAQ,CAAC,2BAA2B,EAC1E,UAAoB,QAAQ,CAAC,MAAM;;QAEnC,IAAI;YACF,kBAAO,CAAC,aAAa,CAAC,cAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,CAAC;YACvD,kBAAO,CAAC,aAAa,CAAC,cAAI,CAAC,OAAO,CAAC,wBAAwB,CAAC,CAAC,CAAC;YAC9D,kBAAO,CAAC,aAAa,CAAC,cAAI,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC,CAAC;SACvD;QAAC,OAAO,GAAG,EAAE;YACZ,MAAM,IAAI,KAAK,CAAC,oCAAoC,GAAG,EAAE,CAAC,CAAC;SAC5D;QAED,MAAM,iBAAiB,GAAuC;YAC5D,WAAW,EAAE,QAAQ,CAAC,WAAW;YACjC,QAAQ,EAAE,QAAQ,CAAC,QAAQ;YAC3B,YAAY,EAAE,QAAQ,CAAC,eAAe;YACtC,KAAK,EAAE,QAAQ,CAAC,KAAK;YACrB,QAAQ,EAAE,2BAA2B;SACtC,CAAC;QACF,IAAI,aAAiC,CAAC;QACtC,IAAI;YACF,aAAa,GAAG,MAAM,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAAC,CAAC;SAC1D;QAAC,OAAO,GAAG,EAAE;YACZ,MAAM,IAAI,KAAK,CAAC,2CAA2C,GAAG,EAAE,CAAC,CAAC;SACnE;QAED,MAAM,wBAAwB,GAA8B;YAC1D,EAAE,EAAE,aAAa;YACjB,OAAO;YACP,QAAQ,EAAE,2BAA2B;SACtC,CAAC;QACF,IAAI,oBAAwC,CAAC;QAC7C,IAAI;YACF,oBAAoB,GAAG,MAAM,MAAM,CAAC,UAAU,CAAC,wBAAwB,CAAC,CAAC;SAC1E;QAAC,OAAO,GAAG,EAAE;YACZ,MAAM,IAAI,KAAK,CAAC,kDAAkD,GAAG,EAAE,CAAC,CAAC;SAC1E;QAED,IAAI;YACF,IAAI,CAAC,YAAE,CAAC,UAAU,CAAC,iBAAiB,CAAC,EAAE;gBACrC,YAAE,CAAC,aAAa,CAAC,GAAG,iBAAiB,EAAE,EAAE,aAAa,CAAC,IAAI,CAAC,CAAC;gBAC7D,YAAE,CAAC,aAAa,CAAC,GAAG,wBAAwB,EAAE,EAAE,oBAAoB,CAAC,IAAI,CAAC,CAAC;gBAC3E,YAAE,CAAC,aAAa,CAAC,GAAG,gBAAgB,EAAE,EAAE,oBAAoB,CAAC,GAAG,CAAC,CAAC;aACnE;SACF;QAAC,OAAO,GAAG,EAAE;YACZ,MAAM,IAAI,KAAK,CAAC,4CAA4C,GAAG,EAAE,CAAC,CAAC;SACpE;QAED,IAAI,iBAAiB,KAAK,QAAQ,CAAC,iBAAiB,EAAE;YACpD,OAAO,CAAC,GAAG,CACT,oDAAoD,GAAG,QAAQ,CAAC,oBAAoB,CACrF,CAAC;SACH;aAAM;YACL,OAAO,CAAC,GAAG,CAAC,iDAAiD,CAAC,CAAC;SAChE;IACH,CAAC;CAAA;AA1DD,oDA0DC"}
+8
View File
@@ -0,0 +1,8 @@
/// <reference types="node" />
interface IHttpsServerOptions {
ca: Buffer;
cert: Buffer;
key: Buffer;
}
export declare function getHttpsServerOptions(daysUntilCertificateExpires?: number, domains?: string[], machine?: boolean): Promise<IHttpsServerOptions>;
export {};
+70
View File
@@ -0,0 +1,70 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getHttpsServerOptions = void 0;
const fs_1 = __importDefault(require("fs"));
const defaults = __importStar(require("./defaults"));
const install_1 = require("./install");
function getHttpsServerOptions(daysUntilCertificateExpires, domains, machine) {
return __awaiter(this, void 0, void 0, function* () {
yield (0, install_1.ensureCertificatesAreInstalled)(daysUntilCertificateExpires, domains, machine);
const httpsServerOptions = {};
try {
httpsServerOptions.ca = fs_1.default.readFileSync(defaults.caCertificatePath);
}
catch (err) {
throw new Error(`Unable to read the CA certificate file.\n${err}`);
}
try {
httpsServerOptions.cert = fs_1.default.readFileSync(defaults.localhostCertificatePath);
}
catch (err) {
throw new Error(`Unable to read the certificate file.\n${err}`);
}
try {
httpsServerOptions.key = fs_1.default.readFileSync(defaults.localhostKeyPath);
}
catch (err) {
throw new Error(`Unable to read the certificate key.\n${err}`);
}
return httpsServerOptions;
});
}
exports.getHttpsServerOptions = getHttpsServerOptions;
//# sourceMappingURL=httpsServerOptions.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"httpsServerOptions.js","sourceRoot":"","sources":["../src/httpsServerOptions.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAElC,4CAAoB;AACpB,qDAAuC;AACvC,uCAA2D;AAU3D,SAAsB,qBAAqB,CACzC,2BAAoC,EACpC,OAAkB,EAClB,OAAiB;;QAEjB,MAAM,IAAA,wCAA8B,EAAC,2BAA2B,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QAEpF,MAAM,kBAAkB,GAAG,EAAyB,CAAC;QACrD,IAAI;YACF,kBAAkB,CAAC,EAAE,GAAG,YAAE,CAAC,YAAY,CAAC,QAAQ,CAAC,iBAAiB,CAAC,CAAC;SACrE;QAAC,OAAO,GAAG,EAAE;YACZ,MAAM,IAAI,KAAK,CAAC,4CAA4C,GAAG,EAAE,CAAC,CAAC;SACpE;QAED,IAAI;YACF,kBAAkB,CAAC,IAAI,GAAG,YAAE,CAAC,YAAY,CAAC,QAAQ,CAAC,wBAAwB,CAAC,CAAC;SAC9E;QAAC,OAAO,GAAG,EAAE;YACZ,MAAM,IAAI,KAAK,CAAC,yCAAyC,GAAG,EAAE,CAAC,CAAC;SACjE;QAED,IAAI;YACF,kBAAkB,CAAC,GAAG,GAAG,YAAE,CAAC,YAAY,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAC;SACrE;QAAC,OAAO,GAAG,EAAE;YACZ,MAAM,IAAI,KAAK,CAAC,wCAAwC,GAAG,EAAE,CAAC,CAAC;SAChE;QAED,OAAO,kBAAkB,CAAC;IAC5B,CAAC;CAAA;AA3BD,sDA2BC"}
+2
View File
@@ -0,0 +1,2 @@
export declare function ensureCertificatesAreInstalled(daysUntilCertificateExpires?: number, domains?: string[], machine?: boolean): Promise<void>;
export declare function installCaCertificate(caCertificatePath?: string, machine?: boolean): Promise<void>;
+111
View File
@@ -0,0 +1,111 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.installCaCertificate = exports.ensureCertificatesAreInstalled = void 0;
const child_process_1 = require("child_process");
const path_1 = __importDefault(require("path"));
const defaults = __importStar(require("./defaults"));
const generate_1 = require("./generate");
const uninstall_1 = require("./uninstall");
const verify_1 = require("./verify");
const defaults_1 = require("./defaults");
const office_addin_usage_data_1 = require("office-addin-usage-data");
/* global console process __dirname */
function getInstallCommand(caCertificatePath, machine = false) {
switch (process.platform) {
case "win32": {
const script = path_1.default.resolve(__dirname, "..\\scripts\\install.ps1");
return `powershell -ExecutionPolicy Bypass -File "${script}" ${machine ? "LocalMachine" : "CurrentUser"} "${caCertificatePath}"`;
}
case "darwin": {
// macOS
const prefix = machine ? "sudo " : "";
const keychainFile = machine
? "/Library/Keychains/System.keychain"
: "~/Library/Keychains/login.keychain-db";
return `${prefix}security add-trusted-cert -d -r trustRoot -k ${keychainFile} '${caCertificatePath}'`;
}
case "linux": {
const script = path_1.default.resolve(__dirname, "../scripts/install_linux.sh");
return `sudo sh '${script}' '${caCertificatePath}'`;
}
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}`);
}
}
function ensureCertificatesAreInstalled(daysUntilCertificateExpires = defaults.daysUntilCertificateExpires, domains = defaults.domain, machine = false) {
return __awaiter(this, void 0, void 0, function* () {
try {
const areCertificatesValid = (0, verify_1.verifyCertificates)();
if (areCertificatesValid) {
console.log(`You already have trusted access to https://localhost.\nCertificate: ${defaults.localhostCertificatePath}\nKey: ${defaults.localhostKeyPath}`);
}
else {
yield (0, uninstall_1.uninstallCaCertificate)(false, false);
(0, uninstall_1.deleteCertificateFiles)(defaults.certificateDirectory);
yield (0, generate_1.generateCertificates)(defaults.caCertificatePath, defaults.localhostCertificatePath, defaults.localhostKeyPath, daysUntilCertificateExpires, domains);
yield installCaCertificate(defaults.caCertificatePath, machine);
}
defaults_1.usageDataObject.reportSuccess("ensureCertificatesAreInstalled()");
}
catch (err) {
defaults_1.usageDataObject.reportException("ensureCertificatesAreInstalled()", err);
throw err;
}
});
}
exports.ensureCertificatesAreInstalled = ensureCertificatesAreInstalled;
function installCaCertificate(caCertificatePath = defaults.caCertificatePath, machine = false) {
return __awaiter(this, void 0, void 0, function* () {
const command = getInstallCommand(caCertificatePath, machine);
try {
console.log(`Installing CA certificate "Developer CA for Microsoft Office Add-ins"...`);
// If the certificate is already installed by another instance skip it.
if (!(0, verify_1.isCaCertificateInstalled)()) {
(0, child_process_1.execSync)(command, { stdio: "pipe" });
}
console.log(`You now have trusted access to https://localhost.\nCertificate: ${defaults.localhostCertificatePath}\nKey: ${defaults.localhostKeyPath}`);
}
catch (error) {
throw new Error(`Unable to install the CA certificate. ${error.stderr.toString()}`);
}
});
}
exports.installCaCertificate = installCaCertificate;
//# sourceMappingURL=install.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"install.js","sourceRoot":"","sources":["../src/install.ts"],"names":[],"mappings":"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"}
+5
View File
@@ -0,0 +1,5 @@
export * from "./generate";
export * from "./httpsServerOptions";
export * from "./install";
export * from "./verify";
export * from "./uninstall";
+24
View File
@@ -0,0 +1,24 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./generate"), exports);
__exportStar(require("./httpsServerOptions"), exports);
__exportStar(require("./install"), exports);
__exportStar(require("./verify"), exports);
__exportStar(require("./uninstall"), exports);
//# sourceMappingURL=main.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;;;;;;;;;;;;;AAElC,6CAA2B;AAC3B,uDAAqC;AACrC,4CAA0B;AAC1B,2CAAyB;AACzB,8CAA4B"}
+2
View File
@@ -0,0 +1,2 @@
export declare function deleteCertificateFiles(certificateDirectory?: string): void;
export declare function uninstallCaCertificate(machine?: boolean, verbose?: boolean): Promise<void>;
+103
View File
@@ -0,0 +1,103 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uninstallCaCertificate = exports.deleteCertificateFiles = void 0;
const child_process_1 = require("child_process");
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const defaults = __importStar(require("./defaults"));
const verify_1 = require("./verify");
const defaults_1 = require("./defaults");
const office_addin_usage_data_1 = require("office-addin-usage-data");
/* global console process __dirname */
function getUninstallCommand(machine = false) {
switch (process.platform) {
case "win32": {
const script = path_1.default.resolve(__dirname, "..\\scripts\\uninstall.ps1");
return `powershell -ExecutionPolicy Bypass -File "${script}" ${machine ? "LocalMachine" : "CurrentUser"} "${defaults.certificateName}"`;
}
case "darwin": {
// macOS
const script = path_1.default.resolve(__dirname, "../scripts/uninstall.sh");
return `sudo sh '${script}' '${defaults.certificateName}'`;
}
case "linux": {
const script = path_1.default.resolve(__dirname, "../scripts/uninstall_linux.sh");
return `sudo sh '${script}' '${defaults.caCertificateFileName}'`;
}
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}`);
}
}
// Deletes the generated certificate files and delete the certificate directory if its empty
function deleteCertificateFiles(certificateDirectory = defaults.certificateDirectory) {
if (fs_extra_1.default.existsSync(certificateDirectory)) {
fs_extra_1.default.removeSync(path_1.default.join(certificateDirectory, defaults.localhostCertificateFileName));
fs_extra_1.default.removeSync(path_1.default.join(certificateDirectory, defaults.localhostKeyFileName));
fs_extra_1.default.removeSync(path_1.default.join(certificateDirectory, defaults.caCertificateFileName));
if (fs_extra_1.default.readdirSync(certificateDirectory).length === 0) {
fs_extra_1.default.removeSync(certificateDirectory);
}
}
}
exports.deleteCertificateFiles = deleteCertificateFiles;
function uninstallCaCertificate(machine = false, verbose = true) {
return __awaiter(this, void 0, void 0, function* () {
if ((0, verify_1.isCaCertificateInstalled)(/* returnInvalidCertificate */ true)) {
const command = getUninstallCommand(machine);
try {
console.log(`Uninstalling CA certificate "Developer CA for Microsoft Office Add-ins"...`);
(0, child_process_1.execSync)(command, { stdio: "pipe" });
console.log(`You no longer have trusted access to https://localhost.`);
defaults_1.usageDataObject.reportSuccess("uninstallCaCertificate()");
}
catch (error) {
defaults_1.usageDataObject.reportException("uninstallCaCertificate()", error);
throw new Error(`Unable to uninstall the CA certificate.\n${error.stderr.toString()}`);
}
}
else {
if (verbose) {
console.log(`The CA certificate is not installed.`);
}
}
});
}
exports.uninstallCaCertificate = uninstallCaCertificate;
//# sourceMappingURL=uninstall.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"uninstall.js","sourceRoot":"","sources":["../src/uninstall.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAElC,iDAAyC;AACzC,wDAA+B;AAC/B,gDAAwB;AACxB,qDAAuC;AACvC,qCAAoD;AACpD,yCAA6C;AAC7C,qEAAwD;AAExD,sCAAsC;AAEtC,SAAS,mBAAmB,CAAC,UAAmB,KAAK;IACnD,QAAQ,OAAO,CAAC,QAAQ,EAAE;QACxB,KAAK,OAAO,CAAC,CAAC;YACZ,MAAM,MAAM,GAAG,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,4BAA4B,CAAC,CAAC;YACrE,OAAO,6CAA6C,MAAM,KAAK,OAAO,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,aAAa,KACrG,QAAQ,CAAC,eACX,GAAG,CAAC;SACL;QACD,KAAK,QAAQ,CAAC,CAAC;YACb,QAAQ;YACR,MAAM,MAAM,GAAG,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,yBAAyB,CAAC,CAAC;YAClE,OAAO,YAAY,MAAM,MAAM,QAAQ,CAAC,eAAe,GAAG,CAAC;SAC5D;QACD,KAAK,OAAO,CAAC,CAAC;YACZ,MAAM,MAAM,GAAG,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,+BAA+B,CAAC,CAAC;YACxE,OAAO,YAAY,MAAM,MAAM,QAAQ,CAAC,qBAAqB,GAAG,CAAC;SAClE;QACD;YACE,MAAM,IAAI,uCAAa,CAAC,2BAA2B,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;KAC1E;AACH,CAAC;AAED,4FAA4F;AAC5F,SAAgB,sBAAsB,CACpC,uBAA+B,QAAQ,CAAC,oBAAoB;IAE5D,IAAI,kBAAO,CAAC,UAAU,CAAC,oBAAoB,CAAC,EAAE;QAC5C,kBAAO,CAAC,UAAU,CAAC,cAAI,CAAC,IAAI,CAAC,oBAAoB,EAAE,QAAQ,CAAC,4BAA4B,CAAC,CAAC,CAAC;QAC3F,kBAAO,CAAC,UAAU,CAAC,cAAI,CAAC,IAAI,CAAC,oBAAoB,EAAE,QAAQ,CAAC,oBAAoB,CAAC,CAAC,CAAC;QACnF,kBAAO,CAAC,UAAU,CAAC,cAAI,CAAC,IAAI,CAAC,oBAAoB,EAAE,QAAQ,CAAC,qBAAqB,CAAC,CAAC,CAAC;QAEpF,IAAI,kBAAO,CAAC,WAAW,CAAC,oBAAoB,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE;YAC1D,kBAAO,CAAC,UAAU,CAAC,oBAAoB,CAAC,CAAC;SAC1C;KACF;AACH,CAAC;AAZD,wDAYC;AAED,SAAsB,sBAAsB,CAAC,UAAmB,KAAK,EAAE,UAAmB,IAAI;;QAC5F,IAAI,IAAA,iCAAwB,EAAC,8BAA8B,CAAC,IAAI,CAAC,EAAE;YACjE,MAAM,OAAO,GAAG,mBAAmB,CAAC,OAAO,CAAC,CAAC;YAE7C,IAAI;gBACF,OAAO,CAAC,GAAG,CAAC,4EAA4E,CAAC,CAAC;gBAC1F,IAAA,wBAAQ,EAAC,OAAO,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC;gBACrC,OAAO,CAAC,GAAG,CAAC,yDAAyD,CAAC,CAAC;gBACvE,0BAAe,CAAC,aAAa,CAAC,0BAA0B,CAAC,CAAC;aAC3D;YAAC,OAAO,KAAU,EAAE;gBACnB,0BAAe,CAAC,eAAe,CAAC,0BAA0B,EAAE,KAAK,CAAC,CAAC;gBACnE,MAAM,IAAI,KAAK,CAAC,4CAA4C,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;aACxF;SACF;aAAM;YACL,IAAI,OAAO,EAAE;gBACX,OAAO,CAAC,GAAG,CAAC,sCAAsC,CAAC,CAAC;aACrD;SACF;IACH,CAAC;CAAA;AAlBD,wDAkBC"}
+3
View File
@@ -0,0 +1,3 @@
export declare const outputMarker: string;
export declare function isCaCertificateInstalled(returnInvalidCertificate?: boolean): boolean;
export declare function verifyCertificates(certificatePath?: string, keyPath?: string): boolean;
+134
View File
@@ -0,0 +1,134 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyCertificates = exports.isCaCertificateInstalled = exports.outputMarker = void 0;
const child_process_1 = require("child_process");
const crypto_1 = __importDefault(require("crypto"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const defaults = __importStar(require("./defaults"));
const defaults_1 = require("./defaults");
const office_addin_usage_data_1 = require("office-addin-usage-data");
/* global Buffer process __dirname */
// On win32 this is a unique hash used with PowerShell command to reliably delineate command output
exports.outputMarker = process.platform === "win32"
? `[${crypto_1.default.createHash("md5").update(`${defaults.certificateName}${defaults.caCertificatePath}`).digest("hex")}]`
: "";
function getVerifyCommand(returnInvalidCertificate) {
switch (process.platform) {
case "win32": {
const script = path_1.default.resolve(__dirname, "..\\scripts\\verify.ps1");
const defaultCommand = `powershell -ExecutionPolicy Bypass -File "${script}" -CaCertificateName "${defaults.certificateName}" -CaCertificatePath "${defaults.caCertificatePath}" -LocalhostCertificatePath "${defaults.localhostCertificatePath}" -OutputMarker "${exports.outputMarker}"`;
if (returnInvalidCertificate) {
return defaultCommand + ` -ReturnInvalidCertificate`;
}
return defaultCommand;
}
case "darwin": {
// macOS
const script = path_1.default.resolve(__dirname, "../scripts/verify.sh");
return `sh '${script}' '${defaults.certificateName}'`;
}
case "linux": {
const script = path_1.default.resolve(__dirname, "../scripts/verify_linux.sh");
return `sh '${script}' '${defaults.caCertificateFileName}'`;
}
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}`);
}
}
function isCaCertificateInstalled(returnInvalidCertificate = false) {
const command = getVerifyCommand(returnInvalidCertificate);
try {
const output = (0, child_process_1.execSync)(command, { stdio: "pipe" }).toString();
if (process.platform === "win32") {
// Remove any PowerShell output that preceeds invoking the actual certificate check command
return (output.slice(output.lastIndexOf(exports.outputMarker) + exports.outputMarker.length).trim().length !== 0);
}
// script files return empty string if the certificate not found or expired
if (output.length !== 0) {
return true;
}
}
catch (_a) {
// Some commands throw errors if the certifcate is not found or expired
}
return false;
}
exports.isCaCertificateInstalled = isCaCertificateInstalled;
function validateCertificateAndKey(certificatePath, keyPath) {
let certificate = "";
let key = "";
try {
certificate = fs_1.default.readFileSync(certificatePath).toString();
}
catch (err) {
throw new Error(`Unable to read the certificate.\n${err}`);
}
try {
key = fs_1.default.readFileSync(keyPath).toString();
}
catch (err) {
throw new Error(`Unable to read the certificate key.\n${err}`);
}
let encrypted;
try {
encrypted = crypto_1.default.publicEncrypt(certificate, Buffer.from("test"));
}
catch (err) {
throw new Error(`The certificate is not valid.\n${err}`);
}
try {
crypto_1.default.privateDecrypt(key, encrypted);
}
catch (err) {
throw new Error(`The certificate key is not valid.\n${err}`);
}
}
function verifyCertificates(certificatePath = defaults.localhostCertificatePath, keyPath = defaults.localhostKeyPath) {
try {
let isCertificateValid = true;
try {
validateCertificateAndKey(certificatePath, keyPath);
}
catch (_a) {
isCertificateValid = false;
}
let output = isCertificateValid && isCaCertificateInstalled();
defaults_1.usageDataObject.reportSuccess("verifyCertificates()");
return output;
}
catch (err) {
defaults_1.usageDataObject.reportException("verifyCertificates()", err);
throw err;
}
}
exports.verifyCertificates = verifyCertificates;
//# sourceMappingURL=verify.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"verify.js","sourceRoot":"","sources":["../src/verify.ts"],"names":[],"mappings":"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"}
+22
View File
@@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>
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.
File diff suppressed because it is too large Load Diff
+16
View File
@@ -0,0 +1,16 @@
import commander from './index.js';
// wrapper to provide named exports for ESM.
export const {
program,
createCommand,
createArgument,
createOption,
CommanderError,
InvalidArgumentError,
InvalidOptionArgumentError, // deprecated old name
Command,
Argument,
Option,
Help,
} = commander;
+24
View File
@@ -0,0 +1,24 @@
const { Argument } = require('./lib/argument.js');
const { Command } = require('./lib/command.js');
const { CommanderError, InvalidArgumentError } = require('./lib/error.js');
const { Help } = require('./lib/help.js');
const { Option } = require('./lib/option.js');
exports.program = new Command();
exports.createCommand = (name) => new Command(name);
exports.createOption = (flags, description) => new Option(flags, description);
exports.createArgument = (name, description) => new Argument(name, description);
/**
* Expose classes
*/
exports.Command = Command;
exports.Option = Option;
exports.Argument = Argument;
exports.Help = Help;
exports.CommanderError = CommanderError;
exports.InvalidArgumentError = InvalidArgumentError;
exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated
@@ -0,0 +1,149 @@
const { InvalidArgumentError } = require('./error.js');
class Argument {
/**
* Initialize a new command argument with the given name and description.
* The default is that the argument is required, and you can explicitly
* indicate this with <> around the name. Put [] around the name for an optional argument.
*
* @param {string} name
* @param {string} [description]
*/
constructor(name, description) {
this.description = description || '';
this.variadic = false;
this.parseArg = undefined;
this.defaultValue = undefined;
this.defaultValueDescription = undefined;
this.argChoices = undefined;
switch (name[0]) {
case '<': // e.g. <required>
this.required = true;
this._name = name.slice(1, -1);
break;
case '[': // e.g. [optional]
this.required = false;
this._name = name.slice(1, -1);
break;
default:
this.required = true;
this._name = name;
break;
}
if (this._name.length > 3 && this._name.slice(-3) === '...') {
this.variadic = true;
this._name = this._name.slice(0, -3);
}
}
/**
* Return argument name.
*
* @return {string}
*/
name() {
return this._name;
}
/**
* @package
*/
_concatValue(value, previous) {
if (previous === this.defaultValue || !Array.isArray(previous)) {
return [value];
}
return previous.concat(value);
}
/**
* Set the default value, and optionally supply the description to be displayed in the help.
*
* @param {*} value
* @param {string} [description]
* @return {Argument}
*/
default(value, description) {
this.defaultValue = value;
this.defaultValueDescription = description;
return this;
}
/**
* Set the custom handler for processing CLI command arguments into argument values.
*
* @param {Function} [fn]
* @return {Argument}
*/
argParser(fn) {
this.parseArg = fn;
return this;
}
/**
* Only allow argument value to be one of choices.
*
* @param {string[]} values
* @return {Argument}
*/
choices(values) {
this.argChoices = values.slice();
this.parseArg = (arg, previous) => {
if (!this.argChoices.includes(arg)) {
throw new InvalidArgumentError(
`Allowed choices are ${this.argChoices.join(', ')}.`,
);
}
if (this.variadic) {
return this._concatValue(arg, previous);
}
return arg;
};
return this;
}
/**
* Make argument required.
*
* @returns {Argument}
*/
argRequired() {
this.required = true;
return this;
}
/**
* Make argument optional.
*
* @returns {Argument}
*/
argOptional() {
this.required = false;
return this;
}
}
/**
* Takes an argument and returns its human readable equivalent for help usage.
*
* @param {Argument} arg
* @return {string}
* @private
*/
function humanReadableArgName(arg) {
const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');
return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';
}
exports.Argument = Argument;
exports.humanReadableArgName = humanReadableArgName;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,39 @@
/**
* CommanderError class
*/
class CommanderError extends Error {
/**
* Constructs the CommanderError class
* @param {number} exitCode suggested exit code which could be used with process.exit
* @param {string} code an id string representing the error
* @param {string} message human-readable description of the error
*/
constructor(exitCode, code, message) {
super(message);
// properly capture stack trace in Node.js
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.code = code;
this.exitCode = exitCode;
this.nestedError = undefined;
}
}
/**
* InvalidArgumentError class
*/
class InvalidArgumentError extends CommanderError {
/**
* Constructs the InvalidArgumentError class
* @param {string} [message] explanation of why argument is invalid
*/
constructor(message) {
super(1, 'commander.invalidArgument', message);
// properly capture stack trace in Node.js
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
}
}
exports.CommanderError = CommanderError;
exports.InvalidArgumentError = InvalidArgumentError;
+709
View File
@@ -0,0 +1,709 @@
const { humanReadableArgName } = require('./argument.js');
/**
* TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
* https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
* @typedef { import("./argument.js").Argument } Argument
* @typedef { import("./command.js").Command } Command
* @typedef { import("./option.js").Option } Option
*/
// Although this is a class, methods are static in style to allow override using subclass or just functions.
class Help {
constructor() {
this.helpWidth = undefined;
this.minWidthToWrap = 40;
this.sortSubcommands = false;
this.sortOptions = false;
this.showGlobalOptions = false;
}
/**
* prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
* and just before calling `formatHelp()`.
*
* Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
*
* @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
*/
prepareContext(contextOptions) {
this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
}
/**
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
*
* @param {Command} cmd
* @returns {Command[]}
*/
visibleCommands(cmd) {
const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
const helpCommand = cmd._getHelpCommand();
if (helpCommand && !helpCommand._hidden) {
visibleCommands.push(helpCommand);
}
if (this.sortSubcommands) {
visibleCommands.sort((a, b) => {
// @ts-ignore: because overloaded return type
return a.name().localeCompare(b.name());
});
}
return visibleCommands;
}
/**
* Compare options for sort.
*
* @param {Option} a
* @param {Option} b
* @returns {number}
*/
compareOptions(a, b) {
const getSortKey = (option) => {
// WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.
return option.short
? option.short.replace(/^-/, '')
: option.long.replace(/^--/, '');
};
return getSortKey(a).localeCompare(getSortKey(b));
}
/**
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
*
* @param {Command} cmd
* @returns {Option[]}
*/
visibleOptions(cmd) {
const visibleOptions = cmd.options.filter((option) => !option.hidden);
// Built-in help option.
const helpOption = cmd._getHelpOption();
if (helpOption && !helpOption.hidden) {
// Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
if (!removeShort && !removeLong) {
visibleOptions.push(helpOption); // no changes needed
} else if (helpOption.long && !removeLong) {
visibleOptions.push(
cmd.createOption(helpOption.long, helpOption.description),
);
} else if (helpOption.short && !removeShort) {
visibleOptions.push(
cmd.createOption(helpOption.short, helpOption.description),
);
}
}
if (this.sortOptions) {
visibleOptions.sort(this.compareOptions);
}
return visibleOptions;
}
/**
* Get an array of the visible global options. (Not including help.)
*
* @param {Command} cmd
* @returns {Option[]}
*/
visibleGlobalOptions(cmd) {
if (!this.showGlobalOptions) return [];
const globalOptions = [];
for (
let ancestorCmd = cmd.parent;
ancestorCmd;
ancestorCmd = ancestorCmd.parent
) {
const visibleOptions = ancestorCmd.options.filter(
(option) => !option.hidden,
);
globalOptions.push(...visibleOptions);
}
if (this.sortOptions) {
globalOptions.sort(this.compareOptions);
}
return globalOptions;
}
/**
* Get an array of the arguments if any have a description.
*
* @param {Command} cmd
* @returns {Argument[]}
*/
visibleArguments(cmd) {
// Side effect! Apply the legacy descriptions before the arguments are displayed.
if (cmd._argsDescription) {
cmd.registeredArguments.forEach((argument) => {
argument.description =
argument.description || cmd._argsDescription[argument.name()] || '';
});
}
// If there are any arguments with a description then return all the arguments.
if (cmd.registeredArguments.find((argument) => argument.description)) {
return cmd.registeredArguments;
}
return [];
}
/**
* Get the command term to show in the list of subcommands.
*
* @param {Command} cmd
* @returns {string}
*/
subcommandTerm(cmd) {
// Legacy. Ignores custom usage string, and nested commands.
const args = cmd.registeredArguments
.map((arg) => humanReadableArgName(arg))
.join(' ');
return (
cmd._name +
(cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +
(cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option
(args ? ' ' + args : '')
);
}
/**
* Get the option term to show in the list of options.
*
* @param {Option} option
* @returns {string}
*/
optionTerm(option) {
return option.flags;
}
/**
* Get the argument term to show in the list of arguments.
*
* @param {Argument} argument
* @returns {string}
*/
argumentTerm(argument) {
return argument.name();
}
/**
* Get the longest command term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestSubcommandTermLength(cmd, helper) {
return helper.visibleCommands(cmd).reduce((max, command) => {
return Math.max(
max,
this.displayWidth(
helper.styleSubcommandTerm(helper.subcommandTerm(command)),
),
);
}, 0);
}
/**
* Get the longest option term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestOptionTermLength(cmd, helper) {
return helper.visibleOptions(cmd).reduce((max, option) => {
return Math.max(
max,
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),
);
}, 0);
}
/**
* Get the longest global option term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestGlobalOptionTermLength(cmd, helper) {
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
return Math.max(
max,
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),
);
}, 0);
}
/**
* Get the longest argument term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestArgumentTermLength(cmd, helper) {
return helper.visibleArguments(cmd).reduce((max, argument) => {
return Math.max(
max,
this.displayWidth(
helper.styleArgumentTerm(helper.argumentTerm(argument)),
),
);
}, 0);
}
/**
* Get the command usage to be displayed at the top of the built-in help.
*
* @param {Command} cmd
* @returns {string}
*/
commandUsage(cmd) {
// Usage
let cmdName = cmd._name;
if (cmd._aliases[0]) {
cmdName = cmdName + '|' + cmd._aliases[0];
}
let ancestorCmdNames = '';
for (
let ancestorCmd = cmd.parent;
ancestorCmd;
ancestorCmd = ancestorCmd.parent
) {
ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;
}
return ancestorCmdNames + cmdName + ' ' + cmd.usage();
}
/**
* Get the description for the command.
*
* @param {Command} cmd
* @returns {string}
*/
commandDescription(cmd) {
// @ts-ignore: because overloaded return type
return cmd.description();
}
/**
* Get the subcommand summary to show in the list of subcommands.
* (Fallback to description for backwards compatibility.)
*
* @param {Command} cmd
* @returns {string}
*/
subcommandDescription(cmd) {
// @ts-ignore: because overloaded return type
return cmd.summary() || cmd.description();
}
/**
* Get the option description to show in the list of options.
*
* @param {Option} option
* @return {string}
*/
optionDescription(option) {
const extraInfo = [];
if (option.argChoices) {
extraInfo.push(
// use stringify to match the display of the default value
`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
);
}
if (option.defaultValue !== undefined) {
// default for boolean and negated more for programmer than end user,
// but show true/false for boolean option as may be for hand-rolled env or config processing.
const showDefault =
option.required ||
option.optional ||
(option.isBoolean() && typeof option.defaultValue === 'boolean');
if (showDefault) {
extraInfo.push(
`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,
);
}
}
// preset for boolean and negated are more for programmer than end user
if (option.presetArg !== undefined && option.optional) {
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
}
if (option.envVar !== undefined) {
extraInfo.push(`env: ${option.envVar}`);
}
if (extraInfo.length > 0) {
return `${option.description} (${extraInfo.join(', ')})`;
}
return option.description;
}
/**
* Get the argument description to show in the list of arguments.
*
* @param {Argument} argument
* @return {string}
*/
argumentDescription(argument) {
const extraInfo = [];
if (argument.argChoices) {
extraInfo.push(
// use stringify to match the display of the default value
`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
);
}
if (argument.defaultValue !== undefined) {
extraInfo.push(
`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,
);
}
if (extraInfo.length > 0) {
const extraDescription = `(${extraInfo.join(', ')})`;
if (argument.description) {
return `${argument.description} ${extraDescription}`;
}
return extraDescription;
}
return argument.description;
}
/**
* Generate the built-in help text.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {string}
*/
formatHelp(cmd, helper) {
const termWidth = helper.padWidth(cmd, helper);
const helpWidth = helper.helpWidth ?? 80; // in case prepareContext() was not called
function callFormatItem(term, description) {
return helper.formatItem(term, termWidth, description, helper);
}
// Usage
let output = [
`${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,
'',
];
// Description
const commandDescription = helper.commandDescription(cmd);
if (commandDescription.length > 0) {
output = output.concat([
helper.boxWrap(
helper.styleCommandDescription(commandDescription),
helpWidth,
),
'',
]);
}
// Arguments
const argumentList = helper.visibleArguments(cmd).map((argument) => {
return callFormatItem(
helper.styleArgumentTerm(helper.argumentTerm(argument)),
helper.styleArgumentDescription(helper.argumentDescription(argument)),
);
});
if (argumentList.length > 0) {
output = output.concat([
helper.styleTitle('Arguments:'),
...argumentList,
'',
]);
}
// Options
const optionList = helper.visibleOptions(cmd).map((option) => {
return callFormatItem(
helper.styleOptionTerm(helper.optionTerm(option)),
helper.styleOptionDescription(helper.optionDescription(option)),
);
});
if (optionList.length > 0) {
output = output.concat([
helper.styleTitle('Options:'),
...optionList,
'',
]);
}
if (helper.showGlobalOptions) {
const globalOptionList = helper
.visibleGlobalOptions(cmd)
.map((option) => {
return callFormatItem(
helper.styleOptionTerm(helper.optionTerm(option)),
helper.styleOptionDescription(helper.optionDescription(option)),
);
});
if (globalOptionList.length > 0) {
output = output.concat([
helper.styleTitle('Global Options:'),
...globalOptionList,
'',
]);
}
}
// Commands
const commandList = helper.visibleCommands(cmd).map((cmd) => {
return callFormatItem(
helper.styleSubcommandTerm(helper.subcommandTerm(cmd)),
helper.styleSubcommandDescription(helper.subcommandDescription(cmd)),
);
});
if (commandList.length > 0) {
output = output.concat([
helper.styleTitle('Commands:'),
...commandList,
'',
]);
}
return output.join('\n');
}
/**
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
*
* @param {string} str
* @returns {number}
*/
displayWidth(str) {
return stripColor(str).length;
}
/**
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
*
* @param {string} str
* @returns {string}
*/
styleTitle(str) {
return str;
}
styleUsage(str) {
// Usage has lots of parts the user might like to color separately! Assume default usage string which is formed like:
// command subcommand [options] [command] <foo> [bar]
return str
.split(' ')
.map((word) => {
if (word === '[options]') return this.styleOptionText(word);
if (word === '[command]') return this.styleSubcommandText(word);
if (word[0] === '[' || word[0] === '<')
return this.styleArgumentText(word);
return this.styleCommandText(word); // Restrict to initial words?
})
.join(' ');
}
styleCommandDescription(str) {
return this.styleDescriptionText(str);
}
styleOptionDescription(str) {
return this.styleDescriptionText(str);
}
styleSubcommandDescription(str) {
return this.styleDescriptionText(str);
}
styleArgumentDescription(str) {
return this.styleDescriptionText(str);
}
styleDescriptionText(str) {
return str;
}
styleOptionTerm(str) {
return this.styleOptionText(str);
}
styleSubcommandTerm(str) {
// This is very like usage with lots of parts! Assume default string which is formed like:
// subcommand [options] <foo> [bar]
return str
.split(' ')
.map((word) => {
if (word === '[options]') return this.styleOptionText(word);
if (word[0] === '[' || word[0] === '<')
return this.styleArgumentText(word);
return this.styleSubcommandText(word); // Restrict to initial words?
})
.join(' ');
}
styleArgumentTerm(str) {
return this.styleArgumentText(str);
}
styleOptionText(str) {
return str;
}
styleArgumentText(str) {
return str;
}
styleSubcommandText(str) {
return str;
}
styleCommandText(str) {
return str;
}
/**
* Calculate the pad width from the maximum term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
padWidth(cmd, helper) {
return Math.max(
helper.longestOptionTermLength(cmd, helper),
helper.longestGlobalOptionTermLength(cmd, helper),
helper.longestSubcommandTermLength(cmd, helper),
helper.longestArgumentTermLength(cmd, helper),
);
}
/**
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
*
* @param {string} str
* @returns {boolean}
*/
preformatted(str) {
return /\n[^\S\r\n]/.test(str);
}
/**
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
*
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
* TTT DDD DDDD
* DD DDD
*
* @param {string} term
* @param {number} termWidth
* @param {string} description
* @param {Help} helper
* @returns {string}
*/
formatItem(term, termWidth, description, helper) {
const itemIndent = 2;
const itemIndentStr = ' '.repeat(itemIndent);
if (!description) return itemIndentStr + term;
// Pad the term out to a consistent width, so descriptions are aligned.
const paddedTerm = term.padEnd(
termWidth + term.length - helper.displayWidth(term),
);
// Format the description.
const spacerWidth = 2; // between term and description
const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called
const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
let formattedDescription;
if (
remainingWidth < this.minWidthToWrap ||
helper.preformatted(description)
) {
formattedDescription = description;
} else {
const wrappedDescription = helper.boxWrap(description, remainingWidth);
formattedDescription = wrappedDescription.replace(
/\n/g,
'\n' + ' '.repeat(termWidth + spacerWidth),
);
}
// Construct and overall indent.
return (
itemIndentStr +
paddedTerm +
' '.repeat(spacerWidth) +
formattedDescription.replace(/\n/g, `\n${itemIndentStr}`)
);
}
/**
* Wrap a string at whitespace, preserving existing line breaks.
* Wrapping is skipped if the width is less than `minWidthToWrap`.
*
* @param {string} str
* @param {number} width
* @returns {string}
*/
boxWrap(str, width) {
if (width < this.minWidthToWrap) return str;
const rawLines = str.split(/\r\n|\n/);
// split up text by whitespace
const chunkPattern = /[\s]*[^\s]+/g;
const wrappedLines = [];
rawLines.forEach((line) => {
const chunks = line.match(chunkPattern);
if (chunks === null) {
wrappedLines.push('');
return;
}
let sumChunks = [chunks.shift()];
let sumWidth = this.displayWidth(sumChunks[0]);
chunks.forEach((chunk) => {
const visibleWidth = this.displayWidth(chunk);
// Accumulate chunks while they fit into width.
if (sumWidth + visibleWidth <= width) {
sumChunks.push(chunk);
sumWidth += visibleWidth;
return;
}
wrappedLines.push(sumChunks.join(''));
const nextChunk = chunk.trimStart(); // trim space at line break
sumChunks = [nextChunk];
sumWidth = this.displayWidth(nextChunk);
});
wrappedLines.push(sumChunks.join(''));
});
return wrappedLines.join('\n');
}
}
/**
* Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.
*
* @param {string} str
* @returns {string}
* @package
*/
function stripColor(str) {
// eslint-disable-next-line no-control-regex
const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
return str.replace(sgrPattern, '');
}
exports.Help = Help;
exports.stripColor = stripColor;
@@ -0,0 +1,367 @@
const { InvalidArgumentError } = require('./error.js');
class Option {
/**
* Initialize a new `Option` with the given `flags` and `description`.
*
* @param {string} flags
* @param {string} [description]
*/
constructor(flags, description) {
this.flags = flags;
this.description = description || '';
this.required = flags.includes('<'); // A value must be supplied when the option is specified.
this.optional = flags.includes('['); // A value is optional when the option is specified.
// variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument
this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.
this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
const optionFlags = splitOptionFlags(flags);
this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags).
this.long = optionFlags.longFlag;
this.negate = false;
if (this.long) {
this.negate = this.long.startsWith('--no-');
}
this.defaultValue = undefined;
this.defaultValueDescription = undefined;
this.presetArg = undefined;
this.envVar = undefined;
this.parseArg = undefined;
this.hidden = false;
this.argChoices = undefined;
this.conflictsWith = [];
this.implied = undefined;
}
/**
* Set the default value, and optionally supply the description to be displayed in the help.
*
* @param {*} value
* @param {string} [description]
* @return {Option}
*/
default(value, description) {
this.defaultValue = value;
this.defaultValueDescription = description;
return this;
}
/**
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
* The custom processing (parseArg) is called.
*
* @example
* new Option('--color').default('GREYSCALE').preset('RGB');
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
*
* @param {*} arg
* @return {Option}
*/
preset(arg) {
this.presetArg = arg;
return this;
}
/**
* Add option name(s) that conflict with this option.
* An error will be displayed if conflicting options are found during parsing.
*
* @example
* new Option('--rgb').conflicts('cmyk');
* new Option('--js').conflicts(['ts', 'jsx']);
*
* @param {(string | string[])} names
* @return {Option}
*/
conflicts(names) {
this.conflictsWith = this.conflictsWith.concat(names);
return this;
}
/**
* Specify implied option values for when this option is set and the implied options are not.
*
* The custom processing (parseArg) is not called on the implied values.
*
* @example
* program
* .addOption(new Option('--log', 'write logging information to file'))
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
*
* @param {object} impliedOptionValues
* @return {Option}
*/
implies(impliedOptionValues) {
let newImplied = impliedOptionValues;
if (typeof impliedOptionValues === 'string') {
// string is not documented, but easy mistake and we can do what user probably intended.
newImplied = { [impliedOptionValues]: true };
}
this.implied = Object.assign(this.implied || {}, newImplied);
return this;
}
/**
* Set environment variable to check for option value.
*
* An environment variable is only used if when processed the current option value is
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
*
* @param {string} name
* @return {Option}
*/
env(name) {
this.envVar = name;
return this;
}
/**
* Set the custom handler for processing CLI option arguments into option values.
*
* @param {Function} [fn]
* @return {Option}
*/
argParser(fn) {
this.parseArg = fn;
return this;
}
/**
* Whether the option is mandatory and must have a value after parsing.
*
* @param {boolean} [mandatory=true]
* @return {Option}
*/
makeOptionMandatory(mandatory = true) {
this.mandatory = !!mandatory;
return this;
}
/**
* Hide option in help.
*
* @param {boolean} [hide=true]
* @return {Option}
*/
hideHelp(hide = true) {
this.hidden = !!hide;
return this;
}
/**
* @package
*/
_concatValue(value, previous) {
if (previous === this.defaultValue || !Array.isArray(previous)) {
return [value];
}
return previous.concat(value);
}
/**
* Only allow option value to be one of choices.
*
* @param {string[]} values
* @return {Option}
*/
choices(values) {
this.argChoices = values.slice();
this.parseArg = (arg, previous) => {
if (!this.argChoices.includes(arg)) {
throw new InvalidArgumentError(
`Allowed choices are ${this.argChoices.join(', ')}.`,
);
}
if (this.variadic) {
return this._concatValue(arg, previous);
}
return arg;
};
return this;
}
/**
* Return option name.
*
* @return {string}
*/
name() {
if (this.long) {
return this.long.replace(/^--/, '');
}
return this.short.replace(/^-/, '');
}
/**
* Return option name, in a camelcase format that can be used
* as an object attribute key.
*
* @return {string}
*/
attributeName() {
if (this.negate) {
return camelcase(this.name().replace(/^no-/, ''));
}
return camelcase(this.name());
}
/**
* Check if `arg` matches the short or long flag.
*
* @param {string} arg
* @return {boolean}
* @package
*/
is(arg) {
return this.short === arg || this.long === arg;
}
/**
* Return whether a boolean option.
*
* Options are one of boolean, negated, required argument, or optional argument.
*
* @return {boolean}
* @package
*/
isBoolean() {
return !this.required && !this.optional && !this.negate;
}
}
/**
* This class is to make it easier to work with dual options, without changing the existing
* implementation. We support separate dual options for separate positive and negative options,
* like `--build` and `--no-build`, which share a single option value. This works nicely for some
* use cases, but is tricky for others where we want separate behaviours despite
* the single shared option value.
*/
class DualOptions {
/**
* @param {Option[]} options
*/
constructor(options) {
this.positiveOptions = new Map();
this.negativeOptions = new Map();
this.dualOptions = new Set();
options.forEach((option) => {
if (option.negate) {
this.negativeOptions.set(option.attributeName(), option);
} else {
this.positiveOptions.set(option.attributeName(), option);
}
});
this.negativeOptions.forEach((value, key) => {
if (this.positiveOptions.has(key)) {
this.dualOptions.add(key);
}
});
}
/**
* Did the value come from the option, and not from possible matching dual option?
*
* @param {*} value
* @param {Option} option
* @returns {boolean}
*/
valueFromOption(value, option) {
const optionKey = option.attributeName();
if (!this.dualOptions.has(optionKey)) return true;
// Use the value to deduce if (probably) came from the option.
const preset = this.negativeOptions.get(optionKey).presetArg;
const negativeValue = preset !== undefined ? preset : false;
return option.negate === (negativeValue === value);
}
}
/**
* Convert string from kebab-case to camelCase.
*
* @param {string} str
* @return {string}
* @private
*/
function camelcase(str) {
return str.split('-').reduce((str, word) => {
return str + word[0].toUpperCase() + word.slice(1);
});
}
/**
* Split the short and long flag out of something like '-m,--mixed <value>'
*
* @private
*/
function splitOptionFlags(flags) {
let shortFlag;
let longFlag;
// short flag, single dash and single character
const shortFlagExp = /^-[^-]$/;
// long flag, double dash and at least one character
const longFlagExp = /^--[^-]/;
const flagParts = flags.split(/[ |,]+/).concat('guard');
// Normal is short and/or long.
if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
// Long then short. Rarely used but fine.
if (!shortFlag && shortFlagExp.test(flagParts[0]))
shortFlag = flagParts.shift();
// Allow two long flags, like '--ws, --workspace'
// This is the supported way to have a shortish option flag.
if (!shortFlag && longFlagExp.test(flagParts[0])) {
shortFlag = longFlag;
longFlag = flagParts.shift();
}
// Check for unprocessed flag. Fail noisily rather than silently ignore.
if (flagParts[0].startsWith('-')) {
const unsupportedFlag = flagParts[0];
const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
if (/^-[^-][^-]/.test(unsupportedFlag))
throw new Error(
`${baseError}
- a short flag is a single dash and a single character
- either use a single dash and a single character (for a short flag)
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`,
);
if (shortFlagExp.test(unsupportedFlag))
throw new Error(`${baseError}
- too many short flags`);
if (longFlagExp.test(unsupportedFlag))
throw new Error(`${baseError}
- too many long flags`);
throw new Error(`${baseError}
- unrecognised flag format`);
}
if (shortFlag === undefined && longFlag === undefined)
throw new Error(
`option creation failed due to no flags found in '${flags}'.`,
);
return { shortFlag, longFlag };
}
exports.Option = Option;
exports.DualOptions = DualOptions;
@@ -0,0 +1,101 @@
const maxDistance = 3;
function editDistance(a, b) {
// https://en.wikipedia.org/wiki/DamerauLevenshtein_distance
// Calculating optimal string alignment distance, no substring is edited more than once.
// (Simple implementation.)
// Quick early exit, return worst case.
if (Math.abs(a.length - b.length) > maxDistance)
return Math.max(a.length, b.length);
// distance between prefix substrings of a and b
const d = [];
// pure deletions turn a into empty string
for (let i = 0; i <= a.length; i++) {
d[i] = [i];
}
// pure insertions turn empty string into b
for (let j = 0; j <= b.length; j++) {
d[0][j] = j;
}
// fill matrix
for (let j = 1; j <= b.length; j++) {
for (let i = 1; i <= a.length; i++) {
let cost = 1;
if (a[i - 1] === b[j - 1]) {
cost = 0;
} else {
cost = 1;
}
d[i][j] = Math.min(
d[i - 1][j] + 1, // deletion
d[i][j - 1] + 1, // insertion
d[i - 1][j - 1] + cost, // substitution
);
// transposition
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
}
}
}
return d[a.length][b.length];
}
/**
* Find close matches, restricted to same number of edits.
*
* @param {string} word
* @param {string[]} candidates
* @returns {string}
*/
function suggestSimilar(word, candidates) {
if (!candidates || candidates.length === 0) return '';
// remove possible duplicates
candidates = Array.from(new Set(candidates));
const searchingOptions = word.startsWith('--');
if (searchingOptions) {
word = word.slice(2);
candidates = candidates.map((candidate) => candidate.slice(2));
}
let similar = [];
let bestDistance = maxDistance;
const minSimilarity = 0.4;
candidates.forEach((candidate) => {
if (candidate.length <= 1) return; // no one character guesses
const distance = editDistance(word, candidate);
const length = Math.max(word.length, candidate.length);
const similarity = (length - distance) / length;
if (similarity > minSimilarity) {
if (distance < bestDistance) {
// better edit distance, throw away previous worse matches
bestDistance = distance;
similar = [candidate];
} else if (distance === bestDistance) {
similar.push(candidate);
}
}
});
similar.sort((a, b) => a.localeCompare(b));
if (searchingOptions) {
similar = similar.map((candidate) => `--${candidate}`);
}
if (similar.length > 1) {
return `\n(Did you mean one of ${similar.join(', ')}?)`;
}
if (similar.length === 1) {
return `\n(Did you mean ${similar[0]}?)`;
}
return '';
}
exports.suggestSimilar = suggestSimilar;
@@ -0,0 +1,16 @@
{
"versions": [
{
"version": "*",
"target": {
"node": "supported"
},
"response": {
"type": "time-permitting"
},
"backing": {
"npm-funding": true
}
}
]
}
@@ -0,0 +1,82 @@
{
"name": "commander",
"version": "13.1.0",
"description": "the complete solution for node.js command-line programs",
"keywords": [
"commander",
"command",
"option",
"parser",
"cli",
"argument",
"args",
"argv"
],
"author": "TJ Holowaychuk <tj@vision-media.ca>",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/tj/commander.js.git"
},
"scripts": {
"check": "npm run check:type && npm run check:lint && npm run check:format",
"check:format": "prettier --check .",
"check:lint": "eslint .",
"check:type": "npm run check:type:js && npm run check:type:ts",
"check:type:ts": "tsd && tsc -p tsconfig.ts.json",
"check:type:js": "tsc -p tsconfig.js.json",
"fix": "npm run fix:lint && npm run fix:format",
"fix:format": "prettier --write .",
"fix:lint": "eslint --fix .",
"test": "jest && npm run check:type:ts",
"test-all": "jest && npm run test-esm && npm run check",
"test-esm": "node ./tests/esm-imports-test.mjs"
},
"files": [
"index.js",
"lib/*.js",
"esm.mjs",
"typings/index.d.ts",
"typings/esm.d.mts",
"package-support.json"
],
"type": "commonjs",
"main": "./index.js",
"exports": {
".": {
"require": {
"types": "./typings/index.d.ts",
"default": "./index.js"
},
"import": {
"types": "./typings/esm.d.mts",
"default": "./esm.mjs"
},
"default": "./index.js"
},
"./esm.mjs": {
"types": "./typings/esm.d.mts",
"import": "./esm.mjs"
}
},
"devDependencies": {
"@eslint/js": "^9.4.0",
"@types/jest": "^29.2.4",
"@types/node": "^22.7.4",
"eslint": "^9.17.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-jest": "^28.3.0",
"globals": "^15.7.0",
"jest": "^29.3.1",
"prettier": "^3.2.5",
"ts-jest": "^29.0.3",
"tsd": "^0.31.0",
"typescript": "^5.0.4",
"typescript-eslint": "^8.12.2"
},
"types": "typings/index.d.ts",
"engines": {
"node": ">=18"
},
"support": true
}
@@ -0,0 +1,3 @@
// Just reexport the types from cjs
// This is a bit indirect. There is not an index.js, but TypeScript will look for index.d.ts for types.
export * from './index.js';
File diff suppressed because it is too large Load Diff
+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.
+292
View File
@@ -0,0 +1,292 @@
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')
```
### 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,171 @@
'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 (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,182 @@
'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')
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)
}
const promises = []
// loop through the files in the current directory to copy everything
for await (const item of await fs.opendir(src)) {
const srcItem = path.join(src, item.name)
const destItem = path.join(dest, item.name)
promises.push(
runFilter(srcItem, destItem, opts).then(include => {
if (include) {
// only copy the item if it matches the filter function
return stat.checkPaths(srcItem, destItem, 'copy', opts).then(({ destStat }) => {
// If the item is a copyable file, `getStatsAndPerformCopy` will copy it
// If the item is a directory, `getStatsAndPerformCopy` will call `onDir` recursively
return getStatsAndPerformCopy(destStat, srcItem, destItem, opts)
})
}
})
)
}
await Promise.all(promises)
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 (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,67 @@
'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()) {
const [srcStat, dstStat] = await Promise.all([
fs.stat(srcpath),
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()) {
const 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,158 @@
'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) {
return destStat.ino && destStat.dev && 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.0",
"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": "https://github.com/jprichardson/node-fs-extra"
},
"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
}
+64
View File
@@ -0,0 +1,64 @@
{
"name": "office-addin-dev-certs",
"version": "2.0.3",
"description": "For managing certificates when developing Office Add-ins.",
"main": "./lib/main.js",
"scripts": {
"build": "rimraf lib && concurrently \"tsc -p tsconfig.json\"",
"cli": "node lib/cli.js",
"lint": "office-addin-lint check",
"lint:fix": "office-addin-lint fix",
"prettier": "office-addin-lint prettier",
"start": "rimraf lib && concurrently \"npm run watch\"",
"test": "mocha -r ts-node/register test/**/*.ts",
"watch": "tsc -p tsconfig.json -w"
},
"author": "Office Dev",
"license": "MIT",
"bin": {
"office-addin-dev-certs": "./cli.js"
},
"keywords": [
"Office",
"add-in",
"localhost",
"SSL",
"https",
"certificates",
"keys",
"cert",
"development",
"secure",
"server"
],
"dependencies": {
"commander": "^13.0.0",
"fs-extra": "^11.2.0",
"mkcert": "^3.2.0",
"office-addin-cli": "^2.0.3",
"office-addin-usage-data": "^2.0.3"
},
"devDependencies": {
"@types/fs-extra": "^11.0.4",
"@types/mkcert": "^1.2.2",
"@types/mocha": "^10.0.6",
"@types/node": "^14.17.2",
"@types/sinon": "^17.0.3",
"concurrently": "^9.0.0",
"mocha": "^11.0.0",
"office-addin-lint": "^3.0.3",
"rimraf": "^6.0.1",
"sinon": "^19.0.2",
"ts-node": "^10.9.1",
"typescript": "^4.7.4"
},
"repository": {
"type": "git",
"url": "https://github.com/OfficeDev/Office-Addin-Scripts"
},
"bugs": {
"url": "https://github.com/OfficeDev/Office-Addin-Scripts/issues"
},
"prettier": "office-addin-prettier-config",
"gitHead": "0a83e04842c872533d72b043ebc55e9a6013f34e"
}
+27
View File
@@ -0,0 +1,27 @@
if($args.Count -ne 2){
throw "Usage: install.ps1 <LocalMachine | CurrentUser> <CA-certificate-path>"
}
# Without this, the script always succeeds (exit code = 0)
$ErrorActionPreference = 'Stop'
$machine = $args[0]
$caCertificatePath=$args[1]
if(Get-Command -name Import-Certificate -ErrorAction SilentlyContinue){
if ($PSVersionTable.PSVersion.Major -le 5) {
# The following line is required in case pwsh is one of the parent callers
# because the changes it makes to PSModulePath are not backward compatible with Windows powershell.
$env:PSModulePath = [Environment]::GetEnvironmentVariable('PSModulePath', 'Machine')
}
Import-Certificate -CertStoreLocation cert:\\$machine\\Root ${caCertificatePath}
}
else{
# Legacy system support
$pfx = new-object System.Security.Cryptography.X509Certificates.X509Certificate2
$pfx.import($caCertificatePath)
$store = new-object System.Security.Cryptography.X509Certificates.X509Store("Root", $machine)
$store.open("MaxAllowed")
$store.add($pfx)
$store.close()
}
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
if [ -f "/usr/sbin/update-ca-certificates" ]; then
sudo mkdir -p /usr/local/share/ca-certificates/office-addin-dev-certs && sudo cp $1 /usr/local/share/ca-certificates/office-addin-dev-certs && sudo /usr/sbin/update-ca-certificates
elif [ -f "/usr/sbin/update-ca-trust" ]; then
sudo cp $1 /etc/ca-certificates/trust-source/anchors/office-addin-dev-certs-ca.crt && sudo /usr/sbin/update-ca-trust
fi
+27
View File
@@ -0,0 +1,27 @@
if($args.Count -ne 2){
throw "Usage: uninstall.ps1 <LocalMachine | CurrentUser> <CA-certficate-name>"
}
# Without this, the script always succeeds (exit code = 0)
$ErrorActionPreference = 'Stop'
$machine = $args[0]
$caCertificateName=$args[1]
if(Get-Command -name Import-Certificate -ErrorAction SilentlyContinue){
if ($PSVersionTable.PSVersion.Major -le 5) {
# The following line is required in case pwsh is one of the parent callers
# because the changes it makes to PSModulePath are not backward compatible with Windows powershell.
$env:PSModulePath = [Environment]::GetEnvironmentVariable('PSModulePath', 'Machine')
}
Get-ChildItem cert:\\$machine\\Root | Where-Object { $_.IssuerName.Name -like "*CN=$caCertificateName*" } | Remove-Item
}
else{
# Legacy system support
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("root", $machine)
$store.Open("MaxAllowed")
$certs = $store.Certificates.Find("FindBySubjectName", $caCertificateName, $false)
foreach ($cert in $certs){
$store.Remove($cert)
}
$store.close()
}
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
hashes=$(security find-certificate -c "$1" -a -Z | grep SHA-1 | awk '{ print $NF }')
for hash in $hashes; do
security delete-certificate -Z $hash
done
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
if [ -f "/usr/sbin/update-ca-certificates" ]; then
sudo rm -r /usr/local/share/ca-certificates/office-addin-dev-certs/$1 && sudo /usr/sbin/update-ca-certificates --fresh
elif [ -f "/usr/sbin/update-ca-trust" ]; then
sudo rm -r /etc/ca-certificates/trust-source/anchors/office-addin-dev-certs-ca.crt && sudo /usr/sbin/update-ca-trust
fi
+73
View File
@@ -0,0 +1,73 @@
Param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$CaCertificateName,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$CaCertificatePath,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$LocalhostCertificatePath,
[Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[string]
$OutputMarker,
[switch]
$ReturnInvalidCertificate
)
# An optional output marker that can be used to find the beginning of this script's output
if ($OutputMarker) {
Write-Output $OutputMarker
}
# Without this, the script always succeeds (exit code = 0)
$ErrorActionPreference = 'Stop'
if ($PSVersionTable.PSVersion.Major -le 5) {
# The following line is required in case pwsh is one of the parent callers
# because the changes it makes to PSModulePath are not backward compatible with Windows powershell.
$env:PSModulePath = [Environment]::GetEnvironmentVariable('PSModulePath', 'Machine')
}
if(Get-Command -name Import-Certificate -ErrorAction SilentlyContinue){
$result = Get-ChildItem cert:\\CurrentUser\\Root | Where-Object Issuer -like "*CN=$CaCertificateName*"
if (!$ReturnInvalidCertificate) {
$result = $result | Where-Object { $_.NotAfter -gt (Get-Date).AddDays(1) }
if ($result -and ($result.Length -eq 1) -and (Test-Path $CaCertificatePath) -and (Test-Path $LocalhostCertificatePath)) {
# Check that CA certificate in store is the same as ca.crt
$caCert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($CaCertificatePath)
$caThumbprint = $caCert.Thumbprint
$result = $result | Where-Object Thumbprint -eq $caThumbprint
if ($result) {
# Check that it matches the issuer of localhost.crt
$localhostCert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($LocalhostCertificatePath)
$localhostChain = [System.Security.Cryptography.X509Certificates.X509Chain]::new()
$localhostChain.Build($localhostCert) | Out-Null
$localhostTrustedIssuer = $localhostChain.ChainElements.Certificate | Where-Object { $_.Subject -eq $localhostCert.Issuer -and $_.Thumbprint -eq $caThumbprint }
if (!$localhostTrustedIssuer) {
$result = $null
}
}
}
else {
$result = $null
}
}
$result | Format-List
}
else{
# Legacy system support
Get-ChildItem cert:\\CurrentUser\\Root | Where-Object { $_.Subject -like "*CN=$CaCertificateName*"} | Where-Object { $_.NotAfter -gt (Get-Date).AddDays(1) } | Format-List
}
+14
View File
@@ -0,0 +1,14 @@
#!/bin/bash
certs=$(security find-certificate -a -c "$1" -p)
while read line; do
if [[ "$line" == *"--BEGIN"* ]]; then
cert=$line
else
cert="$cert"$'\n'"$line"
if [[ "$line" == *"--END"* ]]; then
if [ 0 -lt $(echo "$cert" | openssl x509 -checkend 86400 | grep -c "will not expire") ]; then
echo "$cert"
fi
fi
fi
done <<< "$certs"
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
if [ -f "/usr/sbin/update-ca-certificates" ]; then
echo [ -f /usr/local/share/ca-certificates/office-addin-dev-certs/$1 ] && openssl x509 -in /usr/local/share/ca-certificates/office-addin-dev-certs/$1 -checkend 86400 -noout
elif [ -f "/usr/sbin/update-ca-trust" ]; then
echo [ -f /etc/ca-certificates/trust-source/anchors/office-addin-dev-certs-ca.crt ] && openssl x509 -in /etc/ca-certificates/trust-source/anchors/office-addin-dev-certs-ca.crt -checkend 86400 -noout
fi