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
+5
View File
@@ -0,0 +1,5 @@
# Set the default behavior, in case people don't have core.autocrlf set.
* text=auto
# Declare files that will always have LF line endings on checkout.
cli.js text eol=lf
+11
View File
@@ -0,0 +1,11 @@
office-addin-start-debug v0.0.3
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.
+130
View File
@@ -0,0 +1,130 @@
# Office-Addin-Debugging
This package provides the orchestration of components related to debugging Office Add-ins. When debugging is started, it will ensure that the dev-server is running, that dev settings are configured for debugging, and will register and sideload the Office Add-in. When debugging is stopped, it will unregister and shutdown components.
## Command-Line Interface
* [start](#start)
* [stop](#stop)
#
## start
Starts debugging.
Syntax:
`office-addin-debugging start <manifest> [platform] [options]`
`manifest`: path to manifest file.
`platform`: which type of application:
* `desktop`: Office app for Windows or Mac
* `web`: Office app in the web browser
Notes:
* The dev server is needed to download the add-in from the source location specified in the manifest.
* `--packager` is needed unless `--debug-method` is `direct` and `--no-live-reload` is specified.
Options:
`--app <app`>
Specifies which Office app to use:
* `excel`
* `onenote`
* `outlook`
* `project`
* `powerpoint`
* `word`
If this is not specified, the behavior depends on the `<Hosts>` specified in the manifest.
For a single host, it will automatically start that Office app.
For multiple hosts, it will prompt to choose the desired host.
`--debug-method <method>`
Specifies which debug method to use:
* `direct`: debug directly using the JavaScript engine.
* `web`: debug using the JavaScript engine in a web browser or Node.
`--dev-server <command>`
Specifies to run the dev server using the specified command.
`--dev-server-port <port>`
Specifies the port for the dev server. If provided, the dev server is only started if not already running.
`--document`
Specifies the document to sideload. The document option can either be the local path to a document or a url.
` --no-debug`
Start without debugging.
` --no-live-reload`
Do not enable live-reload.
` --no-sideload`
Do not start the Office app and load the Office add-in.
` --packager <command>`
If this option is provided, the packager is started with the specified command.
` --packager-host <host>`
Host name of the packager. Default: `localhost`.
` --packager-port <port>`
Port number of the packager. Default: `8081`.
` --prod`
Specifies that debugging session is for production mode. Default is development mode.
` --source-bundle-url-host <host>`
Host name to obtain the source bundle. Default: `localhost`.
` --source-bundle-url-port <port>`
Port number to obtain the source bundle. Default: `8081`.
` --source-bundle-url-path <path>`
Path used to obtain the source bundle.
` --source-bundle-url-extension <extension>`
Extension used to obtain the source bundle. Default: `.bundle`.
`-h, --help`
Output usage information.
#
### stop
Stops debugging.
Syntax:
`office-addin-debugging stop <manifest> [options]`
`manifest`: path to manifest file.
Options:
` --prod`
Specifies that debugging session is for production mode. Default is development mode.
#
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");
+20
View File
@@ -0,0 +1,20 @@
import officeAddins from "eslint-plugin-office-addins";
import tsParser from "@typescript-eslint/parser";
import sdl from "@microsoft/eslint-plugin-sdl";
export default [
...officeAddins.configs.recommended,
...sdl.configs.recommended,
{
plugins: {
"office-addins": officeAddins,
},
languageOptions: {
parser: tsParser,
parserOptions: {
projectService: true,
tsconfigRootDir: "__dirname"
}
},
},
];
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env node
export {};
+72
View File
@@ -0,0 +1,72 @@
#!/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"));
/* global process */
const commander = new commander_1.Command();
commander.name("office-addin-debugging");
commander.version(process.env.npm_package_version || "(version not available)");
commander
.command("start <manifest-path> [platform]")
.option("--app <app>", "Specify which Office app to use.")
.option("--debug-method <method>", "The debug method to use.")
.option("--dev-server <command>", "Run the dev server.")
.option("--dev-server-port <port>", "Verify the dev server is running using this port.")
.option("--document <document>", "Document to be used for sideloading.")
.option("--no-debug", "Start without debugging.")
.option("--no-live-reload", "Do not enable live-reload.")
.option("--no-sideload", "Do not start the Office app and load the add-in.")
.option("--dev-tools", "Open the web browser developer tools when debugging (if supported).")
.option("--packager <command>", "Run the packager.")
.option("--packager-host <host>")
.option("--packager-port <port>")
.option("--prod", "Specifies that debugging session is for production mode. Default is dev mode.")
.option("--source-bundle-url-host <host>")
.option("--source-bundle-url-port <port>")
.option("--source-bundle-url-path <path>")
.option("--source-bundle-url-extension <extension>")
.action(commands.start);
commander
.command("stop <manifest-path> [platform]")
.option("--prod", "Specifies production mode.")
.action(commands.stop);
// 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;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,kCAAkC,CAAC;KAC3C,MAAM,CAAC,aAAa,EAAE,kCAAkC,CAAC;KACzD,MAAM,CAAC,yBAAyB,EAAE,0BAA0B,CAAC;KAC7D,MAAM,CAAC,wBAAwB,EAAE,qBAAqB,CAAC;KACvD,MAAM,CAAC,0BAA0B,EAAE,mDAAmD,CAAC;KACvF,MAAM,CAAC,uBAAuB,EAAE,sCAAsC,CAAC;KACvE,MAAM,CAAC,YAAY,EAAE,0BAA0B,CAAC;KAChD,MAAM,CAAC,kBAAkB,EAAE,4BAA4B,CAAC;KACxD,MAAM,CAAC,eAAe,EAAE,kDAAkD,CAAC;KAC3E,MAAM,CAAC,aAAa,EAAE,qEAAqE,CAAC;KAC5F,MAAM,CAAC,sBAAsB,EAAE,mBAAmB,CAAC;KACnD,MAAM,CAAC,wBAAwB,CAAC;KAChC,MAAM,CAAC,wBAAwB,CAAC;KAChC,MAAM,CAAC,QAAQ,EAAE,+EAA+E,CAAC;KACjG,MAAM,CAAC,iCAAiC,CAAC;KACzC,MAAM,CAAC,iCAAiC,CAAC;KACzC,MAAM,CAAC,iCAAiC,CAAC;KACzC,MAAM,CAAC,2CAA2C,CAAC;KACnD,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAE1B,SAAS;KACN,OAAO,CAAC,iCAAiC,CAAC;KAC1C,MAAM,CAAC,QAAQ,EAAE,4BAA4B,CAAC;KAC9C,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;AAEzB,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"}
+3
View File
@@ -0,0 +1,3 @@
import { OptionValues } from "commander";
export declare function start(manifestPath: string, platform: string | undefined, options: OptionValues): Promise<void>;
export declare function stop(manifestPath: string, platform: string | undefined, options: OptionValues): Promise<void>;
+151
View File
@@ -0,0 +1,151 @@
"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.stop = exports.start = void 0;
const fs_1 = __importDefault(require("fs"));
const office_addin_cli_1 = require("office-addin-cli");
const office_addin_usage_data_1 = require("office-addin-usage-data");
const devSettings = __importStar(require("office-addin-dev-settings"));
const office_addin_manifest_1 = require("office-addin-manifest");
const start_1 = require("./start");
const stop_1 = require("./stop");
const defaults_1 = require("./defaults");
const office_addin_usage_data_2 = require("office-addin-usage-data");
/* global process */
function determineManifestPath(platform, dev) {
let manifestPath = process.env.npm_package_config_manifest_location || "";
manifestPath = manifestPath
.replace("${flavor}", dev ? "dev" : "prod")
.replace("${platform}", platform);
if (!manifestPath) {
throw new office_addin_usage_data_2.ExpectedError(`The manifest path was not provided.`);
}
if (!fs_1.default.existsSync(manifestPath)) {
throw new office_addin_usage_data_2.ExpectedError(`The manifest path does not exist: ${manifestPath}.`);
}
return manifestPath;
}
function parseDevServerPort(optionValue) {
const devServerPort = (0, office_addin_cli_1.parseNumber)(optionValue, "--dev-server-port should specify a number.");
if (devServerPort !== undefined) {
if (!Number.isInteger(devServerPort)) {
throw new office_addin_usage_data_2.ExpectedError("--dev-server-port should be an integer.");
}
if (devServerPort < 0 || devServerPort > 65535) {
throw new office_addin_usage_data_2.ExpectedError("--dev-server-port should be between 0 and 65535.");
}
}
return devServerPort;
}
function start(manifestPath, platform, options) {
return __awaiter(this, void 0, void 0, function* () {
try {
const appPlatformToDebug = (0, start_1.parsePlatform)(platform || process.env.npm_package_config_app_platform_to_debug || start_1.Platform.Win32);
const appTypeToDebug = devSettings.parseAppType(appPlatformToDebug || process.env.npm_package_config_app_type_to_debug || start_1.AppType.Desktop);
const appToDebug = options.app || process.env.npm_package_config_app_to_debug;
const app = appToDebug ? (0, office_addin_manifest_1.parseOfficeApp)(appToDebug) : undefined;
const dev = options.prod ? false : true;
const debuggingMethod = (0, start_1.parseDebuggingMethod)(options.debugMethod);
const devServer = options.devServer || (yield (0, office_addin_cli_1.getPackageJsonScript)("dev-server"));
const devServerPort = parseDevServerPort(options.devServerPort || process.env.npm_package_config_dev_server_port);
const document = options.document || process.env.npm_package_config_document;
const enableDebugging = options.debug;
const enableLiveReload = options.liveReload === true;
const enableSideload = options.sideload !== false; // enable if true or undefined; only disable if false
const openDevTools = options.devTools === true;
const packager = options.packager || (yield (0, office_addin_cli_1.getPackageJsonScript)("packager"));
const packagerHost = options.PackagerHost || process.env.npm_package_config_packager_host;
const packagerPort = options.PackagerPort || process.env.npm_package_config_packager_port;
const sourceBundleUrlComponents = new devSettings.SourceBundleUrlComponents(options.sourceBundleUrlHost, options.sourceBundleUrlPort, options.sourceBundleUrlPath, options.sourceBundleUrlExtension);
if (appPlatformToDebug === undefined) {
throw new office_addin_usage_data_2.ExpectedError("Please specify the platform to debug.");
}
if (appTypeToDebug === undefined) {
throw new office_addin_usage_data_2.ExpectedError("Please specify the application type to debug.");
}
if (appPlatformToDebug === start_1.Platform.Android || appPlatformToDebug === start_1.Platform.iOS) {
throw new office_addin_usage_data_2.ExpectedError(`Platform type ${appPlatformToDebug} not currently supported for debugging`);
}
if (!manifestPath) {
manifestPath = determineManifestPath(appPlatformToDebug, dev);
}
yield (0, start_1.startDebugging)(manifestPath, {
appType: appTypeToDebug,
app,
debuggingMethod,
sourceBundleUrlComponents,
devServerCommandLine: devServer,
devServerPort,
packagerCommandLine: packager,
packagerHost,
packagerPort,
enableDebugging,
enableLiveReload,
enableSideload,
openDevTools,
document,
});
defaults_1.usageDataObject.reportSuccess("start");
}
catch (err) {
defaults_1.usageDataObject.reportException("start", err);
(0, office_addin_usage_data_1.logErrorMessage)(`Unable to start debugging.\n${err}`);
}
});
}
exports.start = start;
function stop(manifestPath, platform, options) {
return __awaiter(this, void 0, void 0, function* () {
try {
const appPlatformToDebug = (0, start_1.parsePlatform)(platform || process.env.npm_package_config_app_plaform_to_debug || start_1.Platform.Win32);
const dev = options.prod ? false : true;
if (manifestPath === "" && appPlatformToDebug !== undefined) {
manifestPath = determineManifestPath(appPlatformToDebug, dev);
}
yield (0, stop_1.stopDebugging)(manifestPath);
defaults_1.usageDataObject.reportSuccess("stop");
}
catch (err) {
defaults_1.usageDataObject.reportException("stop", err);
(0, office_addin_usage_data_1.logErrorMessage)(`Unable to stop debugging.\n${err}`);
}
});
}
exports.stop = stop;
//# 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,4CAAoB;AACpB,uDAAqE;AACrE,qEAA0D;AAC1D,uEAAyD;AACzD,iEAAkE;AAClE,mCAAiG;AACj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AAC;CAAA;AAjFD,sBAiFC;AAED,SAAsB,IAAI,CACxB,YAAoB,EACpB,QAA4B,EAC5B,OAAqB;;QAErB,IAAI;YACF,MAAM,kBAAkB,GAAyB,IAAA,qBAAa,EAC5D,QAAQ,IAAI,OAAO,CAAC,GAAG,CAAC,uCAAuC,IAAI,gBAAQ,CAAC,KAAK,CAClF,CAAC;YACF,MAAM,GAAG,GAAY,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;YAEjD,IAAI,YAAY,KAAK,EAAE,IAAI,kBAAkB,KAAK,SAAS,EAAE;gBAC3D,YAAY,GAAG,qBAAqB,CAAC,kBAAkB,EAAE,GAAG,CAAC,CAAC;aAC/D;YAED,MAAM,IAAA,oBAAa,EAAC,YAAY,CAAC,CAAC;YAClC,0BAAe,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;SACvC;QAAC,OAAO,GAAQ,EAAE;YACjB,0BAAe,CAAC,eAAe,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;YAC7C,IAAA,yCAAe,EAAC,8BAA8B,GAAG,EAAE,CAAC,CAAC;SACtD;IACH,CAAC;CAAA;AArBD,oBAqBC"}
+22
View File
@@ -0,0 +1,22 @@
export interface IDebuggingInfo {
devServer: IDevServerInfo;
}
export interface IDevServerInfo {
processId: number | undefined;
}
export declare function getDebuggingInfoPath(): string;
/**
* Saves the process id of the dev server
* @param id process id
*/
export declare function saveDevServerProcessId(id: number): Promise<void>;
/**
* Read the process id from either the environment variable or
* from the json file containing the debug info
*/
export declare function readDevServerProcessId(): number | undefined;
/**
* Deletes the environment variable containing process id
* and deletes the debug info json file if it exists
*/
export declare function clearDevServerProcessId(): void;
+109
View File
@@ -0,0 +1,109 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
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.clearDevServerProcessId = exports.readDevServerProcessId = exports.saveDevServerProcessId = exports.getDebuggingInfoPath = void 0;
const fs_1 = __importDefault(require("fs"));
const office_addin_cli_1 = require("office-addin-cli");
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
/* global process */
const processIdFile = "office-addin-debugging.json";
const processIdFilePath = path_1.default.join(os_1.default.tmpdir(), processIdFile);
function getDebuggingInfoPath() {
return processIdFilePath;
}
exports.getDebuggingInfoPath = getDebuggingInfoPath;
/**
* Creates the DebuggingInfo object
*/
function createDebuggingInfo() {
const devServer = {
processId: undefined,
};
const debuggingInfo = {
devServer,
};
return debuggingInfo;
}
/**
* Set the process id of the dev server in the Debugging object
* @param debuggingInfo DebuggingInfo object
* @param id dev server process id
*/
function setDevServerProcessId(debuggingInfo, id) {
debuggingInfo.devServer.processId = id;
}
/**
* Write the DebuggingInfo to the json file
* @param debuggingInfo DebuggingInfo object
* @param pathToFile Path to the json file containing debug info
*/
function writeDebuggingInfo(debuggingInfo, pathToFile) {
const debuggingInfoJSON = JSON.stringify(debuggingInfo, null, 4);
fs_1.default.writeFileSync(pathToFile, debuggingInfoJSON);
}
/**
* Read the DebuggingInfo object
* @param pathToFile Path to the json file containing debug info
*/
function readDebuggingInfo(pathToFile) {
const json = fs_1.default.readFileSync(pathToFile);
return JSON.parse(json.toString());
}
/**
* Saves the process id of the dev server
* @param id process id
*/
function saveDevServerProcessId(id) {
return __awaiter(this, void 0, void 0, function* () {
process.env.OfficeAddinDevServerProcessId = id.toString();
const debuggingInfo = createDebuggingInfo();
setDevServerProcessId(debuggingInfo, id);
writeDebuggingInfo(debuggingInfo, processIdFilePath);
});
}
exports.saveDevServerProcessId = saveDevServerProcessId;
/**
* Read the process id from either the environment variable or
* from the json file containing the debug info
*/
function readDevServerProcessId() {
let id;
if (process.env.OfficeAddinDevServerProcessId) {
id = (0, office_addin_cli_1.parseNumber)(process.env.OfficeAddinDevServerProcessId);
}
else if (fs_1.default.existsSync(processIdFilePath)) {
const devServerProperties = readDebuggingInfo(processIdFilePath);
if (devServerProperties.devServer && devServerProperties.devServer.processId) {
const pid = devServerProperties.devServer.processId;
id = (0, office_addin_cli_1.parseNumber)(pid.toString(), `Invalid process id found in ${processIdFilePath}`);
}
}
return id;
}
exports.readDevServerProcessId = readDevServerProcessId;
/**
* Deletes the environment variable containing process id
* and deletes the debug info json file if it exists
*/
function clearDevServerProcessId() {
if (fs_1.default.existsSync(processIdFilePath)) {
fs_1.default.unlinkSync(processIdFilePath);
}
delete process.env.OfficeAddinDevServerProcessId;
}
exports.clearDevServerProcessId = clearDevServerProcessId;
//# sourceMappingURL=debugInfo.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"debugInfo.js","sourceRoot":"","sources":["../src/debugInfo.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;;;;;;;;;;;;AAElC,4CAAoB;AACpB,uDAA+C;AAC/C,4CAAoB;AACpB,gDAAwB;AAExB,oBAAoB;AAEpB,MAAM,aAAa,GAAG,6BAA6B,CAAC;AACpD,MAAM,iBAAiB,GAAG,cAAI,CAAC,IAAI,CAAC,YAAE,CAAC,MAAM,EAAE,EAAE,aAAa,CAAC,CAAC;AAUhE,SAAgB,oBAAoB;IAClC,OAAO,iBAAiB,CAAC;AAC3B,CAAC;AAFD,oDAEC;AAED;;GAEG;AACH,SAAS,mBAAmB;IAC1B,MAAM,SAAS,GAAmB;QAChC,SAAS,EAAE,SAAS;KACrB,CAAC;I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iBAAiB,CAAC,CAAC;QACjE,IAAI,mBAAmB,CAAC,SAAS,IAAI,mBAAmB,CAAC,SAAS,CAAC,SAAS,EAAE;YAC5E,MAAM,GAAG,GAAG,mBAAmB,CAAC,SAAS,CAAC,SAAS,CAAC;YACpD,EAAE,GAAG,IAAA,8BAAW,EAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,+BAA+B,iBAAiB,EAAE,CAAC,CAAC;SACtF;KACF;IACD,OAAO,EAAE,CAAC;AACZ,CAAC;AAZD,wDAYC;AAED;;;GAGG;AACH,SAAgB,uBAAuB;IACrC,IAAI,YAAE,CAAC,UAAU,CAAC,iBAAiB,CAAC,EAAE;QACpC,YAAE,CAAC,UAAU,CAAC,iBAAiB,CAAC,CAAC;KAClC;IACD,OAAO,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC;AACnD,CAAC;AALD,0DAKC"}
+2
View File
@@ -0,0 +1,2 @@
import { OfficeAddinUsageData } from "office-addin-usage-data";
export declare const usageDataObject: OfficeAddinUsageData;
+13
View File
@@ -0,0 +1,13 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.usageDataObject = void 0;
const office_addin_usage_data_1 = require("office-addin-usage-data");
// Usage data defaults
exports.usageDataObject = new office_addin_usage_data_1.OfficeAddinUsageData({
projectName: "office-addin-debugging",
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,qEAGiC;AAEjC,sBAAsB;AACT,QAAA,eAAe,GAAyB,IAAI,8CAAoB,CAAC;IAC5E,WAAW,EAAE,wBAAwB;IACrC,kBAAkB,EAAE,kEAAwC;IAC5D,WAAW,EAAE,KAAK;CACnB,CAAC,CAAC"}
+4
View File
@@ -0,0 +1,4 @@
export * from "./port";
export * from "./process";
export * from "./start";
export * from "./stop";
+23
View File
@@ -0,0 +1,23 @@
"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("./port"), exports);
__exportStar(require("./process"), exports);
__exportStar(require("./start"), exports);
__exportStar(require("./stop"), 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,yCAAuB;AACvB,4CAA0B;AAC1B,0CAAwB;AACxB,yCAAuB"}
+17
View File
@@ -0,0 +1,17 @@
/**
* Determines whether a port is in use.
* @param port port number (0 - 65535)
* @returns true if port is in use; false otherwise.
*/
export declare function isPortInUse(port: number): Promise<boolean>;
/**
* Return the process ids using the port.
* @param port port number (0 - 65535)
* @returns Promise to array containing process ids, or empty if none.
*/
export declare function getProcessIdsForPort(port: number): Promise<number[]>;
/**
* Returns a random port number which is not in use.
* @returns Promise to number from 0 to 65535
*/
export declare function randomPortNotInUse(): Promise<number>;
+163
View File
@@ -0,0 +1,163 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
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.randomPortNotInUse = exports.getProcessIdsForPort = exports.isPortInUse = void 0;
const child_process_1 = __importDefault(require("child_process"));
const crypto_1 = __importDefault(require("crypto"));
const net_1 = __importDefault(require("net"));
const office_addin_usage_data_1 = require("office-addin-usage-data");
/* global process */
/**
* Determines whether a port is in use.
* @param port port number (0 - 65535)
* @returns true if port is in use; false otherwise.
*/
function isPortInUse(port) {
validatePort(port);
return new Promise((resolve) => {
const server = net_1.default
.createServer()
.once("error", () => {
resolve(true);
})
.once("listening", () => {
server.close();
resolve(false);
})
.listen(port);
});
}
exports.isPortInUse = isPortInUse;
/**
* Parse the port from a string which ends with colon and a number.
* @param text string to parse
* @example "127.0.0.1:3000" returns 3000
* @example "[::1]:1900" returns 1900
* @example "Local Address" returns undefined
*/
function parsePort(text) {
const result = text.match(/:(\d+)$/);
return result ? parseInt(result[1], 10) : undefined;
}
/**
* Return the process ids using the port.
* @param port port number (0 - 65535)
* @returns Promise to array containing process ids, or empty if none.
*/
function getProcessIdsForPort(port) {
validatePort(port);
return new Promise((resolve, reject) => {
const isWin32 = process.platform === "win32";
const isLinux = process.platform === "linux";
const command = isWin32
? `netstat -ano | findstr :${port}`
: isLinux
? `netstat -tlpna | grep :${port}`
: `lsof -n -i:${port}`;
child_process_1.default.exec(command, (error, stdout) => {
if (error) {
if (error.code === 1) {
// no processes are using the port
resolve([]);
}
else {
reject(error);
}
}
else {
const processIds = new Set();
const lines = stdout.trim().split("\n");
if (isWin32) {
lines.forEach((line) => {
/* eslint-disable-next-line @typescript-eslint/no-unused-vars */
const [protocol, localAddress, foreignAddress, status, processId] = line
.trim()
.split(" ")
.filter((text) => text);
if (processId !== undefined && processId.trim() !== "0") {
const localAddressPort = parsePort(localAddress);
if (localAddressPort === port) {
processIds.add(parseInt(processId, 10));
}
}
});
}
else if (isLinux) {
lines.forEach((line) => {
/* eslint-disable-next-line @typescript-eslint/no-unused-vars */
const [proto, recv, send, local_address, remote_address, state, program] = line
.trim()
.split(" ")
.filter((text) => text);
if (local_address !== undefined &&
local_address.endsWith(`:${port}`) &&
program !== undefined) {
const pid = parseInt(program, 10);
if (!isNaN(pid)) {
processIds.add(pid);
}
}
});
}
else {
lines.forEach((line) => {
/* eslint-disable-next-line @typescript-eslint/no-unused-vars */
const [process, processId, user, fd, type, device, size, node, name] = line
.trim()
.split(" ")
.filter((text) => text);
if (processId !== undefined && processId !== "PID") {
processIds.add(parseInt(processId, 10));
}
});
}
resolve(Array.from(processIds));
}
});
});
}
exports.getProcessIdsForPort = getProcessIdsForPort;
/**
* Returns a random port number which is not in use.
* @returns Promise to number from 0 to 65535
*/
function randomPortNotInUse() {
return __awaiter(this, void 0, void 0, function* () {
let port;
do {
port = randomPortNumber();
} while (yield isPortInUse(port));
return port;
});
}
exports.randomPortNotInUse = randomPortNotInUse;
/**
* Returns a random number between 0 and 65535
*/
function randomPortNumber() {
return crypto_1.default.randomBytes(2).readUInt16LE(0);
}
/**
* Throw an error if the port is not a valid number.
* @param port port number
* @throws Error if port is not a number from 0 to 65535.
*/
function validatePort(port) {
if (typeof port !== "number" || port < 0 || port > 65535) {
throw new office_addin_usage_data_1.ExpectedError("Port should be a number from 0 to 65535.");
}
}
//# sourceMappingURL=port.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"port.js","sourceRoot":"","sources":["../src/port.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kC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AAI,GAAG,gBAAgB,EAAE,CAAC;SAC3B,QAAQ,MAAM,WAAW,CAAC,IAAI,CAAC,EAAE;QAElC,OAAO,IAAI,CAAC;IACd,CAAC;CAAA;AAPD,gDAOC;AAED;;GAEG;AACH,SAAS,gBAAgB;IACvB,OAAO,gBAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;AAC/C,CAAC;AAED;;;;GAIG;AACH,SAAS,YAAY,CAAC,IAAY;IAChC,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,GAAG,CAAC,IAAI,IAAI,GAAG,KAAK,EAAE;QACxD,MAAM,IAAI,uCAAa,CAAC,0CAA0C,CAAC,CAAC;KACrE;AACH,CAAC"}
+5
View File
@@ -0,0 +1,5 @@
/// <reference types="node" />
import { ChildProcess } from "child_process";
export declare function startProcess(commandLine: string, verbose?: boolean): Promise<void>;
export declare function startDetachedProcess(commandLine: string, verbose?: boolean): ChildProcess;
export declare function stopProcess(processId: number): void;
+53
View File
@@ -0,0 +1,53 @@
"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.stopProcess = exports.startDetachedProcess = exports.startProcess = void 0;
const devSettings = __importStar(require("office-addin-dev-settings"));
function startProcess(commandLine, verbose = false) {
return __awaiter(this, void 0, void 0, function* () {
yield devSettings.startProcess(commandLine, verbose);
});
}
exports.startProcess = startProcess;
function startDetachedProcess(commandLine, verbose = false) {
return devSettings.startDetachedProcess(commandLine, verbose);
}
exports.startDetachedProcess = startDetachedProcess;
function stopProcess(processId) {
devSettings.stopProcess(processId);
}
exports.stopProcess = stopProcess;
//# sourceMappingURL=process.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"process.js","sourceRoot":"","sources":["../src/process.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGlC,uEAAyD;AAEzD,SAAsB,YAAY,CAAC,WAAmB,EAAE,UAAmB,KAAK;;QAC9E,MAAM,WAAW,CAAC,YAAY,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;IACvD,CAAC;CAAA;AAFD,oCAEC;AAED,SAAgB,oBAAoB,CAAC,WAAmB,EAAE,UAAmB,KAAK;IAChF,OAAO,WAAW,CAAC,oBAAoB,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;AAChE,CAAC;AAFD,oDAEC;AAED,SAAgB,WAAW,CAAC,SAAiB;IAC3C,WAAW,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC;AACrC,CAAC;AAFD,kCAEC"}
+94
View File
@@ -0,0 +1,94 @@
import * as devSettings from "office-addin-dev-settings";
import { DebuggingMethod } from "office-addin-dev-settings";
import { OfficeApp } from "office-addin-manifest";
export declare enum AppType {
Desktop = "desktop",
Web = "web"
}
export declare enum Platform {
Android = "android",
Desktop = "desktop",
iOS = "ios",
MacOS = "macos",
Win32 = "win32",
Web = "web"
}
export declare function isDevServerRunning(port: number): Promise<boolean>;
export declare function isPackagerRunning(statusUrl: string): Promise<boolean>;
export declare function parseDebuggingMethod(text: string): DebuggingMethod | undefined;
export declare function parsePlatform(text: string): Platform | undefined;
export declare function runDevServer(commandLine: string, port?: number): Promise<void>;
export declare function runNodeDebugger(host?: string, port?: string): Promise<void>;
export declare function runPackager(commandLine: string, host?: string, port?: string): Promise<void>;
/**
* `startDebugging` options.
*/
export interface StartDebuggingOptions {
/**
* The type of application to debug.
*/
appType: AppType;
/**
* The Office application to debug.
* If unspecified and there is more than one application in the manifest will prompt to specify the application.
*/
app?: OfficeApp;
/**
* The method to use when debugging.
*/
debuggingMethod?: DebuggingMethod;
/**
* Specify components of the source bundle url.
*/
sourceBundleUrlComponents?: devSettings.SourceBundleUrlComponents;
/**
* If provided, starts the dev server.
*/
devServerCommandLine?: string;
/**
* If provided, port to verify that the dev server is running.
*/
devServerPort?: number;
/**
* If provided, starts the packager.
*/
packagerCommandLine?: string;
/**
* Specifies the host name of the packager.
*/
packagerHost?: string;
/**
* Specifies the port of the packager.
*/
packagerPort?: string;
/**
* Enable debugging.
* Starts with debugging if true or undefined.
*/
enableDebugging?: boolean;
/**
* Enable live reload.
*/
enableLiveReload?: boolean;
/**
* Enables launch of the Office host app and sideload of the add-in (if true or undefined).
* Set to false to disable sideload.
*/
enableSideload?: boolean;
/**
* Open Dev Tools.
*/
openDevTools?: boolean;
/**
* If provided, the document to open for sideloading to web.
*/
document?: string;
}
/**
* Start debugging
* @param options startDebugging options.
*/
export declare function startDebugging(manifestPath: string, options: StartDebuggingOptions): Promise<void>;
export declare function waitUntil(callback: () => Promise<boolean>, retryCount: number, retryDelay: number): Promise<boolean>;
export declare function waitUntilDevServerIsRunning(port: number, retryCount?: number, retryDelay?: number): Promise<boolean>;
export declare function waitUntilPackagerIsRunning(statusUrl: string, retryCount?: number, retryDelay?: number): Promise<boolean>;
+385
View File
@@ -0,0 +1,385 @@
"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.waitUntilPackagerIsRunning = exports.waitUntilDevServerIsRunning = exports.waitUntil = exports.startDebugging = exports.runPackager = exports.runNodeDebugger = exports.runDevServer = exports.parsePlatform = exports.parseDebuggingMethod = exports.isPackagerRunning = exports.isDevServerRunning = exports.Platform = exports.AppType = void 0;
const adm_zip_1 = __importDefault(require("adm-zip"));
const node_fetch_1 = __importDefault(require("node-fetch"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const devCerts = __importStar(require("office-addin-dev-certs"));
const devSettings = __importStar(require("office-addin-dev-settings"));
const os_1 = __importDefault(require("os"));
const office_addin_dev_settings_1 = require("office-addin-dev-settings");
const office_addin_manifest_1 = require("office-addin-manifest");
const nodeDebugger = __importStar(require("office-addin-node-debugger"));
const debugInfo = __importStar(require("./debugInfo"));
const port_1 = require("./port");
const process_1 = require("./process");
const defaults_1 = require("./defaults");
const office_addin_usage_data_1 = require("office-addin-usage-data");
/* global console process setTimeout */
var AppType;
(function (AppType) {
AppType["Desktop"] = "desktop";
AppType["Web"] = "web";
})(AppType = exports.AppType || (exports.AppType = {}));
var Platform;
(function (Platform) {
Platform["Android"] = "android";
Platform["Desktop"] = "desktop";
Platform["iOS"] = "ios";
Platform["MacOS"] = "macos";
Platform["Win32"] = "win32";
Platform["Web"] = "web";
})(Platform = exports.Platform || (exports.Platform = {}));
function defaultDebuggingMethod() {
return office_addin_dev_settings_1.DebuggingMethod.Direct;
}
function delay(milliseconds) {
return new Promise((resolve) => {
setTimeout(resolve, milliseconds);
});
}
function isDevServerRunning(port) {
return __awaiter(this, void 0, void 0, function* () {
// isPortInUse(port) will return false when webpack-dev-server is running.
// it should be fixed, but for now, use getProcessIdsForPort(port)
const processIds = yield (0, port_1.getProcessIdsForPort)(port);
const isRunning = processIds.length > 0;
return isRunning;
});
}
exports.isDevServerRunning = isDevServerRunning;
function isPackagerRunning(statusUrl) {
return __awaiter(this, void 0, void 0, function* () {
const statusRunningResponse = `packager-status:running`;
try {
const response = yield node_fetch_1.default.default(statusUrl);
console.log(`packager: ${response.status} ${response.statusText}`);
const text = yield response.text();
console.log(`packager: ${text}`);
return statusRunningResponse === text;
}
catch (_a) {
return false;
}
});
}
exports.isPackagerRunning = isPackagerRunning;
function parseDebuggingMethod(text) {
switch (text) {
case "direct":
return office_addin_dev_settings_1.DebuggingMethod.Direct;
case "proxy":
return office_addin_dev_settings_1.DebuggingMethod.Proxy;
default:
return undefined;
}
}
exports.parseDebuggingMethod = parseDebuggingMethod;
function parsePlatform(text) {
if (text === AppType.Desktop) {
text = process.platform;
}
switch (text) {
case "android":
return Platform.Android;
case "darwin":
return Platform.MacOS;
case "ios":
return Platform.iOS;
case "macos":
return Platform.MacOS;
case "web":
return Platform.Web;
case "win32":
return Platform.Win32;
default:
throw new office_addin_usage_data_1.ExpectedError(`The current platform is not supported: ${text}`);
}
}
exports.parsePlatform = parsePlatform;
function runDevServer(commandLine, port) {
return __awaiter(this, void 0, void 0, function* () {
if (commandLine) {
// if the dev server is running
if (port !== undefined && (yield isDevServerRunning(port))) {
console.log(`The dev server is already running on port ${port}.`);
}
else {
// On non-Windows platforms, prompt for installing the dev certs before starting the dev server.
// This is a workaround for the fact that the detached process does not show a window on Mac,
// therefore the user cannot enter the password when prompted.
if (process.platform !== "win32") {
if (!devCerts.verifyCertificates()) {
yield devCerts.ensureCertificatesAreInstalled();
}
}
// start the dev server
console.log(`Starting the dev server... (${commandLine})`);
const devServerProcess = (0, process_1.startDetachedProcess)(commandLine);
yield debugInfo.saveDevServerProcessId(devServerProcess.pid);
if (port !== undefined) {
// wait until the dev server is running
const isRunning = yield waitUntilDevServerIsRunning(port);
if (isRunning) {
console.log(`The dev server is running on port ${port}. Process id: ${devServerProcess.pid}`);
}
else {
throw new Error(`The dev server is not running on port ${port}.`);
}
}
}
}
});
}
exports.runDevServer = runDevServer;
function runNodeDebugger(host, port) {
return __awaiter(this, void 0, void 0, function* () {
nodeDebugger.run(host, port);
console.log("The node debugger is running.");
});
}
exports.runNodeDebugger = runNodeDebugger;
function runPackager(commandLine, host = "localhost", port = "8081") {
return __awaiter(this, void 0, void 0, function* () {
if (commandLine) {
// eslint-disable-next-line @microsoft/sdl/no-insecure-url
const packagerUrl = `http://${host}:${port}`;
const statusUrl = `${packagerUrl}/status`;
// if the packager is running
if (yield isPackagerRunning(statusUrl)) {
console.log(`The packager is already running. ${packagerUrl}`);
}
else {
// start the packager
console.log(`Starting the packager... (${commandLine})`);
yield (0, process_1.startDetachedProcess)(commandLine);
// wait until the packager is running
if (yield waitUntilPackagerIsRunning(statusUrl)) {
console.log(`The packager is running. ${packagerUrl}`);
}
else {
throw new Error(`The packager is not running. ${packagerUrl}`);
}
}
}
});
}
exports.runPackager = runPackager;
/**
* Start debugging
* @param options startDebugging options.
*/
function startDebugging(manifestPath, options) {
var _a, _b, _c;
return __awaiter(this, void 0, void 0, function* () {
const { appType, app, debuggingMethod, sourceBundleUrlComponents, devServerCommandLine, devServerPort, packagerCommandLine, packagerHost, packagerPort, enableDebugging, enableLiveReload, enableSideload, openDevTools, document, } = Object.assign(Object.assign({}, options), {
// Defaults when variable is undefined.
debuggingMethod: options.debuggingMethod || defaultDebuggingMethod(), enableDebugging: (_a = options.enableDebugging) !== null && _a !== void 0 ? _a : true, enableSideload: (_b = options.enableSideload) !== null && _b !== void 0 ? _b : true, enableLiveReload: (_c = options.enableLiveReload) !== null && _c !== void 0 ? _c : true });
try {
if (appType === undefined) {
throw new office_addin_usage_data_1.ExpectedError("Please specify the application type to debug.");
}
const isWindowsPlatform = process.platform === "win32";
const isDesktopAppType = appType === AppType.Desktop;
const isProxyDebuggingMethod = debuggingMethod === office_addin_dev_settings_1.DebuggingMethod.Proxy;
// live reload can only be enabled for the desktop app type
// when using proxy debugging and the packager
const canEnableLiveReload = isDesktopAppType && isProxyDebuggingMethod && !!packagerCommandLine;
// only use live reload if enabled and it can be enabled
const useLiveReload = enableLiveReload && canEnableLiveReload;
console.log(enableDebugging ? "Debugging is being started..." : "Starting without debugging...");
console.log(`App type: ${appType}`);
if (manifestPath.endsWith(".zip")) {
manifestPath = yield extractManifest(manifestPath);
}
const manifestInfo = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(manifestPath);
if (!manifestInfo.id) {
throw new office_addin_usage_data_1.ExpectedError("Manifest does not contain the id for the Office Add-in.");
}
// enable loopback for Edge
if (isWindowsPlatform && parseInt(os_1.default.release(), 10) === 10) {
const name = isDesktopAppType ? "EdgeWebView" : "EdgeWebBrowser";
try {
yield devSettings.ensureLoopbackIsEnabled(name);
}
catch (err) {
// if add loopback exemption failed, report the error then continue
console.error(err);
console.warn("Failed to add loopback exemption.\nWill try to sideload the Office Add-in without the loopback exemption, but it might not load correctly from localhost.\n");
defaults_1.usageDataObject.reportException("startDebugging()", err, {
app: app,
document: document,
appType: appType,
});
}
}
// enable debugging
if (isDesktopAppType && isWindowsPlatform) {
yield devSettings.enableDebugging(manifestInfo.id, enableDebugging, debuggingMethod, openDevTools);
if (enableDebugging) {
console.log(`Enabled debugging for add-in ${manifestInfo.id}.`);
}
}
// enable runtimelogging
if (isDesktopAppType && isWindowsPlatform) {
const path = yield devSettings.getRuntimeLoggingPath();
if (path) {
console.log(`Runtime logging is enabled. File: ${path}`);
}
else {
console.log("Enabling runtime logging..");
yield devSettings.enableRuntimeLogging(path);
const logPath = yield devSettings.getRuntimeLoggingPath();
console.log(`Runtime logging has been enabled. File: ${logPath}`);
}
}
// enable live reload
if (isDesktopAppType && isWindowsPlatform) {
yield devSettings.enableLiveReload(manifestInfo.id, useLiveReload);
if (useLiveReload) {
console.log(`Enabled live-reload for add-in ${manifestInfo.id}.`);
}
}
// set source bundle url
if (isDesktopAppType && isWindowsPlatform) {
if (sourceBundleUrlComponents) {
yield devSettings.setSourceBundleUrl(manifestInfo.id, sourceBundleUrlComponents);
}
}
// Run packager and dev server at the same time and wait for them to complete.
let packagerPromise;
let devServerPromise;
if (packagerCommandLine && isProxyDebuggingMethod && isDesktopAppType) {
packagerPromise = runPackager(packagerCommandLine, packagerHost, packagerPort);
}
if (devServerCommandLine) {
devServerPromise = runDevServer(devServerCommandLine, devServerPort);
}
if (packagerPromise !== undefined) {
try {
yield packagerPromise;
}
catch (err) {
console.log(`Unable to start the packager. ${err}`);
}
}
if (devServerPromise !== undefined) {
try {
yield devServerPromise;
}
catch (err) {
console.log(`Unable to start the dev server. ${err}`);
}
}
if (enableDebugging && isProxyDebuggingMethod && isDesktopAppType) {
try {
yield runNodeDebugger();
}
catch (err) {
console.log(`Unable to start the node debugger. ${err}`);
}
}
if (enableSideload) {
try {
console.log(`Sideloading the Office Add-in...`);
yield (0, office_addin_dev_settings_1.sideloadAddIn)(manifestPath, app, true, appType, document);
}
catch (err) {
throw new Error(`Unable to sideload the Office Add-in. \n${err}`);
}
}
console.log(enableDebugging ? "Debugging started." : "Started.");
defaults_1.usageDataObject.reportSuccess("startDebugging()", {
app: app,
document: document,
appType: appType,
});
}
catch (err) {
defaults_1.usageDataObject.reportException("startDebugging()", err, {
app: app,
document: document,
appType: appType,
});
throw err;
}
});
}
exports.startDebugging = startDebugging;
function waitUntil(callback, retryCount, retryDelay) {
return __awaiter(this, void 0, void 0, function* () {
let done = yield callback();
while (!done && retryCount) {
--retryCount;
yield delay(retryDelay);
done = yield callback();
}
return done;
});
}
exports.waitUntil = waitUntil;
function waitUntilDevServerIsRunning(port, retryCount = 30, retryDelay = 1000) {
return __awaiter(this, void 0, void 0, function* () {
return waitUntil(() => __awaiter(this, void 0, void 0, function* () { return yield isDevServerRunning(port); }), retryCount, retryDelay);
});
}
exports.waitUntilDevServerIsRunning = waitUntilDevServerIsRunning;
function waitUntilPackagerIsRunning(statusUrl, retryCount = 30, retryDelay = 1000) {
return __awaiter(this, void 0, void 0, function* () {
return waitUntil(() => __awaiter(this, void 0, void 0, function* () { return yield isPackagerRunning(statusUrl); }), retryCount, retryDelay);
});
}
exports.waitUntilPackagerIsRunning = waitUntilPackagerIsRunning;
function extractManifest(zipPath) {
return __awaiter(this, void 0, void 0, function* () {
const targetPath = path_1.default.join(process.env.TEMP, "addinManifest");
const zip = new adm_zip_1.default(zipPath); // reading archives
zip.extractAllTo(targetPath, true); // overwrite
const manifestPath = path_1.default.join(targetPath, "manifest.json");
if (fs_1.default.existsSync(manifestPath)) {
return manifestPath;
}
else {
throw new Error(`The zip file '${zipPath}' does not contain a "manifest.json" file`);
}
});
}
//# sourceMappingURL=start.js.map
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
export declare function stopDebugging(manifestPath: string): Promise<void>;
+81
View File
@@ -0,0 +1,81 @@
"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.stopDebugging = void 0;
const office_addin_dev_settings_1 = require("office-addin-dev-settings");
const office_addin_manifest_1 = require("office-addin-manifest");
const debugInfo = __importStar(require("./debugInfo"));
const process_1 = require("./process");
const defaults_1 = require("./defaults");
const office_addin_usage_data_1 = require("office-addin-usage-data");
/* global console process */
function stopDebugging(manifestPath) {
return __awaiter(this, void 0, void 0, function* () {
try {
console.log("Debugging is being stopped...");
const isWindowsPlatform = process.platform === "win32";
const manifestInfo = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(manifestPath);
if (!manifestInfo.id) {
throw new office_addin_usage_data_1.ExpectedError("Manifest does not contain the id for the Office Add-in.");
}
// clear dev settings
if (isWindowsPlatform) {
yield (0, office_addin_dev_settings_1.clearDevSettings)(manifestInfo.id);
}
// unregister
try {
yield (0, office_addin_dev_settings_1.unregisterAddIn)(manifestPath);
}
catch (err) {
console.log(`Unable to unregister the Office Add-in. ${err}`);
}
const processId = debugInfo.readDevServerProcessId();
if (processId) {
(0, process_1.stopProcess)(processId);
console.log(`Stopped dev server. Process id: ${processId}`);
debugInfo.clearDevServerProcessId();
}
console.log("Debugging has been stopped.");
defaults_1.usageDataObject.reportSuccess("stopDebugging()");
}
catch (err) {
defaults_1.usageDataObject.reportException("stopDebugging()", err);
throw err;
}
});
}
exports.stopDebugging = stopDebugging;
//# sourceMappingURL=stop.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"stop.js","sourceRoot":"","sources":["../src/stop.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAElC,yEAA8E;AAC9E,iEAA4D;AAC5D,uDAAyC;AACzC,uCAAwC;AACxC,yCAA6C;AAC7C,qEAAwD;AAExD,4BAA4B;AAE5B,SAAsB,aAAa,CAAC,YAAoB;;QACtD,IAAI;YACF,OAAO,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAC;YAE7C,MAAM,iBAAiB,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC;YACvD,MAAM,YAAY,GAAG,MAAM,2CAAmB,CAAC,gBAAgB,CAAC,YAAY,CAAC,CAAC;YAE9E,IAAI,CAAC,YAAY,CAAC,EAAE,EAAE;gBACpB,MAAM,IAAI,uCAAa,CAAC,yDAAyD,CAAC,CAAC;aACpF;YAED,qBAAqB;YACrB,IAAI,iBAAiB,EAAE;gBACrB,MAAM,IAAA,4CAAgB,EAAC,YAAY,CAAC,EAAE,CAAC,CAAC;aACzC;YAED,aAAa;YACb,IAAI;gBACF,MAAM,IAAA,2CAAe,EAAC,YAAY,CAAC,CAAC;aACrC;YAAC,OAAO,GAAG,EAAE;gBACZ,OAAO,CAAC,GAAG,CAAC,2CAA2C,GAAG,EAAE,CAAC,CAAC;aAC/D;YAED,MAAM,SAAS,GAAG,SAAS,CAAC,sBAAsB,EAAE,CAAC;YACrD,IAAI,SAAS,EAAE;gBACb,IAAA,qBAAW,EAAC,SAAS,CAAC,CAAC;gBACvB,OAAO,CAAC,GAAG,CAAC,mCAAmC,SAAS,EAAE,CAAC,CAAC;gBAC5D,SAAS,CAAC,uBAAuB,EAAE,CAAC;aACrC;YAED,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;YAC3C,0BAAe,CAAC,aAAa,CAAC,iBAAiB,CAAC,CAAC;SAClD;QAAC,OAAO,GAAQ,EAAE;YACjB,0BAAe,CAAC,eAAe,CAAC,iBAAiB,EAAE,GAAG,CAAC,CAAC;YACxD,MAAM,GAAG,CAAC;SACX;IACH,CAAC;CAAA;AApCD,sCAoCC"}
+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
+62
View File
@@ -0,0 +1,62 @@
{
"name": "office-addin-debugging",
"version": "6.0.3",
"description": "For debugging 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",
"node-debugger": "office-addin-node-debugger",
"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-debugging": "./cli.js"
},
"keywords": [
"Office"
],
"dependencies": {
"adm-zip": "0.5.12",
"commander": "^13.0.0",
"node-fetch": "^2.6.1",
"office-addin-cli": "^2.0.3",
"office-addin-dev-certs": "^2.0.3",
"office-addin-dev-settings": "^3.0.3",
"office-addin-manifest": "^2.0.3",
"office-addin-node-debugger": "^1.0.3",
"office-addin-usage-data": "^2.0.3"
},
"devDependencies": {
"@microsoft/eslint-plugin-sdl": "^1.0.1",
"@types/adm-zip": "^0.5.5",
"@types/express": "^5.0.0",
"@types/mocha": "^10.0.6",
"@types/node": "^14.17.2",
"@types/node-fetch": "^2.5.10",
"@types/ws": "^6.0.4",
"concurrently": "^9.0.0",
"express": "^4.21.1",
"mocha": "^11.0.1",
"office-addin-lint": "^3.0.3",
"rimraf": "^6.0.1",
"ts-node": "^10.9.1",
"typescript": "^4.7.4",
"ws": "^7.4.6"
},
"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"
}