/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ "./src/client/activation/activationManager.ts": /*!****************************************************!*\ !*** ./src/client/activation/activationManager.ts ***! \****************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ExtensionActivationManager = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const types_1 = __webpack_require__(/*! ../common/application/types */ "./src/client/common/application/types.ts"); const constants_1 = __webpack_require__(/*! ../common/constants */ "./src/client/common/constants.ts"); const logging_1 = __webpack_require__(/*! ../logging */ "./src/client/logging/index.ts"); const types_2 = __webpack_require__(/*! ./types */ "./src/client/activation/types.ts"); let ExtensionActivationManager = class ExtensionActivationManager { constructor(activationServices, singleActivationServices, documentManager, workspaceService, activeResourceService) { this.activationServices = activationServices; this.singleActivationServices = singleActivationServices; this.documentManager = documentManager; this.workspaceService = workspaceService; this.activeResourceService = activeResourceService; this.activatedWorkspaces = new Set(); this.isInterpreterSetForWorkspacePromises = new Map(); this.disposables = []; } filterServices() { if (!this.workspaceService.isTrusted) { this.activationServices = this.activationServices.filter((service) => service.supportedWorkspaceTypes.untrustedWorkspace); this.singleActivationServices = this.singleActivationServices.filter((service) => service.supportedWorkspaceTypes.untrustedWorkspace); } if (this.workspaceService.isVirtualWorkspace) { this.activationServices = this.activationServices.filter((service) => service.supportedWorkspaceTypes.virtualWorkspace); this.singleActivationServices = this.singleActivationServices.filter((service) => service.supportedWorkspaceTypes.virtualWorkspace); } } dispose() { while (this.disposables.length > 0) { const disposable = this.disposables.shift(); disposable.dispose(); } if (this.docOpenedHandler) { this.docOpenedHandler.dispose(); this.docOpenedHandler = undefined; } } async activate() { this.filterServices(); await this.initialize(); await Promise.all([ ...this.singleActivationServices.map((item) => item.activate()), this.activateWorkspace(this.activeResourceService.getActiveResource()), ]); } async activateWorkspace(resource) { const key = this.getWorkspaceKey(resource); if (this.activatedWorkspaces.has(key)) { return; } this.activatedWorkspaces.add(key); await Promise.all(this.activationServices.map((item) => item.activate(resource))); } async initialize() { this.addHandlers(); this.addRemoveDocOpenedHandlers(); } onDocOpened(doc) { var _a; if (doc.languageId !== constants_1.PYTHON_LANGUAGE) { return; } const key = this.getWorkspaceKey(doc.uri); const hasWorkspaceFolders = (((_a = this.workspaceService.workspaceFolders) === null || _a === void 0 ? void 0 : _a.length) || 0) > 0; if (key === '' && hasWorkspaceFolders) { return; } if (this.activatedWorkspaces.has(key)) { return; } const folder = this.workspaceService.getWorkspaceFolder(doc.uri); this.activateWorkspace(folder ? folder.uri : undefined).ignoreErrors(); } addHandlers() { this.disposables.push(this.workspaceService.onDidChangeWorkspaceFolders(this.onWorkspaceFoldersChanged, this)); } addRemoveDocOpenedHandlers() { if (this.hasMultipleWorkspaces()) { if (!this.docOpenedHandler) { this.docOpenedHandler = this.documentManager.onDidOpenTextDocument(this.onDocOpened, this); } return; } if (this.docOpenedHandler) { this.docOpenedHandler.dispose(); this.docOpenedHandler = undefined; } } onWorkspaceFoldersChanged() { const workspaceKeys = this.workspaceService.workspaceFolders.map((workspaceFolder) => this.getWorkspaceKey(workspaceFolder.uri)); const activatedWkspcKeys = Array.from(this.activatedWorkspaces.keys()); const activatedWkspcFoldersRemoved = activatedWkspcKeys.filter((item) => workspaceKeys.indexOf(item) < 0); if (activatedWkspcFoldersRemoved.length > 0) { for (const folder of activatedWkspcFoldersRemoved) { this.activatedWorkspaces.delete(folder); } } this.addRemoveDocOpenedHandlers(); } hasMultipleWorkspaces() { var _a; return (((_a = this.workspaceService.workspaceFolders) === null || _a === void 0 ? void 0 : _a.length) || 0) > 1; } getWorkspaceKey(resource) { return this.workspaceService.getWorkspaceFolderIdentifier(resource, ''); } }; __decorate([ (0, logging_1.traceDecoratorError)('Failed to activate a workspace') ], ExtensionActivationManager.prototype, "activateWorkspace", null); ExtensionActivationManager = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.multiInject)(types_2.IExtensionActivationService)), __param(1, (0, inversify_1.multiInject)(types_2.IExtensionSingleActivationService)), __param(2, (0, inversify_1.inject)(types_1.IDocumentManager)), __param(3, (0, inversify_1.inject)(types_1.IWorkspaceService)), __param(4, (0, inversify_1.inject)(types_1.IActiveResourceService)) ], ExtensionActivationManager); exports.ExtensionActivationManager = ExtensionActivationManager; /***/ }), /***/ "./src/client/activation/serviceRegistry.ts": /*!**************************************************!*\ !*** ./src/client/activation/serviceRegistry.ts ***! \**************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.registerTypes = void 0; const activationManager_1 = __webpack_require__(/*! ./activationManager */ "./src/client/activation/activationManager.ts"); const types_1 = __webpack_require__(/*! ./types */ "./src/client/activation/types.ts"); function registerTypes(serviceManager) { serviceManager.add(types_1.IExtensionActivationManager, activationManager_1.ExtensionActivationManager); } exports.registerTypes = registerTypes; /***/ }), /***/ "./src/client/activation/types.ts": /*!****************************************!*\ !*** ./src/client/activation/types.ts ***! \****************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.IExtensionSingleActivationService = exports.IExtensionActivationService = exports.IExtensionActivationManager = void 0; exports.IExtensionActivationManager = Symbol('IExtensionActivationManager'); exports.IExtensionActivationService = Symbol('IExtensionActivationService'); exports.IExtensionSingleActivationService = Symbol('IExtensionSingleActivationService'); /***/ }), /***/ "./src/client/common/application/activeResource.ts": /*!*********************************************************!*\ !*** ./src/client/common/application/activeResource.ts ***! \*********************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ActiveResourceService = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const types_1 = __webpack_require__(/*! ./types */ "./src/client/common/application/types.ts"); let ActiveResourceService = class ActiveResourceService { constructor(documentManager, workspaceService) { this.documentManager = documentManager; this.workspaceService = workspaceService; } getActiveResource() { const editor = this.documentManager.activeTextEditor; if (editor && !editor.document.isUntitled) { return editor.document.uri; } return Array.isArray(this.workspaceService.workspaceFolders) && this.workspaceService.workspaceFolders.length > 0 ? this.workspaceService.workspaceFolders[0].uri : undefined; } }; ActiveResourceService = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_1.IDocumentManager)), __param(1, (0, inversify_1.inject)(types_1.IWorkspaceService)) ], ActiveResourceService); exports.ActiveResourceService = ActiveResourceService; /***/ }), /***/ "./src/client/common/application/applicationEnvironment.ts": /*!*****************************************************************!*\ !*** ./src/client/common/application/applicationEnvironment.ts ***! \*****************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ApplicationEnvironment = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const path = __webpack_require__(/*! path */ "path"); const semver_1 = __webpack_require__(/*! semver */ "./node_modules/semver/semver.js"); const vscode = __webpack_require__(/*! vscode */ "vscode"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const types_1 = __webpack_require__(/*! ../platform/types */ "./src/client/common/platform/types.ts"); const types_2 = __webpack_require__(/*! ../types */ "./src/client/common/types.ts"); const platform_1 = __webpack_require__(/*! ../utils/platform */ "./src/client/common/utils/platform.ts"); let ApplicationEnvironment = class ApplicationEnvironment { constructor(platform, pathUtils, process) { this.platform = platform; this.pathUtils = pathUtils; this.process = process; } get userSettingsFile() { const vscodeFolderName = this.channel === 'insiders' ? 'Code - Insiders' : 'Code'; switch (this.platform.osType) { case platform_1.OSType.OSX: return path.join(this.pathUtils.home, 'Library', 'Application Support', vscodeFolderName, 'User', 'settings.json'); case platform_1.OSType.Linux: return path.join(this.pathUtils.home, '.config', vscodeFolderName, 'User', 'settings.json'); case platform_1.OSType.Windows: return this.process.env.APPDATA ? path.join(this.process.env.APPDATA, vscodeFolderName, 'User', 'settings.json') : undefined; default: return; } } get appName() { return vscode.env.appName; } get vscodeVersion() { return vscode.version; } get appRoot() { return vscode.env.appRoot; } get uiKind() { return vscode.env.uiKind; } get language() { return vscode.env.language; } get sessionId() { return vscode.env.sessionId; } get machineId() { return vscode.env.machineId; } get remoteName() { return vscode.env.remoteName; } get extensionName() { return this.packageJson.displayName; } get shell() { return vscode.env.shell; } get onDidChangeShell() { try { return vscode.env.onDidChangeShell; } catch (ex) { (0, logging_1.traceError)('Failed to get onDidChangeShell API', ex); return new vscode.EventEmitter().event; } } get packageJson() { return __webpack_require__(/*! ../../../../package.json */ "./package.json"); } get channel() { return this.appName.indexOf('Insider') > 0 ? 'insiders' : 'stable'; } get extensionChannel() { const version = (0, semver_1.parse)(this.packageJson.version); return !version || version.prerelease.length > 0 || version.minor % 2 == 1 ? 'insiders' : 'stable'; } get uriScheme() { return vscode.env.uriScheme; } }; ApplicationEnvironment = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_1.IPlatformService)), __param(1, (0, inversify_1.inject)(types_2.IPathUtils)), __param(2, (0, inversify_1.inject)(types_2.ICurrentProcess)) ], ApplicationEnvironment); exports.ApplicationEnvironment = ApplicationEnvironment; /***/ }), /***/ "./src/client/common/application/applicationShell.ts": /*!***********************************************************!*\ !*** ./src/client/common/application/applicationShell.ts ***! \***********************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ApplicationShell = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); let ApplicationShell = class ApplicationShell { get onDidChangeWindowState() { return vscode_1.window.onDidChangeWindowState; } showInformationMessage(message, options, ...items) { return vscode_1.window.showInformationMessage(message, options, ...items); } showWarningMessage(message, options, ...items) { return vscode_1.window.showWarningMessage(message, options, ...items); } showErrorMessage(message, options, ...items) { return vscode_1.window.showErrorMessage(message, options, ...items); } showQuickPick(items, options, token) { return vscode_1.window.showQuickPick(items, options, token); } showOpenDialog(options) { return vscode_1.window.showOpenDialog(options); } showSaveDialog(options) { return vscode_1.window.showSaveDialog(options); } showInputBox(options, token) { return vscode_1.window.showInputBox(options, token); } showTextDocument(document, column, preserveFocus) { return vscode_1.window.showTextDocument(document, column, preserveFocus); } openUrl(url) { vscode_1.env.openExternal(vscode_1.Uri.parse(url)); } setStatusBarMessage(text, arg) { return vscode_1.window.setStatusBarMessage(text, arg); } createStatusBarItem(alignment, priority, id) { return id ? vscode_1.window.createStatusBarItem(id, alignment, priority) : vscode_1.window.createStatusBarItem(alignment, priority); } showWorkspaceFolderPick(options) { return vscode_1.window.showWorkspaceFolderPick(options); } withProgress(options, task) { return vscode_1.window.withProgress(options, task); } withProgressCustomIcon(icon, task) { const token = new vscode_1.CancellationTokenSource().token; const statusBarProgress = this.createStatusBarItem(vscode_1.StatusBarAlignment.Left); const progress = { report: (value) => { statusBarProgress.text = `${icon} ${value.message}`; }, }; statusBarProgress.show(); return task(progress, token).then((result) => { statusBarProgress.dispose(); return result; }); } createQuickPick() { return vscode_1.window.createQuickPick(); } createInputBox() { return vscode_1.window.createInputBox(); } createTreeView(viewId, options) { return vscode_1.window.createTreeView(viewId, options); } createOutputChannel(name) { return vscode_1.window.createOutputChannel(name, { log: true }); } createLanguageStatusItem(id, selector) { return vscode_1.languages.createLanguageStatusItem(id, selector); } }; ApplicationShell = __decorate([ (0, inversify_1.injectable)() ], ApplicationShell); exports.ApplicationShell = ApplicationShell; /***/ }), /***/ "./src/client/common/application/commandManager.ts": /*!*********************************************************!*\ !*** ./src/client/common/application/commandManager.ts ***! \*********************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CommandManager = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); let CommandManager = class CommandManager { registerCommand(command, callback, thisArg) { return vscode_1.commands.registerCommand(command, callback, thisArg); } registerTextEditorCommand(command, callback, thisArg) { return vscode_1.commands.registerTextEditorCommand(command, callback, thisArg); } executeCommand(command, ...rest) { return vscode_1.commands.executeCommand(command, ...rest); } getCommands(filterInternal) { return vscode_1.commands.getCommands(filterInternal); } }; CommandManager = __decorate([ (0, inversify_1.injectable)() ], CommandManager); exports.CommandManager = CommandManager; /***/ }), /***/ "./src/client/common/application/documentManager.ts": /*!**********************************************************!*\ !*** ./src/client/common/application/documentManager.ts ***! \**********************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DocumentManager = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); let DocumentManager = class DocumentManager { get textDocuments() { return vscode_1.workspace.textDocuments; } get activeTextEditor() { return vscode_1.window.activeTextEditor; } get visibleTextEditors() { return vscode_1.window.visibleTextEditors; } get onDidChangeActiveTextEditor() { return vscode_1.window.onDidChangeActiveTextEditor; } get onDidChangeTextDocument() { return vscode_1.workspace.onDidChangeTextDocument; } get onDidChangeVisibleTextEditors() { return vscode_1.window.onDidChangeVisibleTextEditors; } get onDidChangeTextEditorSelection() { return vscode_1.window.onDidChangeTextEditorSelection; } get onDidChangeTextEditorOptions() { return vscode_1.window.onDidChangeTextEditorOptions; } get onDidChangeTextEditorViewColumn() { return vscode_1.window.onDidChangeTextEditorViewColumn; } get onDidOpenTextDocument() { return vscode_1.workspace.onDidOpenTextDocument; } get onDidCloseTextDocument() { return vscode_1.workspace.onDidCloseTextDocument; } get onDidSaveTextDocument() { return vscode_1.workspace.onDidSaveTextDocument; } showTextDocument(uri, options, preserveFocus) { return vscode_1.window.showTextDocument(uri, options, preserveFocus); } openTextDocument(arg) { return vscode_1.workspace.openTextDocument(arg); } applyEdit(edit) { return vscode_1.workspace.applyEdit(edit); } createTextEditorDecorationType(options) { return vscode_1.window.createTextEditorDecorationType(options); } }; DocumentManager = __decorate([ (0, inversify_1.injectable)() ], DocumentManager); exports.DocumentManager = DocumentManager; /***/ }), /***/ "./src/client/common/application/terminalManager.ts": /*!**********************************************************!*\ !*** ./src/client/common/application/terminalManager.ts ***! \**********************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TerminalManager = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); let TerminalManager = class TerminalManager { constructor() { this.didOpenTerminal = new vscode_1.EventEmitter(); vscode_1.window.onDidOpenTerminal((terminal) => { this.didOpenTerminal.fire(monkeyPatchTerminal(terminal)); }); } get onDidCloseTerminal() { return vscode_1.window.onDidCloseTerminal; } get onDidOpenTerminal() { return this.didOpenTerminal.event; } createTerminal(options) { return monkeyPatchTerminal(vscode_1.window.createTerminal(options)); } }; TerminalManager = __decorate([ (0, inversify_1.injectable)() ], TerminalManager); exports.TerminalManager = TerminalManager; function monkeyPatchTerminal(terminal) { if (!terminal.isPatched) { const oldSendText = terminal.sendText.bind(terminal); terminal.sendText = (text, addNewLine = true) => { (0, logging_1.traceLog)(`Send text to terminal: ${text}`); return oldSendText(text, addNewLine); }; terminal.isPatched = true; } return terminal; } /***/ }), /***/ "./src/client/common/application/types.ts": /*!************************************************!*\ !*** ./src/client/common/application/types.ts ***! \************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.IActiveResourceService = exports.IApplicationEnvironment = exports.ITerminalManager = exports.IWorkspaceService = exports.IDocumentManager = exports.IJupyterExtensionDependencyManager = exports.ICommandManager = exports.IApplicationShell = void 0; exports.IApplicationShell = Symbol('IApplicationShell'); exports.ICommandManager = Symbol('ICommandManager'); exports.IJupyterExtensionDependencyManager = Symbol('IJupyterExtensionDependencyManager'); exports.IDocumentManager = Symbol('IDocumentManager'); exports.IWorkspaceService = Symbol('IWorkspaceService'); exports.ITerminalManager = Symbol('ITerminalManager'); exports.IApplicationEnvironment = Symbol('IApplicationEnvironment'); exports.IActiveResourceService = Symbol('IActiveResourceService'); /***/ }), /***/ "./src/client/common/application/workspace.ts": /*!****************************************************!*\ !*** ./src/client/common/application/workspace.ts ***! \****************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WorkspaceService = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const path = __webpack_require__(/*! path */ "path"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const platform_1 = __webpack_require__(/*! ../utils/platform */ "./src/client/common/utils/platform.ts"); let WorkspaceService = class WorkspaceService { get onDidChangeConfiguration() { return vscode_1.workspace.onDidChangeConfiguration; } get rootPath() { return Array.isArray(vscode_1.workspace.workspaceFolders) && vscode_1.workspace.workspaceFolders.length > 0 ? vscode_1.workspace.workspaceFolders[0].uri.fsPath : undefined; } get workspaceFolders() { return vscode_1.workspace.workspaceFolders; } get onDidChangeWorkspaceFolders() { return vscode_1.workspace.onDidChangeWorkspaceFolders; } get workspaceFile() { return vscode_1.workspace.workspaceFile; } getConfiguration(section, resource, languageSpecific = false) { if (languageSpecific) { return vscode_1.workspace.getConfiguration(section, { uri: resource, languageId: 'python' }); } else { return vscode_1.workspace.getConfiguration(section, resource); } } getWorkspaceFolder(uri) { return uri ? vscode_1.workspace.getWorkspaceFolder(uri) : undefined; } asRelativePath(pathOrUri, includeWorkspaceFolder) { return vscode_1.workspace.asRelativePath(pathOrUri, includeWorkspaceFolder); } createFileSystemWatcher(globPattern, ignoreCreateEvents, ignoreChangeEvents, ignoreDeleteEvents) { return vscode_1.workspace.createFileSystemWatcher(globPattern, ignoreCreateEvents, ignoreChangeEvents, ignoreDeleteEvents); } findFiles(include, exclude, maxResults, token) { const excludePattern = exclude === undefined ? this.searchExcludes : exclude; return vscode_1.workspace.findFiles(include, excludePattern, maxResults, token); } getWorkspaceFolderIdentifier(resource, defaultValue = '') { const workspaceFolder = resource ? vscode_1.workspace.getWorkspaceFolder(resource) : undefined; return workspaceFolder ? path.normalize((0, platform_1.getOSType)() === platform_1.OSType.Windows ? workspaceFolder.uri.fsPath.toUpperCase() : workspaceFolder.uri.fsPath) : defaultValue; } get isVirtualWorkspace() { const isVirtualWorkspace = vscode_1.workspace.workspaceFolders && vscode_1.workspace.workspaceFolders.every((f) => f.uri.scheme !== 'file'); return !!isVirtualWorkspace; } get isTrusted() { return vscode_1.workspace.isTrusted; } get onDidGrantWorkspaceTrust() { return vscode_1.workspace.onDidGrantWorkspaceTrust; } openTextDocument(options) { return vscode_1.workspace.openTextDocument(options); } get searchExcludes() { const searchExcludes = this.getConfiguration('search.exclude'); const enabledSearchExcludes = Object.keys(searchExcludes).filter((key) => searchExcludes.get(key) === true); return `{${enabledSearchExcludes.join(',')}}`; } async save(uri) { try { const result = await vscode_1.workspace.save(uri); return result; } catch (ex) { return undefined; } } }; WorkspaceService = __decorate([ (0, inversify_1.injectable)() ], WorkspaceService); exports.WorkspaceService = WorkspaceService; /***/ }), /***/ "./src/client/common/cancellation.ts": /*!*******************************************!*\ !*** ./src/client/common/cancellation.ts ***! \*******************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Cancellation = exports.wrapCancellationTokens = exports.createPromiseFromCancellation = exports.CancellationError = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const async_1 = __webpack_require__(/*! ./utils/async */ "./src/client/common/utils/async.ts"); const localize = __webpack_require__(/*! ./utils/localize */ "./src/client/common/utils/localize.ts"); class CancellationError extends Error { constructor() { super(localize.Common.canceled); } } exports.CancellationError = CancellationError; function createPromiseFromCancellation(options) { return new Promise((resolve, reject) => { if (!options.token) { return; } const complete = () => { const optionsToken = options.token; if (optionsToken.isCancellationRequested) { if (options.cancelAction === 'resolve') { return resolve(options.defaultValue); } if (options.cancelAction === 'reject') { return reject(new CancellationError()); } } }; options.token.onCancellationRequested(complete); }); } exports.createPromiseFromCancellation = createPromiseFromCancellation; function wrapCancellationTokens(...tokens) { const wrappedCancellantionToken = new vscode_1.CancellationTokenSource(); for (const token of tokens) { if (!token) { continue; } if (token.isCancellationRequested) { return token; } token.onCancellationRequested(() => wrappedCancellantionToken.cancel()); } return wrappedCancellantionToken.token; } exports.wrapCancellationTokens = wrapCancellationTokens; var Cancellation; (function (Cancellation) { function race(work, token) { if (token) { const deferred = (0, async_1.createDeferred)(); token.onCancellationRequested(() => { if (!deferred.completed) { deferred.reject(new CancellationError()); } }); if (token.isCancellationRequested) { deferred.reject(new CancellationError()); } else { work(token) .then((v) => { if (!deferred.completed) { deferred.resolve(v); } }) .catch((e) => { if (!deferred.completed) { deferred.reject(e); } }); } return deferred.promise; } else { return work(); } } Cancellation.race = race; function isCanceled(cancelToken) { return cancelToken ? cancelToken.isCancellationRequested : false; } Cancellation.isCanceled = isCanceled; function throwIfCanceled(cancelToken) { if (isCanceled(cancelToken)) { throw new CancellationError(); } } Cancellation.throwIfCanceled = throwIfCanceled; })(Cancellation = exports.Cancellation || (exports.Cancellation = {})); /***/ }), /***/ "./src/client/common/configSettings.ts": /*!*********************************************!*\ !*** ./src/client/common/configSettings.ts ***! \*********************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PythonSettings = void 0; const path = __webpack_require__(/*! path */ "path"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); __webpack_require__(/*! ./extensions */ "./src/client/common/extensions.ts"); const workspace_1 = __webpack_require__(/*! ./application/workspace */ "./src/client/common/application/workspace.ts"); const constants_1 = __webpack_require__(/*! ./constants */ "./src/client/common/constants.ts"); const decorators_1 = __webpack_require__(/*! ./utils/decorators */ "./src/client/common/utils/decorators.ts"); const systemVariables_1 = __webpack_require__(/*! ./variables/systemVariables */ "./src/client/common/variables/systemVariables.ts"); const untildify = __webpack_require__(/*! untildify */ "./node_modules/untildify/index.js"); class PythonSettings { constructor(api, workspaceFolder, workspace) { this.api = api; this.envFile = ''; this.venvPath = ''; this.venvFolders = []; this.activeStateToolPath = ''; this.condaPath = ''; this.pipenvPath = ''; this.poetryPath = ''; this.devOptions = []; this.disableInstallationChecks = false; this.globalModuleInstallation = false; this.autoUpdateLanguageServer = true; this.languageServerIsDefault = true; this.changed = new vscode_1.EventEmitter(); this.disposables = []; this._defaultInterpreterPath = ''; this.workspace = workspace || new workspace_1.WorkspaceService(); this.workspaceRoot = workspaceFolder; this.initialize(); } static onConfigChange() { return PythonSettings.configChanged.event; } get pythonPath() { try { return this.api.environments.getActiveEnvironmentPath(this.workspaceRoot).path; } catch (_a) { return 'python'; } } get defaultInterpreterPath() { return this._defaultInterpreterPath; } set defaultInterpreterPath(value) { if (this._defaultInterpreterPath === value) { return; } try { this._defaultInterpreterPath = this.api.environments.getActiveEnvironmentPath().path; } catch (ex) { this._defaultInterpreterPath = value; } } static getInstance(api, resource, workspace) { workspace = workspace || new workspace_1.WorkspaceService(); const workspaceFolderUri = PythonSettings.getSettingsUriAndTarget(resource, workspace).uri; const workspaceFolderKey = workspaceFolderUri ? workspaceFolderUri.fsPath : ''; if (!PythonSettings.pythonSettings.has(workspaceFolderKey)) { const settings = new PythonSettings(api, workspaceFolderUri, workspace); PythonSettings.pythonSettings.set(workspaceFolderKey, settings); } return PythonSettings.pythonSettings.get(workspaceFolderKey); } static debounceConfigChangeNotification(event) { PythonSettings.configChanged.fire(event); } static getSettingsUriAndTarget(resource, workspace) { workspace = workspace || new workspace_1.WorkspaceService(); const workspaceFolder = resource ? workspace.getWorkspaceFolder(resource) : undefined; let workspaceFolderUri = workspaceFolder ? workspaceFolder.uri : undefined; if (!workspaceFolderUri && Array.isArray(workspace.workspaceFolders) && workspace.workspaceFolders.length > 0) { workspaceFolderUri = workspace.workspaceFolders[0].uri; } const target = workspaceFolderUri ? vscode_1.ConfigurationTarget.WorkspaceFolder : vscode_1.ConfigurationTarget.Global; return { uri: workspaceFolderUri, target }; } static dispose() { if (!(0, constants_1.isTestExecution)()) { throw new Error('Dispose can only be called from unit tests'); } PythonSettings.pythonSettings.forEach((item) => item && item.dispose()); PythonSettings.pythonSettings.clear(); } static toSerializable(settings) { const clone = {}; const keys = Object.entries(settings); keys.forEach((e) => { const [k, v] = e; if (!k.includes('Manager') && !k.includes('Service') && !k.includes('onDid')) { clone[k] = v; } }); return clone; } dispose() { this.disposables.forEach((disposable) => disposable && disposable.dispose()); this.disposables = []; } update(pythonSettings) { var _a; const workspaceRoot = (_a = this.workspaceRoot) === null || _a === void 0 ? void 0 : _a.fsPath; const systemVariables = new systemVariables_1.SystemVariables(undefined, workspaceRoot, this.workspace); const defaultInterpreterPath = systemVariables.resolveAny(pythonSettings.get('defaultInterpreterPath')); this.defaultInterpreterPath = defaultInterpreterPath || constants_1.DEFAULT_INTERPRETER_SETTING; this.venvPath = systemVariables.resolveAny(pythonSettings.get('venvPath')); this.venvFolders = systemVariables.resolveAny(pythonSettings.get('venvFolders')); const activeStateToolPath = systemVariables.resolveAny(pythonSettings.get('activeStateToolPath')); this.activeStateToolPath = activeStateToolPath && activeStateToolPath.length > 0 ? getAbsolutePath(activeStateToolPath, workspaceRoot) : activeStateToolPath; const condaPath = systemVariables.resolveAny(pythonSettings.get('condaPath')); this.condaPath = condaPath && condaPath.length > 0 ? getAbsolutePath(condaPath, workspaceRoot) : condaPath; const pipenvPath = systemVariables.resolveAny(pythonSettings.get('pipenvPath')); this.pipenvPath = pipenvPath && pipenvPath.length > 0 ? getAbsolutePath(pipenvPath, workspaceRoot) : pipenvPath; const poetryPath = systemVariables.resolveAny(pythonSettings.get('poetryPath')); this.poetryPath = poetryPath && poetryPath.length > 0 ? getAbsolutePath(poetryPath, workspaceRoot) : poetryPath; this.autoUpdateLanguageServer = systemVariables.resolveAny(pythonSettings.get('autoUpdateLanguageServer', true)); const envFileSetting = pythonSettings.get('envFile'); this.envFile = systemVariables.resolveAny(envFileSetting); this.devOptions = systemVariables.resolveAny(pythonSettings.get('devOptions')); this.devOptions = Array.isArray(this.devOptions) ? this.devOptions : []; this.disableInstallationChecks = pythonSettings.get('disableInstallationCheck') === true; this.globalModuleInstallation = pythonSettings.get('globalModuleInstallation') === true; const terminalSettings = systemVariables.resolveAny(pythonSettings.get('terminal')); if (this.terminal) { Object.assign(this.terminal, terminalSettings); } else { this.terminal = terminalSettings; if ((0, constants_1.isTestExecution)() && !this.terminal) { this.terminal = {}; } } } onWorkspaceFoldersChanged() { const workspaceKeys = this.workspace.workspaceFolders.map((workspaceFolder) => workspaceFolder.uri.fsPath); const activatedWkspcKeys = Array.from(PythonSettings.pythonSettings.keys()); const activatedWkspcFoldersRemoved = activatedWkspcKeys.filter((item) => workspaceKeys.indexOf(item) < 0); if (activatedWkspcFoldersRemoved.length > 0) { for (const folder of activatedWkspcFoldersRemoved) { PythonSettings.pythonSettings.delete(folder); } } } register() { PythonSettings.pythonSettings = new Map(); this.initialize(); } onDidChanged(event) { const currentConfig = this.workspace.getConfiguration('python', this.workspaceRoot); this.update(currentConfig); this.debounceChangeNotification(event); } initialize() { this.disposables.push(this.workspace.onDidChangeWorkspaceFolders(this.onWorkspaceFoldersChanged, this)); this.disposables.push(this.workspace.onDidChangeConfiguration((event) => { if (event.affectsConfiguration('python')) { this.onDidChanged(event); } })); const initialConfig = this.workspace.getConfiguration('python', this.workspaceRoot); if (initialConfig) { this.update(initialConfig); } } debounceChangeNotification(event) { this.changed.fire(event); } } PythonSettings.pythonSettings = new Map(); PythonSettings.configChanged = new vscode_1.EventEmitter(); __decorate([ (0, decorators_1.debounceSync)(1) ], PythonSettings.prototype, "debounceChangeNotification", null); __decorate([ (0, decorators_1.debounceSync)(1) ], PythonSettings, "debounceConfigChangeNotification", null); exports.PythonSettings = PythonSettings; function getAbsolutePath(pathToCheck, rootDir) { if (!rootDir) { rootDir = __dirname; } pathToCheck = untildify(pathToCheck); if ((0, constants_1.isTestExecution)() && !pathToCheck) { return rootDir; } if (pathToCheck.indexOf(path.sep) === -1) { return pathToCheck; } return path.isAbsolute(pathToCheck) ? pathToCheck : path.resolve(rootDir, pathToCheck); } /***/ }), /***/ "./src/client/common/configuration/executionSettings/pipEnvExecution.ts": /*!******************************************************************************!*\ !*** ./src/client/common/configuration/executionSettings/pipEnvExecution.ts ***! \******************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PipEnvExecutionPath = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const types_1 = __webpack_require__(/*! ../../types */ "./src/client/common/types.ts"); let PipEnvExecutionPath = class PipEnvExecutionPath { constructor(configService) { this.configService = configService; } get executable() { return this.configService.getSettings().pipenvPath; } }; PipEnvExecutionPath = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_1.IConfigurationService)) ], PipEnvExecutionPath); exports.PipEnvExecutionPath = PipEnvExecutionPath; /***/ }), /***/ "./src/client/common/configuration/service.ts": /*!****************************************************!*\ !*** ./src/client/common/configuration/service.ts ***! \****************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ConfigurationService = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const types_1 = __webpack_require__(/*! ../../ioc/types */ "./src/client/ioc/types.ts"); const types_2 = __webpack_require__(/*! ../application/types */ "./src/client/common/application/types.ts"); const configSettings_1 = __webpack_require__(/*! ../configSettings */ "./src/client/common/configSettings.ts"); let ConfigurationService = class ConfigurationService { constructor(serviceContainer) { this.serviceContainer = serviceContainer; this.workspaceService = this.serviceContainer.get(types_2.IWorkspaceService); } initialize(api) { this.api = api; } get onDidChange() { return configSettings_1.PythonSettings.onConfigChange(); } getSettings(resource) { return configSettings_1.PythonSettings.getInstance(this.api, resource, this.workspaceService); } }; ConfigurationService = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_1.IServiceContainer)) ], ConfigurationService); exports.ConfigurationService = ConfigurationService; /***/ }), /***/ "./src/client/common/constants.ts": /*!****************************************!*\ !*** ./src/client/common/constants.ts ***! \****************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (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 })); exports.UseProposedApi = exports.isUnitTestExecution = exports.isTestExecution = exports.isCI = exports.DEFAULT_INTERPRETER_SETTING = exports.ThemeIcons = exports.Octicons = exports.Commands = exports.CommandSource = exports.AppinsightsKey = exports.JUPYTER_EXTENSION_ID = exports.PYLANCE_EXTENSION_ID = exports.PVSC_EXTENSION_ID = exports.PYTHON_NOTEBOOKS = exports.PYTHON = exports.InteractiveScheme = exports.InteractiveInputScheme = exports.NotebookCellScheme = exports.PYTHON_WARNINGS = exports.PYTHON_LANGUAGE = void 0; exports.PYTHON_LANGUAGE = 'python'; exports.PYTHON_WARNINGS = 'PYTHONWARNINGS'; exports.NotebookCellScheme = 'vscode-notebook-cell'; exports.InteractiveInputScheme = 'vscode-interactive-input'; exports.InteractiveScheme = 'vscode-interactive'; exports.PYTHON = [ { scheme: 'file', language: exports.PYTHON_LANGUAGE }, { scheme: 'untitled', language: exports.PYTHON_LANGUAGE }, { scheme: 'vscode-notebook', language: exports.PYTHON_LANGUAGE }, { scheme: exports.NotebookCellScheme, language: exports.PYTHON_LANGUAGE }, { scheme: exports.InteractiveInputScheme, language: exports.PYTHON_LANGUAGE }, ]; exports.PYTHON_NOTEBOOKS = [ { scheme: 'vscode-notebook', language: exports.PYTHON_LANGUAGE }, { scheme: exports.NotebookCellScheme, language: exports.PYTHON_LANGUAGE }, { scheme: exports.InteractiveInputScheme, language: exports.PYTHON_LANGUAGE }, ]; exports.PVSC_EXTENSION_ID = 'ms-python.python'; exports.PYLANCE_EXTENSION_ID = 'ms-python.vscode-pylance'; exports.JUPYTER_EXTENSION_ID = 'ms-toolsai.jupyter'; exports.AppinsightsKey = '0c6ae279ed8443289764825290e4f9e2-1a736e7c-1324-4338-be46-fc2a58ae4d14-7255'; var CommandSource; (function (CommandSource) { CommandSource["ui"] = "ui"; CommandSource["commandPalette"] = "commandpalette"; })(CommandSource = exports.CommandSource || (exports.CommandSource = {})); var Commands; (function (Commands) { Commands.ClearStorage = 'python.envManager.clearPersistentStorage'; Commands.CreateNewFile = 'python.createNewFile'; Commands.ClearWorkspaceInterpreter = 'python.clearWorkspaceInterpreter'; Commands.Create_Environment = 'python.envManager.createEnvironment'; Commands.Create_Environment_Button = 'python.envManager.createEnvironment-button'; Commands.Create_Terminal = 'python.createTerminal'; Commands.Debug_In_Terminal = 'python.debugInTerminal'; Commands.Enable_Linter = 'python.enableLinting'; Commands.Enable_SourceMap_Support = 'python.enableSourceMapSupport'; Commands.Exec_In_Terminal = 'python.execInTerminal'; Commands.Exec_In_Terminal_Icon = 'python.execInTerminal-icon'; Commands.Exec_In_Separate_Terminal = 'python.execInDedicatedTerminal'; Commands.Exec_Selection_In_Django_Shell = 'python.execSelectionInDjangoShell'; Commands.Exec_Selection_In_Terminal = 'python.execSelectionInTerminal'; Commands.GetSelectedInterpreterPath = 'python.interpreterPath'; Commands.InstallJupyter = 'python.installJupyter'; Commands.InstallPython = 'python.installPython'; Commands.InstallPythonOnLinux = 'python.installPythonOnLinux'; Commands.InstallPythonOnMac = 'python.installPythonOnMac'; Commands.LaunchTensorBoard = 'python.launchTensorBoard'; Commands.PickLocalProcess = 'python.pickLocalProcess'; Commands.RefreshTensorBoard = 'python.refreshTensorBoard'; Commands.ReportIssue = 'python.reportIssue'; Commands.Run_Linter = 'python.runLinting'; Commands.Set_Interpreter = 'python.setInterpreter'; Commands.Set_Linter = 'python.setLinter'; Commands.Set_ShebangInterpreter = 'python.setShebangInterpreter'; Commands.Sort_Imports = 'python.sortImports'; Commands.Start_REPL = 'python.startREPL'; Commands.Tests_Configure = 'python.configureTests'; Commands.TriggerEnvironmentSelection = 'python.triggerEnvSelection'; Commands.ViewOutput = 'python.viewOutput'; })(Commands = exports.Commands || (exports.Commands = {})); var Octicons; (function (Octicons) { Octicons.Add = '$(add)'; Octicons.Test_Pass = '$(check)'; Octicons.Test_Fail = '$(alert)'; Octicons.Test_Error = '$(x)'; Octicons.Test_Skip = '$(circle-slash)'; Octicons.Downloading = '$(cloud-download)'; Octicons.Installing = '$(desktop-download)'; Octicons.Search_Stop = '$(search-stop)'; Octicons.Star = '$(star-full)'; Octicons.Gear = '$(gear)'; Octicons.Warning = '$(warning)'; Octicons.Error = '$(error)'; Octicons.Lightbulb = '$(lightbulb)'; })(Octicons = exports.Octicons || (exports.Octicons = {})); var ThemeIcons; (function (ThemeIcons) { ThemeIcons.Refresh = 'refresh'; ThemeIcons.SpinningLoader = 'loading~spin'; })(ThemeIcons = exports.ThemeIcons || (exports.ThemeIcons = {})); exports.DEFAULT_INTERPRETER_SETTING = 'python'; exports.isCI = process.env.TRAVIS === 'true' || process.env.TF_BUILD !== undefined; function isTestExecution() { return process.env.VSC_PYTHON_CI_TEST === '1' || isUnitTestExecution(); } exports.isTestExecution = isTestExecution; function isUnitTestExecution() { return process.env.VSC_PYTHON_UNIT_TEST === '1'; } exports.isUnitTestExecution = isUnitTestExecution; exports.UseProposedApi = Symbol('USE_VSC_PROPOSED_API'); __exportStar(__webpack_require__(/*! ../constants */ "./src/client/constants.ts"), exports); /***/ }), /***/ "./src/client/common/editor.ts": /*!*************************************!*\ !*** ./src/client/common/editor.ts ***! \*************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EditorUtils = exports.getTempFileWithDocumentContents = exports.getWorkspaceEditsFromPatch = exports.getTextEditsFromPatch = void 0; const diff_match_patch_1 = __webpack_require__(/*! ./node_modules/diff-match-patch */ "./node_modules/diff-match-patch"); const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const md5 = __webpack_require__(/*! md5 */ "./node_modules/md5/md5.js"); const os_1 = __webpack_require__(/*! os */ "os"); const path = __webpack_require__(/*! path */ "path"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const logging_1 = __webpack_require__(/*! ../logging */ "./src/client/logging/index.ts"); const errorUtils_1 = __webpack_require__(/*! ./errors/errorUtils */ "./src/client/common/errors/errorUtils.ts"); const misc_1 = __webpack_require__(/*! ./utils/misc */ "./src/client/common/utils/misc.ts"); var EditAction; (function (EditAction) { EditAction[EditAction["Delete"] = 0] = "Delete"; EditAction[EditAction["Insert"] = 1] = "Insert"; EditAction[EditAction["Replace"] = 2] = "Replace"; })(EditAction || (EditAction = {})); const NEW_LINE_LENGTH = os_1.EOL.length; class Patch { } class Edit { constructor(action, start) { this.action = action; this.start = start; this.text = ''; } apply() { switch (this.action) { case EditAction.Insert: return vscode_1.TextEdit.insert(this.start, this.text); case EditAction.Delete: return vscode_1.TextEdit.delete(new vscode_1.Range(this.start, this.end)); case EditAction.Replace: return vscode_1.TextEdit.replace(new vscode_1.Range(this.start, this.end), this.text); default: return new vscode_1.TextEdit(new vscode_1.Range(new vscode_1.Position(0, 0), new vscode_1.Position(0, 0)), ''); } } } function getTextEditsFromPatch(before, patch) { if (patch.startsWith('---')) { patch = patch.substring(patch.indexOf('@@')); } if (patch.length === 0) { return []; } patch = patch.replace(/\\ No newline at end of file[\r\n]/, ''); const dmp = __webpack_require__(/*! ./node_modules/diff-match-patch */ "./node_modules/diff-match-patch"); const d = new dmp.diff_match_patch(); const patches = patch_fromText.call(d, patch); if (!Array.isArray(patches) || patches.length === 0) { throw new Error('Unable to parse Patch string'); } const textEdits = []; patches.forEach((p) => { p.diffs.forEach((diff) => { diff[1] += os_1.EOL; }); getTextEditsInternal(before, p.diffs, p.start1).forEach((edit) => textEdits.push(edit.apply())); }); return textEdits; } exports.getTextEditsFromPatch = getTextEditsFromPatch; function getWorkspaceEditsFromPatch(filePatches, workspaceRoot, fs) { const workspaceEdit = new vscode_1.WorkspaceEdit(); filePatches.forEach((patch) => { const indexOfAtAt = patch.indexOf('@@'); if (indexOfAtAt === -1) { return; } const fileNameLines = patch .substring(0, indexOfAtAt) .split(/\r?\n/g) .map((line) => line.trim()) .filter((line) => line.length > 0 && line.toLowerCase().endsWith('.py') && line.indexOf(' a') > 0); if (patch.startsWith('---')) { patch = patch.substring(indexOfAtAt); } if (patch.length === 0) { return; } if (fileNameLines.length === 0) { return; } let fileName = fileNameLines[0].substring(fileNameLines[0].indexOf(' a') + 3).trim(); fileName = workspaceRoot && !path.isAbsolute(fileName) ? path.resolve(workspaceRoot, fileName) : fileName; if (!fs.fileExistsSync(fileName)) { return; } patch = patch.replace(/\\ No newline at end of file[\r\n]/, ''); const dmp = __webpack_require__(/*! ./node_modules/diff-match-patch */ "./node_modules/diff-match-patch"); const d = new dmp.diff_match_patch(); const patches = patch_fromText.call(d, patch); if (!Array.isArray(patches) || patches.length === 0) { throw new Error('Unable to parse Patch string'); } const fileSource = fs.readFileSync(fileName); const fileUri = vscode_1.Uri.file(fileName); patches.forEach((p) => { p.diffs.forEach((diff) => { diff[1] += os_1.EOL; }); getTextEditsInternal(fileSource, p.diffs, p.start1).forEach((edit) => { switch (edit.action) { case EditAction.Delete: workspaceEdit.delete(fileUri, new vscode_1.Range(edit.start, edit.end)); break; case EditAction.Insert: workspaceEdit.insert(fileUri, edit.start, edit.text); break; case EditAction.Replace: workspaceEdit.replace(fileUri, new vscode_1.Range(edit.start, edit.end), edit.text); break; default: break; } }); }); }); return workspaceEdit; } exports.getWorkspaceEditsFromPatch = getWorkspaceEditsFromPatch; function getTextEditsInternal(before, diffs, startLine = 0) { let line = startLine; let character = 0; const beforeLines = before.split(/\r?\n/g); if (line > 0) { beforeLines.filter((_l, i) => i < line).forEach((l) => (character += l.length + NEW_LINE_LENGTH)); } const edits = []; let edit = null; let end; for (let i = 0; i < diffs.length; i += 1) { let start = new vscode_1.Position(line, character); for (let curr = 0; curr < diffs[i][1].length; curr += 1) { if (diffs[i][1][curr] !== '\n') { character += 1; } else { character = 0; line += 1; } } const dmp = __webpack_require__(/*! ./node_modules/diff-match-patch */ "./node_modules/diff-match-patch"); switch (diffs[i][0]) { case dmp.DIFF_DELETE: if (beforeLines[line - 1].length === 0 && beforeLines[start.line - 1] && beforeLines[start.line - 1].length === 0) { start = new vscode_1.Position(start.line - 1, 0); end = new vscode_1.Position(line - 1, 0); } else { end = new vscode_1.Position(line, character); } if (edit === null) { edit = new Edit(EditAction.Delete, start); } else if (edit.action !== EditAction.Delete) { throw new Error('cannot format due to an internal error.'); } edit.end = end; break; case dmp.DIFF_INSERT: if (edit === null) { edit = new Edit(EditAction.Insert, start); } else if (edit.action === EditAction.Delete) { edit.action = EditAction.Replace; } line = start.line; character = start.character; edit.text += diffs[i][1]; break; case dmp.DIFF_EQUAL: if (edit !== null) { edits.push(edit); edit = null; } break; } } if (edit !== null) { edits.push(edit); } return edits; } async function getTempFileWithDocumentContents(document, fs) { let fileName = `${document.uri.fsPath}.${md5(document.uri.fsPath + document.uri.fragment)}.tmp`; try { if ((0, misc_1.isNotebookCell)(document.uri) && !(await fs.fileExists(document.uri.fsPath))) { fileName = (await fs.createTemporaryFile(`${path.basename(document.uri.fsPath)}-${document.uri.fragment}.tmp`)).filePath; } await fs.writeFile(fileName, document.getText()); } catch (ex) { (0, logging_1.traceError)('Failed to create a temporary file', ex); const exception = ex; throw new errorUtils_1.WrappedError(`Failed to create a temporary file, ${exception.message}`, exception); } return fileName; } exports.getTempFileWithDocumentContents = getTempFileWithDocumentContents; function patch_fromText(textline) { const patches = []; if (!textline) { return patches; } const text = textline.split(/[\r\n]/); let textPointer = 0; const patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/; while (textPointer < text.length) { const m = text[textPointer].match(patchHeader); if (!m) { throw new Error(`Invalid patch string: ${text[textPointer]}`); } const patch = new diff_match_patch_1.diff_match_patch.patch_obj(); patches.push(patch); patch.start1 = parseInt(m[1], 10); if (m[2] === '') { patch.start1 -= 1; patch.length1 = 1; } else if (m[2] === '0') { patch.length1 = 0; } else { patch.start1 -= 1; patch.length1 = parseInt(m[2], 10); } patch.start2 = parseInt(m[3], 10); if (m[4] === '') { patch.start2 -= 1; patch.length2 = 1; } else if (m[4] === '0') { patch.length2 = 0; } else { patch.start2 -= 1; patch.length2 = parseInt(m[4], 10); } textPointer += 1; const dmp = __webpack_require__(/*! ./node_modules/diff-match-patch */ "./node_modules/diff-match-patch"); while (textPointer < text.length) { const sign = text[textPointer].charAt(0); let line; try { line = text[textPointer].substring(1); } catch (ex) { throw new Error('Illegal escape in patch_fromText'); } if (sign === '-') { patch.diffs.push([dmp.DIFF_DELETE, line]); } else if (sign === '+') { patch.diffs.push([dmp.DIFF_INSERT, line]); } else if (sign === ' ') { patch.diffs.push([dmp.DIFF_EQUAL, line]); } else if (sign === '@') { break; } else if (sign === '') { } else { throw new Error(`Invalid patch mode '${sign}' in: ${line}`); } textPointer += 1; } } return patches; } let EditorUtils = class EditorUtils { getWorkspaceEditsFromPatch(originalContents, patch, uri) { const workspaceEdit = new vscode_1.WorkspaceEdit(); if (patch.startsWith('---')) { patch = patch.substring(patch.indexOf('@@')); } if (patch.length === 0) { return workspaceEdit; } patch = patch.replace(/\\ No newline at end of file[\r\n]/, ''); const dmp = __webpack_require__(/*! ./node_modules/diff-match-patch */ "./node_modules/diff-match-patch"); const d = new dmp.diff_match_patch(); const patches = patch_fromText.call(d, patch); if (!Array.isArray(patches) || patches.length === 0) { throw new Error('Unable to parse Patch string'); } patches.forEach((p) => { p.diffs.forEach((diff) => { diff[1] += os_1.EOL; }); getTextEditsInternal(originalContents, p.diffs, p.start1).forEach((edit) => { switch (edit.action) { case EditAction.Delete: workspaceEdit.delete(uri, new vscode_1.Range(edit.start, edit.end)); break; case EditAction.Insert: workspaceEdit.insert(uri, edit.start, edit.text); break; case EditAction.Replace: workspaceEdit.replace(uri, new vscode_1.Range(edit.start, edit.end), edit.text); break; default: break; } }); }); return workspaceEdit; } }; EditorUtils = __decorate([ (0, inversify_1.injectable)() ], EditorUtils); exports.EditorUtils = EditorUtils; /***/ }), /***/ "./src/client/common/errors/errorUtils.ts": /*!************************************************!*\ !*** ./src/client/common/errors/errorUtils.ts ***! \************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WrappedError = exports.ErrorUtils = void 0; const os_1 = __webpack_require__(/*! os */ "os"); class ErrorUtils { static outputHasModuleNotInstalledError(moduleName, content) { return content && (content.indexOf(`No module named ${moduleName}`) > 0 || content.indexOf(`No module named '${moduleName}'`) > 0) ? true : false; } } exports.ErrorUtils = ErrorUtils; class WrappedError extends Error { constructor(message, originalException) { super(message); this.stack = `${new Error('').stack}${os_1.EOL}${os_1.EOL}${originalException.stack}`; } } exports.WrappedError = WrappedError; /***/ }), /***/ "./src/client/common/errors/moduleNotInstalledError.ts": /*!*************************************************************!*\ !*** ./src/client/common/errors/moduleNotInstalledError.ts ***! \*************************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ModuleNotInstalledError = void 0; class ModuleNotInstalledError extends Error { constructor(moduleName) { super(`Module '${moduleName}' not installed.`); } } exports.ModuleNotInstalledError = ModuleNotInstalledError; /***/ }), /***/ "./src/client/common/extensions.ts": /*!*****************************************!*\ !*** ./src/client/common/extensions.ts ***! \*****************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.format = exports.trimQuotes = void 0; String.prototype.toCommandArgumentForPythonMgrExt = function () { if (!this) { return this; } return (this.indexOf(' ') >= 0 || this.indexOf('&') >= 0 || this.indexOf('(') >= 0 || this.indexOf(')') >= 0) && !this.startsWith('"') && !this.endsWith('"') ? `"${this}"` : this.toString(); }; String.prototype.fileToCommandArgumentForPythonMgrExt = function () { if (!this) { return this; } return this.toCommandArgumentForPythonMgrExt().replace(/\\/g, '/'); }; function trimQuotes(value) { if (!value) { return value; } return value.replace(/(^['"])|(['"]$)/g, ''); } exports.trimQuotes = trimQuotes; ; Promise.prototype.ignoreErrors = function () { return this.catch(() => { }); }; function format(value) { const args = arguments; return value.replace(/{(\d+)}/g, (match, number) => (args[number] === undefined ? match : args[number])); } exports.format = format; ; /***/ }), /***/ "./src/client/common/persistentState.ts": /*!**********************************************!*\ !*** ./src/client/common/persistentState.ts ***! \**********************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getGlobalStorage = exports.PersistentStateFactory = exports.WORKSPACE_PERSISTENT_KEYS_DEPRECATED = exports.GLOBAL_PERSISTENT_KEYS_DEPRECATED = exports.PersistentState = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const logging_1 = __webpack_require__(/*! ../logging */ "./src/client/logging/index.ts"); const types_1 = __webpack_require__(/*! ./application/types */ "./src/client/common/application/types.ts"); const constants_1 = __webpack_require__(/*! ./constants */ "./src/client/common/constants.ts"); const types_2 = __webpack_require__(/*! ./types */ "./src/client/common/types.ts"); const decorators_1 = __webpack_require__(/*! ./utils/decorators */ "./src/client/common/utils/decorators.ts"); class PersistentState { constructor(storage, key, defaultValue, expiryDurationMs) { this.storage = storage; this.key = key; this.defaultValue = defaultValue; this.expiryDurationMs = expiryDurationMs; } get value() { if (this.expiryDurationMs) { const cachedData = this.storage.get(this.key, { data: this.defaultValue }); if (!cachedData || !cachedData.expiry || cachedData.expiry < Date.now()) { return this.defaultValue; } else { return cachedData.data; } } else { return this.storage.get(this.key, this.defaultValue); } } async updateValue(newValue, retryOnce = true) { try { if (this.expiryDurationMs) { await this.storage.update(this.key, { data: newValue, expiry: Date.now() + this.expiryDurationMs }); } else { await this.storage.update(this.key, newValue); } if (retryOnce && JSON.stringify(this.value) != JSON.stringify(newValue)) { (0, logging_1.traceVerbose)('Storage update failed for key', this.key, ' retrying by resetting first'); await this.updateValue(undefined, false); await this.updateValue(newValue, false); if (JSON.stringify(this.value) != JSON.stringify(newValue)) { (0, logging_1.traceWarn)('Retry failed, storage update failed for key', this.key); } } } catch (ex) { (0, logging_1.traceError)('Error while updating storage for key:', this.key, ex); } } } exports.PersistentState = PersistentState; exports.GLOBAL_PERSISTENT_KEYS_DEPRECATED = 'PYTHON_EXTENSION_GLOBAL_STORAGE_KEYS'; exports.WORKSPACE_PERSISTENT_KEYS_DEPRECATED = 'PYTHON_EXTENSION_WORKSPACE_STORAGE_KEYS'; const GLOBAL_PERSISTENT_KEYS = 'PYTHON_GLOBAL_STORAGE_KEYS'; const WORKSPACE_PERSISTENT_KEYS = 'PYTHON_WORKSPACE_STORAGE_KEYS'; let PersistentStateFactory = class PersistentStateFactory { constructor(globalState, workspaceState, cmdManager) { this.globalState = globalState; this.workspaceState = workspaceState; this.cmdManager = cmdManager; this.supportedWorkspaceTypes = { untrustedWorkspace: false, virtualWorkspace: true }; this._globalKeysStorage = new PersistentState(this.globalState, GLOBAL_PERSISTENT_KEYS, []); this._workspaceKeysStorage = new PersistentState(this.workspaceState, WORKSPACE_PERSISTENT_KEYS, []); } async activate() { var _a; (_a = this.cmdManager) === null || _a === void 0 ? void 0 : _a.registerCommand(constants_1.Commands.ClearStorage, this.cleanAllPersistentStates.bind(this)); const globalKeysStorageDeprecated = this.createGlobalPersistentState(exports.GLOBAL_PERSISTENT_KEYS_DEPRECATED, []); const workspaceKeysStorageDeprecated = this.createWorkspacePersistentState(exports.WORKSPACE_PERSISTENT_KEYS_DEPRECATED, []); if (globalKeysStorageDeprecated.value.length > 0) { globalKeysStorageDeprecated.updateValue([]).ignoreErrors(); } if (workspaceKeysStorageDeprecated.value.length > 0) { workspaceKeysStorageDeprecated.updateValue([]).ignoreErrors(); } } createGlobalPersistentState(key, defaultValue, expiryDurationMs) { this.addKeyToStorage('global', key, defaultValue).ignoreErrors(); return new PersistentState(this.globalState, key, defaultValue, expiryDurationMs); } createWorkspacePersistentState(key, defaultValue, expiryDurationMs) { this.addKeyToStorage('workspace', key, defaultValue).ignoreErrors(); return new PersistentState(this.workspaceState, key, defaultValue, expiryDurationMs); } async addKeyToStorage(keyStorageType, key, defaultValue) { const storage = keyStorageType === 'global' ? this._globalKeysStorage : this._workspaceKeysStorage; const found = storage.value.find((value) => value.key === key); if (!found) { await storage.updateValue([{ key, defaultValue }, ...storage.value]); } } async cleanAllPersistentStates() { await Promise.all(this._globalKeysStorage.value.map(async (keyContent) => { const storage = this.createGlobalPersistentState(keyContent.key); await storage.updateValue(keyContent.defaultValue); })); await Promise.all(this._workspaceKeysStorage.value.map(async (keyContent) => { const storage = this.createWorkspacePersistentState(keyContent.key); await storage.updateValue(keyContent.defaultValue); })); await this._globalKeysStorage.updateValue([]); await this._workspaceKeysStorage.updateValue([]); } }; __decorate([ (0, decorators_1.cache)(-1, true) ], PersistentStateFactory.prototype, "addKeyToStorage", null); PersistentStateFactory = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_2.IMemento)), __param(0, (0, inversify_1.named)(types_2.GLOBAL_MEMENTO)), __param(1, (0, inversify_1.inject)(types_2.IMemento)), __param(1, (0, inversify_1.named)(types_2.WORKSPACE_MEMENTO)), __param(2, (0, inversify_1.inject)(types_1.ICommandManager)) ], PersistentStateFactory); exports.PersistentStateFactory = PersistentStateFactory; function getGlobalStorage(context, key, defaultValue) { const globalKeysStorage = new PersistentState(context.globalState, GLOBAL_PERSISTENT_KEYS, []); const found = globalKeysStorage.value.find((value) => value.key === key); if (!found) { const newValue = [{ key, defaultValue }, ...globalKeysStorage.value]; globalKeysStorage.updateValue(newValue).ignoreErrors(); } const raw = new PersistentState(context.globalState, key, defaultValue); return { get() { return raw.value; }, set(value) { return raw.updateValue(value); }, }; } exports.getGlobalStorage = getGlobalStorage; /***/ }), /***/ "./src/client/common/platform/errors.ts": /*!**********************************************!*\ !*** ./src/client/common/platform/errors.ts ***! \**********************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isNoPermissionsError = exports.isNotDirError = exports.isFileIsDirError = exports.isFileExistsError = exports.isFileNotFoundError = exports.createDirNotEmptyError = void 0; const vscode = __webpack_require__(/*! vscode */ "vscode"); var vscErrors; (function (vscErrors) { const FILE_NOT_FOUND = vscode.FileSystemError.FileNotFound().name; const FILE_EXISTS = vscode.FileSystemError.FileExists().name; const IS_DIR = vscode.FileSystemError.FileIsADirectory().name; const NOT_DIR = vscode.FileSystemError.FileNotADirectory().name; const NO_PERM = vscode.FileSystemError.NoPermissions().name; const known = [ FILE_NOT_FOUND, FILE_EXISTS, IS_DIR, NOT_DIR, NO_PERM, ]; function errorMatches(err, expectedName) { if (!known.includes(err.name)) { return undefined; } return err.name === expectedName; } function isFileNotFound(err) { return errorMatches(err, FILE_NOT_FOUND); } vscErrors.isFileNotFound = isFileNotFound; function isFileExists(err) { return errorMatches(err, FILE_EXISTS); } vscErrors.isFileExists = isFileExists; function isFileIsDir(err) { return errorMatches(err, IS_DIR); } vscErrors.isFileIsDir = isFileIsDir; function isNotDir(err) { return errorMatches(err, NOT_DIR); } vscErrors.isNotDir = isNotDir; function isNoPermissions(err) { return errorMatches(err, NO_PERM); } vscErrors.isNoPermissions = isNoPermissions; })(vscErrors || (vscErrors = {})); function createDirNotEmptyError(dirname) { const err = new Error(`directory "${dirname}" not empty`); err.name = 'SystemError'; err.code = 'ENOTEMPTY'; err.path = dirname; err.syscall = 'rmdir'; return err; } exports.createDirNotEmptyError = createDirNotEmptyError; function isSystemError(err, expectedCode) { const code = err.code; if (!code) { return undefined; } return code === expectedCode; } function isFileNotFoundError(err) { const error = err; const matched = vscErrors.isFileNotFound(error); if (matched !== undefined) { return matched; } return isSystemError(error, 'ENOENT'); } exports.isFileNotFoundError = isFileNotFoundError; function isFileExistsError(err) { const error = err; const matched = vscErrors.isFileExists(error); if (matched !== undefined) { return matched; } return isSystemError(error, 'EEXIST'); } exports.isFileExistsError = isFileExistsError; function isFileIsDirError(err) { const matched = vscErrors.isFileIsDir(err); if (matched !== undefined) { return matched; } return isSystemError(err, 'EISDIR'); } exports.isFileIsDirError = isFileIsDirError; function isNotDirError(err) { const matched = vscErrors.isNotDir(err); if (matched !== undefined) { return matched; } return isSystemError(err, 'ENOTDIR'); } exports.isNotDirError = isNotDirError; function isNoPermissionsError(err) { const error = err; const matched = vscErrors.isNoPermissions(error); if (matched !== undefined) { return matched; } return isSystemError(error, 'EACCES'); } exports.isNoPermissionsError = isNoPermissionsError; /***/ }), /***/ "./src/client/common/platform/fileSystem.ts": /*!**************************************************!*\ !*** ./src/client/common/platform/fileSystem.ts ***! \**************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FileSystem = exports.getHashString = exports.FileSystemUtils = exports.RawFileSystem = exports.convertStat = void 0; const crypto_1 = __webpack_require__(/*! crypto */ "crypto"); const fs = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const glob = __webpack_require__(/*! glob */ "./node_modules/glob/glob.js"); const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const util_1 = __webpack_require__(/*! util */ "util"); const vscode = __webpack_require__(/*! vscode */ "vscode"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); __webpack_require__(/*! ../extensions */ "./src/client/common/extensions.ts"); const filesystem_1 = __webpack_require__(/*! ../utils/filesystem */ "./src/client/common/utils/filesystem.ts"); const errors_1 = __webpack_require__(/*! ./errors */ "./src/client/common/platform/errors.ts"); const fs_paths_1 = __webpack_require__(/*! ./fs-paths */ "./src/client/common/platform/fs-paths.ts"); const fs_temp_1 = __webpack_require__(/*! ./fs-temp */ "./src/client/common/platform/fs-temp.ts"); const types_1 = __webpack_require__(/*! ./types */ "./src/client/common/platform/types.ts"); const ENCODING = 'utf8'; function convertStat(old, filetype) { return { type: filetype, size: old.size, ctime: Math.round(old.ctimeMs), mtime: Math.round(old.mtimeMs), }; } exports.convertStat = convertStat; function filterByFileType(files, fileType) { if (fileType === types_1.FileType.Unknown) { return files.filter(([_file, ft]) => ft === types_1.FileType.Unknown || ft === (types_1.FileType.SymbolicLink & types_1.FileType.Unknown)); } return files.filter(([_file, ft]) => (ft & fileType) > 0); } class RawFileSystem { constructor(paths, vscfs, fsExtra) { this.paths = paths; this.vscfs = vscfs; this.fsExtra = fsExtra; } static withDefaults(paths, vscfs, fsExtra) { return new RawFileSystem(paths || fs_paths_1.FileSystemPaths.withDefaults(), vscfs || vscode.workspace.fs, fsExtra || fs); } async pathExists(filename) { return this.fsExtra.pathExists(filename); } async stat(filename) { const uri = vscode.Uri.file(filename); return this.vscfs.stat(uri); } async lstat(filename) { const stat = await this.fsExtra.lstat(filename); const fileType = (0, filesystem_1.convertFileType)(stat); return convertStat(stat, fileType); } async chmod(filename, mode) { return this.fsExtra.chmod(filename, mode); } async move(src, tgt) { const srcUri = vscode.Uri.file(src); const tgtUri = vscode.Uri.file(tgt); await this.vscfs.stat(vscode.Uri.file(this.paths.dirname(tgt))); const options = { overwrite: false }; try { await this.vscfs.rename(srcUri, tgtUri, options); } catch (err) { if (!(0, errors_1.isFileExistsError)(err)) { throw err; } const stat = await this.vscfs.stat(tgtUri); if (stat.type === types_1.FileType.Directory) { throw err; } options.overwrite = true; await this.vscfs.rename(srcUri, tgtUri, options); } } async readData(filename) { const uri = vscode.Uri.file(filename); const data = await this.vscfs.readFile(uri); return Buffer.from(data); } async readText(filename) { const uri = vscode.Uri.file(filename); const result = await this.vscfs.readFile(uri); const data = Buffer.from(result); return data.toString(ENCODING); } async writeText(filename, text) { const uri = vscode.Uri.file(filename); const data = Buffer.from(text); await this.vscfs.writeFile(uri, data); } async appendText(filename, text) { return this.fsExtra.appendFile(filename, text); } async copyFile(src, dest) { const srcURI = vscode.Uri.file(src); const destURI = vscode.Uri.file(dest); await this.vscfs.stat(vscode.Uri.file(this.paths.dirname(dest))); await this.vscfs.copy(srcURI, destURI, { overwrite: true, }); } async rmfile(filename) { const uri = vscode.Uri.file(filename); return this.vscfs.delete(uri, { recursive: false, useTrash: false, }); } async rmdir(dirname) { const uri = vscode.Uri.file(dirname); const files = await this.vscfs.readDirectory(uri); if (files && files.length > 0) { throw (0, errors_1.createDirNotEmptyError)(dirname); } return this.vscfs.delete(uri, { recursive: true, useTrash: false, }); } async rmtree(dirname) { const uri = vscode.Uri.file(dirname); await this.vscfs.stat(uri); return this.vscfs.delete(uri, { recursive: true, useTrash: false, }); } async mkdirp(dirname) { const uri = vscode.Uri.file(dirname); await this.vscfs.createDirectory(uri); } async listdir(dirname) { const uri = vscode.Uri.file(dirname); const files = await this.vscfs.readDirectory(uri); return files.map(([basename, filetype]) => { const filename = this.paths.join(dirname, basename); return [filename, filetype]; }); } statSync(filename) { let stat = this.fsExtra.lstatSync(filename); let filetype = types_1.FileType.Unknown; if (stat.isSymbolicLink()) { filetype = types_1.FileType.SymbolicLink; stat = this.fsExtra.statSync(filename); } filetype |= (0, filesystem_1.convertFileType)(stat); return convertStat(stat, filetype); } readTextSync(filename) { return this.fsExtra.readFileSync(filename, ENCODING); } createReadStream(filename) { return this.fsExtra.createReadStream(filename); } createWriteStream(filename) { return this.fsExtra.createWriteStream(filename); } } exports.RawFileSystem = RawFileSystem; class FileSystemUtils { constructor(raw, pathUtils, paths, tmp, getHash, globFiles) { this.raw = raw; this.pathUtils = pathUtils; this.paths = paths; this.tmp = tmp; this.getHash = getHash; this.globFiles = globFiles; } static withDefaults(raw, pathUtils, tmp, getHash, globFiles) { pathUtils = pathUtils || fs_paths_1.FileSystemPathUtils.withDefaults(); return new FileSystemUtils(raw || RawFileSystem.withDefaults(pathUtils.paths), pathUtils, pathUtils.paths, tmp || fs_temp_1.TemporaryFileSystem.withDefaults(), getHash || getHashString, globFiles || (0, util_1.promisify)(glob)); } async createDirectory(directoryPath) { return this.raw.mkdirp(directoryPath); } async deleteDirectory(directoryPath) { return this.raw.rmdir(directoryPath); } async deleteFile(filename) { return this.raw.rmfile(filename); } async pathExists(filename, fileType) { if (fileType === undefined) { return this.raw.pathExists(filename); } let stat; try { stat = await this.raw.stat(filename); } catch (err) { if ((0, errors_1.isFileNotFoundError)(err)) { return false; } (0, logging_1.traceError)(`stat() failed for "${filename}"`, err); return false; } if (fileType === types_1.FileType.Unknown) { return stat.type === types_1.FileType.Unknown; } return (stat.type & fileType) === fileType; } async fileExists(filename) { return this.pathExists(filename, types_1.FileType.File); } async directoryExists(dirname) { return this.pathExists(dirname, types_1.FileType.Directory); } async listdir(dirname) { try { return await this.raw.listdir(dirname); } catch (err) { if (!(await this.pathExists(dirname))) { return []; } throw err; } } async getSubDirectories(dirname) { const files = await this.listdir(dirname); const filtered = filterByFileType(files, types_1.FileType.Directory); return filtered.map(([filename, _fileType]) => filename); } async getFiles(dirname) { const files = await this.listdir(dirname); const filtered = filterByFileType(files, types_1.FileType.File); return filtered.map(([filename, _fileType]) => filename); } async isDirReadonly(dirname) { const filePath = `${dirname}${this.paths.sep}___vscpTest___`; try { await this.raw.stat(dirname); await this.raw.writeText(filePath, ''); } catch (err) { if ((0, errors_1.isNoPermissionsError)(err)) { return true; } throw err; } this.raw .rmfile(filePath) .ignoreErrors(); return false; } async getFileHash(filename) { const stat = await this.raw.lstat(filename); const data = `${stat.ctime}-${stat.mtime}`; return this.getHash(data); } async search(globPattern, cwd, dot) { let options; if (cwd) { options = { ...options, cwd }; } if (dot) { options = { ...options, dot }; } const found = await this.globFiles(globPattern, options); return Array.isArray(found) ? found : []; } fileExistsSync(filePath) { try { this.raw.statSync(filePath); } catch (err) { if ((0, errors_1.isFileNotFoundError)(err)) { return false; } throw err; } return true; } } exports.FileSystemUtils = FileSystemUtils; function getHashString(data) { const hash = (0, crypto_1.createHash)('sha512'); hash.update(data); return hash.digest('hex'); } exports.getHashString = getHashString; let FileSystem = class FileSystem { constructor() { this.utils = FileSystemUtils.withDefaults(); } get directorySeparatorChar() { return this.utils.paths.sep; } arePathsSame(path1, path2) { return this.utils.pathUtils.arePathsSame(path1, path2); } getDisplayName(path) { return this.utils.pathUtils.getDisplayName(path); } async stat(filename) { return this.utils.raw.stat(filename); } async createDirectory(dirname) { return this.utils.createDirectory(dirname); } async deleteDirectory(dirname) { return this.utils.deleteDirectory(dirname); } async listdir(dirname) { return this.utils.listdir(dirname); } async readFile(filePath) { return this.utils.raw.readText(filePath); } async readData(filePath) { return this.utils.raw.readData(filePath); } async writeFile(filename, data) { return this.utils.raw.writeText(filename, data); } async appendFile(filename, text) { return this.utils.raw.appendText(filename, text); } async copyFile(src, dest) { return this.utils.raw.copyFile(src, dest); } async deleteFile(filename) { return this.utils.deleteFile(filename); } async chmod(filename, mode) { return this.utils.raw.chmod(filename, mode); } async move(src, tgt) { await this.utils.raw.move(src, tgt); } readFileSync(filePath) { return this.utils.raw.readTextSync(filePath); } createReadStream(filePath) { return this.utils.raw.createReadStream(filePath); } createWriteStream(filePath) { return this.utils.raw.createWriteStream(filePath); } async fileExists(filename) { return this.utils.fileExists(filename); } pathExists(filename) { return this.utils.pathExists(filename); } fileExistsSync(filename) { return this.utils.fileExistsSync(filename); } async directoryExists(dirname) { return this.utils.directoryExists(dirname); } async getSubDirectories(dirname) { return this.utils.getSubDirectories(dirname); } async getFiles(dirname) { return this.utils.getFiles(dirname); } async getFileHash(filename) { return this.utils.getFileHash(filename); } async search(globPattern, cwd, dot) { return this.utils.search(globPattern, cwd, dot); } async createTemporaryFile(suffix, mode) { return this.utils.tmp.createFile(suffix, mode); } async isDirReadonly(dirname) { return this.utils.isDirReadonly(dirname); } }; FileSystem = __decorate([ (0, inversify_1.injectable)() ], FileSystem); exports.FileSystem = FileSystem; /***/ }), /***/ "./src/client/common/platform/fileSystemWatcher.ts": /*!*********************************************************!*\ !*** ./src/client/common/platform/fileSystemWatcher.ts ***! \*********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.watchLocationForPattern = exports.FileChangeType = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const resourceLifecycle_1 = __webpack_require__(/*! ../utils/resourceLifecycle */ "./src/client/common/utils/resourceLifecycle.ts"); var FileChangeType; (function (FileChangeType) { FileChangeType["Changed"] = "changed"; FileChangeType["Created"] = "created"; FileChangeType["Deleted"] = "deleted"; })(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {})); function watchLocationForPattern(baseDir, pattern, callback) { const globPattern = new vscode_1.RelativePattern(baseDir, pattern); const disposables = new resourceLifecycle_1.Disposables(); (0, logging_1.traceVerbose)(`Start watching: ${baseDir} with pattern ${pattern} using VSCode API`); try { const watcher = vscode_1.workspace.createFileSystemWatcher(globPattern); disposables.push(watcher.onDidCreate((e) => callback(FileChangeType.Created, e.fsPath))); disposables.push(watcher.onDidChange((e) => callback(FileChangeType.Changed, e.fsPath))); disposables.push(watcher.onDidDelete((e) => callback(FileChangeType.Deleted, e.fsPath))); } catch (ex) { (0, logging_1.traceError)(`Failed to create File System watcher for patter ${pattern} in ${baseDir}`, ex); } return disposables; } exports.watchLocationForPattern = watchLocationForPattern; /***/ }), /***/ "./src/client/common/platform/fs-paths.ts": /*!************************************************!*\ !*** ./src/client/common/platform/fs-paths.ts ***! \************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.arePathsSame = exports.isParentPath = exports.normCase = exports.normCasePath = exports.FileSystemPathUtils = exports.Executables = exports.FileSystemPaths = void 0; const nodepath = __webpack_require__(/*! path */ "path"); const exec_1 = __webpack_require__(/*! ../utils/exec */ "./src/client/common/utils/exec.ts"); const platform_1 = __webpack_require__(/*! ../utils/platform */ "./src/client/common/utils/platform.ts"); const untildify = __webpack_require__(/*! untildify */ "./node_modules/untildify/index.js"); class FileSystemPaths { constructor(isCaseInsensitive, raw) { this.isCaseInsensitive = isCaseInsensitive; this.raw = raw; } static withDefaults(isCaseInsensitive) { if (isCaseInsensitive === undefined) { isCaseInsensitive = (0, platform_1.getOSType)() === platform_1.OSType.Windows; } return new FileSystemPaths(isCaseInsensitive, nodepath); } get sep() { return this.raw.sep; } join(...filenames) { return this.raw.join(...filenames); } dirname(filename) { return this.raw.dirname(filename); } basename(filename, suffix) { return this.raw.basename(filename, suffix); } normalize(filename) { return this.raw.normalize(filename); } normCase(filename) { filename = this.raw.normalize(filename); return this.isCaseInsensitive ? filename.toUpperCase() : filename; } } exports.FileSystemPaths = FileSystemPaths; class Executables { constructor(delimiter, osType) { this.delimiter = delimiter; this.osType = osType; } static withDefaults() { return new Executables(nodepath.delimiter, (0, platform_1.getOSType)()); } get envVar() { return (0, exec_1.getSearchPathEnvVarNames)(this.osType)[0]; } } exports.Executables = Executables; class FileSystemPathUtils { constructor(home, paths, executables, raw) { this.home = home; this.paths = paths; this.executables = executables; this.raw = raw; } static withDefaults(paths) { if (paths === undefined) { paths = FileSystemPaths.withDefaults(); } return new FileSystemPathUtils(untildify('~'), paths, Executables.withDefaults(), nodepath); } arePathsSame(path1, path2) { path1 = this.paths.normCase(path1); path2 = this.paths.normCase(path2); return path1 === path2; } getDisplayName(filename, cwd) { if (cwd && isParentPath(filename, cwd)) { return `.${this.paths.sep}${this.raw.relative(cwd, filename)}`; } else if (isParentPath(filename, this.home)) { return `~${this.paths.sep}${this.raw.relative(this.home, filename)}`; } else { return filename; } } } exports.FileSystemPathUtils = FileSystemPathUtils; function normCasePath(filePath) { return normCase(nodepath.normalize(filePath)); } exports.normCasePath = normCasePath; function normCase(s) { return (0, platform_1.getOSType)() === platform_1.OSType.Windows ? s.toUpperCase() : s; } exports.normCase = normCase; function isParentPath(filePath, parentPath) { if (!parentPath.endsWith(nodepath.sep)) { parentPath += nodepath.sep; } if (!filePath.endsWith(nodepath.sep)) { filePath += nodepath.sep; } return normCasePath(filePath).startsWith(normCasePath(parentPath)); } exports.isParentPath = isParentPath; function arePathsSame(path1, path2) { return normCasePath(path1) === normCasePath(path2); } exports.arePathsSame = arePathsSame; /***/ }), /***/ "./src/client/common/platform/fs-temp.ts": /*!***********************************************!*\ !*** ./src/client/common/platform/fs-temp.ts ***! \***********************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TemporaryFileSystem = void 0; const tmp = __webpack_require__(/*! tmp */ "./node_modules/tmp/lib/tmp.js"); class TemporaryFileSystem { constructor(raw) { this.raw = raw; } static withDefaults() { return new TemporaryFileSystem(tmp); } createFile(suffix, mode) { const opts = { postfix: suffix, mode, }; return new Promise((resolve, reject) => { this.raw.file(opts, (err, filename, _fd, cleanUp) => { if (err) { return reject(err); } resolve({ filePath: filename, dispose: cleanUp, }); }); }); } } exports.TemporaryFileSystem = TemporaryFileSystem; /***/ }), /***/ "./src/client/common/platform/pathUtils.ts": /*!*************************************************!*\ !*** ./src/client/common/platform/pathUtils.ts ***! \*************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PathUtils = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const path = __webpack_require__(/*! path */ "path"); const types_1 = __webpack_require__(/*! ../types */ "./src/client/common/types.ts"); const platform_1 = __webpack_require__(/*! ../utils/platform */ "./src/client/common/utils/platform.ts"); const fs_paths_1 = __webpack_require__(/*! ./fs-paths */ "./src/client/common/platform/fs-paths.ts"); const untildify = __webpack_require__(/*! untildify */ "./node_modules/untildify/index.js"); let PathUtils = class PathUtils { constructor(isWindows) { const osType = isWindows ? platform_1.OSType.Windows : platform_1.OSType.Unknown; this.utils = new fs_paths_1.FileSystemPathUtils(untildify('~'), fs_paths_1.FileSystemPaths.withDefaults(), new fs_paths_1.Executables(path.delimiter, osType), path); } get home() { return this.utils.home; } get delimiter() { return this.utils.executables.delimiter; } get separator() { return this.utils.paths.sep; } getPathVariableName() { return this.utils.executables.envVar; } getDisplayName(pathValue, cwd) { return this.utils.getDisplayName(pathValue, cwd); } basename(pathValue, ext) { return this.utils.paths.basename(pathValue, ext); } }; PathUtils = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_1.IsWindows)) ], PathUtils); exports.PathUtils = PathUtils; /***/ }), /***/ "./src/client/common/platform/platformService.ts": /*!*******************************************************!*\ !*** ./src/client/common/platform/platformService.ts ***! \*******************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isWindows = exports.PlatformService = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const os = __webpack_require__(/*! os */ "os"); const semver_1 = __webpack_require__(/*! semver */ "./node_modules/semver/semver.js"); const exec_1 = __webpack_require__(/*! ../utils/exec */ "./src/client/common/utils/exec.ts"); const platform_1 = __webpack_require__(/*! ../utils/platform */ "./src/client/common/utils/platform.ts"); const version_1 = __webpack_require__(/*! ../utils/version */ "./src/client/common/utils/version.ts"); let PlatformService = class PlatformService { constructor() { this.osType = (0, platform_1.getOSType)(); } get pathVariableName() { return (0, exec_1.getSearchPathEnvVarNames)(this.osType)[0]; } get virtualEnvBinName() { return this.isWindows ? 'Scripts' : 'bin'; } async getVersion() { if (this.version) { return this.version; } switch (this.osType) { case platform_1.OSType.Windows: case platform_1.OSType.OSX: try { const ver = (0, semver_1.coerce)(os.release()); if (ver) { this.version = ver; return this.version; } throw new Error('Unable to parse version'); } catch (ex) { return (0, version_1.parseSemVerSafe)(os.release()); } default: throw new Error('Not Supported'); } } get isWindows() { return isWindows(); } get isMac() { return this.osType === platform_1.OSType.OSX; } get isLinux() { return this.osType === platform_1.OSType.Linux; } get osRelease() { return os.release(); } get is64bit() { return (0, platform_1.getArchitecture)() === platform_1.Architecture.x64; } }; PlatformService = __decorate([ (0, inversify_1.injectable)() ], PlatformService); exports.PlatformService = PlatformService; function isWindows() { return (0, platform_1.getOSType)() === platform_1.OSType.Windows; } exports.isWindows = isWindows; /***/ }), /***/ "./src/client/common/platform/registry.ts": /*!************************************************!*\ !*** ./src/client/common/platform/registry.ts ***! \************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getArchitectureDisplayName = void 0; const platform_1 = __webpack_require__(/*! ../utils/platform */ "./src/client/common/utils/platform.ts"); function getArchitectureDisplayName(arch) { switch (arch) { case platform_1.Architecture.x64: return '64-bit'; case platform_1.Architecture.x86: return '32-bit'; default: return ''; } } exports.getArchitectureDisplayName = getArchitectureDisplayName; /***/ }), /***/ "./src/client/common/platform/serviceRegistry.ts": /*!*******************************************************!*\ !*** ./src/client/common/platform/serviceRegistry.ts ***! \*******************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.registerTypes = void 0; const fileSystem_1 = __webpack_require__(/*! ./fileSystem */ "./src/client/common/platform/fileSystem.ts"); const platformService_1 = __webpack_require__(/*! ./platformService */ "./src/client/common/platform/platformService.ts"); const types_1 = __webpack_require__(/*! ./types */ "./src/client/common/platform/types.ts"); function registerTypes(serviceManager) { serviceManager.addSingleton(types_1.IPlatformService, platformService_1.PlatformService); serviceManager.addSingleton(types_1.IFileSystem, fileSystem_1.FileSystem); } exports.registerTypes = registerTypes; /***/ }), /***/ "./src/client/common/platform/types.ts": /*!*********************************************!*\ !*** ./src/client/common/platform/types.ts ***! \*********************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.IFileSystem = exports.IFileSystemPathUtils = exports.IPlatformService = exports.RegistryHive = exports.FileType = void 0; const vscode = __webpack_require__(/*! vscode */ "vscode"); exports.FileType = vscode.FileType; var RegistryHive; (function (RegistryHive) { RegistryHive[RegistryHive["HKCU"] = 0] = "HKCU"; RegistryHive[RegistryHive["HKLM"] = 1] = "HKLM"; })(RegistryHive = exports.RegistryHive || (exports.RegistryHive = {})); exports.IPlatformService = Symbol('IPlatformService'); exports.IFileSystemPathUtils = Symbol('IFileSystemPathUtils'); exports.IFileSystem = Symbol('IFileSystem'); /***/ }), /***/ "./src/client/common/process/constants.ts": /*!************************************************!*\ !*** ./src/client/common/process/constants.ts ***! \************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DEFAULT_ENCODING = void 0; exports.DEFAULT_ENCODING = 'utf8'; /***/ }), /***/ "./src/client/common/process/currentProcess.ts": /*!*****************************************************!*\ !*** ./src/client/common/process/currentProcess.ts ***! \*****************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CurrentProcess = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); let CurrentProcess = class CurrentProcess { constructor() { this.on = (event, listener) => { process.on(event, listener); return process; }; } get env() { return process.env; } get argv() { return process.argv; } get stdout() { return process.stdout; } get stdin() { return process.stdin; } get execPath() { return process.execPath; } }; CurrentProcess = __decorate([ (0, inversify_1.injectable)() ], CurrentProcess); exports.CurrentProcess = CurrentProcess; /***/ }), /***/ "./src/client/common/process/decoder.ts": /*!**********************************************!*\ !*** ./src/client/common/process/decoder.ts ***! \**********************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.decodeBuffer = void 0; const iconv = __webpack_require__(/*! iconv-lite */ "./node_modules/iconv-lite/lib/index.js"); const constants_1 = __webpack_require__(/*! ./constants */ "./src/client/common/process/constants.ts"); function decodeBuffer(buffers, encoding = constants_1.DEFAULT_ENCODING) { encoding = iconv.encodingExists(encoding) ? encoding : constants_1.DEFAULT_ENCODING; return iconv.decode(Buffer.concat(buffers), encoding); } exports.decodeBuffer = decodeBuffer; /***/ }), /***/ "./src/client/common/process/internal/python.ts": /*!******************************************************!*\ !*** ./src/client/common/process/internal/python.ts ***! \******************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getModuleVersion = exports.isModuleInstalled = exports.isValid = exports.getUserSitePackages = exports.getSitePackages = exports.getExecutable = exports.execModule = exports.execCode = void 0; function execCode(code) { let args = ['-c', code]; return args; } exports.execCode = execCode; function execModule(name, moduleArgs) { const args = ['-m', name, ...moduleArgs]; return args; } exports.execModule = execModule; function getExecutable() { const args = ['-c', 'import sys;print(sys.executable)']; function parse(out) { return out.trim(); } return [args, parse]; } exports.getExecutable = getExecutable; function getSitePackages() { const args = ['-c', 'from distutils.sysconfig import get_python_lib; print(get_python_lib())']; function parse(out) { return out.trim(); } return [args, parse]; } exports.getSitePackages = getSitePackages; function getUserSitePackages() { const args = ['site', '--user-site']; function parse(out) { return out.trim(); } return [args, parse]; } exports.getUserSitePackages = getUserSitePackages; function isValid() { const args = ['-c', 'print(1234)']; function parse(out) { return out.startsWith('1234'); } return [args, parse]; } exports.isValid = isValid; function isModuleInstalled(name) { const args = ['-c', `import ${name}`]; function parse(_out) { return true; } return [args, parse]; } exports.isModuleInstalled = isModuleInstalled; function getModuleVersion(name) { const args = ['-c', `import ${name}; print(${name}.__version__)`]; function parse(out) { return out.trim(); } return [args, parse]; } exports.getModuleVersion = getModuleVersion; /***/ }), /***/ "./src/client/common/process/internal/scripts/constants.ts": /*!*****************************************************************!*\ !*** ./src/client/common/process/internal/scripts/constants.ts ***! \*****************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports._SCRIPTS_DIR = void 0; const path = __webpack_require__(/*! path */ "path"); const constants_1 = __webpack_require__(/*! ../../../constants */ "./src/client/common/constants.ts"); exports._SCRIPTS_DIR = path.join(constants_1.EXTENSION_ROOT_DIR, 'pythonFiles'); /***/ }), /***/ "./src/client/common/process/internal/scripts/index.ts": /*!*************************************************************!*\ !*** ./src/client/common/process/internal/scripts/index.ts ***! \*************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.installedCheckScript = exports.createCondaScript = exports.createVenvScript = exports.linterScript = exports.tensorboardLauncher = exports.execution_py_testlauncher = exports.visualstudio_py_testlauncher = exports.pytestlauncher = exports.testlauncher = exports.shell_exec = exports.printEnvVariables = exports.normalizeSelection = exports.interpreterInfo = exports.OUTPUT_MARKER_SCRIPT = void 0; const path = __webpack_require__(/*! path */ "path"); const constants_1 = __webpack_require__(/*! ./constants */ "./src/client/common/process/internal/scripts/constants.ts"); const SCRIPTS_DIR = constants_1._SCRIPTS_DIR; exports.OUTPUT_MARKER_SCRIPT = path.join(constants_1._SCRIPTS_DIR, 'get_output_via_markers.py'); function interpreterInfo() { const script = path.join(SCRIPTS_DIR, 'interpreterInfo.py'); const args = [script]; function parse(out) { try { return JSON.parse(out); } catch (ex) { throw Error(`python ${args} returned bad JSON (${out}) (${ex})`); } } return [args, parse]; } exports.interpreterInfo = interpreterInfo; function normalizeSelection() { const script = path.join(SCRIPTS_DIR, 'normalizeSelection.py'); const args = [script]; function parse(out) { return out; } return [args, parse]; } exports.normalizeSelection = normalizeSelection; function printEnvVariables() { const script = path.join(SCRIPTS_DIR, 'printEnvVariables.py').fileToCommandArgumentForPythonMgrExt(); const args = [script]; function parse(out) { return JSON.parse(out); } return [args, parse]; } exports.printEnvVariables = printEnvVariables; function shell_exec(command, lockfile, shellArgs) { const script = path.join(SCRIPTS_DIR, 'shell_exec.py'); return [ script, command.fileToCommandArgumentForPythonMgrExt(), ...shellArgs, lockfile.fileToCommandArgumentForPythonMgrExt(), ]; } exports.shell_exec = shell_exec; function testlauncher(testArgs) { const script = path.join(SCRIPTS_DIR, 'testlauncher.py'); return [script, ...testArgs]; } exports.testlauncher = testlauncher; function pytestlauncher(testArgs) { const script = path.join(SCRIPTS_DIR, 'vscode_pytest', 'run_pytest_script.py'); return [script, ...testArgs]; } exports.pytestlauncher = pytestlauncher; function visualstudio_py_testlauncher(testArgs) { const script = path.join(SCRIPTS_DIR, 'visualstudio_py_testlauncher.py'); return [script, ...testArgs]; } exports.visualstudio_py_testlauncher = visualstudio_py_testlauncher; function execution_py_testlauncher(testArgs) { const script = path.join(SCRIPTS_DIR, 'unittestadapter', 'execution.py'); return [script, ...testArgs]; } exports.execution_py_testlauncher = execution_py_testlauncher; function tensorboardLauncher(args) { const script = path.join(SCRIPTS_DIR, 'tensorboard_launcher.py'); return [script, ...args]; } exports.tensorboardLauncher = tensorboardLauncher; function linterScript() { const script = path.join(SCRIPTS_DIR, 'linter.py'); return script; } exports.linterScript = linterScript; function createVenvScript() { const script = path.join(SCRIPTS_DIR, 'create_venv.py'); return script; } exports.createVenvScript = createVenvScript; function createCondaScript() { const script = path.join(SCRIPTS_DIR, 'create_conda.py'); return script; } exports.createCondaScript = createCondaScript; function installedCheckScript() { const script = path.join(SCRIPTS_DIR, 'installed_check.py'); return script; } exports.installedCheckScript = installedCheckScript; /***/ }), /***/ "./src/client/common/process/logger.ts": /*!*********************************************!*\ !*** ./src/client/common/process/logger.ts ***! \*********************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProcessLogger = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const types_1 = __webpack_require__(/*! ../application/types */ "./src/client/common/application/types.ts"); const constants_1 = __webpack_require__(/*! ../constants */ "./src/client/common/constants.ts"); const platform_1 = __webpack_require__(/*! ../utils/platform */ "./src/client/common/utils/platform.ts"); const lodash_1 = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js"); const stringUtils_1 = __webpack_require__(/*! ../stringUtils */ "./src/client/common/stringUtils.ts"); const baseShellDetector_1 = __webpack_require__(/*! ../terminal/shellDetectors/baseShellDetector */ "./src/client/common/terminal/shellDetectors/baseShellDetector.ts"); const extensions_1 = __webpack_require__(/*! ../extensions */ "./src/client/common/extensions.ts"); let ProcessLogger = class ProcessLogger { constructor(workspaceService) { this.workspaceService = workspaceService; } logProcess(fileOrCommand, args, options) { if (!(0, constants_1.isTestExecution)() && constants_1.isCI && process.env.UITEST_DISABLE_PROCESS_LOGGING) { return; } let command = args ? [fileOrCommand, ...args].map((e) => (0, extensions_1.trimQuotes)(e).toCommandArgumentForPythonMgrExt()).join(' ') : fileOrCommand; const info = [`> ${this.getDisplayCommands(command)}`]; if (options === null || options === void 0 ? void 0 : options.cwd) { info.push(`cwd: ${this.getDisplayCommands(options.cwd.toString())}`); } if (typeof (options === null || options === void 0 ? void 0 : options.shell) === 'string') { info.push(`shell: ${(0, baseShellDetector_1.identifyShellFromShellPath)(options === null || options === void 0 ? void 0 : options.shell)}`); } info.forEach((line) => { (0, logging_1.traceLog)(line); }); } getDisplayCommands(command) { if (this.workspaceService.workspaceFolders && this.workspaceService.workspaceFolders.length === 1) { command = replaceMatchesWithCharacter(command, this.workspaceService.workspaceFolders[0].uri.fsPath, '.'); } const home = (0, platform_1.getUserHomeDir)(); if (home) { command = replaceMatchesWithCharacter(command, home, '~'); } return command; } }; ProcessLogger = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_1.IWorkspaceService)) ], ProcessLogger); exports.ProcessLogger = ProcessLogger; function replaceMatchesWithCharacter(original, match, character) { function getRegex(match) { let pattern = (0, lodash_1.escapeRegExp)(match); if ((0, platform_1.getOSType)() === platform_1.OSType.Windows) { pattern = (0, stringUtils_1.replaceAll)(pattern, '\\\\', '(\\\\|/)'); } let regex = new RegExp(pattern, 'ig'); return regex; } function isPrevioustoMatchRegexALetter(chunk, index) { return chunk[index].match(/[a-z]/); } let chunked = original.split(' '); for (let i = 0; i < chunked.length; i++) { let regex = getRegex(match); const regexResult = regex.exec(chunked[i]); if (regexResult) { const regexIndex = regexResult.index; if (regexIndex > 0 && isPrevioustoMatchRegexALetter(chunked[i], regexIndex - 1)) regex = getRegex(match.substring(1)); chunked[i] = chunked[i].replace(regex, character); } } return chunked.join(' '); } /***/ }), /***/ "./src/client/common/process/proc.ts": /*!*******************************************!*\ !*** ./src/client/common/process/proc.ts ***! \*******************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProcessService = void 0; const events_1 = __webpack_require__(/*! events */ "events"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const rawProcessApis_1 = __webpack_require__(/*! ./rawProcessApis */ "./src/client/common/process/rawProcessApis.ts"); class ProcessService extends events_1.EventEmitter { constructor(env) { super(); this.env = env; this.processesToKill = new Set(); } static isAlive(pid) { try { process.kill(pid, 0); return true; } catch (_a) { return false; } } static kill(pid) { (0, rawProcessApis_1.killPid)(pid); } dispose() { this.removeAllListeners(); this.processesToKill.forEach((p) => { try { p.dispose(); } catch (_a) { } }); } execObservable(file, args, options = {}) { const result = (0, rawProcessApis_1.execObservable)(file, args, options, this.env, this.processesToKill); this.emit('exec', file, args, options); return result; } exec(file, args, options = {}) { const promise = (0, rawProcessApis_1.plainExec)(file, args, options, this.env, this.processesToKill); this.emit('exec', file, args, options); return promise; } shellExec(command, options = {}) { this.emit('exec', command, undefined, options); const disposables = new Set(); return (0, rawProcessApis_1.shellExec)(command, options, this.env, disposables).finally(() => { disposables.forEach((p) => { try { p.dispose(); } catch (_a) { (0, logging_1.traceError)(`Unable to kill process for ${command}`); } }); }); } } exports.ProcessService = ProcessService; /***/ }), /***/ "./src/client/common/process/processFactory.ts": /*!*****************************************************!*\ !*** ./src/client/common/process/processFactory.ts ***! \*****************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProcessServiceFactory = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const types_1 = __webpack_require__(/*! ../types */ "./src/client/common/types.ts"); const types_2 = __webpack_require__(/*! ../variables/types */ "./src/client/common/variables/types.ts"); const proc_1 = __webpack_require__(/*! ./proc */ "./src/client/common/process/proc.ts"); const types_3 = __webpack_require__(/*! ./types */ "./src/client/common/process/types.ts"); let ProcessServiceFactory = class ProcessServiceFactory { constructor(envVarsService, processLogger, disposableRegistry) { this.envVarsService = envVarsService; this.processLogger = processLogger; this.disposableRegistry = disposableRegistry; } async create(resource, options) { const customEnvVars = (options === null || options === void 0 ? void 0 : options.doNotUseCustomEnvs) ? undefined : await this.envVarsService.getEnvironmentVariables(resource); const proc = new proc_1.ProcessService(customEnvVars); this.disposableRegistry.push(proc); return proc.on('exec', this.processLogger.logProcess.bind(this.processLogger)); } }; ProcessServiceFactory = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_2.IEnvironmentVariablesProvider)), __param(1, (0, inversify_1.inject)(types_3.IProcessLogger)), __param(2, (0, inversify_1.inject)(types_1.IDisposableRegistry)) ], ProcessServiceFactory); exports.ProcessServiceFactory = ProcessServiceFactory; /***/ }), /***/ "./src/client/common/process/pythonEnvironment.ts": /*!********************************************************!*\ !*** ./src/client/common/process/pythonEnvironment.ts ***! \********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createMicrosoftStoreEnv = exports.createCondaEnv = exports.createPythonEnv = void 0; const path = __webpack_require__(/*! path */ "path"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const conda_1 = __webpack_require__(/*! ../../pythonEnvironments/common/environmentManagers/conda */ "./src/client/pythonEnvironments/common/environmentManagers/conda.ts"); const exec_1 = __webpack_require__(/*! ../../pythonEnvironments/exec */ "./src/client/pythonEnvironments/exec.ts"); const executable_1 = __webpack_require__(/*! ../../pythonEnvironments/info/executable */ "./src/client/pythonEnvironments/info/executable.ts"); const interpreter_1 = __webpack_require__(/*! ../../pythonEnvironments/info/interpreter */ "./src/client/pythonEnvironments/info/interpreter.ts"); const constants_1 = __webpack_require__(/*! ../constants */ "./src/client/common/constants.ts"); const internalPython = __webpack_require__(/*! ./internal/python */ "./src/client/common/process/internal/python.ts"); const cachedExecutablePath = new Map(); class PythonEnvironment { constructor(pythonPath, deps) { this.pythonPath = pythonPath; this.deps = deps; this.cachedInterpreterInformation = null; } getExecutionInfo(pythonArgs = [], pythonExecutable) { const python = this.deps.getPythonArgv(this.pythonPath); return (0, exec_1.buildPythonExecInfo)(python, pythonArgs, pythonExecutable); } getExecutionObservableInfo(pythonArgs = [], pythonExecutable) { const python = this.deps.getObservablePythonArgv(this.pythonPath); return (0, exec_1.buildPythonExecInfo)(python, pythonArgs, pythonExecutable); } async getInterpreterInformation() { if (this.cachedInterpreterInformation === null) { this.cachedInterpreterInformation = await this.getInterpreterInformationImpl(); } return this.cachedInterpreterInformation; } async getExecutablePath() { if (await this.deps.isValidExecutable(this.pythonPath)) { return this.pythonPath; } const result = cachedExecutablePath.get(this.pythonPath); if (result !== undefined && !(0, constants_1.isTestExecution)()) { return result; } const python = this.getExecutionInfo(); const promise = (0, executable_1.getExecutablePath)(python, this.deps.shellExec); cachedExecutablePath.set(this.pythonPath, promise); return promise; } async getModuleVersion(moduleName) { const [args, parse] = internalPython.getModuleVersion(moduleName); const info = this.getExecutionInfo(args); let data; try { data = await this.deps.exec(info.command, info.args); } catch (ex) { (0, logging_1.traceVerbose)(`Error when getting version of module ${moduleName}`, ex); return undefined; } return parse(data.stdout); } async isModuleInstalled(moduleName) { const [args,] = internalPython.isModuleInstalled(moduleName); const info = this.getExecutionInfo(args); try { await this.deps.exec(info.command, info.args); } catch (ex) { (0, logging_1.traceVerbose)(`Error when checking if module is installed ${moduleName}`, ex); return false; } return true; } async getInterpreterInformationImpl() { try { const python = this.getExecutionInfo(); return await (0, interpreter_1.getInterpreterInfo)(python, this.deps.shellExec, { verbose: logging_1.traceVerbose, error: logging_1.traceError }); } catch (ex) { (0, logging_1.traceError)(`Failed to get interpreter information for '${this.pythonPath}'`, ex); } } } function createDeps(isValidExecutable, pythonArgv, observablePythonArgv, exec, shellExec) { return { getPythonArgv: (python) => { if (path.basename(python) === python) { pythonArgv = python.split(' '); } return pythonArgv || [python]; }, getObservablePythonArgv: (python) => { if (path.basename(python) === python) { observablePythonArgv = python.split(' '); } return observablePythonArgv || [python]; }, isValidExecutable, exec: async (cmd, args) => exec(cmd, args, { throwOnStdErr: true }), shellExec, }; } function createPythonEnv(pythonPath, procs, fs) { const deps = createDeps(async (filename) => fs.pathExists(filename), undefined, undefined, (file, args, opts) => procs.exec(file, args, opts), (command, opts) => procs.shellExec(command, opts)); return new PythonEnvironment(pythonPath, deps); } exports.createPythonEnv = createPythonEnv; async function createCondaEnv(condaInfo, procs, fs) { const conda = await conda_1.Conda.getConda(); const pythonArgv = await (conda === null || conda === void 0 ? void 0 : conda.getRunPythonArgs({ name: condaInfo.name, prefix: condaInfo.path })); if (!pythonArgv) { return undefined; } const deps = createDeps(async (filename) => fs.pathExists(filename), pythonArgv, pythonArgv, (file, args, opts) => procs.exec(file, args, opts), (command, opts) => procs.shellExec(command, opts)); const interpreterPath = await (conda === null || conda === void 0 ? void 0 : conda.getInterpreterPathForEnvironment({ name: condaInfo.name, prefix: condaInfo.path, })); if (!interpreterPath) { return undefined; } return new PythonEnvironment(interpreterPath, deps); } exports.createCondaEnv = createCondaEnv; function createMicrosoftStoreEnv(pythonPath, procs) { const deps = createDeps(async (_f) => true, undefined, undefined, (file, args, opts) => procs.exec(file, args, opts), (command, opts) => procs.shellExec(command, opts)); return new PythonEnvironment(pythonPath, deps); } exports.createMicrosoftStoreEnv = createMicrosoftStoreEnv; /***/ }), /***/ "./src/client/common/process/pythonExecutionFactory.ts": /*!*************************************************************!*\ !*** ./src/client/common/process/pythonExecutionFactory.ts ***! \*************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PythonExecutionFactory = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const types_1 = __webpack_require__(/*! ../../interpreter/activation/types */ "./src/client/interpreter/activation/types.ts"); const contracts_1 = __webpack_require__(/*! ../../interpreter/contracts */ "./src/client/interpreter/contracts.ts"); const types_2 = __webpack_require__(/*! ../../ioc/types */ "./src/client/ioc/types.ts"); const telemetry_1 = __webpack_require__(/*! ../../telemetry */ "./src/client/telemetry/index.ts"); const constants_1 = __webpack_require__(/*! ../../telemetry/constants */ "./src/client/telemetry/constants.ts"); const types_3 = __webpack_require__(/*! ../platform/types */ "./src/client/common/platform/types.ts"); const types_4 = __webpack_require__(/*! ../types */ "./src/client/common/types.ts"); const proc_1 = __webpack_require__(/*! ./proc */ "./src/client/common/process/proc.ts"); const pythonEnvironment_1 = __webpack_require__(/*! ./pythonEnvironment */ "./src/client/common/process/pythonEnvironment.ts"); const pythonProcess_1 = __webpack_require__(/*! ./pythonProcess */ "./src/client/common/process/pythonProcess.ts"); const types_5 = __webpack_require__(/*! ./types */ "./src/client/common/process/types.ts"); let PythonExecutionFactory = class PythonExecutionFactory { constructor(serviceContainer, activationHelper, processServiceFactory, configService, pyenvs) { this.serviceContainer = serviceContainer; this.activationHelper = activationHelper; this.processServiceFactory = processServiceFactory; this.configService = configService; this.pyenvs = pyenvs; this.disposables = this.serviceContainer.get(types_4.IDisposableRegistry); this.logger = this.serviceContainer.get(types_5.IProcessLogger); this.fileSystem = this.serviceContainer.get(types_3.IFileSystem); } async create(options) { let { pythonPath } = options; if (!pythonPath || pythonPath === 'python') { const activatedEnvLaunch = this.serviceContainer.get(contracts_1.IActivatedEnvironmentLaunch); await activatedEnvLaunch.selectIfLaunchedViaActivatedEnv(); pythonPath = this.configService.getSettings(options.resource).pythonPath; } const processService = await this.processServiceFactory.create(options.resource); const condaExecutionService = await this.createCondaExecutionService(pythonPath, processService); if (condaExecutionService) { return condaExecutionService; } const windowsStoreInterpreterCheck = this.pyenvs.isMicrosoftStoreInterpreter.bind(this.pyenvs); const env = (await windowsStoreInterpreterCheck(pythonPath)) ? (0, pythonEnvironment_1.createMicrosoftStoreEnv)(pythonPath, processService) : (0, pythonEnvironment_1.createPythonEnv)(pythonPath, processService, this.fileSystem); return createPythonService(processService, env); } async createActivatedEnvironment(options) { const envVars = await this.activationHelper.getActivatedEnvironmentVariables(options.resource, options.interpreter, options.allowEnvironmentFetchExceptions); const hasEnvVars = envVars && Object.keys(envVars).length > 0; (0, telemetry_1.sendTelemetryEvent)(constants_1.EventName.PYTHON_INTERPRETER_ACTIVATION_ENVIRONMENT_VARIABLES, undefined, { hasEnvVars }); if (!hasEnvVars) { return this.create({ resource: options.resource, pythonPath: options.interpreter ? options.interpreter.path : undefined, }); } const pythonPath = options.interpreter ? options.interpreter.path : this.configService.getSettings(options.resource).pythonPath; const processService = new proc_1.ProcessService({ ...envVars }); processService.on('exec', this.logger.logProcess.bind(this.logger)); this.disposables.push(processService); const condaExecutionService = await this.createCondaExecutionService(pythonPath, processService); if (condaExecutionService) { return condaExecutionService; } const env = (0, pythonEnvironment_1.createPythonEnv)(pythonPath, processService, this.fileSystem); return createPythonService(processService, env); } async createCondaExecutionService(pythonPath, processService) { const condaLocatorService = this.serviceContainer.get(contracts_1.IComponentAdapter); const [condaEnvironment] = await Promise.all([condaLocatorService.getCondaEnvironment(pythonPath)]); if (!condaEnvironment) { return undefined; } const env = await (0, pythonEnvironment_1.createCondaEnv)(condaEnvironment, processService, this.fileSystem); if (!env) { return undefined; } return createPythonService(processService, env); } }; PythonExecutionFactory = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_2.IServiceContainer)), __param(1, (0, inversify_1.inject)(types_1.IEnvironmentActivationService)), __param(2, (0, inversify_1.inject)(types_5.IProcessServiceFactory)), __param(3, (0, inversify_1.inject)(types_4.IConfigurationService)), __param(4, (0, inversify_1.inject)(contracts_1.IComponentAdapter)) ], PythonExecutionFactory); exports.PythonExecutionFactory = PythonExecutionFactory; function createPythonService(procService, env) { const procs = (0, pythonProcess_1.createPythonProcessService)(procService, env); return { getInterpreterInformation: () => env.getInterpreterInformation(), getExecutablePath: () => env.getExecutablePath(), isModuleInstalled: (m) => env.isModuleInstalled(m), getModuleVersion: (m) => env.getModuleVersion(m), getExecutionInfo: (a) => env.getExecutionInfo(a), execObservable: (a, o) => procs.execObservable(a, o), execModuleObservable: (m, a, o) => procs.execModuleObservable(m, a, o), exec: (a, o) => procs.exec(a, o), execModule: (m, a, o) => procs.execModule(m, a, o), execForLinter: (m, a, o) => procs.execForLinter(m, a, o), }; } /***/ }), /***/ "./src/client/common/process/pythonProcess.ts": /*!****************************************************!*\ !*** ./src/client/common/process/pythonProcess.ts ***! \****************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createPythonProcessService = void 0; const errorUtils_1 = __webpack_require__(/*! ../errors/errorUtils */ "./src/client/common/errors/errorUtils.ts"); const moduleNotInstalledError_1 = __webpack_require__(/*! ../errors/moduleNotInstalledError */ "./src/client/common/errors/moduleNotInstalledError.ts"); const internalPython = __webpack_require__(/*! ./internal/python */ "./src/client/common/process/internal/python.ts"); class PythonProcessService { constructor(deps) { this.deps = deps; } execObservable(args, options) { const opts = { ...options }; const executable = this.deps.getExecutionObservableInfo(args); return this.deps.execObservable(executable.command, executable.args, opts); } execModuleObservable(moduleName, moduleArgs, options) { const args = internalPython.execModule(moduleName, moduleArgs); const opts = { ...options }; const executable = this.deps.getExecutionObservableInfo(args); return this.deps.execObservable(executable.command, executable.args, opts); } async exec(args, options) { const opts = { ...options }; const executable = this.deps.getExecutionInfo(args); return this.deps.exec(executable.command, executable.args, opts); } async execModule(moduleName, moduleArgs, options) { const args = internalPython.execModule(moduleName, moduleArgs); const opts = { ...options }; const executable = this.deps.getExecutionInfo(args); const result = await this.deps.exec(executable.command, executable.args, opts); if (moduleName && errorUtils_1.ErrorUtils.outputHasModuleNotInstalledError(moduleName, result.stderr)) { const isInstalled = await this.deps.isModuleInstalled(moduleName); if (!isInstalled) { throw new moduleNotInstalledError_1.ModuleNotInstalledError(moduleName); } } return result; } async execForLinter(moduleName, args, options) { const opts = { ...options }; const executable = this.deps.getExecutionInfo(args); const result = await this.deps.exec(executable.command, executable.args, opts); if (moduleName && errorUtils_1.ErrorUtils.outputHasModuleNotInstalledError(moduleName, result.stderr)) { const isInstalled = await this.deps.isModuleInstalled(moduleName); if (!isInstalled) { throw new moduleNotInstalledError_1.ModuleNotInstalledError(moduleName); } } return result; } } function createPythonProcessService(procs, env) { const deps = { isModuleInstalled: async (m) => env.isModuleInstalled(m), getExecutionInfo: (a) => env.getExecutionInfo(a), getExecutionObservableInfo: (a) => env.getExecutionObservableInfo(a), exec: async (f, a, o) => procs.exec(f, a, o), execObservable: (f, a, o) => procs.execObservable(f, a, o), }; return new PythonProcessService(deps); } exports.createPythonProcessService = createPythonProcessService; /***/ }), /***/ "./src/client/common/process/pythonToolService.ts": /*!********************************************************!*\ !*** ./src/client/common/process/pythonToolService.ts ***! \********************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PythonToolExecutionService = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const types_1 = __webpack_require__(/*! ../../ioc/types */ "./src/client/ioc/types.ts"); const types_2 = __webpack_require__(/*! ./types */ "./src/client/common/process/types.ts"); let PythonToolExecutionService = class PythonToolExecutionService { constructor(serviceContainer) { this.serviceContainer = serviceContainer; } async execObservable(executionInfo, options, resource) { if (options.env) { throw new Error('Environment variables are not supported'); } if (executionInfo.moduleName && executionInfo.moduleName.length > 0) { const pythonExecutionService = await this.serviceContainer .get(types_2.IPythonExecutionFactory) .create({ resource }); return pythonExecutionService.execModuleObservable(executionInfo.moduleName, executionInfo.args, options); } else { const processService = await this.serviceContainer .get(types_2.IProcessServiceFactory) .create(resource); return processService.execObservable(executionInfo.execPath, executionInfo.args, { ...options }); } } async exec(executionInfo, options, resource) { if (options.env) { throw new Error('Environment variables are not supported'); } if (executionInfo.moduleName && executionInfo.moduleName.length > 0) { const pythonExecutionService = await this.serviceContainer .get(types_2.IPythonExecutionFactory) .create({ resource }); return pythonExecutionService.execModule(executionInfo.moduleName, executionInfo.args, options); } else { const processService = await this.serviceContainer .get(types_2.IProcessServiceFactory) .create(resource); return processService.exec(executionInfo.execPath, executionInfo.args, { ...options }); } } async execForLinter(executionInfo, options, resource) { if (options.env) { throw new Error('Environment variables are not supported'); } const pythonExecutionService = await this.serviceContainer .get(types_2.IPythonExecutionFactory) .create({ resource }); if (executionInfo.execPath) { return pythonExecutionService.exec(executionInfo.args, options); } return pythonExecutionService.execForLinter(executionInfo.moduleName, executionInfo.args, options); } }; PythonToolExecutionService = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_1.IServiceContainer)) ], PythonToolExecutionService); exports.PythonToolExecutionService = PythonToolExecutionService; /***/ }), /***/ "./src/client/common/process/rawProcessApis.ts": /*!*****************************************************!*\ !*** ./src/client/common/process/rawProcessApis.ts ***! \*****************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.killPid = exports.execObservable = exports.plainExec = exports.shellExec = void 0; const child_process_1 = __webpack_require__(/*! child_process */ "child_process"); const Observable_1 = __webpack_require__(/*! rxjs/Observable */ "./node_modules/rxjs/Observable.js"); const async_1 = __webpack_require__(/*! ../utils/async */ "./src/client/common/utils/async.ts"); const constants_1 = __webpack_require__(/*! ./constants */ "./src/client/common/process/constants.ts"); const types_1 = __webpack_require__(/*! ./types */ "./src/client/common/process/types.ts"); const misc_1 = __webpack_require__(/*! ../utils/misc */ "./src/client/common/utils/misc.ts"); const decoder_1 = __webpack_require__(/*! ./decoder */ "./src/client/common/process/decoder.ts"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const PS_ERROR_SCREEN_BOGUS = /your [0-9]+x[0-9]+ screen size is bogus\. expect trouble/; function getDefaultOptions(options, defaultEnv) { const defaultOptions = { ...options }; const execOptions = defaultOptions; if (execOptions) { execOptions.encoding = typeof execOptions.encoding === 'string' && execOptions.encoding.length > 0 ? execOptions.encoding : constants_1.DEFAULT_ENCODING; const { encoding } = execOptions; delete execOptions.encoding; execOptions.encoding = encoding; } if (!defaultOptions.env || Object.keys(defaultOptions.env).length === 0) { const env = defaultEnv || process.env; defaultOptions.env = { ...env }; } else { defaultOptions.env = { ...defaultOptions.env }; } if (execOptions && execOptions.extraVariables) { defaultOptions.env = { ...defaultOptions.env, ...execOptions.extraVariables }; } defaultOptions.env.PYTHONUNBUFFERED = '1'; if (!defaultOptions.env.PYTHONIOENCODING) { defaultOptions.env.PYTHONIOENCODING = 'utf-8'; } return defaultOptions; } function shellExec(command, options = {}, defaultEnv, disposables) { const shellOptions = getDefaultOptions(options, defaultEnv); (0, logging_1.traceVerbose)(`Shell Exec: ${command} with options: ${JSON.stringify(shellOptions, null, 4)}`); return new Promise((resolve, reject) => { const callback = (e, stdout, stderr) => { if (e && e !== null) { reject(e); } else if (shellOptions.throwOnStdErr && stderr && stderr.length) { reject(new Error(stderr)); } else { stdout = filterOutputUsingCondaRunMarkers(stdout); resolve({ stderr: stderr && stderr.length > 0 ? stderr : undefined, stdout }); } }; const proc = (0, child_process_1.exec)(command, shellOptions, callback); const disposable = { dispose: () => { if (!proc.killed) { proc.kill(); } }, }; if (disposables) { disposables.add(disposable); } }); } exports.shellExec = shellExec; function plainExec(file, args, options = {}, defaultEnv, disposables) { var _a, _b; const spawnOptions = getDefaultOptions(options, defaultEnv); const encoding = spawnOptions.encoding ? spawnOptions.encoding : 'utf8'; const proc = (0, child_process_1.spawn)(file, args, spawnOptions); (_a = proc.stdout) === null || _a === void 0 ? void 0 : _a.on('error', misc_1.noop); (_b = proc.stderr) === null || _b === void 0 ? void 0 : _b.on('error', misc_1.noop); const deferred = (0, async_1.createDeferred)(); const disposable = { dispose: () => { if (!proc.killed) { proc.kill(); } }, }; disposables === null || disposables === void 0 ? void 0 : disposables.add(disposable); const internalDisposables = []; const on = (ee, name, fn) => { ee === null || ee === void 0 ? void 0 : ee.on(name, fn); internalDisposables.push({ dispose: () => ee === null || ee === void 0 ? void 0 : ee.removeListener(name, fn) }); }; if (options.token) { internalDisposables.push(options.token.onCancellationRequested(disposable.dispose)); } const stdoutBuffers = []; on(proc.stdout, 'data', (data) => { var _a; stdoutBuffers.push(data); (_a = options.outputChannel) === null || _a === void 0 ? void 0 : _a.append(data.toString()); }); const stderrBuffers = []; on(proc.stderr, 'data', (data) => { var _a; if (options.mergeStdOutErr) { stdoutBuffers.push(data); stderrBuffers.push(data); } else { stderrBuffers.push(data); } (_a = options.outputChannel) === null || _a === void 0 ? void 0 : _a.append(data.toString()); }); proc.once('close', () => { if (deferred.completed) { return; } const stderr = stderrBuffers.length === 0 ? undefined : (0, decoder_1.decodeBuffer)(stderrBuffers, encoding); if (stderr && stderr.length > 0 && options.throwOnStdErr && !(PS_ERROR_SCREEN_BOGUS.test(stderr) && stderr.replace(PS_ERROR_SCREEN_BOGUS, '').trim().length === 0)) { deferred.reject(new types_1.StdErrError(stderr)); } else { let stdout = (0, decoder_1.decodeBuffer)(stdoutBuffers, encoding); stdout = filterOutputUsingCondaRunMarkers(stdout); deferred.resolve({ stdout, stderr }); } internalDisposables.forEach((d) => d.dispose()); disposable.dispose(); }); proc.once('error', (ex) => { deferred.reject(ex); internalDisposables.forEach((d) => d.dispose()); disposable.dispose(); }); return deferred.promise; } exports.plainExec = plainExec; function filterOutputUsingCondaRunMarkers(stdout) { const regex = />>>PYTHON-EXEC-OUTPUT([\s\S]*)<<= 2 ? match[1].trim() : undefined; return filteredOut !== undefined ? filteredOut : stdout; } function removeCondaRunMarkers(out) { out = out.replace('>>>PYTHON-EXEC-OUTPUT\r\n', '').replace('>>>PYTHON-EXEC-OUTPUT\n', ''); return out.replace('<< { const internalDisposables = []; const on = (ee, name, fn) => { ee === null || ee === void 0 ? void 0 : ee.on(name, fn); internalDisposables.push({ dispose: () => ee === null || ee === void 0 ? void 0 : ee.removeListener(name, fn) }); }; if (options.token) { internalDisposables.push(options.token.onCancellationRequested(() => { if (!procExited && !proc.killed) { proc.kill(); procExited = true; } })); } const sendOutput = (source, data) => { let out = (0, decoder_1.decodeBuffer)([data], encoding); if (source === 'stderr' && options.throwOnStdErr) { subscriber.error(new types_1.StdErrError(out)); } else { out = removeCondaRunMarkers(out); subscriber.next({ source, out }); } }; on(proc.stdout, 'data', (data) => sendOutput('stdout', data)); on(proc.stderr, 'data', (data) => sendOutput('stderr', data)); proc.once('close', () => { procExited = true; subscriber.complete(); internalDisposables.forEach((d) => d.dispose()); }); proc.once('exit', () => { procExited = true; subscriber.complete(); internalDisposables.forEach((d) => d.dispose()); }); proc.once('error', (ex) => { procExited = true; subscriber.error(ex); internalDisposables.forEach((d) => d.dispose()); }); }); return { proc, out: output, dispose: disposable.dispose, }; } exports.execObservable = execObservable; function killPid(pid) { try { if (process.platform === 'win32') { (0, child_process_1.execSync)(`taskkill /pid ${pid} /T /F`); } else { process.kill(pid); } } catch (_a) { } } exports.killPid = killPid; /***/ }), /***/ "./src/client/common/process/serviceRegistry.ts": /*!******************************************************!*\ !*** ./src/client/common/process/serviceRegistry.ts ***! \******************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.registerTypes = void 0; const processFactory_1 = __webpack_require__(/*! ./processFactory */ "./src/client/common/process/processFactory.ts"); const pythonExecutionFactory_1 = __webpack_require__(/*! ./pythonExecutionFactory */ "./src/client/common/process/pythonExecutionFactory.ts"); const pythonToolService_1 = __webpack_require__(/*! ./pythonToolService */ "./src/client/common/process/pythonToolService.ts"); const types_1 = __webpack_require__(/*! ./types */ "./src/client/common/process/types.ts"); function registerTypes(serviceManager) { serviceManager.addSingleton(types_1.IProcessServiceFactory, processFactory_1.ProcessServiceFactory); serviceManager.addSingleton(types_1.IPythonExecutionFactory, pythonExecutionFactory_1.PythonExecutionFactory); serviceManager.addSingleton(types_1.IPythonToolExecutionService, pythonToolService_1.PythonToolExecutionService); } exports.registerTypes = registerTypes; /***/ }), /***/ "./src/client/common/process/types.ts": /*!********************************************!*\ !*** ./src/client/common/process/types.ts ***! \********************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.IPythonToolExecutionService = exports.StdErrError = exports.IPythonExecutionService = exports.IPythonExecutionFactory = exports.IProcessServiceFactory = exports.IProcessLogger = void 0; exports.IProcessLogger = Symbol('IProcessLogger'); exports.IProcessServiceFactory = Symbol('IProcessServiceFactory'); exports.IPythonExecutionFactory = Symbol('IPythonExecutionFactory'); exports.IPythonExecutionService = Symbol('IPythonExecutionService'); class StdErrError extends Error { constructor(message) { super(message); } } exports.StdErrError = StdErrError; exports.IPythonToolExecutionService = Symbol('IPythonToolRunnerService'); /***/ }), /***/ "./src/client/common/serviceRegistry.ts": /*!**********************************************!*\ !*** ./src/client/common/serviceRegistry.ts ***! \**********************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.registerTypes = void 0; const types_1 = __webpack_require__(/*! ../activation/types */ "./src/client/activation/types.ts"); const types_2 = __webpack_require__(/*! ./types */ "./src/client/common/types.ts"); const activeResource_1 = __webpack_require__(/*! ./application/activeResource */ "./src/client/common/application/activeResource.ts"); const applicationEnvironment_1 = __webpack_require__(/*! ./application/applicationEnvironment */ "./src/client/common/application/applicationEnvironment.ts"); const applicationShell_1 = __webpack_require__(/*! ./application/applicationShell */ "./src/client/common/application/applicationShell.ts"); const commandManager_1 = __webpack_require__(/*! ./application/commandManager */ "./src/client/common/application/commandManager.ts"); const documentManager_1 = __webpack_require__(/*! ./application/documentManager */ "./src/client/common/application/documentManager.ts"); const terminalManager_1 = __webpack_require__(/*! ./application/terminalManager */ "./src/client/common/application/terminalManager.ts"); const types_3 = __webpack_require__(/*! ./application/types */ "./src/client/common/application/types.ts"); const workspace_1 = __webpack_require__(/*! ./application/workspace */ "./src/client/common/application/workspace.ts"); const service_1 = __webpack_require__(/*! ./configuration/service */ "./src/client/common/configuration/service.ts"); const pipEnvExecution_1 = __webpack_require__(/*! ./configuration/executionSettings/pipEnvExecution */ "./src/client/common/configuration/executionSettings/pipEnvExecution.ts"); const editor_1 = __webpack_require__(/*! ./editor */ "./src/client/common/editor.ts"); const persistentState_1 = __webpack_require__(/*! ./persistentState */ "./src/client/common/persistentState.ts"); const pathUtils_1 = __webpack_require__(/*! ./platform/pathUtils */ "./src/client/common/platform/pathUtils.ts"); const currentProcess_1 = __webpack_require__(/*! ./process/currentProcess */ "./src/client/common/process/currentProcess.ts"); const logger_1 = __webpack_require__(/*! ./process/logger */ "./src/client/common/process/logger.ts"); const types_4 = __webpack_require__(/*! ./process/types */ "./src/client/common/process/types.ts"); const activator_1 = __webpack_require__(/*! ./terminal/activator */ "./src/client/common/terminal/activator/index.ts"); const bash_1 = __webpack_require__(/*! ./terminal/environmentActivationProviders/bash */ "./src/client/common/terminal/environmentActivationProviders/bash.ts"); const nushell_1 = __webpack_require__(/*! ./terminal/environmentActivationProviders/nushell */ "./src/client/common/terminal/environmentActivationProviders/nushell.ts"); const commandPrompt_1 = __webpack_require__(/*! ./terminal/environmentActivationProviders/commandPrompt */ "./src/client/common/terminal/environmentActivationProviders/commandPrompt.ts"); const condaActivationProvider_1 = __webpack_require__(/*! ./terminal/environmentActivationProviders/condaActivationProvider */ "./src/client/common/terminal/environmentActivationProviders/condaActivationProvider.ts"); const pipEnvActivationProvider_1 = __webpack_require__(/*! ./terminal/environmentActivationProviders/pipEnvActivationProvider */ "./src/client/common/terminal/environmentActivationProviders/pipEnvActivationProvider.ts"); const pyenvActivationProvider_1 = __webpack_require__(/*! ./terminal/environmentActivationProviders/pyenvActivationProvider */ "./src/client/common/terminal/environmentActivationProviders/pyenvActivationProvider.ts"); const factory_1 = __webpack_require__(/*! ./terminal/factory */ "./src/client/common/terminal/factory.ts"); const helper_1 = __webpack_require__(/*! ./terminal/helper */ "./src/client/common/terminal/helper.ts"); const settingsShellDetector_1 = __webpack_require__(/*! ./terminal/shellDetectors/settingsShellDetector */ "./src/client/common/terminal/shellDetectors/settingsShellDetector.ts"); const terminalNameShellDetector_1 = __webpack_require__(/*! ./terminal/shellDetectors/terminalNameShellDetector */ "./src/client/common/terminal/shellDetectors/terminalNameShellDetector.ts"); const userEnvironmentShellDetector_1 = __webpack_require__(/*! ./terminal/shellDetectors/userEnvironmentShellDetector */ "./src/client/common/terminal/shellDetectors/userEnvironmentShellDetector.ts"); const vscEnvironmentShellDetector_1 = __webpack_require__(/*! ./terminal/shellDetectors/vscEnvironmentShellDetector */ "./src/client/common/terminal/shellDetectors/vscEnvironmentShellDetector.ts"); const types_5 = __webpack_require__(/*! ./terminal/types */ "./src/client/common/terminal/types.ts"); const multiStepInput_1 = __webpack_require__(/*! ./utils/multiStepInput */ "./src/client/common/utils/multiStepInput.ts"); const random_1 = __webpack_require__(/*! ./utils/random */ "./src/client/common/utils/random.ts"); const platformService_1 = __webpack_require__(/*! ./platform/platformService */ "./src/client/common/platform/platformService.ts"); function registerTypes(serviceManager) { serviceManager.addSingletonInstance(types_2.IsWindows, (0, platformService_1.isWindows)()); serviceManager.addSingleton(types_3.IActiveResourceService, activeResource_1.ActiveResourceService); serviceManager.addSingleton(types_2.IRandom, random_1.Random); serviceManager.addSingleton(types_2.IPersistentStateFactory, persistentState_1.PersistentStateFactory); serviceManager.addBinding(types_2.IPersistentStateFactory, types_1.IExtensionSingleActivationService); serviceManager.addSingleton(types_5.ITerminalServiceFactory, factory_1.TerminalServiceFactory); serviceManager.addSingleton(types_2.IPathUtils, pathUtils_1.PathUtils); serviceManager.addSingleton(types_3.IApplicationShell, applicationShell_1.ApplicationShell); serviceManager.addSingleton(types_2.ICurrentProcess, currentProcess_1.CurrentProcess); serviceManager.addSingleton(types_3.ICommandManager, commandManager_1.CommandManager); serviceManager.addSingleton(types_2.IConfigurationService, service_1.ConfigurationService); serviceManager.addSingleton(types_3.IWorkspaceService, workspace_1.WorkspaceService); serviceManager.addSingleton(types_4.IProcessLogger, logger_1.ProcessLogger); serviceManager.addSingleton(types_3.IDocumentManager, documentManager_1.DocumentManager); serviceManager.addSingleton(types_3.ITerminalManager, terminalManager_1.TerminalManager); serviceManager.addSingleton(types_3.IApplicationEnvironment, applicationEnvironment_1.ApplicationEnvironment); serviceManager.addSingleton(types_2.IEditorUtils, editor_1.EditorUtils); serviceManager.addSingleton(types_5.ITerminalActivator, activator_1.TerminalActivator); serviceManager.addSingleton(types_5.ITerminalHelper, helper_1.TerminalHelper); serviceManager.addSingleton(types_5.ITerminalActivationCommandProvider, bash_1.Bash, types_5.TerminalActivationProviders.bashCShellFish); serviceManager.addSingleton(types_5.ITerminalActivationCommandProvider, commandPrompt_1.CommandPromptAndPowerShell, types_5.TerminalActivationProviders.commandPromptAndPowerShell); serviceManager.addSingleton(types_5.ITerminalActivationCommandProvider, nushell_1.Nushell, types_5.TerminalActivationProviders.nushell); serviceManager.addSingleton(types_5.ITerminalActivationCommandProvider, pyenvActivationProvider_1.PyEnvActivationCommandProvider, types_5.TerminalActivationProviders.pyenv); serviceManager.addSingleton(types_5.ITerminalActivationCommandProvider, condaActivationProvider_1.CondaActivationCommandProvider, types_5.TerminalActivationProviders.conda); serviceManager.addSingleton(types_5.ITerminalActivationCommandProvider, pipEnvActivationProvider_1.PipEnvActivationCommandProvider, types_5.TerminalActivationProviders.pipenv); serviceManager.addSingleton(types_2.IToolExecutionPath, pipEnvExecution_1.PipEnvExecutionPath, types_2.ToolExecutionPath.pipenv); serviceManager.addSingleton(multiStepInput_1.IMultiStepInputFactory, multiStepInput_1.MultiStepInputFactory); serviceManager.addSingleton(types_5.IShellDetector, terminalNameShellDetector_1.TerminalNameShellDetector); serviceManager.addSingleton(types_5.IShellDetector, settingsShellDetector_1.SettingsShellDetector); serviceManager.addSingleton(types_5.IShellDetector, userEnvironmentShellDetector_1.UserEnvironmentShellDetector); serviceManager.addSingleton(types_5.IShellDetector, vscEnvironmentShellDetector_1.VSCEnvironmentShellDetector); } exports.registerTypes = registerTypes; /***/ }), /***/ "./src/client/common/stringUtils.ts": /*!******************************************!*\ !*** ./src/client/common/stringUtils.ts ***! \******************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.replaceAll = exports.splitLines = void 0; function splitLines(source, splitOptions = { removeEmptyEntries: true, trim: true }) { let lines = source.split(/\r?\n/g); if (splitOptions === null || splitOptions === void 0 ? void 0 : splitOptions.trim) { lines = lines.map((line) => line.trim()); } if (splitOptions === null || splitOptions === void 0 ? void 0 : splitOptions.removeEmptyEntries) { lines = lines.filter((line) => line.length > 0); } return lines; } exports.splitLines = splitLines; function replaceAll(source, substr, newSubstr) { if (!source) { return source; } function escapeRegExp(unescapedStr) { return unescapedStr.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } return source.replace(new RegExp(escapeRegExp(substr), 'g'), newSubstr); } exports.replaceAll = replaceAll; /***/ }), /***/ "./src/client/common/terminal/activator/base.ts": /*!******************************************************!*\ !*** ./src/client/common/terminal/activator/base.ts ***! \******************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BaseTerminalActivator = void 0; const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); const async_1 = __webpack_require__(/*! ../../utils/async */ "./src/client/common/utils/async.ts"); class BaseTerminalActivator { constructor(helper) { this.helper = helper; this.activatedTerminals = new Map(); } async activateEnvironmentInTerminal(terminal, options) { if (this.activatedTerminals.has(terminal)) { return this.activatedTerminals.get(terminal); } const deferred = (0, async_1.createDeferred)(); this.activatedTerminals.set(terminal, deferred.promise); const terminalShellType = this.helper.identifyTerminalShell(terminal); const activationCommands = await this.helper.getEnvironmentActivationCommands(terminalShellType, options === null || options === void 0 ? void 0 : options.resource, options === null || options === void 0 ? void 0 : options.interpreter); let activated = false; if (activationCommands) { for (const command of activationCommands) { terminal.show(options === null || options === void 0 ? void 0 : options.preserveFocus); (0, logging_1.traceVerbose)(`Command sent to terminal: ${command}`); terminal.sendText(command); await this.waitForCommandToProcess(terminalShellType); activated = true; } } deferred.resolve(activated); return activated; } async waitForCommandToProcess(_shell) { await (0, async_1.sleep)(500); } } exports.BaseTerminalActivator = BaseTerminalActivator; /***/ }), /***/ "./src/client/common/terminal/activator/index.ts": /*!*******************************************************!*\ !*** ./src/client/common/terminal/activator/index.ts ***! \*******************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TerminalActivator = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const types_1 = __webpack_require__(/*! ../types */ "./src/client/common/terminal/types.ts"); const base_1 = __webpack_require__(/*! ./base */ "./src/client/common/terminal/activator/base.ts"); let TerminalActivator = class TerminalActivator { constructor(helper) { this.helper = helper; this.pendingActivations = new WeakMap(); this.initialize(); } async activateEnvironmentInTerminal(terminal, options) { let promise = this.pendingActivations.get(terminal); if (promise) { return promise; } promise = this.activateEnvironmentInTerminalImpl(terminal, options); this.pendingActivations.set(terminal, promise); return promise; } async activateEnvironmentInTerminalImpl(_terminal, _options) { return false; } initialize() { this.baseActivator = new base_1.BaseTerminalActivator(this.helper); } }; TerminalActivator = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_1.ITerminalHelper)) ], TerminalActivator); exports.TerminalActivator = TerminalActivator; /***/ }), /***/ "./src/client/common/terminal/environmentActivationProviders/baseActivationProvider.ts": /*!*********************************************************************************************!*\ !*** ./src/client/common/terminal/environmentActivationProviders/baseActivationProvider.ts ***! \*********************************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VenvBaseActivationCommandProvider = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const path = __webpack_require__(/*! path */ "path"); const contracts_1 = __webpack_require__(/*! ../../../interpreter/contracts */ "./src/client/interpreter/contracts.ts"); const types_1 = __webpack_require__(/*! ../../../ioc/types */ "./src/client/ioc/types.ts"); const types_2 = __webpack_require__(/*! ../../platform/types */ "./src/client/common/platform/types.ts"); function getVenvExecutableFinder(basename, pathDirname, pathJoin, fileExists) { const basenames = typeof basename === 'string' ? [basename] : basename; return async (python) => { const binDir = pathDirname(python); for (const name of basenames) { const filename = pathJoin(binDir, name); if (await fileExists(filename)) { return filename; } } return undefined; }; } let BaseActivationCommandProvider = class BaseActivationCommandProvider { constructor(serviceContainer) { this.serviceContainer = serviceContainer; } async getActivationCommands(resource, targetShell) { const interpreter = await this.serviceContainer .get(contracts_1.IInterpreterService) .getActiveInterpreter(resource); if (!interpreter) { return undefined; } return this.getActivationCommandsForInterpreter(interpreter.path, targetShell); } }; BaseActivationCommandProvider = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_1.IServiceContainer)) ], BaseActivationCommandProvider); class VenvBaseActivationCommandProvider extends BaseActivationCommandProvider { isShellSupported(targetShell) { return this.scripts[targetShell] !== undefined; } async findScriptFile(pythonPath, targetShell) { const fs = this.serviceContainer.get(types_2.IFileSystem); const candidates = this.scripts[targetShell]; if (!candidates) { return undefined; } const findScript = getVenvExecutableFinder(candidates, path.dirname, path.join, (n) => fs.fileExists(n)); return findScript(pythonPath); } } exports.VenvBaseActivationCommandProvider = VenvBaseActivationCommandProvider; /***/ }), /***/ "./src/client/common/terminal/environmentActivationProviders/bash.ts": /*!***************************************************************************!*\ !*** ./src/client/common/terminal/environmentActivationProviders/bash.ts ***! \***************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Bash = exports.getAllScripts = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); __webpack_require__(/*! ../../extensions */ "./src/client/common/extensions.ts"); const types_1 = __webpack_require__(/*! ../types */ "./src/client/common/terminal/types.ts"); const baseActivationProvider_1 = __webpack_require__(/*! ./baseActivationProvider */ "./src/client/common/terminal/environmentActivationProviders/baseActivationProvider.ts"); const SCRIPTS = { [types_1.TerminalShellType.wsl]: ['activate.sh', 'activate'], [types_1.TerminalShellType.ksh]: ['activate.sh', 'activate'], [types_1.TerminalShellType.zsh]: ['activate.sh', 'activate'], [types_1.TerminalShellType.gitbash]: ['activate.sh', 'activate'], [types_1.TerminalShellType.bash]: ['activate.sh', 'activate'], [types_1.TerminalShellType.tcshell]: ['activate.csh'], [types_1.TerminalShellType.cshell]: ['activate.csh'], [types_1.TerminalShellType.fish]: ['activate.fish'], }; function getAllScripts() { const scripts = []; for (const names of Object.values(SCRIPTS)) { for (const name of names) { if (!scripts.includes(name)) { scripts.push(name); } } } return scripts; } exports.getAllScripts = getAllScripts; let Bash = class Bash extends baseActivationProvider_1.VenvBaseActivationCommandProvider { constructor() { super(...arguments); this.scripts = SCRIPTS; } async getActivationCommandsForInterpreter(pythonPath, targetShell) { const scriptFile = await this.findScriptFile(pythonPath, targetShell); if (!scriptFile) { return undefined; } return [`source ${scriptFile.fileToCommandArgumentForPythonMgrExt()}`]; } }; Bash = __decorate([ (0, inversify_1.injectable)() ], Bash); exports.Bash = Bash; /***/ }), /***/ "./src/client/common/terminal/environmentActivationProviders/commandPrompt.ts": /*!************************************************************************************!*\ !*** ./src/client/common/terminal/environmentActivationProviders/commandPrompt.ts ***! \************************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CommandPromptAndPowerShell = exports.getAllScripts = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const path = __webpack_require__(/*! path */ "path"); const types_1 = __webpack_require__(/*! ../../../ioc/types */ "./src/client/ioc/types.ts"); __webpack_require__(/*! ../../extensions */ "./src/client/common/extensions.ts"); const types_2 = __webpack_require__(/*! ../types */ "./src/client/common/terminal/types.ts"); const baseActivationProvider_1 = __webpack_require__(/*! ./baseActivationProvider */ "./src/client/common/terminal/environmentActivationProviders/baseActivationProvider.ts"); const SCRIPTS = { [types_2.TerminalShellType.commandPrompt]: ['activate.bat', 'Activate.ps1'], [types_2.TerminalShellType.powershell]: ['Activate.ps1', 'activate.bat'], [types_2.TerminalShellType.powershellCore]: ['Activate.ps1', 'activate.bat'], }; function getAllScripts(pathJoin) { const scripts = []; for (const names of Object.values(SCRIPTS)) { for (const name of names) { if (!scripts.includes(name)) { scripts.push(name, pathJoin('Scripts', name), pathJoin('scripts', name)); } } } return scripts; } exports.getAllScripts = getAllScripts; let CommandPromptAndPowerShell = class CommandPromptAndPowerShell extends baseActivationProvider_1.VenvBaseActivationCommandProvider { constructor(serviceContainer) { super(serviceContainer); this.scripts = {}; for (const [key, names] of Object.entries(SCRIPTS)) { const shell = key; const scripts = []; for (const name of names) { scripts.push(name, path.join('Scripts', name), path.join('scripts', name)); } this.scripts[shell] = scripts; } } async getActivationCommandsForInterpreter(pythonPath, targetShell) { const scriptFile = await this.findScriptFile(pythonPath, targetShell); if (!scriptFile) { return undefined; } if (targetShell === types_2.TerminalShellType.commandPrompt && scriptFile.endsWith('activate.bat')) { return [scriptFile.fileToCommandArgumentForPythonMgrExt()]; } if ((targetShell === types_2.TerminalShellType.powershell || targetShell === types_2.TerminalShellType.powershellCore) && scriptFile.endsWith('Activate.ps1')) { return [`& ${scriptFile.fileToCommandArgumentForPythonMgrExt()}`]; } if (targetShell === types_2.TerminalShellType.commandPrompt && scriptFile.endsWith('Activate.ps1')) { return []; } return undefined; } }; CommandPromptAndPowerShell = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_1.IServiceContainer)) ], CommandPromptAndPowerShell); exports.CommandPromptAndPowerShell = CommandPromptAndPowerShell; /***/ }), /***/ "./src/client/common/terminal/environmentActivationProviders/condaActivationProvider.ts": /*!**********************************************************************************************!*\ !*** ./src/client/common/terminal/environmentActivationProviders/condaActivationProvider.ts ***! \**********************************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports._getPowershellCommands = exports.CondaActivationCommandProvider = void 0; __webpack_require__(/*! ../../extensions */ "./src/client/common/extensions.ts"); const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const path = __webpack_require__(/*! path */ "path"); const contracts_1 = __webpack_require__(/*! ../../../interpreter/contracts */ "./src/client/interpreter/contracts.ts"); const types_1 = __webpack_require__(/*! ../../platform/types */ "./src/client/common/platform/types.ts"); const types_2 = __webpack_require__(/*! ../../types */ "./src/client/common/types.ts"); const types_3 = __webpack_require__(/*! ../types */ "./src/client/common/terminal/types.ts"); let CondaActivationCommandProvider = class CondaActivationCommandProvider { constructor(condaService, platform, configService, pyenvs) { this.condaService = condaService; this.platform = platform; this.configService = configService; this.pyenvs = pyenvs; } isShellSupported() { return true; } getActivationCommands(resource, targetShell) { const { pythonPath } = this.configService.getSettings(resource); return this.getActivationCommandsForInterpreter(pythonPath, targetShell); } async getActivationCommandsForInterpreter(pythonPath, targetShell) { const envInfo = await this.pyenvs.getCondaEnvironment(pythonPath); if (!envInfo) { return undefined; } const condaEnv = envInfo.name.length > 0 ? envInfo.name : envInfo.path; const interpreterPath = await this.condaService.getInterpreterPathForEnvironment(envInfo); const activatePath = await this.condaService.getActivationScriptFromInterpreter(interpreterPath, envInfo.name); if (activatePath === null || activatePath === void 0 ? void 0 : activatePath.path) { if (this.platform.isWindows && targetShell !== types_3.TerminalShellType.bash && targetShell !== types_3.TerminalShellType.gitbash) { return [activatePath.path, `conda activate ${condaEnv.toCommandArgumentForPythonMgrExt()}`]; } const condaInfo = await this.condaService.getCondaInfo(); if (activatePath.type !== 'global' || (condaInfo === null || condaInfo === void 0 ? void 0 : condaInfo.conda_shlvl) === undefined || condaInfo.conda_shlvl === -1) { if (activatePath.path === 'activate') { return [ `source ${activatePath.path}`, `conda activate ${condaEnv.toCommandArgumentForPythonMgrExt()}`, ]; } return [`source ${activatePath.path} ${condaEnv.toCommandArgumentForPythonMgrExt()}`]; } return [`conda activate ${condaEnv.toCommandArgumentForPythonMgrExt()}`]; } switch (targetShell) { case types_3.TerminalShellType.powershell: case types_3.TerminalShellType.powershellCore: return _getPowershellCommands(condaEnv); case types_3.TerminalShellType.fish: return getFishCommands(condaEnv, await this.condaService.getCondaFile()); default: if (this.platform.isWindows) { return this.getWindowsCommands(condaEnv); } return getUnixCommands(condaEnv, await this.condaService.getCondaFile()); } } async getWindowsActivateCommand() { let activateCmd = 'activate'; const condaExePath = await this.condaService.getCondaFile(); if (condaExePath && path.basename(condaExePath) !== condaExePath) { const condaScriptsPath = path.dirname(condaExePath); activateCmd = path.join(condaScriptsPath, activateCmd); activateCmd = activateCmd.toCommandArgumentForPythonMgrExt(); } return activateCmd; } async getWindowsCommands(condaEnv) { const activate = await this.getWindowsActivateCommand(); return [`${activate} ${condaEnv.toCommandArgumentForPythonMgrExt()}`]; } }; CondaActivationCommandProvider = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(contracts_1.ICondaService)), __param(1, (0, inversify_1.inject)(types_1.IPlatformService)), __param(2, (0, inversify_1.inject)(types_2.IConfigurationService)), __param(3, (0, inversify_1.inject)(contracts_1.IComponentAdapter)) ], CondaActivationCommandProvider); exports.CondaActivationCommandProvider = CondaActivationCommandProvider; async function _getPowershellCommands(condaEnv) { return [`conda activate ${condaEnv.toCommandArgumentForPythonMgrExt()}`]; } exports._getPowershellCommands = _getPowershellCommands; async function getFishCommands(condaEnv, condaFile) { return [`${condaFile.fileToCommandArgumentForPythonMgrExt()} activate ${condaEnv.toCommandArgumentForPythonMgrExt()}`]; } async function getUnixCommands(condaEnv, condaFile) { const condaDir = path.dirname(condaFile); const activateFile = path.join(condaDir, 'activate'); return [`source ${activateFile.fileToCommandArgumentForPythonMgrExt()} ${condaEnv.toCommandArgumentForPythonMgrExt()}`]; } /***/ }), /***/ "./src/client/common/terminal/environmentActivationProviders/nushell.ts": /*!******************************************************************************!*\ !*** ./src/client/common/terminal/environmentActivationProviders/nushell.ts ***! \******************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Nushell = exports.getAllScripts = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); __webpack_require__(/*! ../../extensions */ "./src/client/common/extensions.ts"); const types_1 = __webpack_require__(/*! ../types */ "./src/client/common/terminal/types.ts"); const baseActivationProvider_1 = __webpack_require__(/*! ./baseActivationProvider */ "./src/client/common/terminal/environmentActivationProviders/baseActivationProvider.ts"); const SCRIPTS = { [types_1.TerminalShellType.nushell]: ['activate.nu'], }; function getAllScripts() { const scripts = []; for (const names of Object.values(SCRIPTS)) { for (const name of names) { if (!scripts.includes(name)) { scripts.push(name); } } } return scripts; } exports.getAllScripts = getAllScripts; let Nushell = class Nushell extends baseActivationProvider_1.VenvBaseActivationCommandProvider { constructor() { super(...arguments); this.scripts = SCRIPTS; } async getActivationCommandsForInterpreter(pythonPath, targetShell) { const scriptFile = await this.findScriptFile(pythonPath, targetShell); if (!scriptFile) { return undefined; } return [`overlay use ${scriptFile.fileToCommandArgumentForPythonMgrExt()}`]; } }; Nushell = __decorate([ (0, inversify_1.injectable)() ], Nushell); exports.Nushell = Nushell; /***/ }), /***/ "./src/client/common/terminal/environmentActivationProviders/pipEnvActivationProvider.ts": /*!***********************************************************************************************!*\ !*** ./src/client/common/terminal/environmentActivationProviders/pipEnvActivationProvider.ts ***! \***********************************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PipEnvActivationCommandProvider = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); __webpack_require__(/*! ../../extensions */ "./src/client/common/extensions.ts"); const contracts_1 = __webpack_require__(/*! ../../../interpreter/contracts */ "./src/client/interpreter/contracts.ts"); const pipenv_1 = __webpack_require__(/*! ../../../pythonEnvironments/common/environmentManagers/pipenv */ "./src/client/pythonEnvironments/common/environmentManagers/pipenv.ts"); const info_1 = __webpack_require__(/*! ../../../pythonEnvironments/info */ "./src/client/pythonEnvironments/info/index.ts"); const types_1 = __webpack_require__(/*! ../../application/types */ "./src/client/common/application/types.ts"); const types_2 = __webpack_require__(/*! ../../types */ "./src/client/common/types.ts"); let PipEnvActivationCommandProvider = class PipEnvActivationCommandProvider { constructor(interpreterService, pipEnvExecution, workspaceService) { this.interpreterService = interpreterService; this.pipEnvExecution = pipEnvExecution; this.workspaceService = workspaceService; } isShellSupported() { return false; } async getActivationCommands(resource) { const interpreter = await this.interpreterService.getActiveInterpreter(resource); if (!interpreter || interpreter.envType !== info_1.EnvironmentType.Pipenv) { return undefined; } const workspaceFolder = resource ? this.workspaceService.getWorkspaceFolder(resource) : undefined; if (workspaceFolder) { if (!(await (0, pipenv_1.isPipenvEnvironmentRelatedToFolder)(interpreter.path, workspaceFolder === null || workspaceFolder === void 0 ? void 0 : workspaceFolder.uri.fsPath))) { return undefined; } } const execName = this.pipEnvExecution.executable; return [`${execName.fileToCommandArgumentForPythonMgrExt()} shell`]; } async getActivationCommandsForInterpreter(pythonPath) { const interpreter = await this.interpreterService.getInterpreterDetails(pythonPath); if (!interpreter || interpreter.envType !== info_1.EnvironmentType.Pipenv) { return undefined; } const execName = this.pipEnvExecution.executable; return [`${execName.fileToCommandArgumentForPythonMgrExt()} shell`]; } }; PipEnvActivationCommandProvider = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(contracts_1.IInterpreterService)), __param(1, (0, inversify_1.inject)(types_2.IToolExecutionPath)), __param(1, (0, inversify_1.named)(types_2.ToolExecutionPath.pipenv)), __param(2, (0, inversify_1.inject)(types_1.IWorkspaceService)) ], PipEnvActivationCommandProvider); exports.PipEnvActivationCommandProvider = PipEnvActivationCommandProvider; /***/ }), /***/ "./src/client/common/terminal/environmentActivationProviders/pyenvActivationProvider.ts": /*!**********************************************************************************************!*\ !*** ./src/client/common/terminal/environmentActivationProviders/pyenvActivationProvider.ts ***! \**********************************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PyEnvActivationCommandProvider = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const contracts_1 = __webpack_require__(/*! ../../../interpreter/contracts */ "./src/client/interpreter/contracts.ts"); const types_1 = __webpack_require__(/*! ../../../ioc/types */ "./src/client/ioc/types.ts"); const info_1 = __webpack_require__(/*! ../../../pythonEnvironments/info */ "./src/client/pythonEnvironments/info/index.ts"); let PyEnvActivationCommandProvider = class PyEnvActivationCommandProvider { constructor(serviceContainer) { this.serviceContainer = serviceContainer; } isShellSupported(_targetShell) { return true; } async getActivationCommands(resource, _) { const interpreter = await this.serviceContainer .get(contracts_1.IInterpreterService) .getActiveInterpreter(resource); if (!interpreter || interpreter.envType !== info_1.EnvironmentType.Pyenv || !interpreter.envName) { return undefined; } return [`pyenv shell ${interpreter.envName.toCommandArgumentForPythonMgrExt()}`]; } async getActivationCommandsForInterpreter(pythonPath, _targetShell) { const interpreter = await this.serviceContainer .get(contracts_1.IInterpreterService) .getInterpreterDetails(pythonPath); if (!interpreter || interpreter.envType !== info_1.EnvironmentType.Pyenv || !interpreter.envName) { return undefined; } return [`pyenv shell ${interpreter.envName.toCommandArgumentForPythonMgrExt()}`]; } }; PyEnvActivationCommandProvider = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_1.IServiceContainer)) ], PyEnvActivationCommandProvider); exports.PyEnvActivationCommandProvider = PyEnvActivationCommandProvider; /***/ }), /***/ "./src/client/common/terminal/factory.ts": /*!***********************************************!*\ !*** ./src/client/common/terminal/factory.ts ***! \***********************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TerminalServiceFactory = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const path = __webpack_require__(/*! path */ "path"); const contracts_1 = __webpack_require__(/*! ../../interpreter/contracts */ "./src/client/interpreter/contracts.ts"); const types_1 = __webpack_require__(/*! ../../ioc/types */ "./src/client/ioc/types.ts"); const types_2 = __webpack_require__(/*! ../application/types */ "./src/client/common/application/types.ts"); const types_3 = __webpack_require__(/*! ../platform/types */ "./src/client/common/platform/types.ts"); const service_1 = __webpack_require__(/*! ./service */ "./src/client/common/terminal/service.ts"); const syncTerminalService_1 = __webpack_require__(/*! ./syncTerminalService */ "./src/client/common/terminal/syncTerminalService.ts"); let TerminalServiceFactory = class TerminalServiceFactory { constructor(serviceContainer, fs, interpreterService) { this.serviceContainer = serviceContainer; this.fs = fs; this.interpreterService = interpreterService; this.terminalServices = new Map(); } getTerminalService(options) { const resource = options === null || options === void 0 ? void 0 : options.resource; const title = options === null || options === void 0 ? void 0 : options.title; let terminalTitle = typeof title === 'string' && title.trim().length > 0 ? title.trim() : 'Python'; const interpreter = options === null || options === void 0 ? void 0 : options.interpreter; const id = this.getTerminalId(terminalTitle, resource, interpreter, options.newTerminalPerFile); if (!this.terminalServices.has(id)) { if (resource && options.newTerminalPerFile) { terminalTitle = `${terminalTitle}: ${path.basename(resource.fsPath).replace('.py', '')}`; } options.title = terminalTitle; const terminalService = new service_1.TerminalService(this.serviceContainer, options); this.terminalServices.set(id, terminalService); } return new syncTerminalService_1.SynchronousTerminalService(this.fs, this.interpreterService, this.terminalServices.get(id), interpreter); } createTerminalService(resource, title) { title = typeof title === 'string' && title.trim().length > 0 ? title.trim() : 'Python'; return new service_1.TerminalService(this.serviceContainer, { resource, title }); } getTerminalId(title, resource, interpreter, newTerminalPerFile) { if (!resource && !interpreter) { return title; } const workspaceFolder = this.serviceContainer .get(types_2.IWorkspaceService) .getWorkspaceFolder(resource || undefined); const fileId = resource && newTerminalPerFile ? resource.fsPath : ''; return `${title}:${(workspaceFolder === null || workspaceFolder === void 0 ? void 0 : workspaceFolder.uri.fsPath) || ''}:${interpreter === null || interpreter === void 0 ? void 0 : interpreter.path}:${fileId}`; } }; TerminalServiceFactory = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_1.IServiceContainer)), __param(1, (0, inversify_1.inject)(types_3.IFileSystem)), __param(2, (0, inversify_1.inject)(contracts_1.IInterpreterService)) ], TerminalServiceFactory); exports.TerminalServiceFactory = TerminalServiceFactory; /***/ }), /***/ "./src/client/common/terminal/helper.ts": /*!**********************************************!*\ !*** ./src/client/common/terminal/helper.ts ***! \**********************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TerminalHelper = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const contracts_1 = __webpack_require__(/*! ../../interpreter/contracts */ "./src/client/interpreter/contracts.ts"); const types_1 = __webpack_require__(/*! ../../ioc/types */ "./src/client/ioc/types.ts"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const info_1 = __webpack_require__(/*! ../../pythonEnvironments/info */ "./src/client/pythonEnvironments/info/index.ts"); const telemetry_1 = __webpack_require__(/*! ../../telemetry */ "./src/client/telemetry/index.ts"); const constants_1 = __webpack_require__(/*! ../../telemetry/constants */ "./src/client/telemetry/constants.ts"); const types_2 = __webpack_require__(/*! ../application/types */ "./src/client/common/application/types.ts"); __webpack_require__(/*! ../extensions */ "./src/client/common/extensions.ts"); const types_3 = __webpack_require__(/*! ../platform/types */ "./src/client/common/platform/types.ts"); const types_4 = __webpack_require__(/*! ../types */ "./src/client/common/types.ts"); const platform_1 = __webpack_require__(/*! ../utils/platform */ "./src/client/common/utils/platform.ts"); const shellDetector_1 = __webpack_require__(/*! ./shellDetector */ "./src/client/common/terminal/shellDetector.ts"); const types_5 = __webpack_require__(/*! ./types */ "./src/client/common/terminal/types.ts"); let TerminalHelper = class TerminalHelper { constructor(platform, terminalManager, serviceContainer, interpreterService, configurationService, conda, bashCShellFish, commandPromptAndPowerShell, nushell, pyenv, pipenv, shellDetectors) { this.platform = platform; this.terminalManager = terminalManager; this.serviceContainer = serviceContainer; this.interpreterService = interpreterService; this.configurationService = configurationService; this.conda = conda; this.bashCShellFish = bashCShellFish; this.commandPromptAndPowerShell = commandPromptAndPowerShell; this.nushell = nushell; this.pyenv = pyenv; this.pipenv = pipenv; this.shellDetector = new shellDetector_1.ShellDetector(this.platform, shellDetectors); } createTerminal(title) { return this.terminalManager.createTerminal({ name: title }); } identifyTerminalShell(terminal) { return this.shellDetector.identifyTerminalShell(terminal); } buildCommandForTerminal(terminalShellType, command, args) { const isPowershell = terminalShellType === types_5.TerminalShellType.powershell || terminalShellType === types_5.TerminalShellType.powershellCore; const commandPrefix = isPowershell ? '& ' : ''; const formattedArgs = args.map((a) => a.toCommandArgumentForPythonMgrExt()); return `${commandPrefix}${command.fileToCommandArgumentForPythonMgrExt()} ${formattedArgs.join(' ')}`.trim(); } async getEnvironmentActivationCommands(terminalShellType, resource, interpreter) { const providers = [this.pipenv, this.pyenv, this.bashCShellFish, this.commandPromptAndPowerShell, this.nushell]; const promise = this.getActivationCommands(resource || undefined, interpreter, terminalShellType, providers); this.sendTelemetry(terminalShellType, constants_1.EventName.PYTHON_INTERPRETER_ACTIVATION_FOR_TERMINAL, interpreter, promise).ignoreErrors(); return promise; } async getEnvironmentActivationShellCommands(resource, shell, interpreter) { if (this.platform.osType === platform_1.OSType.Unknown) { return; } const providers = [this.bashCShellFish, this.commandPromptAndPowerShell, this.nushell]; const promise = this.getActivationCommands(resource, interpreter, shell, providers); this.sendTelemetry(shell, constants_1.EventName.PYTHON_INTERPRETER_ACTIVATION_FOR_RUNNING_CODE, interpreter, promise).ignoreErrors(); return promise; } async sendTelemetry(terminalShellType, eventName, interpreter, promise) { let hasCommands = false; let failed = false; try { const cmds = await promise; hasCommands = Array.isArray(cmds) && cmds.length > 0; } catch (ex) { failed = true; (0, logging_1.traceError)('Failed to get activation commands', ex); } const pythonVersion = interpreter && interpreter.version ? interpreter.version.raw : undefined; const interpreterType = interpreter ? interpreter.envType : info_1.EnvironmentType.Unknown; const data = { failed, hasCommands, interpreterType, terminal: terminalShellType, pythonVersion }; (0, telemetry_1.sendTelemetryEvent)(eventName, undefined, data); } async getActivationCommands(resource, interpreter, terminalShellType, providers) { const settings = this.configurationService.getSettings(resource); const condaService = this.serviceContainer.get(contracts_1.IComponentAdapter); const isCondaEnvironment = interpreter ? interpreter.envType === info_1.EnvironmentType.Conda : await condaService.isCondaEnvironment(settings.pythonPath); if (isCondaEnvironment) { const activationCommands = interpreter ? await this.conda.getActivationCommandsForInterpreter(interpreter.path, terminalShellType) : await this.conda.getActivationCommands(resource, terminalShellType); if (Array.isArray(activationCommands)) { return activationCommands; } } const supportedProviders = providers.filter((provider) => provider.isShellSupported(terminalShellType)); for (const provider of supportedProviders) { const activationCommands = interpreter ? await provider.getActivationCommandsForInterpreter(interpreter.path, terminalShellType) : await provider.getActivationCommands(resource, terminalShellType); if (Array.isArray(activationCommands) && activationCommands.length > 0) { return activationCommands; } } } }; __decorate([ (0, logging_1.traceDecoratorError)('Failed to capture telemetry') ], TerminalHelper.prototype, "sendTelemetry", null); TerminalHelper = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_3.IPlatformService)), __param(1, (0, inversify_1.inject)(types_2.ITerminalManager)), __param(2, (0, inversify_1.inject)(types_1.IServiceContainer)), __param(3, (0, inversify_1.inject)(contracts_1.IInterpreterService)), __param(4, (0, inversify_1.inject)(types_4.IConfigurationService)), __param(5, (0, inversify_1.inject)(types_5.ITerminalActivationCommandProvider)), __param(5, (0, inversify_1.named)(types_5.TerminalActivationProviders.conda)), __param(6, (0, inversify_1.inject)(types_5.ITerminalActivationCommandProvider)), __param(6, (0, inversify_1.named)(types_5.TerminalActivationProviders.bashCShellFish)), __param(7, (0, inversify_1.inject)(types_5.ITerminalActivationCommandProvider)), __param(7, (0, inversify_1.named)(types_5.TerminalActivationProviders.commandPromptAndPowerShell)), __param(8, (0, inversify_1.inject)(types_5.ITerminalActivationCommandProvider)), __param(8, (0, inversify_1.named)(types_5.TerminalActivationProviders.nushell)), __param(9, (0, inversify_1.inject)(types_5.ITerminalActivationCommandProvider)), __param(9, (0, inversify_1.named)(types_5.TerminalActivationProviders.pyenv)), __param(10, (0, inversify_1.inject)(types_5.ITerminalActivationCommandProvider)), __param(10, (0, inversify_1.named)(types_5.TerminalActivationProviders.pipenv)), __param(11, (0, inversify_1.multiInject)(types_5.IShellDetector)) ], TerminalHelper); exports.TerminalHelper = TerminalHelper; /***/ }), /***/ "./src/client/common/terminal/service.ts": /*!***********************************************!*\ !*** ./src/client/common/terminal/service.ts ***! \***********************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TerminalService = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); __webpack_require__(/*! ../../common/extensions */ "./src/client/common/extensions.ts"); const types_1 = __webpack_require__(/*! ../../ioc/types */ "./src/client/ioc/types.ts"); const types_2 = __webpack_require__(/*! ../application/types */ "./src/client/common/application/types.ts"); const types_3 = __webpack_require__(/*! ../types */ "./src/client/common/types.ts"); const types_4 = __webpack_require__(/*! ./types */ "./src/client/common/terminal/types.ts"); let TerminalService = class TerminalService { constructor(serviceContainer, options) { this.serviceContainer = serviceContainer; this.options = options; this.terminalClosed = new vscode_1.EventEmitter(); const disposableRegistry = this.serviceContainer.get(types_3.IDisposableRegistry); disposableRegistry.push(this); this.terminalHelper = this.serviceContainer.get(types_4.ITerminalHelper); this.terminalManager = this.serviceContainer.get(types_2.ITerminalManager); this.terminalManager.onDidCloseTerminal(this.terminalCloseHandler, this, disposableRegistry); this.terminalActivator = this.serviceContainer.get(types_4.ITerminalActivator); } get onDidCloseTerminal() { return this.terminalClosed.event.bind(this.terminalClosed); } dispose() { if (this.terminal) { this.terminal.dispose(); } } async sendCommand(command, args, _) { var _a; await this.ensureTerminal(); const text = this.terminalHelper.buildCommandForTerminal(this.terminalShellType, command, args); if (!((_a = this.options) === null || _a === void 0 ? void 0 : _a.hideFromUser)) { this.terminal.show(true); } this.terminal.sendText(text, true); } async sendText(text) { var _a; await this.ensureTerminal(); if (!((_a = this.options) === null || _a === void 0 ? void 0 : _a.hideFromUser)) { this.terminal.show(true); } this.terminal.sendText(text); } async show(preserveFocus = true) { var _a; await this.ensureTerminal(preserveFocus); if (!((_a = this.options) === null || _a === void 0 ? void 0 : _a.hideFromUser)) { this.terminal.show(preserveFocus); } } async ensureTerminal(preserveFocus = true) { var _a, _b, _c, _d, _e, _f, _g; if (this.terminal) { return; } this.terminalShellType = this.terminalHelper.identifyTerminalShell(this.terminal); this.terminal = this.terminalManager.createTerminal({ name: ((_a = this.options) === null || _a === void 0 ? void 0 : _a.title) || 'Python', env: (_b = this.options) === null || _b === void 0 ? void 0 : _b.env, hideFromUser: (_c = this.options) === null || _c === void 0 ? void 0 : _c.hideFromUser, }); await new Promise((resolve) => setTimeout(resolve, 100)); await this.terminalActivator.activateEnvironmentInTerminal(this.terminal, { resource: (_d = this.options) === null || _d === void 0 ? void 0 : _d.resource, preserveFocus, interpreter: (_e = this.options) === null || _e === void 0 ? void 0 : _e.interpreter, hideFromUser: (_f = this.options) === null || _f === void 0 ? void 0 : _f.hideFromUser, }); if (!((_g = this.options) === null || _g === void 0 ? void 0 : _g.hideFromUser)) { this.terminal.show(preserveFocus); } } terminalCloseHandler(terminal) { if (terminal === this.terminal) { this.terminalClosed.fire(); this.terminal = undefined; } } }; TerminalService = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_1.IServiceContainer)) ], TerminalService); exports.TerminalService = TerminalService; /***/ }), /***/ "./src/client/common/terminal/shellDetector.ts": /*!*****************************************************!*\ !*** ./src/client/common/terminal/shellDetector.ts ***! \*****************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ShellDetector = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const telemetry_1 = __webpack_require__(/*! ../../telemetry */ "./src/client/telemetry/index.ts"); const constants_1 = __webpack_require__(/*! ../../telemetry/constants */ "./src/client/telemetry/constants.ts"); __webpack_require__(/*! ../extensions */ "./src/client/common/extensions.ts"); const types_1 = __webpack_require__(/*! ../platform/types */ "./src/client/common/platform/types.ts"); const platform_1 = __webpack_require__(/*! ../utils/platform */ "./src/client/common/utils/platform.ts"); const types_2 = __webpack_require__(/*! ./types */ "./src/client/common/terminal/types.ts"); const defaultOSShells = { [platform_1.OSType.Linux]: types_2.TerminalShellType.bash, [platform_1.OSType.OSX]: types_2.TerminalShellType.bash, [platform_1.OSType.Windows]: types_2.TerminalShellType.commandPrompt, [platform_1.OSType.Unknown]: types_2.TerminalShellType.other, }; let ShellDetector = class ShellDetector { constructor(platform, shellDetectors) { this.platform = platform; this.shellDetectors = shellDetectors; } identifyTerminalShell(terminal) { let shell; const telemetryProperties = { failed: true, shellIdentificationSource: 'default', terminalProvided: !!terminal, hasCustomShell: undefined, hasShellInEnv: undefined, }; const shellDetectors = this.shellDetectors.slice().sort((a, b) => b.priority - a.priority); for (const detector of shellDetectors) { shell = detector.identify(telemetryProperties, terminal); (0, logging_1.traceVerbose)(`${detector}. Shell identified as ${shell} ${terminal ? `(Terminal name is ${terminal.name})` : ''}`); if (shell && shell !== types_2.TerminalShellType.other) { telemetryProperties.failed = false; break; } } (0, telemetry_1.sendTelemetryEvent)(constants_1.EventName.TERMINAL_SHELL_IDENTIFICATION, undefined, telemetryProperties); (0, logging_1.traceVerbose)(`Shell identified as '${shell}'`); if (shell === undefined || shell === types_2.TerminalShellType.other) { (0, logging_1.traceError)('Unable to identify shell', vscode_1.env.shell, ' for OS ', this.platform.osType); (0, logging_1.traceVerbose)('Using default OS shell'); shell = defaultOSShells[this.platform.osType]; } return shell; } }; ShellDetector = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_1.IPlatformService)), __param(1, (0, inversify_1.multiInject)(types_2.IShellDetector)) ], ShellDetector); exports.ShellDetector = ShellDetector; /***/ }), /***/ "./src/client/common/terminal/shellDetectors/baseShellDetector.ts": /*!************************************************************************!*\ !*** ./src/client/common/terminal/shellDetectors/baseShellDetector.ts ***! \************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.identifyShellFromShellPath = exports.BaseShellDetector = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); const types_1 = __webpack_require__(/*! ../types */ "./src/client/common/terminal/types.ts"); const IS_GITBASH = /(gitbash$)/i; const IS_BASH = /(bash$)/i; const IS_WSL = /(wsl$)/i; const IS_ZSH = /(zsh$)/i; const IS_KSH = /(ksh$)/i; const IS_COMMAND = /(cmd$)/i; const IS_POWERSHELL = /(powershell$)/i; const IS_POWERSHELL_CORE = /(pwsh$)/i; const IS_FISH = /(fish$)/i; const IS_CSHELL = /(csh$)/i; const IS_TCSHELL = /(tcsh$)/i; const IS_NUSHELL = /(nu$)/i; const IS_XONSH = /(xonsh$)/i; const detectableShells = new Map(); detectableShells.set(types_1.TerminalShellType.powershell, IS_POWERSHELL); detectableShells.set(types_1.TerminalShellType.gitbash, IS_GITBASH); detectableShells.set(types_1.TerminalShellType.bash, IS_BASH); detectableShells.set(types_1.TerminalShellType.wsl, IS_WSL); detectableShells.set(types_1.TerminalShellType.zsh, IS_ZSH); detectableShells.set(types_1.TerminalShellType.ksh, IS_KSH); detectableShells.set(types_1.TerminalShellType.commandPrompt, IS_COMMAND); detectableShells.set(types_1.TerminalShellType.fish, IS_FISH); detectableShells.set(types_1.TerminalShellType.tcshell, IS_TCSHELL); detectableShells.set(types_1.TerminalShellType.cshell, IS_CSHELL); detectableShells.set(types_1.TerminalShellType.nushell, IS_NUSHELL); detectableShells.set(types_1.TerminalShellType.powershellCore, IS_POWERSHELL_CORE); detectableShells.set(types_1.TerminalShellType.xonsh, IS_XONSH); let BaseShellDetector = class BaseShellDetector { constructor(priority) { this.priority = priority; } identifyShellFromShellPath(shellPath) { return identifyShellFromShellPath(shellPath); } }; BaseShellDetector = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.unmanaged)()) ], BaseShellDetector); exports.BaseShellDetector = BaseShellDetector; function identifyShellFromShellPath(shellPath) { const basePath = shellPath.replace(/\.exe$/, ''); const shell = Array.from(detectableShells.keys()).reduce((matchedShell, shellToDetect) => { if (matchedShell === types_1.TerminalShellType.other) { const pat = detectableShells.get(shellToDetect); if (pat && pat.test(basePath)) { return shellToDetect; } } return matchedShell; }, types_1.TerminalShellType.other); (0, logging_1.traceVerbose)(`Shell path '${shellPath}', base path '${basePath}'`); (0, logging_1.traceVerbose)(`Shell path identified as shell '${shell}'`); return shell; } exports.identifyShellFromShellPath = identifyShellFromShellPath; /***/ }), /***/ "./src/client/common/terminal/shellDetectors/settingsShellDetector.ts": /*!****************************************************************************!*\ !*** ./src/client/common/terminal/shellDetectors/settingsShellDetector.ts ***! \****************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SettingsShellDetector = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); const types_1 = __webpack_require__(/*! ../../application/types */ "./src/client/common/application/types.ts"); const types_2 = __webpack_require__(/*! ../../platform/types */ "./src/client/common/platform/types.ts"); const platform_1 = __webpack_require__(/*! ../../utils/platform */ "./src/client/common/utils/platform.ts"); const types_3 = __webpack_require__(/*! ../types */ "./src/client/common/terminal/types.ts"); const baseShellDetector_1 = __webpack_require__(/*! ./baseShellDetector */ "./src/client/common/terminal/shellDetectors/baseShellDetector.ts"); let SettingsShellDetector = class SettingsShellDetector extends baseShellDetector_1.BaseShellDetector { constructor(workspace, platform) { super(2); this.workspace = workspace; this.platform = platform; } getTerminalShellPath() { const shellConfig = this.workspace.getConfiguration('terminal.integrated.shell'); let osSection = ''; switch (this.platform.osType) { case platform_1.OSType.Windows: { osSection = 'windows'; break; } case platform_1.OSType.OSX: { osSection = 'osx'; break; } case platform_1.OSType.Linux: { osSection = 'linux'; break; } default: { return ''; } } return shellConfig.get(osSection); } identify(telemetryProperties, _terminal) { const shellPath = this.getTerminalShellPath(); telemetryProperties.hasCustomShell = !!shellPath; const shell = shellPath ? this.identifyShellFromShellPath(shellPath) : types_3.TerminalShellType.other; if (shell !== types_3.TerminalShellType.other) { telemetryProperties.shellIdentificationSource = 'environment'; } else { telemetryProperties.shellIdentificationSource = 'settings'; } (0, logging_1.traceVerbose)(`Shell path from user settings '${shellPath}'`); return shell; } }; SettingsShellDetector = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_1.IWorkspaceService)), __param(1, (0, inversify_1.inject)(types_2.IPlatformService)) ], SettingsShellDetector); exports.SettingsShellDetector = SettingsShellDetector; /***/ }), /***/ "./src/client/common/terminal/shellDetectors/terminalNameShellDetector.ts": /*!********************************************************************************!*\ !*** ./src/client/common/terminal/shellDetectors/terminalNameShellDetector.ts ***! \********************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TerminalNameShellDetector = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); const types_1 = __webpack_require__(/*! ../types */ "./src/client/common/terminal/types.ts"); const baseShellDetector_1 = __webpack_require__(/*! ./baseShellDetector */ "./src/client/common/terminal/shellDetectors/baseShellDetector.ts"); let TerminalNameShellDetector = class TerminalNameShellDetector extends baseShellDetector_1.BaseShellDetector { constructor() { super(4); } identify(telemetryProperties, terminal) { if (!terminal) { return; } const shell = this.identifyShellFromShellPath(terminal.name); (0, logging_1.traceVerbose)(`Terminal name '${terminal.name}' identified as shell '${shell}'`); telemetryProperties.shellIdentificationSource = shell === types_1.TerminalShellType.other ? telemetryProperties.shellIdentificationSource : 'terminalName'; return shell; } }; TerminalNameShellDetector = __decorate([ (0, inversify_1.injectable)() ], TerminalNameShellDetector); exports.TerminalNameShellDetector = TerminalNameShellDetector; /***/ }), /***/ "./src/client/common/terminal/shellDetectors/userEnvironmentShellDetector.ts": /*!***********************************************************************************!*\ !*** ./src/client/common/terminal/shellDetectors/userEnvironmentShellDetector.ts ***! \***********************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UserEnvironmentShellDetector = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); const types_1 = __webpack_require__(/*! ../../platform/types */ "./src/client/common/platform/types.ts"); const types_2 = __webpack_require__(/*! ../../types */ "./src/client/common/types.ts"); const platform_1 = __webpack_require__(/*! ../../utils/platform */ "./src/client/common/utils/platform.ts"); const types_3 = __webpack_require__(/*! ../types */ "./src/client/common/terminal/types.ts"); const baseShellDetector_1 = __webpack_require__(/*! ./baseShellDetector */ "./src/client/common/terminal/shellDetectors/baseShellDetector.ts"); let UserEnvironmentShellDetector = class UserEnvironmentShellDetector extends baseShellDetector_1.BaseShellDetector { constructor(currentProcess, platform) { super(1); this.currentProcess = currentProcess; this.platform = platform; } getDefaultPlatformShell() { return getDefaultShell(this.platform, this.currentProcess); } identify(telemetryProperties, _terminal) { const shellPath = this.getDefaultPlatformShell(); telemetryProperties.hasShellInEnv = !!shellPath; const shell = this.identifyShellFromShellPath(shellPath); if (shell !== types_3.TerminalShellType.other) { telemetryProperties.shellIdentificationSource = 'environment'; } (0, logging_1.traceVerbose)(`Shell path from user env '${shellPath}'`); return shell; } }; UserEnvironmentShellDetector = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_2.ICurrentProcess)), __param(1, (0, inversify_1.inject)(types_1.IPlatformService)) ], UserEnvironmentShellDetector); exports.UserEnvironmentShellDetector = UserEnvironmentShellDetector; function getDefaultShell(platform, currentProcess) { if (platform.osType === platform_1.OSType.Windows) { return getTerminalDefaultShellWindows(platform, currentProcess); } return currentProcess.env.SHELL && currentProcess.env.SHELL !== '/bin/false' ? currentProcess.env.SHELL : '/bin/bash'; } function getTerminalDefaultShellWindows(platform, currentProcess) { const isAtLeastWindows10 = parseFloat(platform.osRelease) >= 10; const is32ProcessOn64Windows = currentProcess.env.hasOwnProperty('PROCESSOR_ARCHITEW6432'); const powerShellPath = `${currentProcess.env.windir}\\${is32ProcessOn64Windows ? 'Sysnative' : 'System32'}\\WindowsPowerShell\\v1.0\\powershell.exe`; return isAtLeastWindows10 ? powerShellPath : getWindowsShell(currentProcess); } function getWindowsShell(currentProcess) { return currentProcess.env.comspec || 'cmd.exe'; } /***/ }), /***/ "./src/client/common/terminal/shellDetectors/vscEnvironmentShellDetector.ts": /*!**********************************************************************************!*\ !*** ./src/client/common/terminal/shellDetectors/vscEnvironmentShellDetector.ts ***! \**********************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VSCEnvironmentShellDetector = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); const types_1 = __webpack_require__(/*! ../../application/types */ "./src/client/common/application/types.ts"); const types_2 = __webpack_require__(/*! ../types */ "./src/client/common/terminal/types.ts"); const baseShellDetector_1 = __webpack_require__(/*! ./baseShellDetector */ "./src/client/common/terminal/shellDetectors/baseShellDetector.ts"); let VSCEnvironmentShellDetector = class VSCEnvironmentShellDetector extends baseShellDetector_1.BaseShellDetector { constructor(appEnv) { super(3); this.appEnv = appEnv; } identify(telemetryProperties, terminal) { const shellPath = (terminal === null || terminal === void 0 ? void 0 : terminal.creationOptions) && 'shellPath' in terminal.creationOptions && terminal.creationOptions.shellPath ? terminal.creationOptions.shellPath : this.appEnv.shell; if (!shellPath) { return; } const shell = this.identifyShellFromShellPath(shellPath); (0, logging_1.traceVerbose)(`Terminal shell path '${shellPath}' identified as shell '${shell}'`); telemetryProperties.shellIdentificationSource = shell === types_2.TerminalShellType.other ? telemetryProperties.shellIdentificationSource : 'vscode'; telemetryProperties.failed = shell === types_2.TerminalShellType.other ? false : true; return shell; } }; VSCEnvironmentShellDetector = __decorate([ __param(0, (0, inversify_1.inject)(types_1.IApplicationEnvironment)) ], VSCEnvironmentShellDetector); exports.VSCEnvironmentShellDetector = VSCEnvironmentShellDetector; /***/ }), /***/ "./src/client/common/terminal/syncTerminalService.ts": /*!***********************************************************!*\ !*** ./src/client/common/terminal/syncTerminalService.ts ***! \***********************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SynchronousTerminalService = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const contracts_1 = __webpack_require__(/*! ../../interpreter/contracts */ "./src/client/interpreter/contracts.ts"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const cancellation_1 = __webpack_require__(/*! ../cancellation */ "./src/client/common/cancellation.ts"); const types_1 = __webpack_require__(/*! ../platform/types */ "./src/client/common/platform/types.ts"); const internalScripts = __webpack_require__(/*! ../process/internal/scripts */ "./src/client/common/process/internal/scripts/index.ts"); const async_1 = __webpack_require__(/*! ../utils/async */ "./src/client/common/utils/async.ts"); const misc_1 = __webpack_require__(/*! ../utils/misc */ "./src/client/common/utils/misc.ts"); var State; (function (State) { State[State["notStarted"] = 0] = "notStarted"; State[State["started"] = 1] = "started"; State[State["completed"] = 2] = "completed"; State[State["errored"] = 4] = "errored"; })(State || (State = {})); class ExecutionState { constructor(lockFile, fs, command) { this.lockFile = lockFile; this.fs = fs; this.command = command; this.state = State.notStarted; this._completed = (0, async_1.createDeferred)(); this.registerStateUpdate(); this._completed.promise.finally(() => this.dispose()).ignoreErrors(); } get completed() { return this._completed.promise; } dispose() { if (this.disposable) { this.disposable.dispose(); this.disposable = undefined; } } registerStateUpdate() { const timeout = setInterval(async () => { const state = await this.getLockFileState(this.lockFile); if (state !== this.state) { (0, logging_1.traceVerbose)(`Command state changed to ${state}. ${this.command.join(' ')}`); } this.state = state; if (state & State.errored) { const errorContents = await this.fs.readFile(`${this.lockFile}.error`).catch(() => ''); this._completed.reject(new Error(`Command failed with errors, check the terminal for details. Command: ${this.command.join(' ')}\n${errorContents}`)); } else if (state & State.completed) { this._completed.resolve(); } }, 100); this.disposable = { dispose: () => clearInterval(timeout), }; } async getLockFileState(file) { const source = await this.fs.readFile(file); let state = State.notStarted; if (source.includes('START')) { state |= State.started; } if (source.includes('END')) { state |= State.completed; } if (source.includes('FAIL')) { state |= State.completed | State.errored; } return state; } } let SynchronousTerminalService = class SynchronousTerminalService { constructor(fs, interpreter, terminalService, pythonInterpreter) { this.fs = fs; this.interpreter = interpreter; this.terminalService = terminalService; this.pythonInterpreter = pythonInterpreter; this.disposables = []; } get onDidCloseTerminal() { return this.terminalService.onDidCloseTerminal; } dispose() { this.terminalService.dispose(); while (this.disposables.length) { const disposable = this.disposables.shift(); if (disposable) { try { disposable.dispose(); } catch (_a) { (0, misc_1.noop)(); } } else { break; } } } async sendCommand(command, args, cancel, swallowExceptions = true) { if (!cancel) { return this.terminalService.sendCommand(command, args); } const lockFile = await this.createLockFile(); const state = new ExecutionState(lockFile.filePath, this.fs, [command, ...args]); try { const pythonExec = this.pythonInterpreter || (await this.interpreter.getActiveInterpreter(undefined)); const sendArgs = internalScripts.shell_exec(command, lockFile.filePath, args); await this.terminalService.sendCommand((pythonExec === null || pythonExec === void 0 ? void 0 : pythonExec.path) || 'python', sendArgs); const promise = swallowExceptions ? state.completed : state.completed.catch(misc_1.noop); await cancellation_1.Cancellation.race(() => promise, cancel); } finally { state.dispose(); lockFile.dispose(); } } sendText(text) { return this.terminalService.sendText(text); } show(preserveFocus) { return this.terminalService.show(preserveFocus); } createLockFile() { return this.fs.createTemporaryFile('.log').then((l) => { this.disposables.push(l); return l; }); } }; SynchronousTerminalService = __decorate([ __param(0, (0, inversify_1.inject)(types_1.IFileSystem)), __param(1, (0, inversify_1.inject)(contracts_1.IInterpreterService)) ], SynchronousTerminalService); exports.SynchronousTerminalService = SynchronousTerminalService; /***/ }), /***/ "./src/client/common/terminal/types.ts": /*!*********************************************!*\ !*** ./src/client/common/terminal/types.ts ***! \*********************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.IShellDetector = exports.ITerminalActivationCommandProvider = exports.ITerminalActivator = exports.ITerminalHelper = exports.ITerminalServiceFactory = exports.TerminalShellType = exports.TerminalActivationProviders = void 0; var TerminalActivationProviders; (function (TerminalActivationProviders) { TerminalActivationProviders["bashCShellFish"] = "bashCShellFish"; TerminalActivationProviders["commandPromptAndPowerShell"] = "commandPromptAndPowerShell"; TerminalActivationProviders["nushell"] = "nushell"; TerminalActivationProviders["pyenv"] = "pyenv"; TerminalActivationProviders["conda"] = "conda"; TerminalActivationProviders["pipenv"] = "pipenv"; })(TerminalActivationProviders = exports.TerminalActivationProviders || (exports.TerminalActivationProviders = {})); var TerminalShellType; (function (TerminalShellType) { TerminalShellType["powershell"] = "powershell"; TerminalShellType["powershellCore"] = "powershellCore"; TerminalShellType["commandPrompt"] = "commandPrompt"; TerminalShellType["gitbash"] = "gitbash"; TerminalShellType["bash"] = "bash"; TerminalShellType["zsh"] = "zsh"; TerminalShellType["ksh"] = "ksh"; TerminalShellType["fish"] = "fish"; TerminalShellType["cshell"] = "cshell"; TerminalShellType["tcshell"] = "tshell"; TerminalShellType["nushell"] = "nushell"; TerminalShellType["wsl"] = "wsl"; TerminalShellType["xonsh"] = "xonsh"; TerminalShellType["other"] = "other"; })(TerminalShellType = exports.TerminalShellType || (exports.TerminalShellType = {})); exports.ITerminalServiceFactory = Symbol('ITerminalServiceFactory'); exports.ITerminalHelper = Symbol('ITerminalHelper'); exports.ITerminalActivator = Symbol('ITerminalActivator'); exports.ITerminalActivationCommandProvider = Symbol('ITerminalActivationCommandProvider'); exports.IShellDetector = Symbol('IShellDetector'); /***/ }), /***/ "./src/client/common/types.ts": /*!************************************!*\ !*** ./src/client/common/types.ts ***! \************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.IEditorUtils = exports.IExtensionContext = exports.ISocketServer = exports.ToolExecutionPath = exports.IToolExecutionPath = exports.IConfigurationService = exports.ICurrentProcess = exports.IRandom = exports.IPathUtils = exports.Product = exports.ProductType = exports.ProductInstallStatus = exports.InstallerResponse = exports.IPersistentStateFactory = exports.WORKSPACE_MEMENTO = exports.GLOBAL_MEMENTO = exports.IMemento = exports.IDisposableRegistry = exports.IsWindows = exports.IDocumentSymbolProvider = exports.ITestOutputChannel = exports.ILogOutputChannel = void 0; exports.ILogOutputChannel = Symbol('ILogOutputChannel'); exports.ITestOutputChannel = Symbol('ITestOutputChannel'); exports.IDocumentSymbolProvider = Symbol('IDocumentSymbolProvider'); exports.IsWindows = Symbol('IS_WINDOWS'); exports.IDisposableRegistry = Symbol('IDisposableRegistry'); exports.IMemento = Symbol('IGlobalMemento'); exports.GLOBAL_MEMENTO = Symbol('IGlobalMemento'); exports.WORKSPACE_MEMENTO = Symbol('IWorkspaceMemento'); exports.IPersistentStateFactory = Symbol('IPersistentStateFactory'); var InstallerResponse; (function (InstallerResponse) { InstallerResponse[InstallerResponse["Installed"] = 0] = "Installed"; InstallerResponse[InstallerResponse["Disabled"] = 1] = "Disabled"; InstallerResponse[InstallerResponse["Ignore"] = 2] = "Ignore"; })(InstallerResponse = exports.InstallerResponse || (exports.InstallerResponse = {})); var ProductInstallStatus; (function (ProductInstallStatus) { ProductInstallStatus[ProductInstallStatus["Installed"] = 0] = "Installed"; ProductInstallStatus[ProductInstallStatus["NotInstalled"] = 1] = "NotInstalled"; ProductInstallStatus[ProductInstallStatus["NeedsUpgrade"] = 2] = "NeedsUpgrade"; })(ProductInstallStatus = exports.ProductInstallStatus || (exports.ProductInstallStatus = {})); var ProductType; (function (ProductType) { ProductType["DataScience"] = "DataScience"; ProductType["Python"] = "Python"; })(ProductType = exports.ProductType || (exports.ProductType = {})); var Product; (function (Product) { Product[Product["pytest"] = 1] = "pytest"; Product[Product["pylint"] = 3] = "pylint"; Product[Product["flake8"] = 4] = "flake8"; Product[Product["pycodestyle"] = 5] = "pycodestyle"; Product[Product["pylama"] = 6] = "pylama"; Product[Product["prospector"] = 7] = "prospector"; Product[Product["pydocstyle"] = 8] = "pydocstyle"; Product[Product["yapf"] = 9] = "yapf"; Product[Product["autopep8"] = 10] = "autopep8"; Product[Product["mypy"] = 11] = "mypy"; Product[Product["unittest"] = 12] = "unittest"; Product[Product["isort"] = 15] = "isort"; Product[Product["black"] = 16] = "black"; Product[Product["bandit"] = 17] = "bandit"; Product[Product["tensorboard"] = 24] = "tensorboard"; Product[Product["torchProfilerInstallName"] = 25] = "torchProfilerInstallName"; Product[Product["torchProfilerImportName"] = 26] = "torchProfilerImportName"; Product[Product["pip"] = 27] = "pip"; Product[Product["ensurepip"] = 28] = "ensurepip"; Product[Product["python"] = 29] = "python"; })(Product = exports.Product || (exports.Product = {})); exports.IPathUtils = Symbol('IPathUtils'); exports.IRandom = Symbol('IRandom'); exports.ICurrentProcess = Symbol('ICurrentProcess'); exports.IConfigurationService = Symbol('IConfigurationService'); exports.IToolExecutionPath = Symbol('IToolExecutionPath'); var ToolExecutionPath; (function (ToolExecutionPath) { ToolExecutionPath["pipenv"] = "pipenv"; })(ToolExecutionPath = exports.ToolExecutionPath || (exports.ToolExecutionPath = {})); exports.ISocketServer = Symbol('ISocketServer'); exports.IExtensionContext = Symbol('ExtensionContext'); exports.IEditorUtils = Symbol('IEditorUtils'); /***/ }), /***/ "./src/client/common/utils/arrayUtils.ts": /*!***********************************************!*\ !*** ./src/client/common/utils/arrayUtils.ts ***! \***********************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.asyncForEach = exports.asyncFilter = void 0; async function asyncFilter(arr, asyncPredicate) { const results = await Promise.all(arr.map(asyncPredicate)); return arr.filter((_v, index) => results[index]); } exports.asyncFilter = asyncFilter; async function asyncForEach(arr, asyncFunc) { await Promise.all(arr.map(asyncFunc)); } exports.asyncForEach = asyncForEach; /***/ }), /***/ "./src/client/common/utils/async.ts": /*!******************************************!*\ !*** ./src/client/common/utils/async.ts ***! \******************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.flattenIterator = exports.iterable = exports.mapToIterator = exports.chain = exports.iterEmpty = exports.createDeferredFromPromise = exports.createDeferredFrom = exports.createDeferred = exports.isPromise = exports.isThenable = exports.sleep = void 0; async function sleep(timeout) { return new Promise((resolve) => { setTimeout(() => resolve(timeout), timeout); }); } exports.sleep = sleep; function isThenable(v) { return typeof (v === null || v === void 0 ? void 0 : v.then) === 'function'; } exports.isThenable = isThenable; function isPromise(v) { return typeof (v === null || v === void 0 ? void 0 : v.then) === 'function' && typeof (v === null || v === void 0 ? void 0 : v.catch) === 'function'; } exports.isPromise = isPromise; class DeferredImpl { constructor(scope = null) { this.scope = scope; this._resolved = false; this._rejected = false; this._promise = new Promise((res, rej) => { this._resolve = res; this._reject = rej; }); } resolve(_value) { if (this.completed) { return; } this._resolve.apply(this.scope ? this.scope : this, [_value]); this._resolved = true; } reject(_reason) { if (this.completed) { return; } this._reject.apply(this.scope ? this.scope : this, [_reason]); this._rejected = true; } get promise() { return this._promise; } get resolved() { return this._resolved; } get rejected() { return this._rejected; } get completed() { return this._rejected || this._resolved; } } function createDeferred(scope = null) { return new DeferredImpl(scope); } exports.createDeferred = createDeferred; function createDeferredFrom(...promises) { const deferred = createDeferred(); Promise.all(promises) .then(deferred.resolve.bind(deferred)) .catch(deferred.reject.bind(deferred)); return deferred; } exports.createDeferredFrom = createDeferredFrom; function createDeferredFromPromise(promise) { const deferred = createDeferred(); promise.then(deferred.resolve.bind(deferred)).catch(deferred.reject.bind(deferred)); return deferred; } exports.createDeferredFromPromise = createDeferredFromPromise; function iterEmpty() { return (async function* () { })(); } exports.iterEmpty = iterEmpty; async function getNext(it, indexMaybe) { const index = indexMaybe === undefined ? -1 : indexMaybe; try { const result = await it.next(); return { index, result, err: null }; } catch (err) { return { index, err: err, result: null }; } } const NEVER = new Promise(() => { }); async function* chain(iterators, onError) { const promises = iterators.map(getNext); let numRunning = iterators.length; while (numRunning > 0) { const { index, result, err } = await Promise.race(promises); if (err !== null) { promises[index] = NEVER; numRunning -= 1; if (onError !== undefined) { await onError(err, index); } } else if (result.done) { promises[index] = NEVER; numRunning -= 1; if (result.value !== undefined) { yield result.value; } } else { promises[index] = getNext(iterators[index], index); yield result.value; } } } exports.chain = chain; async function* mapToIterator(items, func, race = true) { if (race) { const iterators = items.map((item) => { async function* generator() { yield func(item); } return generator(); }); yield* iterable(chain(iterators)); } else { yield* items.map(func); } } exports.mapToIterator = mapToIterator; function iterable(iterator) { const it = iterator; if (it[Symbol.asyncIterator] === undefined) { it[Symbol.asyncIterator] = () => it; } return it; } exports.iterable = iterable; async function flattenIterator(iterator) { const results = []; for await (const item of iterable(iterator)) { results.push(item); } return results; } exports.flattenIterator = flattenIterator; /***/ }), /***/ "./src/client/common/utils/cacheUtils.ts": /*!***********************************************!*\ !*** ./src/client/common/utils/cacheUtils.ts ***! \***********************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InMemoryCache = exports.clearCache = exports.getCacheKeyFromFunctionArgs = exports.getGlobalCacheStore = void 0; const globalCacheStore = new Map(); function getGlobalCacheStore() { return globalCacheStore; } exports.getGlobalCacheStore = getGlobalCacheStore; function getCacheKeyFromFunctionArgs(keyPrefix, fnArgs) { const argsKey = fnArgs.map((arg) => `${JSON.stringify(arg)}`).join('-Arg-Separator-'); return `KeyPrefix=${keyPrefix}-Args=${argsKey}`; } exports.getCacheKeyFromFunctionArgs = getCacheKeyFromFunctionArgs; function clearCache() { globalCacheStore.clear(); } exports.clearCache = clearCache; class InMemoryCache { constructor(expiryDurationMs) { this.expiryDurationMs = expiryDurationMs; } get hasData() { if (!this.cacheData || this.hasExpired(this.cacheData.expiry)) { this.cacheData = undefined; return false; } return true; } get data() { var _a; if (!this.hasData) { return; } return (_a = this.cacheData) === null || _a === void 0 ? void 0 : _a.value; } set data(value) { if (value !== undefined) { this.cacheData = { expiry: this.calculateExpiry(), value, }; } else { this.cacheData = undefined; } } clear() { this.cacheData = undefined; } hasExpired(expiry) { return expiry <= Date.now(); } calculateExpiry() { return Date.now() + this.expiryDurationMs; } } exports.InMemoryCache = InMemoryCache; /***/ }), /***/ "./src/client/common/utils/decorators.ts": /*!***********************************************!*\ !*** ./src/client/common/utils/decorators.ts ***! \***********************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.swallowExceptions = exports.cache = exports.makeDebounceAsyncDecorator = exports.makeDebounceDecorator = exports.debounceAsync = exports.debounceSync = void 0; __webpack_require__(/*! ../../common/extensions */ "./src/client/common/extensions.ts"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const constants_1 = __webpack_require__(/*! ../constants */ "./src/client/common/constants.ts"); const async_1 = __webpack_require__(/*! ./async */ "./src/client/common/utils/async.ts"); const cacheUtils_1 = __webpack_require__(/*! ./cacheUtils */ "./src/client/common/utils/cacheUtils.ts"); const stopWatch_1 = __webpack_require__(/*! ./stopWatch */ "./src/client/common/utils/stopWatch.ts"); const _debounce = __webpack_require__(/*! lodash/debounce */ "./node_modules/lodash/debounce.js"); function debounceSync(wait) { if ((0, constants_1.isTestExecution)()) { wait = undefined; } return makeDebounceDecorator(wait); } exports.debounceSync = debounceSync; function debounceAsync(wait) { if ((0, constants_1.isTestExecution)()) { wait = undefined; } return makeDebounceAsyncDecorator(wait); } exports.debounceAsync = debounceAsync; function makeDebounceDecorator(wait) { return function (_target, _propertyName, descriptor) { const options = {}; const originalMethod = descriptor.value; const debounced = _debounce(function () { return originalMethod.apply(this, arguments); }, wait, options); descriptor.value = debounced; }; } exports.makeDebounceDecorator = makeDebounceDecorator; function makeDebounceAsyncDecorator(wait) { return function (_target, _propertyName, descriptor) { const originalMethod = descriptor.value; const state = { started: false, deferred: undefined, timer: undefined }; descriptor.value = function () { const existingDeferred = state.deferred; if (existingDeferred && state.started) { return existingDeferred.promise; } const existingDeferredCompleted = existingDeferred && existingDeferred.completed; const deferred = (state.deferred = !existingDeferred || existingDeferredCompleted ? (0, async_1.createDeferred)() : existingDeferred); if (state.timer) { clearTimeout(state.timer); } state.timer = setTimeout(async () => { state.started = true; originalMethod .apply(this) .then((r) => { state.started = false; deferred.resolve(r); }) .catch((ex) => { state.started = false; deferred.reject(ex); }); }, wait || 0); return deferred.promise; }; }; } exports.makeDebounceAsyncDecorator = makeDebounceAsyncDecorator; const cacheStoreForMethods = (0, cacheUtils_1.getGlobalCacheStore)(); const extensionStartUpTime = 200000; const moduleLoadWatch = new stopWatch_1.StopWatch(); function cache(expiryDurationMs, cachePromise = false, expiryDurationAfterStartUpMs) { return function (target, propertyName, descriptor) { const originalMethod = descriptor.value; const className = 'constructor' in target && target.constructor.name ? target.constructor.name : ''; const keyPrefix = `Cache_Method_Output_${className}.${propertyName}`; descriptor.value = async function (...args) { if ((0, constants_1.isTestExecution)()) { return originalMethod.apply(this, args); } let key; try { key = (0, cacheUtils_1.getCacheKeyFromFunctionArgs)(keyPrefix, args); } catch (ex) { (0, logging_1.traceError)('Error while creating key for keyPrefix:', keyPrefix, ex); return originalMethod.apply(this, args); } const cachedItem = cacheStoreForMethods.get(key); if (cachedItem && (cachedItem.expiry > Date.now() || expiryDurationMs === -1)) { (0, logging_1.traceVerbose)(`Cached data exists ${key}`); return Promise.resolve(cachedItem.data); } const expiryMs = expiryDurationAfterStartUpMs && moduleLoadWatch.elapsedTime > extensionStartUpTime ? expiryDurationAfterStartUpMs : expiryDurationMs; const promise = originalMethod.apply(this, args); if (cachePromise) { cacheStoreForMethods.set(key, { data: promise, expiry: Date.now() + expiryMs }); } else { promise .then((result) => cacheStoreForMethods.set(key, { data: result, expiry: Date.now() + expiryMs })) .ignoreErrors(); } return promise; }; }; } exports.cache = cache; function swallowExceptions(scopeName) { return function (_target, propertyName, descriptor) { const originalMethod = descriptor.value; const errorMessage = `Python Extension (Error in ${scopeName || propertyName}, method:${propertyName}):`; descriptor.value = function (...args) { try { const result = originalMethod.apply(this, args); if (result && typeof result.then === 'function' && typeof result.catch === 'function') { return result.catch((error) => { if ((0, constants_1.isTestExecution)()) { return; } (0, logging_1.traceError)(errorMessage, error); }); } } catch (error) { if ((0, constants_1.isTestExecution)()) { return; } (0, logging_1.traceError)(errorMessage, error); } }; }; } exports.swallowExceptions = swallowExceptions; /***/ }), /***/ "./src/client/common/utils/exec.ts": /*!*****************************************!*\ !*** ./src/client/common/utils/exec.ts ***! \*****************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isValidAndExecutable = exports.getSearchPathEntries = exports.getSearchPathEnvVarNames = void 0; const fsapi = __webpack_require__(/*! fs */ "fs"); const path = __webpack_require__(/*! path */ "path"); const platform_1 = __webpack_require__(/*! ./platform */ "./src/client/common/utils/platform.ts"); function getSearchPathEnvVarNames(ostype = (0, platform_1.getOSType)()) { if (ostype === platform_1.OSType.Windows) { return ['Path', 'PATH']; } return ['PATH']; } exports.getSearchPathEnvVarNames = getSearchPathEnvVarNames; function getSearchPathEntries() { const envVars = getSearchPathEnvVarNames(); for (const envVar of envVars) { const value = (0, platform_1.getEnvironmentVariable)(envVar); if (value !== undefined) { return parseSearchPathEntries(value); } } return []; } exports.getSearchPathEntries = getSearchPathEntries; function parseSearchPathEntries(envVarValue) { return envVarValue .split(path.delimiter) .map((entry) => entry.trim()) .filter((entry) => entry.length > 0); } async function isValidAndExecutable(filename) { try { await fsapi.promises.access(filename, fsapi.constants.X_OK); } catch (err) { return false; } if ((0, platform_1.getOSType)() === platform_1.OSType.Windows) { return undefined; } return true; } exports.isValidAndExecutable = isValidAndExecutable; /***/ }), /***/ "./src/client/common/utils/filesystem.ts": /*!***********************************************!*\ !*** ./src/client/common/utils/filesystem.ts ***! \***********************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getFileFilter = exports.getFileType = exports.convertFileType = exports.FileType = void 0; const fs = __webpack_require__(/*! fs */ "fs"); const vscode = __webpack_require__(/*! vscode */ "vscode"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); exports.FileType = vscode.FileType; function convertFileType(info) { if (info.isFile()) { return exports.FileType.File; } if (info.isDirectory()) { return exports.FileType.Directory; } if (info.isSymbolicLink()) { return exports.FileType.SymbolicLink; } return exports.FileType.Unknown; } exports.convertFileType = convertFileType; async function getFileType(filename, opts = { ignoreErrors: true }) { let stat; try { stat = await fs.promises.lstat(filename); } catch (err) { const error = err; if (error.code === 'ENOENT') { return undefined; } if (opts.ignoreErrors) { (0, logging_1.traceError)(`lstat() failed for "${filename}" (${err})`); return exports.FileType.Unknown; } throw err; } return convertFileType(stat); } exports.getFileType = getFileType; function normalizeFileTypes(filetypes) { if (filetypes === undefined) { return undefined; } if (Array.isArray(filetypes)) { if (filetypes.length === 0) { return undefined; } return filetypes; } return [filetypes]; } async function resolveFile(file, opts = {}) { let filename; if (typeof file !== 'string') { if (!opts.ensure) { if (opts.onMissing === undefined) { return file; } if ((await getFileType(file.filename)) !== undefined) { return file; } } filename = file.filename; } else { filename = file; } const filetype = (await getFileType(filename)) || opts.onMissing; if (filetype === undefined) { return undefined; } return { filename, filetype }; } function getFileFilter(opts = { ignoreMissing: true, }) { const ignoreFileType = normalizeFileTypes(opts.ignoreFileType); if (!opts.ignoreMissing && !ignoreFileType) { return undefined; } async function filterFile(file) { let entry = await resolveFile(file, { ensure: opts.ensureEntry }); if (!entry) { if (opts.ignoreMissing) { return false; } const filename = typeof file === 'string' ? file : file.filename; entry = { filename, filetype: exports.FileType.Unknown }; } if (ignoreFileType) { if (ignoreFileType.includes(entry.filetype)) { return false; } } return true; } return filterFile; } exports.getFileFilter = getFileFilter; /***/ }), /***/ "./src/client/common/utils/localize.ts": /*!*********************************************!*\ !*** ./src/client/common/utils/localize.ts ***! \*********************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ToolsExtensions = exports.CreateEnv = exports.SwitchToDefaultLS = exports.Python27Support = exports.OutdatedDebugger = exports.Testing = exports.DebugConfigStrings = exports.ExtensionSurveyBanner = exports.Installer = exports.Linters = exports.OutputChannelNames = exports.InterpreterQuickPickList = exports.Interpreters = exports.LanguageService = exports.TensorBoard = exports.Pylance = exports.AttachProcess = exports.CommonSurvey = exports.Common = exports.Diagnostics = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); var Diagnostics; (function (Diagnostics) { Diagnostics.warnSourceMaps = vscode_1.l10n.t('Source map support is enabled in the Python Extension, this will adversely impact performance of the extension.'); Diagnostics.disableSourceMaps = vscode_1.l10n.t('Disable Source Map Support'); Diagnostics.warnBeforeEnablingSourceMaps = vscode_1.l10n.t('Enabling source map support in the Python Extension will adversely impact performance of the extension.'); Diagnostics.enableSourceMapsAndReloadVSC = vscode_1.l10n.t('Enable and reload Window.'); Diagnostics.lsNotSupported = vscode_1.l10n.t('Your operating system does not meet the minimum requirements of the Python Language Server. Reverting to the alternative autocompletion provider, Jedi.'); Diagnostics.invalidPythonPathInDebuggerSettings = vscode_1.l10n.t('You need to select a Python interpreter before you start debugging.\n\nTip: click on "Select Interpreter" in the status bar.'); Diagnostics.invalidPythonPathInDebuggerLaunch = vscode_1.l10n.t('The Python path in your debug configuration is invalid.'); Diagnostics.invalidDebuggerTypeDiagnostic = vscode_1.l10n.t('Your launch.json file needs to be updated to change the "pythonExperimental" debug configurations to use the "python" debugger type, otherwise Python debugging may not work. Would you like to automatically update your launch.json file now?'); Diagnostics.consoleTypeDiagnostic = vscode_1.l10n.t('Your launch.json file needs to be updated to change the console type string from "none" to "internalConsole", otherwise Python debugging may not work. Would you like to automatically update your launch.json file now?'); Diagnostics.justMyCodeDiagnostic = vscode_1.l10n.t('Configuration "debugStdLib" in launch.json is no longer supported. It\'s recommended to replace it with "justMyCode", which is the exact opposite of using "debugStdLib". Would you like to automatically update your launch.json file to do that?'); Diagnostics.yesUpdateLaunch = vscode_1.l10n.t('Yes, update launch.json'); Diagnostics.invalidTestSettings = vscode_1.l10n.t('Your settings needs to be updated to change the setting "python.unitTest." to "python.testing.", otherwise testing Python code using the extension may not work. Would you like to automatically update your settings now?'); Diagnostics.updateSettings = vscode_1.l10n.t('Yes, update settings'); Diagnostics.checkIsort5UpgradeGuide = vscode_1.l10n.t('We found outdated configuration for sorting imports in this workspace. Check the [isort upgrade guide](https://aka.ms/AA9j5x4) to update your settings.'); Diagnostics.pylanceDefaultMessage = vscode_1.l10n.t("The Python extension now includes Pylance to improve completions, code navigation, overall performance and much more! You can learn more about the update and learn how to change your language server [here](https://aka.ms/new-python-bundle).\n\nRead Pylance's license [here](https://marketplace.visualstudio.com/items/ms-python.vscode-pylance/license)."); })(Diagnostics = exports.Diagnostics || (exports.Diagnostics = {})); var Common; (function (Common) { Common.allow = vscode_1.l10n.t('Allow'); Common.seeInstructions = vscode_1.l10n.t('See Instructions'); Common.close = vscode_1.l10n.t('Close'); Common.bannerLabelYes = vscode_1.l10n.t('Yes'); Common.bannerLabelNo = vscode_1.l10n.t('No'); Common.canceled = vscode_1.l10n.t('Canceled'); Common.cancel = vscode_1.l10n.t('Cancel'); Common.ok = vscode_1.l10n.t('Ok'); Common.error = vscode_1.l10n.t('Error'); Common.gotIt = vscode_1.l10n.t('Got it!'); Common.install = vscode_1.l10n.t('Install'); Common.loadingExtension = vscode_1.l10n.t('Python extension loading...'); Common.openOutputPanel = vscode_1.l10n.t('Show output'); Common.noIWillDoItLater = vscode_1.l10n.t('No, I will do it later'); Common.notNow = vscode_1.l10n.t('Not now'); Common.doNotShowAgain = vscode_1.l10n.t("Don't show again"); Common.reload = vscode_1.l10n.t('Reload'); Common.moreInfo = vscode_1.l10n.t('More Info'); Common.learnMore = vscode_1.l10n.t('Learn more'); Common.and = vscode_1.l10n.t('and'); Common.reportThisIssue = vscode_1.l10n.t('Report this issue'); Common.recommended = vscode_1.l10n.t('Recommended'); Common.clearAll = vscode_1.l10n.t('Clear all'); Common.alwaysIgnore = vscode_1.l10n.t('Always Ignore'); Common.ignore = vscode_1.l10n.t('Ignore'); Common.selectPythonInterpreter = vscode_1.l10n.t('Select Python Interpreter'); Common.openLaunch = vscode_1.l10n.t('Open launch.json'); Common.useCommandPrompt = vscode_1.l10n.t('Use Command Prompt'); Common.download = vscode_1.l10n.t('Download'); Common.showLogs = vscode_1.l10n.t('Show logs'); Common.openFolder = vscode_1.l10n.t('Open Folder...'); })(Common = exports.Common || (exports.Common = {})); var CommonSurvey; (function (CommonSurvey) { CommonSurvey.remindMeLaterLabel = vscode_1.l10n.t('Remind me later'); CommonSurvey.yesLabel = vscode_1.l10n.t('Yes, take survey now'); CommonSurvey.noLabel = vscode_1.l10n.t('No, thanks'); })(CommonSurvey = exports.CommonSurvey || (exports.CommonSurvey = {})); var AttachProcess; (function (AttachProcess) { AttachProcess.attachTitle = vscode_1.l10n.t('Attach to process'); AttachProcess.selectProcessPlaceholder = vscode_1.l10n.t('Select the process to attach to'); AttachProcess.noProcessSelected = vscode_1.l10n.t('No process selected'); AttachProcess.refreshList = vscode_1.l10n.t('Refresh process list'); })(AttachProcess = exports.AttachProcess || (exports.AttachProcess = {})); var Pylance; (function (Pylance) { Pylance.remindMeLater = vscode_1.l10n.t('Remind me later'); Pylance.pylanceNotInstalledMessage = vscode_1.l10n.t('Pylance extension is not installed.'); Pylance.pylanceInstalledReloadPromptMessage = vscode_1.l10n.t('Pylance extension is now installed. Reload window to activate?'); Pylance.pylanceRevertToJediPrompt = vscode_1.l10n.t('The Pylance extension is not installed but the python.languageServer value is set to "Pylance". Would you like to install the Pylance extension to use Pylance, or revert back to Jedi?'); Pylance.pylanceInstallPylance = vscode_1.l10n.t('Install Pylance'); Pylance.pylanceRevertToJedi = vscode_1.l10n.t('Revert to Jedi'); })(Pylance = exports.Pylance || (exports.Pylance = {})); var TensorBoard; (function (TensorBoard) { TensorBoard.enterRemoteUrl = vscode_1.l10n.t('Enter remote URL'); TensorBoard.enterRemoteUrlDetail = vscode_1.l10n.t('Enter a URL pointing to a remote directory containing your TensorBoard log files'); TensorBoard.useCurrentWorkingDirectoryDetail = vscode_1.l10n.t('TensorBoard will search for tfevent files in all subdirectories of the current working directory'); TensorBoard.useCurrentWorkingDirectory = vscode_1.l10n.t('Use current working directory'); TensorBoard.logDirectoryPrompt = vscode_1.l10n.t('Select a log directory to start TensorBoard with'); TensorBoard.progressMessage = vscode_1.l10n.t('Starting TensorBoard session...'); TensorBoard.nativeTensorBoardPrompt = vscode_1.l10n.t('VS Code now has integrated TensorBoard support. Would you like to launch TensorBoard? (Tip: Launch TensorBoard anytime by opening the command palette and searching for "Launch TensorBoard".)'); TensorBoard.selectAFolder = vscode_1.l10n.t('Select a folder'); TensorBoard.selectAFolderDetail = vscode_1.l10n.t('Select a log directory containing tfevent files'); TensorBoard.selectAnotherFolder = vscode_1.l10n.t('Select another folder'); TensorBoard.selectAnotherFolderDetail = vscode_1.l10n.t('Use the file explorer to select another folder'); TensorBoard.installPrompt = vscode_1.l10n.t('The package TensorBoard is required to launch a TensorBoard session. Would you like to install it?'); TensorBoard.installTensorBoardAndProfilerPluginPrompt = vscode_1.l10n.t('TensorBoard >= 2.4.1 and the PyTorch Profiler TensorBoard plugin >= 0.2.0 are required. Would you like to install these packages?'); TensorBoard.installProfilerPluginPrompt = vscode_1.l10n.t('We recommend installing version >= 0.2.0 of the PyTorch Profiler TensorBoard plugin. Would you like to install the package?'); TensorBoard.upgradePrompt = vscode_1.l10n.t('Integrated TensorBoard support is only available for TensorBoard >= 2.4.1. Would you like to upgrade your copy of TensorBoard?'); TensorBoard.launchNativeTensorBoardSessionCodeLens = vscode_1.l10n.t('▶ Launch TensorBoard Session'); TensorBoard.launchNativeTensorBoardSessionCodeAction = vscode_1.l10n.t('Launch TensorBoard session'); TensorBoard.missingSourceFile = vscode_1.l10n.t('The Python extension could not locate the requested source file on disk. Please manually specify the file.'); TensorBoard.selectMissingSourceFile = vscode_1.l10n.t('Choose File'); TensorBoard.selectMissingSourceFileDescription = vscode_1.l10n.t("The source file's contents may not match the original contents in the trace."); })(TensorBoard = exports.TensorBoard || (exports.TensorBoard = {})); var LanguageService; (function (LanguageService) { LanguageService.virtualWorkspaceStatusItem = { detail: vscode_1.l10n.t('Limited IntelliSense supported by Jedi and Pylance'), }; LanguageService.statusItem = { name: vscode_1.l10n.t('Python IntelliSense Status'), text: vscode_1.l10n.t('Partial Mode'), detail: vscode_1.l10n.t('Limited IntelliSense provided by Pylance'), }; LanguageService.startingPylance = vscode_1.l10n.t('Starting Pylance language server.'); LanguageService.startingNone = vscode_1.l10n.t('Editor support is inactive since language server is set to None.'); LanguageService.untrustedWorkspaceMessage = vscode_1.l10n.t('Only Pylance is supported in untrusted workspaces, setting language server to None.'); LanguageService.reloadAfterLanguageServerChange = vscode_1.l10n.t('Reload the window after switching between language servers.'); LanguageService.lsFailedToStart = vscode_1.l10n.t('We encountered an issue starting the language server. Reverting to Jedi language engine. Check the Python output panel for details.'); LanguageService.lsFailedToDownload = vscode_1.l10n.t('We encountered an issue downloading the language server. Reverting to Jedi language engine. Check the Python output panel for details.'); LanguageService.lsFailedToExtract = vscode_1.l10n.t('We encountered an issue extracting the language server. Reverting to Jedi language engine. Check the Python output panel for details.'); LanguageService.downloadFailedOutputMessage = vscode_1.l10n.t('Language server download failed.'); LanguageService.extractionFailedOutputMessage = vscode_1.l10n.t('Language server extraction failed.'); LanguageService.extractionCompletedOutputMessage = vscode_1.l10n.t('Language server download complete.'); LanguageService.extractionDoneOutputMessage = vscode_1.l10n.t('done.'); LanguageService.reloadVSCodeIfSeachPathHasChanged = vscode_1.l10n.t('Search paths have changed for this Python interpreter. Reload the extension to ensure that the IntelliSense works correctly.'); })(LanguageService = exports.LanguageService || (exports.LanguageService = {})); var Interpreters; (function (Interpreters) { Interpreters.requireJupyter = vscode_1.l10n.t('Running in Interactive window requires Jupyter Extension. Would you like to install it? [Learn more](https://aka.ms/pythonJupyterSupport).'); Interpreters.installingPython = vscode_1.l10n.t('Installing Python into Environment...'); Interpreters.discovering = vscode_1.l10n.t('Discovering Python Interpreters'); Interpreters.refreshing = vscode_1.l10n.t('Refreshing Python Interpreters'); Interpreters.condaInheritEnvMessage = vscode_1.l10n.t('We noticed you\'re using a conda environment. If you are experiencing issues with this environment in the integrated terminal, we recommend that you let the Python extension change "terminal.integrated.inheritEnv" to false in your user settings. [Learn more](https://aka.ms/AA66i8f).'); Interpreters.activatingTerminals = vscode_1.l10n.t('Reactivating terminals...'); Interpreters.activateTerminalDescription = vscode_1.l10n.t('Activated environment for'); Interpreters.terminalEnvVarCollectionPrompt = vscode_1.l10n.t('The Python extension automatically activates all terminals using the selected environment, even when the name of the environment{0} is not present in the terminal prompt. [Learn more](https://aka.ms/vscodePythonTerminalActivation).'); Interpreters.activatedCondaEnvLaunch = vscode_1.l10n.t('We noticed VS Code was launched from an activated conda environment, would you like to select it?'); Interpreters.environmentPromptMessage = vscode_1.l10n.t('We noticed a new environment has been created. Do you want to select it for the workspace folder?'); Interpreters.entireWorkspace = vscode_1.l10n.t('Select at workspace level'); Interpreters.clearAtWorkspace = vscode_1.l10n.t('Clear at workspace level'); Interpreters.selectInterpreterTip = vscode_1.l10n.t('Tip: you can change the Python interpreter used by the Python extension by clicking on the Python version in the status bar'); Interpreters.installPythonTerminalMessageLinux = vscode_1.l10n.t('💡 Try installing the Python package using your package manager. Alternatively you can also download it from https://www.python.org/downloads'); Interpreters.installPythonTerminalMacMessage = vscode_1.l10n.t('💡 Brew does not seem to be available. You can download Python from https://www.python.org/downloads. Alternatively, you can install the Python package using some other available package manager.'); Interpreters.changePythonInterpreter = vscode_1.l10n.t('Change Python Interpreter'); Interpreters.selectedPythonInterpreter = vscode_1.l10n.t('Selected Python Interpreter'); })(Interpreters = exports.Interpreters || (exports.Interpreters = {})); var InterpreterQuickPickList; (function (InterpreterQuickPickList) { InterpreterQuickPickList.condaEnvWithoutPythonTooltip = vscode_1.l10n.t('Python is not available in this environment, it will automatically be installed upon selecting it'); InterpreterQuickPickList.noPythonInstalled = vscode_1.l10n.t('Python is not installed'); InterpreterQuickPickList.clickForInstructions = vscode_1.l10n.t('Click for instructions...'); InterpreterQuickPickList.globalGroupName = vscode_1.l10n.t('Global'); InterpreterQuickPickList.workspaceGroupName = vscode_1.l10n.t('Workspace'); InterpreterQuickPickList.enterPath = { label: vscode_1.l10n.t('Enter interpreter path...'), placeholder: vscode_1.l10n.t('Enter path to a Python interpreter.'), }; InterpreterQuickPickList.defaultInterpreterPath = { label: vscode_1.l10n.t('Use Python from `python.defaultInterpreterPath` setting'), }; InterpreterQuickPickList.browsePath = { label: vscode_1.l10n.t('Find...'), detail: vscode_1.l10n.t('Browse your file system to find a Python interpreter.'), openButtonLabel: vscode_1.l10n.t('Select Interpreter'), title: vscode_1.l10n.t('Select Python interpreter'), }; InterpreterQuickPickList.refreshInterpreterList = vscode_1.l10n.t('Refresh Interpreter list'); InterpreterQuickPickList.refreshingInterpreterList = vscode_1.l10n.t('Refreshing Interpreter list...'); })(InterpreterQuickPickList = exports.InterpreterQuickPickList || (exports.InterpreterQuickPickList = {})); var OutputChannelNames; (function (OutputChannelNames) { OutputChannelNames.languageServer = vscode_1.l10n.t('Python Language Server'); OutputChannelNames.python = vscode_1.l10n.t('Python'); OutputChannelNames.pythonTest = vscode_1.l10n.t('Python Test Log'); })(OutputChannelNames = exports.OutputChannelNames || (exports.OutputChannelNames = {})); var Linters; (function (Linters) { Linters.selectLinter = vscode_1.l10n.t('Select Linter'); })(Linters = exports.Linters || (exports.Linters = {})); var Installer; (function (Installer) { Installer.noCondaOrPipInstaller = vscode_1.l10n.t('There is no Conda or Pip installer available in the selected environment.'); Installer.noPipInstaller = vscode_1.l10n.t('There is no Pip installer available in the selected environment.'); Installer.searchForHelp = vscode_1.l10n.t('Search for help'); })(Installer = exports.Installer || (exports.Installer = {})); var ExtensionSurveyBanner; (function (ExtensionSurveyBanner) { ExtensionSurveyBanner.bannerMessage = vscode_1.l10n.t('Can you take 2 minutes to tell us how the Python extension is working for you?'); ExtensionSurveyBanner.bannerLabelYes = vscode_1.l10n.t('Yes, take survey now'); ExtensionSurveyBanner.bannerLabelNo = vscode_1.l10n.t('No, thanks'); ExtensionSurveyBanner.maybeLater = vscode_1.l10n.t('Maybe later'); })(ExtensionSurveyBanner = exports.ExtensionSurveyBanner || (exports.ExtensionSurveyBanner = {})); var DebugConfigStrings; (function (DebugConfigStrings) { DebugConfigStrings.selectConfiguration = { title: vscode_1.l10n.t('Select a debug configuration'), placeholder: vscode_1.l10n.t('Debug Configuration'), }; DebugConfigStrings.launchJsonCompletions = { label: vscode_1.l10n.t('Python'), description: vscode_1.l10n.t('Select a Python debug configuration'), }; let file; (function (file) { file.snippet = { name: vscode_1.l10n.t('Python: Current File'), }; file.selectConfiguration = { label: vscode_1.l10n.t('Python File'), description: vscode_1.l10n.t('Debug the currently active Python file'), }; })(file = DebugConfigStrings.file || (DebugConfigStrings.file = {})); let module; (function (module) { module.snippet = { name: vscode_1.l10n.t('Python: Module'), default: vscode_1.l10n.t('enter-your-module-name'), }; module.selectConfiguration = { label: vscode_1.l10n.t('Module'), description: vscode_1.l10n.t("Debug a Python module by invoking it with '-m'"), }; module.enterModule = { title: vscode_1.l10n.t('Debug Module'), prompt: vscode_1.l10n.t('Enter a Python module/package name'), default: vscode_1.l10n.t('enter-your-module-name'), invalid: vscode_1.l10n.t('Enter a valid module name'), }; })(module = DebugConfigStrings.module || (DebugConfigStrings.module = {})); let attach; (function (attach) { attach.snippet = { name: vscode_1.l10n.t('Python: Remote Attach'), }; attach.selectConfiguration = { label: vscode_1.l10n.t('Remote Attach'), description: vscode_1.l10n.t('Attach to a remote debug server'), }; attach.enterRemoteHost = { title: vscode_1.l10n.t('Remote Debugging'), prompt: vscode_1.l10n.t('Enter a valid host name or IP address'), invalid: vscode_1.l10n.t('Enter a valid host name or IP address'), }; attach.enterRemotePort = { title: vscode_1.l10n.t('Remote Debugging'), prompt: vscode_1.l10n.t('Enter the port number that the debug server is listening on'), invalid: vscode_1.l10n.t('Enter a valid port number'), }; })(attach = DebugConfigStrings.attach || (DebugConfigStrings.attach = {})); let attachPid; (function (attachPid) { attachPid.snippet = { name: vscode_1.l10n.t('Python: Attach using Process Id'), }; attachPid.selectConfiguration = { label: vscode_1.l10n.t('Attach using Process ID'), description: vscode_1.l10n.t('Attach to a local process'), }; })(attachPid = DebugConfigStrings.attachPid || (DebugConfigStrings.attachPid = {})); let django; (function (django) { django.snippet = { name: vscode_1.l10n.t('Python: Django'), }; django.selectConfiguration = { label: vscode_1.l10n.t('Django'), description: vscode_1.l10n.t('Launch and debug a Django web application'), }; django.enterManagePyPath = { title: vscode_1.l10n.t('Debug Django'), prompt: vscode_1.l10n.t("Enter the path to manage.py ('${workspaceFolder}' points to the root of the current workspace folder)"), invalid: vscode_1.l10n.t('Enter a valid Python file path'), }; })(django = DebugConfigStrings.django || (DebugConfigStrings.django = {})); let fastapi; (function (fastapi) { fastapi.snippet = { name: vscode_1.l10n.t('Python: FastAPI'), }; fastapi.selectConfiguration = { label: vscode_1.l10n.t('FastAPI'), description: vscode_1.l10n.t('Launch and debug a FastAPI web application'), }; fastapi.enterAppPathOrNamePath = { title: vscode_1.l10n.t('Debug FastAPI'), prompt: vscode_1.l10n.t("Enter the path to the application, e.g. 'main.py' or 'main'"), invalid: vscode_1.l10n.t('Enter a valid name'), }; })(fastapi = DebugConfigStrings.fastapi || (DebugConfigStrings.fastapi = {})); let flask; (function (flask) { flask.snippet = { name: vscode_1.l10n.t('Python: Flask'), }; flask.selectConfiguration = { label: vscode_1.l10n.t('Flask'), description: vscode_1.l10n.t('Launch and debug a Flask web application'), }; flask.enterAppPathOrNamePath = { title: vscode_1.l10n.t('Debug Flask'), prompt: vscode_1.l10n.t('Python: Flask'), invalid: vscode_1.l10n.t('Enter a valid name'), }; })(flask = DebugConfigStrings.flask || (DebugConfigStrings.flask = {})); let pyramid; (function (pyramid) { pyramid.snippet = { name: vscode_1.l10n.t('Python: Pyramid Application'), }; pyramid.selectConfiguration = { label: vscode_1.l10n.t('Pyramid'), description: vscode_1.l10n.t('Launch and debug a Pyramid web application'), }; pyramid.enterDevelopmentIniPath = { title: vscode_1.l10n.t('Debug Pyramid'), invalid: vscode_1.l10n.t('Enter a valid file path'), }; })(pyramid = DebugConfigStrings.pyramid || (DebugConfigStrings.pyramid = {})); })(DebugConfigStrings = exports.DebugConfigStrings || (exports.DebugConfigStrings = {})); var Testing; (function (Testing) { Testing.configureTests = vscode_1.l10n.t('Configure Test Framework'); Testing.testNotConfigured = vscode_1.l10n.t('No test framework configured.'); Testing.cancelUnittestDiscovery = vscode_1.l10n.t('Canceled unittest test discovery'); Testing.errorUnittestDiscovery = vscode_1.l10n.t('Unittest test discovery error'); Testing.cancelPytestDiscovery = vscode_1.l10n.t('Canceled pytest test discovery'); Testing.errorPytestDiscovery = vscode_1.l10n.t('pytest test discovery error'); Testing.seePythonOutput = vscode_1.l10n.t('(see Output > Python)'); Testing.cancelUnittestExecution = vscode_1.l10n.t('Canceled unittest test execution'); Testing.errorUnittestExecution = vscode_1.l10n.t('Unittest test execution error'); Testing.cancelPytestExecution = vscode_1.l10n.t('Canceled pytest test execution'); Testing.errorPytestExecution = vscode_1.l10n.t('Pytest test execution error'); })(Testing = exports.Testing || (exports.Testing = {})); var OutdatedDebugger; (function (OutdatedDebugger) { OutdatedDebugger.outdatedDebuggerMessage = vscode_1.l10n.t('We noticed you are attaching to ptvsd (Python debugger), which was deprecated on May 1st, 2020. Use [debugpy](https://aka.ms/migrateToDebugpy) instead.'); })(OutdatedDebugger = exports.OutdatedDebugger || (exports.OutdatedDebugger = {})); var Python27Support; (function (Python27Support) { Python27Support.jediMessage = vscode_1.l10n.t('IntelliSense with Jedi for Python 2.7 is no longer supported. [Learn more](https://aka.ms/python-27-support).'); })(Python27Support = exports.Python27Support || (exports.Python27Support = {})); var SwitchToDefaultLS; (function (SwitchToDefaultLS) { SwitchToDefaultLS.bannerMessage = vscode_1.l10n.t("The Microsoft Python Language Server has reached end of life. Your language server has been set to the default for Python in VS Code, Pylance.\n\nIf you'd like to change your language server, you can learn about how to do so [here](https://devblogs.microsoft.com/python/python-in-visual-studio-code-may-2021-release/#configuring-your-language-server).\n\nRead Pylance's license [here](https://marketplace.visualstudio.com/items/ms-python.vscode-pylance/license)."); })(SwitchToDefaultLS = exports.SwitchToDefaultLS || (exports.SwitchToDefaultLS = {})); var CreateEnv; (function (CreateEnv) { CreateEnv.informEnvCreation = vscode_1.l10n.t('The following environment is selected:'); CreateEnv.statusTitle = vscode_1.l10n.t('Creating environment'); CreateEnv.statusStarting = vscode_1.l10n.t('Starting...'); CreateEnv.hasVirtualEnv = vscode_1.l10n.t('Workspace folder contains a virtual environment'); CreateEnv.noWorkspace = vscode_1.l10n.t('A workspace is required when creating an environment using venv.'); CreateEnv.pickWorkspacePlaceholder = vscode_1.l10n.t('Select a workspace to create environment'); CreateEnv.providersQuickPickPlaceholder = vscode_1.l10n.t('Select an environment type'); let Venv; (function (Venv) { Venv.creating = vscode_1.l10n.t('Creating venv...'); Venv.creatingMicrovenv = vscode_1.l10n.t('Creating microvenv...'); Venv.created = vscode_1.l10n.t('Environment created...'); Venv.existing = vscode_1.l10n.t('Using existing environment...'); Venv.downloadingPip = vscode_1.l10n.t('Downloading pip...'); Venv.installingPip = vscode_1.l10n.t('Installing pip...'); Venv.upgradingPip = vscode_1.l10n.t('Upgrading pip...'); Venv.installingPackages = vscode_1.l10n.t('Installing packages...'); Venv.errorCreatingEnvironment = vscode_1.l10n.t('Error while creating virtual environment.'); Venv.selectPythonPlaceHolder = vscode_1.l10n.t('Select a Python installation to create the virtual environment'); Venv.providerDescription = vscode_1.l10n.t('Creates a `.venv` virtual environment in the current workspace'); Venv.error = vscode_1.l10n.t('Creating virtual environment failed with error.'); Venv.tomlExtrasQuickPickTitle = vscode_1.l10n.t('Select optional dependencies to install from pyproject.toml'); Venv.requirementsQuickPickTitle = vscode_1.l10n.t('Select dependencies to install'); Venv.recreate = vscode_1.l10n.t('Recreate'); Venv.recreateDescription = vscode_1.l10n.t('Delete existing ".venv" environment and create a new one'); Venv.useExisting = vscode_1.l10n.t('Use Existing'); Venv.useExistingDescription = vscode_1.l10n.t('Use existing ".venv" environment with no changes to it'); Venv.existingVenvQuickPickPlaceholder = vscode_1.l10n.t('Choose an option to handle the existing ".venv" environment'); Venv.deletingEnvironmentProgress = vscode_1.l10n.t('Deleting existing ".venv" environment...'); Venv.errorDeletingEnvironment = vscode_1.l10n.t('Error while deleting existing ".venv" environment.'); })(Venv = CreateEnv.Venv || (CreateEnv.Venv = {})); let Conda; (function (Conda) { Conda.condaMissing = vscode_1.l10n.t('Install `conda` to create conda environments.'); Conda.created = vscode_1.l10n.t('Environment created...'); Conda.installingPackages = vscode_1.l10n.t('Installing packages...'); Conda.errorCreatingEnvironment = vscode_1.l10n.t('Error while creating conda environment.'); Conda.selectPythonQuickPickPlaceholder = vscode_1.l10n.t('Select the version of Python to install in the environment'); Conda.creating = vscode_1.l10n.t('Creating conda environment...'); Conda.providerDescription = vscode_1.l10n.t('Creates a `.conda` Conda environment in the current workspace'); })(Conda = CreateEnv.Conda || (CreateEnv.Conda = {})); })(CreateEnv = exports.CreateEnv || (exports.CreateEnv = {})); var ToolsExtensions; (function (ToolsExtensions) { ToolsExtensions.flake8PromptMessage = vscode_1.l10n.t('Use the Flake8 extension to enable easier configuration and new features such as quick fixes.'); ToolsExtensions.pylintPromptMessage = vscode_1.l10n.t('Use the Pylint extension to enable easier configuration and new features such as quick fixes.'); ToolsExtensions.isortPromptMessage = vscode_1.l10n.t('To use sort imports, install the isort extension. It provides easier configuration and new features such as code actions.'); ToolsExtensions.installPylintExtension = vscode_1.l10n.t('Install Pylint extension'); ToolsExtensions.installFlake8Extension = vscode_1.l10n.t('Install Flake8 extension'); ToolsExtensions.installISortExtension = vscode_1.l10n.t('Install isort extension'); ToolsExtensions.selectBlackFormatterPrompt = vscode_1.l10n.t('You have the Black formatter extension installed, would you like to use that as the default formatter?'); ToolsExtensions.selectAutopep8FormatterPrompt = vscode_1.l10n.t('You have the Autopep8 formatter extension installed, would you like to use that as the default formatter?'); ToolsExtensions.selectMultipleFormattersPrompt = vscode_1.l10n.t('You have multiple formatters installed, would you like to select one as the default formatter?'); ToolsExtensions.installBlackFormatterPrompt = vscode_1.l10n.t('You triggered formatting with Black, would you like to install one of our new formatter extensions? This will also set it as the default formatter for Python.'); ToolsExtensions.installAutopep8FormatterPrompt = vscode_1.l10n.t('You triggered formatting with Autopep8, would you like to install one of our new formatter extension? This will also set it as the default formatter for Python.'); })(ToolsExtensions = exports.ToolsExtensions || (exports.ToolsExtensions = {})); /***/ }), /***/ "./src/client/common/utils/misc.ts": /*!*****************************************!*\ !*** ./src/client/common/utils/misc.ts ***! \*****************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isNotebookCell = exports.getURIFilter = exports.noop = void 0; const constants_1 = __webpack_require__(/*! ../constants */ "./src/client/common/constants.ts"); const fs_paths_1 = __webpack_require__(/*! ../platform/fs-paths */ "./src/client/common/platform/fs-paths.ts"); function noop() { } exports.noop = noop; function isUri(resource) { if (!resource) { return false; } const uri = resource; return typeof uri.path === 'string' && typeof uri.scheme === 'string'; } function getURIFilter(uri, opts = { checkParent: true }) { let uriPath = uri.path; while (uriPath.endsWith('/')) { uriPath = uriPath.slice(0, -1); } const uriRoot = `${uriPath}/`; function filter(candidate) { let candidatePath = candidate.path; while (candidatePath.endsWith('/')) { candidatePath = candidatePath.slice(0, -1); } if (opts.checkParent && (0, fs_paths_1.isParentPath)(candidatePath, uriRoot)) { return true; } if (opts.checkChild) { const candidateRoot = `${candidatePath}/`; if ((0, fs_paths_1.isParentPath)(uriPath, candidateRoot)) { return true; } } return false; } return filter; } exports.getURIFilter = getURIFilter; function isNotebookCell(documentOrUri) { const uri = isUri(documentOrUri) ? documentOrUri : documentOrUri.uri; return uri.scheme.includes(constants_1.NotebookCellScheme) || uri.scheme.includes(constants_1.InteractiveInputScheme); } exports.isNotebookCell = isNotebookCell; /***/ }), /***/ "./src/client/common/utils/multiStepInput.ts": /*!***************************************************!*\ !*** ./src/client/common/utils/multiStepInput.ts ***! \***************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MultiStepInputFactory = exports.IMultiStepInputFactory = exports.MultiStepInput = exports.InputFlowAction = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const types_1 = __webpack_require__(/*! ../application/types */ "./src/client/common/application/types.ts"); const async_1 = __webpack_require__(/*! ./async */ "./src/client/common/utils/async.ts"); class InputFlowAction { constructor() { } } exports.InputFlowAction = InputFlowAction; InputFlowAction.back = new InputFlowAction(); InputFlowAction.cancel = new InputFlowAction(); InputFlowAction.resume = new InputFlowAction(); class MultiStepInput { constructor(shell) { this.shell = shell; this.steps = []; } run(start, state) { return this.stepThrough(start, state); } async showQuickPick({ title, step, totalSteps, items, activeItem, placeholder, customButtonSetups, matchOnDescription, matchOnDetail, acceptFilterBoxTextAsSelection, onChangeItem, keepScrollPosition, sortByLabel, initialize, }) { const disposables = []; const input = this.shell.createQuickPick(); input.title = title; input.step = step; try { input.sortByLabel = sortByLabel || false; } catch (_a) { } input.totalSteps = totalSteps; input.placeholder = placeholder; input.ignoreFocusOut = true; input.items = items; input.matchOnDescription = matchOnDescription || false; input.matchOnDetail = matchOnDetail || false; input.buttons = this.steps.length > 1 ? [vscode_1.QuickInputButtons.Back] : []; if (customButtonSetups) { for (const customButtonSetup of customButtonSetups) { input.buttons = [...input.buttons, customButtonSetup.button]; } } if (this.current) { this.current.dispose(); } this.current = input; if (onChangeItem) { disposables.push(onChangeItem.event((e) => onChangeItem.callback(e, input))); } if (initialize) { initialize(input); } if (activeItem) { input.activeItems = [await activeItem]; } else { input.activeItems = []; } this.current.show(); input.keepScrollPosition = keepScrollPosition; const deferred = (0, async_1.createDeferred)(); disposables.push(input.onDidTriggerButton(async (item) => { if (item === vscode_1.QuickInputButtons.Back) { deferred.reject(InputFlowAction.back); input.hide(); } if (customButtonSetups) { for (const customButtonSetup of customButtonSetups) { if (JSON.stringify(item) === JSON.stringify(customButtonSetup === null || customButtonSetup === void 0 ? void 0 : customButtonSetup.button)) { await (customButtonSetup === null || customButtonSetup === void 0 ? void 0 : customButtonSetup.callback(input)); } } } }), input.onDidChangeSelection((selectedItems) => deferred.resolve(selectedItems[0])), input.onDidHide(() => { if (!deferred.completed) { deferred.resolve(undefined); } })); if (acceptFilterBoxTextAsSelection) { disposables.push(input.onDidAccept(() => { deferred.resolve(input.value); })); } try { return await deferred.promise; } finally { disposables.forEach((d) => d.dispose()); } } async showInputBox({ title, step, totalSteps, value, prompt, validate, password, buttons, }) { const disposables = []; try { return await new Promise((resolve, reject) => { const input = this.shell.createInputBox(); input.title = title; input.step = step; input.totalSteps = totalSteps; input.password = !!password; input.value = value || ''; input.prompt = prompt; input.ignoreFocusOut = true; input.buttons = [...(this.steps.length > 1 ? [vscode_1.QuickInputButtons.Back] : []), ...(buttons || [])]; let validating = validate(''); disposables.push(input.onDidTriggerButton((item) => { if (item === vscode_1.QuickInputButtons.Back) { reject(InputFlowAction.back); } else { resolve(item); } }), input.onDidAccept(async () => { const inputValue = input.value; input.enabled = false; input.busy = true; if (!(await validate(inputValue))) { resolve(inputValue); } input.enabled = true; input.busy = false; }), input.onDidChangeValue(async (text) => { const current = validate(text); validating = current; const validationMessage = await current; if (current === validating) { input.validationMessage = validationMessage; } }), input.onDidHide(() => { resolve(undefined); })); if (this.current) { this.current.dispose(); } this.current = input; this.current.show(); }); } finally { disposables.forEach((d) => d.dispose()); } } async stepThrough(start, state) { let step = start; while (step) { this.steps.push(step); if (this.current) { this.current.enabled = false; this.current.busy = true; } try { step = await step(this, state); } catch (err) { if (err === InputFlowAction.back) { this.steps.pop(); step = this.steps.pop(); if (step === undefined) { throw err; } } else if (err === InputFlowAction.resume) { step = this.steps.pop(); } else if (err === InputFlowAction.cancel) { step = undefined; } else { throw err; } } } if (this.current) { this.current.dispose(); } } } exports.MultiStepInput = MultiStepInput; exports.IMultiStepInputFactory = Symbol('IMultiStepInputFactory'); let MultiStepInputFactory = class MultiStepInputFactory { constructor(shell) { this.shell = shell; } create() { return new MultiStepInput(this.shell); } }; MultiStepInputFactory = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_1.IApplicationShell)) ], MultiStepInputFactory); exports.MultiStepInputFactory = MultiStepInputFactory; /***/ }), /***/ "./src/client/common/utils/platform.ts": /*!*********************************************!*\ !*** ./src/client/common/utils/platform.ts ***! \*********************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getUserHomeDir = exports.getEnvironmentVariable = exports.getArchitecture = exports.getOSType = exports.OSType = exports.Architecture = void 0; var Architecture; (function (Architecture) { Architecture[Architecture["Unknown"] = 1] = "Unknown"; Architecture[Architecture["x86"] = 2] = "x86"; Architecture[Architecture["x64"] = 3] = "x64"; })(Architecture = exports.Architecture || (exports.Architecture = {})); var OSType; (function (OSType) { OSType["Unknown"] = "Unknown"; OSType["Windows"] = "Windows"; OSType["OSX"] = "OSX"; OSType["Linux"] = "Linux"; })(OSType = exports.OSType || (exports.OSType = {})); function getOSType(platform = process.platform) { if (/^win/.test(platform)) { return OSType.Windows; } else if (/^darwin/.test(platform)) { return OSType.OSX; } else if (/^linux/.test(platform)) { return OSType.Linux; } else { return OSType.Unknown; } } exports.getOSType = getOSType; const architectures = { x86: Architecture.x86, x64: Architecture.x64, '': Architecture.Unknown, }; function getArchitecture() { const fromProc = architectures[process.arch]; if (fromProc !== undefined) { return fromProc; } const arch = __webpack_require__(/*! arch */ "./node_modules/arch/index.js"); return architectures[arch()] || Architecture.Unknown; } exports.getArchitecture = getArchitecture; function getEnvironmentVariable(key) { return process.env[key]; } exports.getEnvironmentVariable = getEnvironmentVariable; function getUserHomeDir() { if (getOSType() === OSType.Windows) { return getEnvironmentVariable('USERPROFILE'); } return getEnvironmentVariable('HOME') || getEnvironmentVariable('HOMEPATH'); } exports.getUserHomeDir = getUserHomeDir; /***/ }), /***/ "./src/client/common/utils/random.ts": /*!*******************************************!*\ !*** ./src/client/common/utils/random.ts ***! \*******************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Random = void 0; const crypto = __webpack_require__(/*! crypto */ "crypto"); const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); function getRandom() { let num = 0; const buf = crypto.randomBytes(2); num = (buf.readUInt8(0) << 8) + buf.readUInt8(1); const maxValue = Math.pow(16, 4) - 1; return num / maxValue; } function getRandomBetween(min = 0, max = 10) { const randomVal = getRandom(); return min + randomVal * (max - min); } let Random = class Random { getRandomInt(min = 0, max = 10) { return getRandomBetween(min, max); } }; Random = __decorate([ (0, inversify_1.injectable)() ], Random); exports.Random = Random; /***/ }), /***/ "./src/client/common/utils/regexp.ts": /*!*******************************************!*\ !*** ./src/client/common/utils/regexp.ts ***! \*******************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.verboseRegExp = void 0; function verboseRegExp(pattern, flags) { pattern = pattern.replace(/(^| {2})# .*$/gm, ''); pattern = pattern.replace(/\s+?/g, ''); return RegExp(pattern, flags); } exports.verboseRegExp = verboseRegExp; /***/ }), /***/ "./src/client/common/utils/resourceLifecycle.ts": /*!******************************************************!*\ !*** ./src/client/common/utils/resourceLifecycle.ts ***! \******************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Disposables = exports.disposeAll = void 0; async function disposeAll(disposables) { await Promise.all(disposables.map(async (d) => { try { return Promise.resolve(d.dispose()); } catch (err) { } return Promise.resolve(); })); } exports.disposeAll = disposeAll; class Disposables { constructor(...disposables) { this.disposables = []; this.disposables.push(...disposables); } push(...disposables) { this.disposables.push(...disposables); } async dispose() { const { disposables } = this; this.disposables = []; await disposeAll(disposables); } } exports.Disposables = Disposables; /***/ }), /***/ "./src/client/common/utils/stopWatch.ts": /*!**********************************************!*\ !*** ./src/client/common/utils/stopWatch.ts ***! \**********************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.StopWatch = void 0; class StopWatch { constructor() { this.started = new Date().getTime(); } get elapsedTime() { return new Date().getTime() - this.started; } reset() { this.started = new Date().getTime(); } } exports.StopWatch = StopWatch; /***/ }), /***/ "./src/client/common/utils/sysTypes.ts": /*!*********************************************!*\ !*** ./src/client/common/utils/sysTypes.ts ***! \*********************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isNumber = exports.isObject = exports.isString = exports.isArray = void 0; const _typeof = { number: 'number', string: 'string', undefined: 'undefined', object: 'object', function: 'function', }; function isArray(array) { if (Array.isArray) { return Array.isArray(array); } if (array && typeof array.length === _typeof.number && array.constructor === Array) { return true; } return false; } exports.isArray = isArray; function isString(str) { if (typeof str === _typeof.string || str instanceof String) { return true; } return false; } exports.isString = isString; function isObject(obj) { return (typeof obj === _typeof.object && obj !== null && !Array.isArray(obj) && !(obj instanceof RegExp) && !(obj instanceof Date)); } exports.isObject = isObject; function isNumber(obj) { if ((typeof obj === _typeof.number || obj instanceof Number) && !isNaN(obj)) { return true; } return false; } exports.isNumber = isNumber; /***/ }), /***/ "./src/client/common/utils/version.ts": /*!********************************************!*\ !*** ./src/client/common/utils/version.ts ***! \********************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseSemVerSafe = exports.areSimilarVersions = exports.areIdenticalVersion = exports.parseVersionInfo = exports.validateVersionInfo = exports.normalizeVersionInfo = exports.compareVersions = exports.isVersionInfoEmpty = exports.parseBasicVersionInfo = exports.getVersionString = exports.EMPTY_VERSION = void 0; const semver = __webpack_require__(/*! semver */ "./node_modules/semver/semver.js"); const regexp_1 = __webpack_require__(/*! ./regexp */ "./src/client/common/utils/regexp.ts"); function normalizeVersionPart(part) { if (typeof part === 'number') { if (Number.isNaN(part)) { return [-1, 'missing']; } if (part < 0) { return [-1, '']; } return [part, '']; } if (typeof part === 'string') { const parsed = parseInt(part, 10); if (Number.isNaN(parsed)) { return [-1, 'string not numeric']; } if (parsed < 0) { return [-1, '']; } return [parsed, '']; } if (part === undefined || part === null) { return [-1, 'missing']; } return [-1, 'unsupported type']; } exports.EMPTY_VERSION = { major: -1, minor: -1, micro: -1, }; Object.freeze(exports.EMPTY_VERSION); function copyStrict(info) { const copied = { major: info.major, minor: info.minor, micro: info.micro, }; const { unnormalized } = info; if (unnormalized !== undefined) { copied.unnormalized = { major: unnormalized.major, minor: unnormalized.minor, micro: unnormalized.micro, }; } return copied; } function normalizeBasicVersionInfo(info) { if (!info) { return exports.EMPTY_VERSION; } const norm = copyStrict(info); if (norm.unnormalized === undefined) { norm.unnormalized = {}; [norm.major, norm.unnormalized.major] = normalizeVersionPart(norm.major); [norm.minor, norm.unnormalized.minor] = normalizeVersionPart(norm.minor); [norm.micro, norm.unnormalized.micro] = normalizeVersionPart(norm.micro); } return norm; } function validateVersionPart(prop, part, unnormalized) { if (part === 0 || part > 0) { return; } if (!unnormalized || unnormalized === '') { return; } throw Error(`invalid ${prop} version (failed to normalize; ${unnormalized})`); } function validateBasicVersionInfo(info) { var _a, _b, _c; const raw = info; validateVersionPart('major', info.major, (_a = raw.unnormalized) === null || _a === void 0 ? void 0 : _a.major); validateVersionPart('minor', info.minor, (_b = raw.unnormalized) === null || _b === void 0 ? void 0 : _b.minor); validateVersionPart('micro', info.micro, (_c = raw.unnormalized) === null || _c === void 0 ? void 0 : _c.micro); if (info.major < 0) { throw Error('missing major version'); } if (info.minor < 0) { if (info.micro === 0 || info.micro > 0) { throw Error('missing minor version'); } } } function getVersionString(info) { if (info.major < 0) { return ''; } if (info.minor < 0) { return `${info.major}`; } if (info.micro < 0) { return `${info.major}.${info.minor}`; } return `${info.major}.${info.minor}.${info.micro}`; } exports.getVersionString = getVersionString; const basicVersionPattern = ` ^ (.*?) # (\\d+) # (?: [.] (\\d+) # (?: [.] (\\d+) # )? )? ([^\\d].*)? # $ `; const basicVersionRegexp = (0, regexp_1.verboseRegExp)(basicVersionPattern, 's'); function parseBasicVersionInfo(verStr) { const match = verStr.match(basicVersionRegexp); if (!match) { return undefined; } const [, before, majorStr, minorStr, microStr, after] = match; if (before && before.endsWith('.')) { return undefined; } if (after && after !== '') { if (after === '.') { return undefined; } if (!before || before === '') { if (!microStr || microStr === '') { return undefined; } } } const major = parseInt(majorStr, 10); const minor = minorStr ? parseInt(minorStr, 10) : -1; const micro = microStr ? parseInt(microStr, 10) : -1; return { version: { major, minor, micro }, before: before || '', after: after || '', }; } exports.parseBasicVersionInfo = parseBasicVersionInfo; function isVersionInfoEmpty(info) { if (!info) { return false; } if (typeof info.major !== 'number' || typeof info.minor !== 'number' || typeof info.micro !== 'number') { return false; } return info.major < 0 && info.minor < 0 && info.micro < 0; } exports.isVersionInfoEmpty = isVersionInfoEmpty; function compareVersions(left, right, compareExtra) { if (left.major < right.major) { return [1, 'major']; } if (left.major > right.major) { return [-1, 'major']; } if (left.major === -1) { return [0, '']; } if (left.minor < right.minor) { return [1, 'minor']; } if (left.minor > right.minor) { return [-1, 'minor']; } if (left.minor === -1) { return [0, '']; } if (left.micro < right.micro) { return [1, 'micro']; } if (left.micro > right.micro) { return [-1, 'micro']; } if (compareExtra !== undefined) { return compareExtra(left, right); } return [0, '']; } exports.compareVersions = compareVersions; function normalizeVersionInfo(info) { const norm = normalizeBasicVersionInfo(info); norm.raw = info.raw; if (!norm.raw) { norm.raw = ''; } return norm; } exports.normalizeVersionInfo = normalizeVersionInfo; function validateVersionInfo(info) { validateBasicVersionInfo(info); } exports.validateVersionInfo = validateVersionInfo; function parseVersionInfo(verStr) { const result = parseBasicVersionInfo(verStr); if (result === undefined) { return undefined; } result.version.raw = verStr; return result; } exports.parseVersionInfo = parseVersionInfo; function areIdenticalVersion(left, right, compareExtra) { const [result] = compareVersions(left, right, compareExtra); return result === 0; } exports.areIdenticalVersion = areIdenticalVersion; function areSimilarVersions(left, right, compareExtra) { const [result, prop] = compareVersions(left, right, compareExtra); if (result === 0) { return true; } if (prop === 'major') { return false; } if (result < 0) { return right[prop] === -1; } return left[prop] === -1; } exports.areSimilarVersions = areSimilarVersions; function parseSemVerSafe(raw) { raw = raw.replace(/\.00*(?=[1-9]|0\.)/, '.'); const ver = semver.coerce(raw); if (ver === null || !semver.valid(ver)) { return new semver.SemVer('0.0.0'); } return ver; } exports.parseSemVerSafe = parseSemVerSafe; /***/ }), /***/ "./src/client/common/utils/workerPool.ts": /*!***********************************************!*\ !*** ./src/client/common/utils/workerPool.ts ***! \***********************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createRunningWorkerPool = exports.QueuePosition = void 0; const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const async_1 = __webpack_require__(/*! ./async */ "./src/client/common/utils/async.ts"); var QueuePosition; (function (QueuePosition) { QueuePosition[QueuePosition["Back"] = 0] = "Back"; QueuePosition[QueuePosition["Front"] = 1] = "Front"; })(QueuePosition = exports.QueuePosition || (exports.QueuePosition = {})); class Worker { constructor(next, workFunc, postResult, name) { this.next = next; this.workFunc = workFunc; this.postResult = postResult; this.name = name; this.stopProcessing = false; } stop() { this.stopProcessing = true; } async start() { while (!this.stopProcessing) { try { const workItem = await this.next(); try { const result = await this.workFunc(workItem); this.postResult(workItem, result); } catch (ex) { this.postResult(workItem, undefined, ex); } } catch (ex) { (0, logging_1.traceError)(`Error while running worker[${this.name}].`, ex); continue; } } } } class WorkQueue { constructor() { this.items = []; this.results = new Map(); } add(item, position) { const workItem = { item }; if (position === QueuePosition.Front) { this.items.unshift(workItem); } else { this.items.push(workItem); } const deferred = (0, async_1.createDeferred)(); this.results.set(workItem, deferred); return deferred.promise; } completed(workItem, result, error) { const deferred = this.results.get(workItem); if (deferred !== undefined) { this.results.delete(workItem); if (error !== undefined) { deferred.reject(error); } deferred.resolve(result); } } next() { return this.items.shift(); } clear() { this.results.forEach((v, k, map) => { v.reject(Error('Queue stopped processing')); map.delete(k); }); } } class WorkerPool { constructor(workerFunc, numWorkers = 2, name = 'Worker') { this.workerFunc = workerFunc; this.numWorkers = numWorkers; this.name = name; this.workers = []; this.waitingWorkersUnblockQueue = []; this.queue = new WorkQueue(); this.stopProcessing = false; } addToQueue(item, position) { if (this.stopProcessing) { throw Error('Queue is stopped'); } const deferred = this.queue.add(item, position); const worker = this.waitingWorkersUnblockQueue.shift(); if (worker) { const workItem = this.queue.next(); if (workItem !== undefined) { worker.unblock(workItem); } else { (0, logging_1.traceError)('Work queue was empty immediately after adding item.'); } } return deferred; } start() { this.stopProcessing = false; let num = this.numWorkers; while (num > 0) { this.workers.push(new Worker(() => this.nextWorkItem(), (workItem) => this.workerFunc(workItem.item), (workItem, result, error) => this.queue.completed(workItem, result, error), `${this.name} ${num}`)); num = num - 1; } this.workers.forEach(async (w) => w.start()); } stop() { this.stopProcessing = true; let worker = this.workers.shift(); while (worker) { worker.stop(); worker = this.workers.shift(); } this.queue.clear(); let blockedWorker = this.waitingWorkersUnblockQueue.shift(); while (blockedWorker) { blockedWorker.stop(); blockedWorker = this.waitingWorkersUnblockQueue.shift(); } } nextWorkItem() { const nextWorkItem = this.queue.next(); if (nextWorkItem !== undefined) { return Promise.resolve(nextWorkItem); } return new Promise((resolve, reject) => { this.waitingWorkersUnblockQueue.push({ unblock: (workItem) => { if (this.stopProcessing) { reject(); } resolve(workItem); }, stop: () => { reject(); }, }); }); } } function createRunningWorkerPool(workerFunc, numWorkers, name) { const pool = new WorkerPool(workerFunc, numWorkers, name); pool.start(); return pool; } exports.createRunningWorkerPool = createRunningWorkerPool; /***/ }), /***/ "./src/client/common/variables/environment.ts": /*!****************************************************!*\ !*** ./src/client/common/variables/environment.ts ***! \****************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.matchTarget = exports.restoreKeys = exports.normCaseKeys = exports.parseEnvFile = exports.EnvironmentVariablesService = void 0; const fs_extra_1 = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const path = __webpack_require__(/*! path */ "path"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const telemetry_1 = __webpack_require__(/*! ../../telemetry */ "./src/client/telemetry/index.ts"); const constants_1 = __webpack_require__(/*! ../../telemetry/constants */ "./src/client/telemetry/constants.ts"); const types_1 = __webpack_require__(/*! ../platform/types */ "./src/client/common/platform/types.ts"); const types_2 = __webpack_require__(/*! ../types */ "./src/client/common/types.ts"); const fs_paths_1 = __webpack_require__(/*! ../platform/fs-paths */ "./src/client/common/platform/fs-paths.ts"); let EnvironmentVariablesService = class EnvironmentVariablesService { constructor(pathUtils, fs) { this.pathUtils = pathUtils; this.fs = fs; } async parseFile(filePath, baseVars) { if (!filePath || !(await this.fs.pathExists(filePath))) { return; } const contents = await this.fs.readFile(filePath).catch((ex) => { (0, logging_1.traceError)('Custom .env is likely not pointing to a valid file', ex); return undefined; }); if (!contents) { return; } return parseEnvFile(contents, baseVars); } parseFileSync(filePath, baseVars) { if (!filePath || !(0, fs_extra_1.pathExistsSync)(filePath)) { return; } let contents; try { contents = (0, fs_extra_1.readFileSync)(filePath, { encoding: 'utf8' }); } catch (ex) { (0, logging_1.traceError)('Custom .env is likely not pointing to a valid file', ex); } if (!contents) { return; } return parseEnvFile(contents, baseVars); } mergeVariables(source, target, options) { if (!target) { return; } const reference = target; target = normCaseKeys(target); source = normCaseKeys(source); const settingsNotToMerge = ['PYTHONPATH', this.pathVariable]; Object.keys(source).forEach((setting) => { if (!(options === null || options === void 0 ? void 0 : options.mergeAll) && settingsNotToMerge.indexOf(setting) >= 0) { return; } if (target[setting] === undefined || (options === null || options === void 0 ? void 0 : options.overwrite)) { target[setting] = source[setting]; } }); restoreKeys(target); matchTarget(reference, target); } appendPythonPath(vars, ...pythonPaths) { return this.appendPaths(vars, 'PYTHONPATH', ...pythonPaths); } appendPath(vars, ...paths) { return this.appendPaths(vars, this.pathVariable, ...paths); } get pathVariable() { if (!this._pathVariable) { this._pathVariable = this.pathUtils.getPathVariableName(); } return (0, fs_paths_1.normCase)(this._pathVariable); } appendPaths(vars, variableName, ...pathsToAppend) { const reference = vars; vars = normCaseKeys(vars); variableName = (0, fs_paths_1.normCase)(variableName); vars = this._appendPaths(vars, variableName, ...pathsToAppend); restoreKeys(vars); matchTarget(reference, vars); return vars; } _appendPaths(vars, variableName, ...pathsToAppend) { const valueToAppend = pathsToAppend .filter((item) => typeof item === 'string' && item.trim().length > 0) .map((item) => item.trim()) .join(path.delimiter); if (valueToAppend.length === 0) { return vars; } const variable = vars ? vars[variableName] : undefined; if (variable && typeof variable === 'string' && variable.length > 0) { vars[variableName] = variable + path.delimiter + valueToAppend; } else { vars[variableName] = valueToAppend; } return vars; } }; EnvironmentVariablesService = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_2.IPathUtils)), __param(1, (0, inversify_1.inject)(types_1.IFileSystem)) ], EnvironmentVariablesService); exports.EnvironmentVariablesService = EnvironmentVariablesService; function parseEnvFile(lines, baseVars) { const globalVars = baseVars ? baseVars : {}; const vars = {}; lines .toString() .split('\n') .forEach((line, _idx) => { const [name, value] = parseEnvLine(line); if (name === '') { return; } vars[name] = substituteEnvVars(value, vars, globalVars); }); return vars; } exports.parseEnvFile = parseEnvFile; function parseEnvLine(line) { const match = line.match(/^\s*(_*[a-zA-Z]\w*)\s*=\s*(.*?)?\s*$/); if (!match) { return ['', '']; } const name = match[1]; let value = match[2]; if (value && value !== '') { if (value[0] === "'" && value[value.length - 1] === "'") { value = value.substring(1, value.length - 1); value = value.replace(/\\n/gm, '\n'); } else if (value[0] === '"' && value[value.length - 1] === '"') { value = value.substring(1, value.length - 1); value = value.replace(/\\n/gm, '\n'); } } else { value = ''; } return [name, value]; } const SUBST_REGEX = /\${([a-zA-Z]\w*)?([^}\w].*)?}/g; function substituteEnvVars(value, localVars, globalVars, missing = '') { let invalid = false; let replacement = value; replacement = replacement.replace(SUBST_REGEX, (match, substName, bogus, offset, orig) => { if (offset > 0 && orig[offset - 1] === '\\') { return match; } if ((bogus && bogus !== '') || !substName || substName === '') { invalid = true; return match; } return localVars[substName] || globalVars[substName] || missing; }); if (!invalid && replacement !== value) { value = replacement; (0, telemetry_1.sendTelemetryEvent)(constants_1.EventName.ENVFILE_VARIABLE_SUBSTITUTION); } return value.replace(/\\\$/g, '$'); } function normCaseKeys(env) { const normalizedEnv = {}; Object.keys(env).forEach((key) => { const normalizedKey = (0, fs_paths_1.normCase)(key); normalizedEnv[normalizedKey] = env[key]; }); return normalizedEnv; } exports.normCaseKeys = normCaseKeys; function restoreKeys(env) { const processEnvKeys = Object.keys(process.env); processEnvKeys.forEach((processEnvKey) => { const originalKey = (0, fs_paths_1.normCase)(processEnvKey); if (originalKey !== processEnvKey && env[originalKey] !== undefined) { env[processEnvKey] = env[originalKey]; delete env[originalKey]; } }); } exports.restoreKeys = restoreKeys; function matchTarget(reference, target) { Object.keys(reference).forEach((key) => { if (target.hasOwnProperty(key)) { reference[key] = target[key]; } else { delete reference[key]; } }); Object.keys(target).forEach((key) => { if (!reference.hasOwnProperty(key)) { reference[key] = target[key]; } }); } exports.matchTarget = matchTarget; /***/ }), /***/ "./src/client/common/variables/environmentVariablesProvider.ts": /*!*********************************************************************!*\ !*** ./src/client/common/variables/environmentVariablesProvider.ts ***! \*********************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EnvironmentVariablesProvider = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const path = __webpack_require__(/*! path */ "path"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const types_1 = __webpack_require__(/*! ../application/types */ "./src/client/common/application/types.ts"); const configSettings_1 = __webpack_require__(/*! ../configSettings */ "./src/client/common/configSettings.ts"); const types_2 = __webpack_require__(/*! ../platform/types */ "./src/client/common/platform/types.ts"); const types_3 = __webpack_require__(/*! ../types */ "./src/client/common/types.ts"); const cacheUtils_1 = __webpack_require__(/*! ../utils/cacheUtils */ "./src/client/common/utils/cacheUtils.ts"); const systemVariables_1 = __webpack_require__(/*! ./systemVariables */ "./src/client/common/variables/systemVariables.ts"); const types_4 = __webpack_require__(/*! ./types */ "./src/client/common/variables/types.ts"); const CACHE_DURATION = 60 * 60 * 1000; let EnvironmentVariablesProvider = class EnvironmentVariablesProvider { constructor(envVarsService, disposableRegistry, platformService, workspaceService, process, cacheDuration = CACHE_DURATION) { this.envVarsService = envVarsService; this.platformService = platformService; this.workspaceService = workspaceService; this.process = process; this.cacheDuration = cacheDuration; this.trackedWorkspaceFolders = new Set(); this.fileWatchers = new Map(); this.disposables = []; this.envVarCaches = new Map(); disposableRegistry.push(this); this.changeEventEmitter = new vscode_1.EventEmitter(); const disposable = this.workspaceService.onDidChangeConfiguration(this.configurationChanged, this); this.disposables.push(disposable); } get onDidEnvironmentVariablesChange() { return this.changeEventEmitter.event; } dispose() { this.changeEventEmitter.dispose(); this.fileWatchers.forEach((watcher) => { if (watcher) { watcher.dispose(); } }); } async getEnvironmentVariables(resource) { const cached = this.getCachedEnvironmentVariables(resource); if (cached) { return cached; } const vars = await this._getEnvironmentVariables(resource); this.setCachedEnvironmentVariables(resource, vars); (0, logging_1.traceVerbose)('Dump environment variables', JSON.stringify(vars, null, 4)); return vars; } getEnvironmentVariablesSync(resource) { const cached = this.getCachedEnvironmentVariables(resource); if (cached) { return cached; } const vars = this._getEnvironmentVariablesSync(resource); this.setCachedEnvironmentVariables(resource, vars); return vars; } getCachedEnvironmentVariables(resource) { var _a, _b; const cacheKey = (_b = (_a = this.getWorkspaceFolderUri(resource)) === null || _a === void 0 ? void 0 : _a.fsPath) !== null && _b !== void 0 ? _b : ''; const cache = this.envVarCaches.get(cacheKey); if (cache) { const cachedData = cache.data; if (cachedData) { return { ...cachedData }; } } return undefined; } setCachedEnvironmentVariables(resource, vars) { var _a, _b; const cacheKey = (_b = (_a = this.getWorkspaceFolderUri(resource)) === null || _a === void 0 ? void 0 : _a.fsPath) !== null && _b !== void 0 ? _b : ''; const cache = new cacheUtils_1.InMemoryCache(this.cacheDuration); this.envVarCaches.set(cacheKey, cache); cache.data = { ...vars }; } async _getEnvironmentVariables(resource) { const customVars = await this.getCustomEnvironmentVariables(resource); return this.getMergedEnvironmentVariables(customVars); } _getEnvironmentVariablesSync(resource) { const customVars = this.getCustomEnvironmentVariablesSync(resource); return this.getMergedEnvironmentVariables(customVars); } getMergedEnvironmentVariables(mergedVars) { if (!mergedVars) { mergedVars = {}; } this.envVarsService.mergeVariables(this.process.env, mergedVars); const pathVariable = this.platformService.pathVariableName; const pathValue = this.process.env[pathVariable]; if (pathValue) { this.envVarsService.appendPath(mergedVars, pathValue); } if (this.process.env.PYTHONPATH) { this.envVarsService.appendPythonPath(mergedVars, this.process.env.PYTHONPATH); } return mergedVars; } async getCustomEnvironmentVariables(resource) { return this.envVarsService.parseFile(this.getEnvFile(resource), this.process.env); } getCustomEnvironmentVariablesSync(resource) { return this.envVarsService.parseFileSync(this.getEnvFile(resource), this.process.env); } getEnvFile(resource) { var _a; const systemVariables = new systemVariables_1.SystemVariables(undefined, (_a = configSettings_1.PythonSettings.getSettingsUriAndTarget(resource, this.workspaceService).uri) === null || _a === void 0 ? void 0 : _a.fsPath, this.workspaceService); const workspaceFolderUri = this.getWorkspaceFolderUri(resource); const envFileSetting = this.workspaceService.getConfiguration('python', resource).get('envFile'); const envFile = systemVariables.resolveAny(envFileSetting); if (envFile === undefined) { (0, logging_1.traceError)('Unable to read `python.envFile` setting for resource', JSON.stringify(resource)); return (workspaceFolderUri === null || workspaceFolderUri === void 0 ? void 0 : workspaceFolderUri.fsPath) ? path.join(workspaceFolderUri === null || workspaceFolderUri === void 0 ? void 0 : workspaceFolderUri.fsPath, '.env') : ''; } this.trackedWorkspaceFolders.add(workspaceFolderUri ? workspaceFolderUri.fsPath : ''); this.createFileWatcher(envFile, workspaceFolderUri); return envFile; } configurationChanged(e) { this.trackedWorkspaceFolders.forEach((item) => { const uri = item && item.length > 0 ? vscode_1.Uri.file(item) : undefined; if (e.affectsConfiguration('python.envFile', uri)) { this.onEnvironmentFileChanged(uri); } }); } createFileWatcher(envFile, workspaceFolderUri) { if (this.fileWatchers.has(envFile)) { return; } try { const envFileWatcher = this.workspaceService.createFileSystemWatcher(envFile); this.fileWatchers.set(envFile, envFileWatcher); if (envFileWatcher) { this.disposables.push(envFileWatcher.onDidChange(() => this.onEnvironmentFileChanged(workspaceFolderUri))); this.disposables.push(envFileWatcher.onDidCreate(() => this.onEnvironmentFileCreated(workspaceFolderUri))); this.disposables.push(envFileWatcher.onDidDelete(() => this.onEnvironmentFileChanged(workspaceFolderUri))); } } catch (ex) { (0, logging_1.traceError)(`Failed to create a file system watcher for ${envFile} in ${workspaceFolderUri === null || workspaceFolderUri === void 0 ? void 0 : workspaceFolderUri.fsPath}`, ex); } } getWorkspaceFolderUri(resource) { if (!resource) { return undefined; } const workspaceFolder = this.workspaceService.getWorkspaceFolder(resource); return workspaceFolder ? workspaceFolder.uri : undefined; } onEnvironmentFileCreated(workspaceFolderUri) { this.onEnvironmentFileChanged(workspaceFolderUri); } onEnvironmentFileChanged(workspaceFolderUri) { this.envVarCaches.clear(); this.changeEventEmitter.fire(workspaceFolderUri); } }; EnvironmentVariablesProvider = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_4.IEnvironmentVariablesService)), __param(1, (0, inversify_1.inject)(types_3.IDisposableRegistry)), __param(2, (0, inversify_1.inject)(types_2.IPlatformService)), __param(3, (0, inversify_1.inject)(types_1.IWorkspaceService)), __param(4, (0, inversify_1.inject)(types_3.ICurrentProcess)), __param(5, (0, inversify_1.optional)()) ], EnvironmentVariablesProvider); exports.EnvironmentVariablesProvider = EnvironmentVariablesProvider; /***/ }), /***/ "./src/client/common/variables/serviceRegistry.ts": /*!********************************************************!*\ !*** ./src/client/common/variables/serviceRegistry.ts ***! \********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.registerTypes = void 0; const environment_1 = __webpack_require__(/*! ./environment */ "./src/client/common/variables/environment.ts"); const environmentVariablesProvider_1 = __webpack_require__(/*! ./environmentVariablesProvider */ "./src/client/common/variables/environmentVariablesProvider.ts"); const types_1 = __webpack_require__(/*! ./types */ "./src/client/common/variables/types.ts"); function registerTypes(serviceManager) { serviceManager.addSingleton(types_1.IEnvironmentVariablesService, environment_1.EnvironmentVariablesService); serviceManager.addSingleton(types_1.IEnvironmentVariablesProvider, environmentVariablesProvider_1.EnvironmentVariablesProvider); } exports.registerTypes = registerTypes; /***/ }), /***/ "./src/client/common/variables/systemVariables.ts": /*!********************************************************!*\ !*** ./src/client/common/variables/systemVariables.ts ***! \********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SystemVariables = void 0; const Path = __webpack_require__(/*! path */ "path"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const workspace_1 = __webpack_require__(/*! ../application/workspace */ "./src/client/common/application/workspace.ts"); const Types = __webpack_require__(/*! ../utils/sysTypes */ "./src/client/common/utils/sysTypes.ts"); class AbstractSystemVariables { resolve(value) { if (Types.isString(value)) { return this.__resolveString(value); } else if (Types.isArray(value)) { return this.__resolveArray(value); } else if (Types.isObject(value)) { return this.__resolveLiteral(value); } return value; } resolveAny(value) { if (Types.isString(value)) { return this.__resolveString(value); } else if (Types.isArray(value)) { return this.__resolveAnyArray(value); } else if (Types.isObject(value)) { return this.__resolveAnyLiteral(value); } return value; } __resolveString(value) { const regexp = /\$\{(.*?)\}/g; return value.replace(regexp, (match, name) => { const newValue = this[name]; if (Types.isString(newValue)) { return newValue; } else { return match && (match.indexOf('env.') > 0 || match.indexOf('env:') > 0) ? '' : match; } }); } __resolveLiteral(values) { const result = Object.create(null); Object.keys(values).forEach((key) => { const value = values[key]; result[key] = this.resolve(value); }); return result; } __resolveAnyLiteral(values) { const result = Object.create(null); Object.keys(values).forEach((key) => { const value = values[key]; result[key] = this.resolveAny(value); }); return result; } __resolveArray(value) { return value.map((s) => this.__resolveString(s)); } __resolveAnyArray(value) { return value.map((s) => this.resolveAny(s)); } } class SystemVariables extends AbstractSystemVariables { constructor(file, rootFolder, workspace, documentManager) { var _a; super(); const workspaceFolder = workspace && file ? workspace.getWorkspaceFolder(file) : undefined; this._workspaceFolder = workspaceFolder ? workspaceFolder.uri.fsPath : rootFolder || __dirname; this._workspaceFolderName = Path.basename(this._workspaceFolder); this._filePath = file ? file.fsPath : undefined; if (documentManager && documentManager.activeTextEditor) { this._lineNumber = documentManager.activeTextEditor.selection.anchor.line + 1; this._selectedText = documentManager.activeTextEditor.document.getText(new vscode_1.Range(documentManager.activeTextEditor.selection.start, documentManager.activeTextEditor.selection.end)); } this._execPath = process.execPath; Object.keys(process.env).forEach((key) => { this[`env:${key}`] = this[`env.${key}`] = process.env[key]; }); workspace = workspace !== null && workspace !== void 0 ? workspace : new workspace_1.WorkspaceService(); try { (_a = workspace.workspaceFolders) === null || _a === void 0 ? void 0 : _a.forEach((folder) => { const basename = Path.basename(folder.uri.fsPath); this[`workspaceFolder:${basename}`] = folder.uri.fsPath; }); } catch (_b) { } } get cwd() { return this.workspaceFolder; } get workspaceRoot() { return this._workspaceFolder; } get workspaceFolder() { return this._workspaceFolder; } get workspaceRootFolderName() { return this._workspaceFolderName; } get workspaceFolderBasename() { return this._workspaceFolderName; } get file() { return this._filePath; } get relativeFile() { return this.file ? Path.relative(this._workspaceFolder, this.file) : undefined; } get relativeFileDirname() { return this.relativeFile ? Path.dirname(this.relativeFile) : undefined; } get fileBasename() { return this.file ? Path.basename(this.file) : undefined; } get fileBasenameNoExtension() { return this.file ? Path.parse(this.file).name : undefined; } get fileDirname() { return this.file ? Path.dirname(this.file) : undefined; } get fileExtname() { return this.file ? Path.extname(this.file) : undefined; } get lineNumber() { return this._lineNumber; } get selectedText() { return this._selectedText; } get execPath() { return this._execPath; } } exports.SystemVariables = SystemVariables; /***/ }), /***/ "./src/client/common/variables/types.ts": /*!**********************************************!*\ !*** ./src/client/common/variables/types.ts ***! \**********************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.IEnvironmentVariablesProvider = exports.IEnvironmentVariablesService = void 0; exports.IEnvironmentVariablesService = Symbol('IEnvironmentVariablesService'); exports.IEnvironmentVariablesProvider = Symbol('IEnvironmentVariablesProvider'); /***/ }), /***/ "./src/client/common/vscodeApis/commandApis.ts": /*!*****************************************************!*\ !*** ./src/client/common/vscodeApis/commandApis.ts ***! \*****************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.executeCommand = exports.registerCommand = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); function registerCommand(command, callback, thisArg) { return vscode_1.commands.registerCommand(command, callback, thisArg); } exports.registerCommand = registerCommand; function executeCommand(command, ...rest) { return vscode_1.commands.executeCommand(command, ...rest); } exports.executeCommand = executeCommand; /***/ }), /***/ "./src/client/common/vscodeApis/windowApis.ts": /*!****************************************************!*\ !*** ./src/client/common/vscodeApis/windowApis.ts ***! \****************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createStepForwardEndNode = exports.createStepBackEndNode = exports.MultiStepNode = exports.showQuickPickWithBack = exports.MultiStepAction = exports.onDidChangeActiveTextEditor = exports.getActiveTextEditor = exports.withProgress = exports.showInformationMessage = exports.showErrorMessage = exports.createQuickPick = exports.showQuickPick = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const async_1 = __webpack_require__(/*! ../utils/async */ "./src/client/common/utils/async.ts"); function showQuickPick(items, options, token) { return vscode_1.window.showQuickPick(items, options, token); } exports.showQuickPick = showQuickPick; function createQuickPick() { return vscode_1.window.createQuickPick(); } exports.createQuickPick = createQuickPick; function showErrorMessage(message, ...items) { return vscode_1.window.showErrorMessage(message, ...items); } exports.showErrorMessage = showErrorMessage; function showInformationMessage(message, ...items) { return vscode_1.window.showInformationMessage(message, ...items); } exports.showInformationMessage = showInformationMessage; function withProgress(options, task) { return vscode_1.window.withProgress(options, task); } exports.withProgress = withProgress; function getActiveTextEditor() { const { activeTextEditor } = vscode_1.window; return activeTextEditor; } exports.getActiveTextEditor = getActiveTextEditor; function onDidChangeActiveTextEditor(handler) { return vscode_1.window.onDidChangeActiveTextEditor(handler); } exports.onDidChangeActiveTextEditor = onDidChangeActiveTextEditor; var MultiStepAction; (function (MultiStepAction) { MultiStepAction["Back"] = "Back"; MultiStepAction["Cancel"] = "Cancel"; MultiStepAction["Continue"] = "Continue"; })(MultiStepAction = exports.MultiStepAction || (exports.MultiStepAction = {})); async function showQuickPickWithBack(items, options, token) { var _a, _b, _c, _d; const quickPick = vscode_1.window.createQuickPick(); const disposables = [quickPick]; quickPick.items = items; quickPick.buttons = [vscode_1.QuickInputButtons.Back]; quickPick.canSelectMany = (_a = options === null || options === void 0 ? void 0 : options.canPickMany) !== null && _a !== void 0 ? _a : false; quickPick.ignoreFocusOut = (_b = options === null || options === void 0 ? void 0 : options.ignoreFocusOut) !== null && _b !== void 0 ? _b : false; quickPick.matchOnDescription = (_c = options === null || options === void 0 ? void 0 : options.matchOnDescription) !== null && _c !== void 0 ? _c : false; quickPick.matchOnDetail = (_d = options === null || options === void 0 ? void 0 : options.matchOnDetail) !== null && _d !== void 0 ? _d : false; quickPick.placeholder = options === null || options === void 0 ? void 0 : options.placeHolder; quickPick.title = options === null || options === void 0 ? void 0 : options.title; const deferred = (0, async_1.createDeferred)(); disposables.push(quickPick, quickPick.onDidTriggerButton((item) => { if (item === vscode_1.QuickInputButtons.Back) { deferred.reject(MultiStepAction.Back); quickPick.hide(); } }), quickPick.onDidAccept(() => { if (!deferred.completed) { if (quickPick.canSelectMany) { deferred.resolve(quickPick.selectedItems.map((item) => item)); } else { deferred.resolve(quickPick.selectedItems[0]); } quickPick.hide(); } }), quickPick.onDidHide(() => { if (!deferred.completed) { deferred.resolve(undefined); } })); if (token) { disposables.push(token.onCancellationRequested(() => { quickPick.hide(); })); } quickPick.show(); try { return await deferred.promise; } finally { disposables.forEach((d) => d.dispose()); } } exports.showQuickPickWithBack = showQuickPickWithBack; class MultiStepNode { constructor(previous, current, next) { this.previous = previous; this.current = current; this.next = next; } static async run(step, context) { let nextStep = step; let flowAction = await nextStep.current(context); while (nextStep !== undefined) { if (flowAction === MultiStepAction.Cancel) { return flowAction; } if (flowAction === MultiStepAction.Back) { nextStep = nextStep === null || nextStep === void 0 ? void 0 : nextStep.previous; } if (flowAction === MultiStepAction.Continue) { nextStep = nextStep === null || nextStep === void 0 ? void 0 : nextStep.next; } if (nextStep) { flowAction = await (nextStep === null || nextStep === void 0 ? void 0 : nextStep.current(flowAction)); } } return flowAction; } } exports.MultiStepNode = MultiStepNode; function createStepBackEndNode(deferred) { return new MultiStepNode(undefined, async () => { if (deferred) { deferred.reject(MultiStepAction.Back); } return Promise.resolve(MultiStepAction.Back); }, undefined); } exports.createStepBackEndNode = createStepBackEndNode; function createStepForwardEndNode(deferred, result) { return new MultiStepNode(undefined, async () => { if (deferred) { deferred.resolve(result); } return Promise.resolve(MultiStepAction.Back); }, undefined); } exports.createStepForwardEndNode = createStepForwardEndNode; /***/ }), /***/ "./src/client/common/vscodeApis/workspaceApis.ts": /*!*******************************************************!*\ !*** ./src/client/common/vscodeApis/workspaceApis.ts ***! \*******************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.onDidChangeConfiguration = exports.onDidChangeTextDocument = exports.onDidOpenTextDocument = exports.getOpenTextDocuments = exports.onDidSaveTextDocument = exports.onDidCloseTextDocument = exports.findFiles = exports.applyEdit = exports.getConfiguration = exports.getWorkspaceFolderPaths = exports.getWorkspaceFolder = exports.getWorkspaceFolders = void 0; const vscode = __webpack_require__(/*! vscode */ "vscode"); function getWorkspaceFolders() { return vscode.workspace.workspaceFolders; } exports.getWorkspaceFolders = getWorkspaceFolders; function getWorkspaceFolder(uri) { return uri ? vscode.workspace.getWorkspaceFolder(uri) : undefined; } exports.getWorkspaceFolder = getWorkspaceFolder; function getWorkspaceFolderPaths() { var _a, _b; return (_b = (_a = vscode.workspace.workspaceFolders) === null || _a === void 0 ? void 0 : _a.map((w) => w.uri.fsPath)) !== null && _b !== void 0 ? _b : []; } exports.getWorkspaceFolderPaths = getWorkspaceFolderPaths; function getConfiguration(section, scope) { return vscode.workspace.getConfiguration(section, scope); } exports.getConfiguration = getConfiguration; function applyEdit(edit) { return vscode.workspace.applyEdit(edit); } exports.applyEdit = applyEdit; function findFiles(include, exclude, maxResults, token) { return vscode.workspace.findFiles(include, exclude, maxResults, token); } exports.findFiles = findFiles; function onDidCloseTextDocument(handler) { return vscode.workspace.onDidCloseTextDocument(handler); } exports.onDidCloseTextDocument = onDidCloseTextDocument; function onDidSaveTextDocument(handler) { return vscode.workspace.onDidSaveTextDocument(handler); } exports.onDidSaveTextDocument = onDidSaveTextDocument; function getOpenTextDocuments() { return vscode.workspace.textDocuments; } exports.getOpenTextDocuments = getOpenTextDocuments; function onDidOpenTextDocument(handler) { return vscode.workspace.onDidOpenTextDocument(handler); } exports.onDidOpenTextDocument = onDidOpenTextDocument; function onDidChangeTextDocument(handler) { return vscode.workspace.onDidChangeTextDocument(handler); } exports.onDidChangeTextDocument = onDidChangeTextDocument; function onDidChangeConfiguration(handler) { return vscode.workspace.onDidChangeConfiguration(handler); } exports.onDidChangeConfiguration = onDidChangeConfiguration; /***/ }), /***/ "./src/client/constants.ts": /*!*********************************!*\ !*** ./src/client/constants.ts ***! \*********************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HiddenFilePrefix = exports.EXTENSION_ROOT_DIR = void 0; const path = __webpack_require__(/*! path */ "path"); const folderName = path.basename(__dirname); exports.EXTENSION_ROOT_DIR = folderName === 'client' ? path.join(__dirname, '..', '..') : path.join(__dirname, '..', '..', '..', '..'); exports.HiddenFilePrefix = '_HiddenFile_'; /***/ }), /***/ "./src/client/extensionActivation.ts": /*!*******************************************!*\ !*** ./src/client/extensionActivation.ts ***! \*******************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.activateFeatures = exports.activateComponents = void 0; const serviceRegistry_1 = __webpack_require__(/*! ./activation/serviceRegistry */ "./src/client/activation/serviceRegistry.ts"); const types_1 = __webpack_require__(/*! ./activation/types */ "./src/client/activation/types.ts"); const types_2 = __webpack_require__(/*! ./common/application/types */ "./src/client/common/application/types.ts"); const constants_1 = __webpack_require__(/*! ./common/constants */ "./src/client/common/constants.ts"); const types_3 = __webpack_require__(/*! ./common/types */ "./src/client/common/types.ts"); const serviceRegistry_2 = __webpack_require__(/*! ../environments/serviceRegistry */ "./src/environments/serviceRegistry.ts"); const pythonEnvironments = __webpack_require__(/*! ./pythonEnvironments */ "./src/client/pythonEnvironments/index.ts"); const types_4 = __webpack_require__(/*! ./interpreter/configuration/types */ "./src/client/interpreter/configuration/types.ts"); const registrations_1 = __webpack_require__(/*! ./pythonEnvironments/creation/registrations */ "./src/client/pythonEnvironments/creation/registrations.ts"); const sillyDI_1 = __webpack_require__(/*! ../environments/sillyDI */ "./src/environments/sillyDI.ts"); async function activateComponents(ext, components) { const legacyActivationResult = await activateLegacy(ext); const promises = [ pythonEnvironments.activate(components.pythonEnvs, ext), ]; return Promise.all([legacyActivationResult, ...promises]); } exports.activateComponents = activateComponents; function activateFeatures(ext, _components) { const interpreterQuickPick = ext.legacyIOC.serviceContainer.get(types_4.IInterpreterQuickPick); (0, registrations_1.registerAllCreateEnvironmentFeatures)(ext.disposables, interpreterQuickPick); } exports.activateFeatures = activateFeatures; async function activateLegacy(ext) { const { context, legacyIOC } = ext; const { serviceManager, serviceContainer } = legacyIOC; const applicationEnv = serviceManager.get(types_2.IApplicationEnvironment); const { enableProposedApi } = applicationEnv.packageJson; serviceManager.addSingletonInstance(constants_1.UseProposedApi, enableProposedApi); (0, serviceRegistry_1.registerTypes)(serviceManager); serviceManager.addSingleton(types_1.IExtensionActivationService, sillyDI_1.Dummy); const manager = serviceContainer.get(types_1.IExtensionActivationManager); context.subscriptions.push(manager); serviceContainer.get(types_3.IConfigurationService).getSettings(); const activationPromise = manager.activate(); (0, serviceRegistry_2.registerTypes)(serviceManager, context); return { fullyReady: activationPromise }; } /***/ }), /***/ "./src/client/extensionInit.ts": /*!*************************************!*\ !*** ./src/client/extensionInit.ts ***! \*************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.initializeComponents = exports.initializeStandard = exports.initializeGlobals = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const serviceRegistry_1 = __webpack_require__(/*! ./common/platform/serviceRegistry */ "./src/client/common/platform/serviceRegistry.ts"); const serviceRegistry_2 = __webpack_require__(/*! ./common/process/serviceRegistry */ "./src/client/common/process/serviceRegistry.ts"); const serviceRegistry_3 = __webpack_require__(/*! ./common/serviceRegistry */ "./src/client/common/serviceRegistry.ts"); const serviceRegistry_4 = __webpack_require__(/*! ./interpreter/serviceRegistry */ "./src/client/interpreter/serviceRegistry.ts"); const types_1 = __webpack_require__(/*! ./common/types */ "./src/client/common/types.ts"); const serviceRegistry_5 = __webpack_require__(/*! ./common/variables/serviceRegistry */ "./src/client/common/variables/serviceRegistry.ts"); const container_1 = __webpack_require__(/*! ./ioc/container */ "./src/client/ioc/container.ts"); const serviceManager_1 = __webpack_require__(/*! ./ioc/serviceManager */ "./src/client/ioc/serviceManager.ts"); const types_2 = __webpack_require__(/*! ./ioc/types */ "./src/client/ioc/types.ts"); const pythonEnvironments = __webpack_require__(/*! ./pythonEnvironments */ "./src/client/pythonEnvironments/index.ts"); const logging_1 = __webpack_require__(/*! ./logging */ "./src/client/logging/index.ts"); const outputChannelLogger_1 = __webpack_require__(/*! ./logging/outputChannelLogger */ "./src/client/logging/outputChannelLogger.ts"); const constants_1 = __webpack_require__(/*! ../environments/constants */ "./src/environments/constants.ts"); function initializeGlobals(context) { const disposables = context.subscriptions; const cont = new inversify_1.Container({ skipBaseClassChecks: true }); const serviceManager = new serviceManager_1.ServiceManager(cont); const serviceContainer = new container_1.ServiceContainer(cont); serviceManager.addSingletonInstance(types_2.IServiceContainer, serviceContainer); serviceManager.addSingletonInstance(types_2.IServiceManager, serviceManager); serviceManager.addSingletonInstance(types_1.IDisposableRegistry, disposables); serviceManager.addSingletonInstance(types_1.IMemento, context.globalState, types_1.GLOBAL_MEMENTO); serviceManager.addSingletonInstance(types_1.IMemento, context.workspaceState, types_1.WORKSPACE_MEMENTO); serviceManager.addSingletonInstance(types_1.IExtensionContext, context); context.subscriptions.push((0, logging_1.registerLogger)(new outputChannelLogger_1.OutputChannelLogger(constants_1.loggingOutputChannel))); return { context, disposables, legacyIOC: { serviceManager, serviceContainer }, }; } exports.initializeGlobals = initializeGlobals; function initializeStandard(ext) { const { serviceManager } = ext.legacyIOC; (0, serviceRegistry_3.registerTypes)(serviceManager); (0, serviceRegistry_5.registerTypes)(serviceManager); (0, serviceRegistry_1.registerTypes)(serviceManager); (0, serviceRegistry_2.registerTypes)(serviceManager); (0, serviceRegistry_4.registerTypes)(serviceManager); } exports.initializeStandard = initializeStandard; async function initializeComponents(ext) { const pythonEnvs = await pythonEnvironments.initialize(ext); return { pythonEnvs, }; } exports.initializeComponents = initializeComponents; /***/ }), /***/ "./src/client/interpreter/activation/service.ts": /*!******************************************************!*\ !*** ./src/client/interpreter/activation/service.ts ***! \******************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EnvironmentActivationService = exports.EnvironmentActivationServiceCache = exports.defaultShells = void 0; __webpack_require__(/*! ../../common/extensions */ "./src/client/common/extensions.ts"); const path = __webpack_require__(/*! path */ "path"); const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const types_1 = __webpack_require__(/*! ../../common/application/types */ "./src/client/common/application/types.ts"); const constants_1 = __webpack_require__(/*! ../../common/constants */ "./src/client/common/constants.ts"); const types_2 = __webpack_require__(/*! ../../common/platform/types */ "./src/client/common/platform/types.ts"); const internalScripts = __webpack_require__(/*! ../../common/process/internal/scripts */ "./src/client/common/process/internal/scripts/index.ts"); const types_3 = __webpack_require__(/*! ../../common/process/types */ "./src/client/common/process/types.ts"); const types_4 = __webpack_require__(/*! ../../common/terminal/types */ "./src/client/common/terminal/types.ts"); const types_5 = __webpack_require__(/*! ../../common/types */ "./src/client/common/types.ts"); const async_1 = __webpack_require__(/*! ../../common/utils/async */ "./src/client/common/utils/async.ts"); const cacheUtils_1 = __webpack_require__(/*! ../../common/utils/cacheUtils */ "./src/client/common/utils/cacheUtils.ts"); const platform_1 = __webpack_require__(/*! ../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const types_6 = __webpack_require__(/*! ../../common/variables/types */ "./src/client/common/variables/types.ts"); const info_1 = __webpack_require__(/*! ../../pythonEnvironments/info */ "./src/client/pythonEnvironments/info/index.ts"); const telemetry_1 = __webpack_require__(/*! ../../telemetry */ "./src/client/telemetry/index.ts"); const constants_2 = __webpack_require__(/*! ../../telemetry/constants */ "./src/client/telemetry/constants.ts"); const contracts_1 = __webpack_require__(/*! ../contracts */ "./src/client/interpreter/contracts.ts"); const types_7 = __webpack_require__(/*! ../../logging/types */ "./src/client/logging/types.ts"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const conda_1 = __webpack_require__(/*! ../../pythonEnvironments/common/environmentManagers/conda */ "./src/client/pythonEnvironments/common/environmentManagers/conda.ts"); const stopWatch_1 = __webpack_require__(/*! ../../common/utils/stopWatch */ "./src/client/common/utils/stopWatch.ts"); const baseShellDetector_1 = __webpack_require__(/*! ../../common/terminal/shellDetectors/baseShellDetector */ "./src/client/common/terminal/shellDetectors/baseShellDetector.ts"); const exec_1 = __webpack_require__(/*! ../../common/utils/exec */ "./src/client/common/utils/exec.ts"); const decorators_1 = __webpack_require__(/*! ../../common/utils/decorators */ "./src/client/common/utils/decorators.ts"); const ENVIRONMENT_PREFIX = 'e8b39361-0157-4923-80e1-22d70d46dee6'; const CACHE_DURATION = 10 * 60 * 1000; const ENVIRONMENT_TIMEOUT = 30000; const CONDA_ENVIRONMENT_TIMEOUT = 60000; exports.defaultShells = { [platform_1.OSType.Windows]: { shell: 'cmd', shellType: types_4.TerminalShellType.commandPrompt }, [platform_1.OSType.OSX]: { shell: 'bash', shellType: types_4.TerminalShellType.bash }, [platform_1.OSType.Linux]: { shell: 'bash', shellType: types_4.TerminalShellType.bash }, [platform_1.OSType.Unknown]: undefined, }; const condaRetryMessages = [ 'The process cannot access the file because it is being used by another process', 'The directory is not empty', ]; class EnvironmentActivationServiceCache { constructor() { this.normalMap = new Map(); } static forceUseStatic() { EnvironmentActivationServiceCache.useStatic = true; } static forceUseNormal() { EnvironmentActivationServiceCache.useStatic = false; } get(key) { if (EnvironmentActivationServiceCache.useStatic) { return EnvironmentActivationServiceCache.staticMap.get(key); } return this.normalMap.get(key); } set(key, value) { if (EnvironmentActivationServiceCache.useStatic) { EnvironmentActivationServiceCache.staticMap.set(key, value); } else { this.normalMap.set(key, value); } } delete(key) { if (EnvironmentActivationServiceCache.useStatic) { EnvironmentActivationServiceCache.staticMap.delete(key); } else { this.normalMap.delete(key); } } clear() { if (!EnvironmentActivationServiceCache.useStatic) { this.normalMap.clear(); } } } exports.EnvironmentActivationServiceCache = EnvironmentActivationServiceCache; EnvironmentActivationServiceCache.useStatic = false; EnvironmentActivationServiceCache.staticMap = new Map(); let EnvironmentActivationService = class EnvironmentActivationService { constructor(helper, platform, processServiceFactory, currentProcess, workspace, interpreterService, envVarsService) { this.helper = helper; this.platform = platform; this.processServiceFactory = processServiceFactory; this.currentProcess = currentProcess; this.workspace = workspace; this.interpreterService = interpreterService; this.envVarsService = envVarsService; this.disposables = []; this.activatedEnvVariablesCache = new EnvironmentActivationServiceCache(); this.envVarsService.onDidEnvironmentVariablesChange(() => this.activatedEnvVariablesCache.clear(), this, this.disposables); } dispose() { this.disposables.forEach((d) => d.dispose()); } async getActivatedEnvironmentVariables(resource, interpreter, allowExceptions, shell) { var _a; const stopWatch = new stopWatch_1.StopWatch(); const workspaceKey = this.workspace.getWorkspaceFolderIdentifier(resource); interpreter = interpreter !== null && interpreter !== void 0 ? interpreter : (await this.interpreterService.getActiveInterpreter(resource)); const interpreterPath = this.platform.isWindows ? interpreter === null || interpreter === void 0 ? void 0 : interpreter.path.toLowerCase() : interpreter === null || interpreter === void 0 ? void 0 : interpreter.path; const cacheKey = `${workspaceKey}_${interpreterPath}_${shell}`; if ((_a = this.activatedEnvVariablesCache.get(cacheKey)) === null || _a === void 0 ? void 0 : _a.hasData) { return this.activatedEnvVariablesCache.get(cacheKey).data; } const memCache = new cacheUtils_1.InMemoryCache(CACHE_DURATION); return this.getActivatedEnvironmentVariablesImpl(resource, interpreter, allowExceptions, shell) .then((vars) => { memCache.data = vars; this.activatedEnvVariablesCache.set(cacheKey, memCache); (0, telemetry_1.sendTelemetryEvent)(constants_2.EventName.PYTHON_INTERPRETER_ACTIVATION_ENVIRONMENT_VARIABLES, stopWatch.elapsedTime, { failed: false }); return vars; }) .catch((ex) => { (0, telemetry_1.sendTelemetryEvent)(constants_2.EventName.PYTHON_INTERPRETER_ACTIVATION_ENVIRONMENT_VARIABLES, stopWatch.elapsedTime, { failed: true }); throw ex; }); } async getProcessEnvironmentVariables(resource, shell) { const globalInterpreters = this.interpreterService .getInterpreters() .filter((i) => !info_1.virtualEnvTypes.includes(i.envType)); const interpreterPath = globalInterpreters.length > 0 && globalInterpreters[0] ? globalInterpreters[0].path : 'python'; try { const [args, parse] = internalScripts.printEnvVariables(); args.forEach((arg, i) => { args[i] = arg.toCommandArgumentForPythonMgrExt(); }); const command = `${interpreterPath} ${args.join(' ')}`; const processService = await this.processServiceFactory.create(resource, { doNotUseCustomEnvs: true }); const result = await processService.shellExec(command, { shell, timeout: ENVIRONMENT_TIMEOUT, maxBuffer: 1000 * 1000, throwOnStdErr: false, }); const returnedEnv = this.parseEnvironmentOutput(result.stdout, parse); return returnedEnv !== null && returnedEnv !== void 0 ? returnedEnv : process.env; } catch (ex) { return process.env; } } async getEnvironmentActivationShellCommands(resource, interpreter) { const shellInfo = exports.defaultShells[this.platform.osType]; if (!shellInfo) { return []; } return this.helper.getEnvironmentActivationShellCommands(resource, shellInfo.shellType, interpreter); } async getActivatedEnvironmentVariablesImpl(resource, interpreter, allowExceptions, shell) { var _a, _b; let shellInfo = exports.defaultShells[this.platform.osType]; if (!shellInfo) { return undefined; } if (shell) { const customShellType = (0, baseShellDetector_1.identifyShellFromShellPath)(shell); shellInfo = { shellType: customShellType, shell }; } try { const processService = await this.processServiceFactory.create(resource); const customEnvVars = (_a = (await this.envVarsService.getEnvironmentVariables(resource))) !== null && _a !== void 0 ? _a : {}; const hasCustomEnvVars = Object.keys(customEnvVars).length; const env = hasCustomEnvVars ? customEnvVars : { ...this.currentProcess.env }; let command; const [args, parse] = internalScripts.printEnvVariables(); args.forEach((arg, i) => { args[i] = arg.toCommandArgumentForPythonMgrExt(); }); if ((interpreter === null || interpreter === void 0 ? void 0 : interpreter.envType) === info_1.EnvironmentType.Conda) { const conda = await conda_1.Conda.getConda(shell); const pythonArgv = await (conda === null || conda === void 0 ? void 0 : conda.getRunPythonArgs({ name: interpreter.envName, prefix: (_b = interpreter.envPath) !== null && _b !== void 0 ? _b : '', })); if (pythonArgv) { command = [...pythonArgv, ...args].map((arg) => arg.toCommandArgumentForPythonMgrExt()).join(' '); } } if (!command) { const activationCommands = await this.helper.getEnvironmentActivationShellCommands(resource, shellInfo.shellType, interpreter); (0, logging_1.traceVerbose)(`Activation Commands received ${activationCommands} for shell ${shellInfo.shell}`); if (!activationCommands || !Array.isArray(activationCommands) || activationCommands.length === 0) { if (interpreter && [info_1.EnvironmentType.Venv, info_1.EnvironmentType.Pyenv].includes(interpreter === null || interpreter === void 0 ? void 0 : interpreter.envType)) { const key = (0, exec_1.getSearchPathEnvVarNames)()[0]; if (env[key]) { env[key] = `${path.dirname(interpreter.path)}${path.delimiter}${env[key]}`; } else { env[key] = `${path.dirname(interpreter.path)}`; } return env; } return undefined; } const activationCommand = fixActivationCommands(activationCommands).join(' && '); const commandSeparator = [types_4.TerminalShellType.powershell, types_4.TerminalShellType.powershellCore].includes(shellInfo.shellType) ? ';' : '&&'; command = `${activationCommand} ${commandSeparator} echo '${ENVIRONMENT_PREFIX}' ${commandSeparator} python ${args.join(' ')}`; } const oldWarnings = env[constants_1.PYTHON_WARNINGS]; env[constants_1.PYTHON_WARNINGS] = 'ignore'; (0, logging_1.traceVerbose)(`${hasCustomEnvVars ? 'Has' : 'No'} Custom Env Vars`); (0, logging_1.traceVerbose)(`Activating Environment to capture Environment variables, ${command}`); let result; let tryCount = 1; let returnedEnv; while (!result) { try { result = await processService.shellExec(command, { env, shell: shellInfo.shell, timeout: (interpreter === null || interpreter === void 0 ? void 0 : interpreter.envType) === info_1.EnvironmentType.Conda ? CONDA_ENVIRONMENT_TIMEOUT : ENVIRONMENT_TIMEOUT, maxBuffer: 1000 * 1000, throwOnStdErr: false, }); try { returnedEnv = this.parseEnvironmentOutput(result.stdout, parse); } catch (ex) { if (!result.stderr) { throw ex; } } if (result.stderr) { if (returnedEnv) { (0, logging_1.traceWarn)('Got env variables but with errors', result.stderr); } else { throw new Error(`StdErr from ShellExec, ${result.stderr} for ${command}`); } } } catch (exc) { const excString = exc.toString(); if (condaRetryMessages.find((m) => excString.includes(m)) && tryCount < 10) { (0, logging_1.traceInfo)(`Conda is busy, attempting to retry ...`); result = undefined; tryCount += 1; await (0, async_1.sleep)(500); } else { throw exc; } } } if (oldWarnings && returnedEnv) { returnedEnv[constants_1.PYTHON_WARNINGS] = oldWarnings; } else if (returnedEnv) { delete returnedEnv[constants_1.PYTHON_WARNINGS]; } return returnedEnv; } catch (e) { (0, logging_1.traceError)('getActivatedEnvironmentVariables', e); (0, telemetry_1.sendTelemetryEvent)(constants_2.EventName.ACTIVATE_ENV_TO_GET_ENV_VARS_FAILED, undefined, { isPossiblyCondaEnv: (interpreter === null || interpreter === void 0 ? void 0 : interpreter.envType) === info_1.EnvironmentType.Conda, terminal: shellInfo.shellType, }); if (allowExceptions) { throw e; } } return undefined; } parseEnvironmentOutput(output, parse) { if (output.indexOf(ENVIRONMENT_PREFIX) === -1) { return parse(output); } output = output.substring(output.indexOf(ENVIRONMENT_PREFIX) + ENVIRONMENT_PREFIX.length); const js = output.substring(output.indexOf('{')).trim(); return parse(js); } }; __decorate([ (0, logging_1.traceDecoratorVerbose)('getActivatedEnvironmentVariables', types_7.TraceOptions.Arguments) ], EnvironmentActivationService.prototype, "getActivatedEnvironmentVariables", null); __decorate([ (0, decorators_1.cache)(-1, true) ], EnvironmentActivationService.prototype, "getProcessEnvironmentVariables", null); __decorate([ (0, logging_1.traceDecoratorError)('Failed to parse Environment variables'), (0, logging_1.traceDecoratorVerbose)('parseEnvironmentOutput', types_7.TraceOptions.None) ], EnvironmentActivationService.prototype, "parseEnvironmentOutput", null); EnvironmentActivationService = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_4.ITerminalHelper)), __param(1, (0, inversify_1.inject)(types_2.IPlatformService)), __param(2, (0, inversify_1.inject)(types_3.IProcessServiceFactory)), __param(3, (0, inversify_1.inject)(types_5.ICurrentProcess)), __param(4, (0, inversify_1.inject)(types_1.IWorkspaceService)), __param(5, (0, inversify_1.inject)(contracts_1.IInterpreterService)), __param(6, (0, inversify_1.inject)(types_6.IEnvironmentVariablesProvider)) ], EnvironmentActivationService); exports.EnvironmentActivationService = EnvironmentActivationService; function fixActivationCommands(commands) { return commands.map((cmd) => cmd.replace(/^source\s+/, '. ')); } /***/ }), /***/ "./src/client/interpreter/activation/types.ts": /*!****************************************************!*\ !*** ./src/client/interpreter/activation/types.ts ***! \****************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ITerminalEnvVarCollectionService = exports.IEnvironmentActivationService = void 0; exports.IEnvironmentActivationService = Symbol('IEnvironmentActivationService'); exports.ITerminalEnvVarCollectionService = Symbol('ITerminalEnvVarCollectionService'); /***/ }), /***/ "./src/client/interpreter/configuration/environmentTypeComparer.ts": /*!*************************************************************************!*\ !*** ./src/client/interpreter/configuration/environmentTypeComparer.ts ***! \*************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEnvLocationHeuristic = exports.isProblematicCondaEnvironment = exports.EnvironmentTypeComparer = exports.EnvLocationHeuristic = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const platform_1 = __webpack_require__(/*! ../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const activestate_1 = __webpack_require__(/*! ../../pythonEnvironments/common/environmentManagers/activestate */ "./src/client/pythonEnvironments/common/environmentManagers/activestate.ts"); const externalDependencies_1 = __webpack_require__(/*! ../../pythonEnvironments/common/externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const info_1 = __webpack_require__(/*! ../../pythonEnvironments/info */ "./src/client/pythonEnvironments/info/index.ts"); const contracts_1 = __webpack_require__(/*! ../contracts */ "./src/client/interpreter/contracts.ts"); const utils_1 = __webpack_require__(/*! ../../../environments/utils */ "./src/environments/utils.ts"); var EnvLocationHeuristic; (function (EnvLocationHeuristic) { EnvLocationHeuristic[EnvLocationHeuristic["Local"] = 1] = "Local"; EnvLocationHeuristic[EnvLocationHeuristic["Global"] = 2] = "Global"; })(EnvLocationHeuristic = exports.EnvLocationHeuristic || (exports.EnvLocationHeuristic = {})); let EnvironmentTypeComparer = class EnvironmentTypeComparer { constructor(interpreterHelper) { var _a, _b; this.interpreterHelper = interpreterHelper; this.workspaceFolderPath = (_b = (_a = this.interpreterHelper.getActiveWorkspaceUri(undefined)) === null || _a === void 0 ? void 0 : _a.folderUri.fsPath) !== null && _b !== void 0 ? _b : ''; } compare(a, b) { if (isProblematicCondaEnvironment(a)) { return 1; } if (isProblematicCondaEnvironment(b)) { return -1; } const envLocationComparison = compareEnvironmentLocation(a, b, this.workspaceFolderPath); if (envLocationComparison !== 0) { return envLocationComparison; } const envTypeComparison = compareEnvironmentType(a, b); if (envTypeComparison !== 0) { return envTypeComparison; } const versionComparison = comparePythonVersionDescending(a.version, b.version); if (versionComparison !== 0) { return versionComparison; } if (isBaseCondaEnvironment(a)) { return 1; } if (isBaseCondaEnvironment(b)) { return -1; } const nameA = getSortName(a, this.interpreterHelper); const nameB = getSortName(b, this.interpreterHelper); if (nameA === nameB) { return 0; } return nameA > nameB ? 1 : -1; } compareV2(a, b) { if ((0, utils_1.isNonPythonCondaEnvironment)(a)) { return 1; } if ((0, utils_1.isNonPythonCondaEnvironment)(b)) { return -1; } const envTypeComparison = compareEnvironmentTypeV2(a, b); if (envTypeComparison !== 0) { return envTypeComparison; } const versionComparison = comparePythonVersionDescendingV2(a, b); if (versionComparison !== 0) { return versionComparison; } if (isBaseCondaEnvironmentV2(a)) { return 1; } if (isBaseCondaEnvironmentV2(b)) { return -1; } const nameA = getSortNameV2(a, this.interpreterHelper); const nameB = getSortNameV2(b, this.interpreterHelper); if (nameA === nameB) { return 0; } return nameA > nameB ? 1 : -1; } getRecommended(interpreters, resource) { const workspaceUri = this.interpreterHelper.getActiveWorkspaceUri(resource); const filteredInterpreters = interpreters.filter((i) => { var _a; if (isProblematicCondaEnvironment(i)) { return false; } if (i.envType === info_1.EnvironmentType.ActiveState && (!i.path || !workspaceUri || !(0, activestate_1.isActiveStateEnvironmentForWorkspace)(i.path, workspaceUri.folderUri.fsPath))) { return false; } if (getEnvLocationHeuristic(i, (workspaceUri === null || workspaceUri === void 0 ? void 0 : workspaceUri.folderUri.fsPath) || '') === EnvLocationHeuristic.Local) { return true; } if (info_1.virtualEnvTypes.includes(i.envType)) { return false; } if (((_a = i.version) === null || _a === void 0 ? void 0 : _a.major) === 2) { return false; } return true; }); filteredInterpreters.sort(this.compare.bind(this)); return filteredInterpreters.length ? filteredInterpreters[0] : undefined; } }; EnvironmentTypeComparer = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(contracts_1.IInterpreterHelper)) ], EnvironmentTypeComparer); exports.EnvironmentTypeComparer = EnvironmentTypeComparer; function getSortName(info, interpreterHelper) { const sortNameParts = []; const envSuffixParts = []; if (info.version) { sortNameParts.push(info.version.raw); } if (info.architecture) { sortNameParts.push(getArchitectureSortName(info.architecture)); } if (info.companyDisplayName && info.companyDisplayName.length > 0) { sortNameParts.push(info.companyDisplayName.trim()); } else { sortNameParts.push('Python'); } if (info.envType) { const name = interpreterHelper.getInterpreterTypeDisplayName(info.envType); if (name) { envSuffixParts.push(name); } } if (info.envName && info.envName.length > 0) { envSuffixParts.push(info.envName); } const envSuffix = envSuffixParts.length === 0 ? '' : `(${envSuffixParts.join(': ')})`; return `${sortNameParts.join(' ')} ${envSuffix}`.trim(); } function getSortNameV2(info, interpreterHelper) { var _a, _b, _c; const sortNameParts = []; const envSuffixParts = []; if ((_a = info.version) === null || _a === void 0 ? void 0 : _a.sysVersion) { sortNameParts.push(info.version.sysVersion); } if (info.executable.bitness) { sortNameParts.push(info.executable.bitness); } const name = interpreterHelper.getInterpreterTypeDisplayName((0, utils_1.getEnvironmentType)(info)); if (name) { envSuffixParts.push(name); } if ((_b = info.environment) === null || _b === void 0 ? void 0 : _b.name) { envSuffixParts.push((_c = info.environment) === null || _c === void 0 ? void 0 : _c.name); } const envSuffix = envSuffixParts.length === 0 ? '' : `(${envSuffixParts.join(': ')})`; return `${sortNameParts.join(' ')} ${envSuffix}`.trim(); } function getArchitectureSortName(arch) { switch (arch) { case platform_1.Architecture.x64: return 'x64'; case platform_1.Architecture.x86: return 'x86'; default: return ''; } } function isBaseCondaEnvironment(environment) { return (environment.envType === info_1.EnvironmentType.Conda && (environment.envName === 'base' || environment.envName === 'miniconda')); } function isBaseCondaEnvironmentV2(environment) { var _a, _b; return ((0, utils_1.isCondaEnvironment)(environment) && (((_a = environment.environment) === null || _a === void 0 ? void 0 : _a.name) === 'base' || ((_b = environment.environment) === null || _b === void 0 ? void 0 : _b.name) === 'miniconda')); } function isProblematicCondaEnvironment(environment) { return environment.envType === info_1.EnvironmentType.Conda && environment.path === 'python'; } exports.isProblematicCondaEnvironment = isProblematicCondaEnvironment; function comparePythonVersionDescending(a, b) { if (!a) { return 1; } if (!b) { return -1; } if (a.raw === b.raw) { return 0; } if (a.major === b.major) { if (a.minor === b.minor) { if (a.patch === b.patch) { return a.build.join(' ') > b.build.join(' ') ? -1 : 1; } return a.patch > b.patch ? -1 : 1; } return a.minor > b.minor ? -1 : 1; } return a.major > b.major ? -1 : 1; } function comparePythonVersionDescendingV2(a, b) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t; if (!a) { return 1; } if (!b) { return -1; } if (((_a = a.version) === null || _a === void 0 ? void 0 : _a.sysVersion) === ((_b = b.version) === null || _b === void 0 ? void 0 : _b.sysVersion)) { return 0; } if (((_c = a.version) === null || _c === void 0 ? void 0 : _c.major) === ((_d = b.version) === null || _d === void 0 ? void 0 : _d.major)) { if (((_e = a.version) === null || _e === void 0 ? void 0 : _e.minor) === ((_f = b.version) === null || _f === void 0 ? void 0 : _f.minor)) { if (((_g = a.version) === null || _g === void 0 ? void 0 : _g.micro) === ((_h = b.version) === null || _h === void 0 ? void 0 : _h.micro)) { return (((_k = (_j = a.version) === null || _j === void 0 ? void 0 : _j.release) === null || _k === void 0 ? void 0 : _k.serial) || 0) > (((_m = (_l = b.version) === null || _l === void 0 ? void 0 : _l.release) === null || _m === void 0 ? void 0 : _m.serial) || 0) ? -1 : 1; } return (((_o = a.version) === null || _o === void 0 ? void 0 : _o.micro) || 0) > (((_p = b.version) === null || _p === void 0 ? void 0 : _p.micro) || 0) ? -1 : 1; } return (((_q = a.version) === null || _q === void 0 ? void 0 : _q.minor) || 0) > (((_r = b.version) === null || _r === void 0 ? void 0 : _r.minor) || 0) ? -1 : 1; } return (((_s = a.version) === null || _s === void 0 ? void 0 : _s.major) || 0) > (((_t = b.version) === null || _t === void 0 ? void 0 : _t.major) || 0) ? -1 : 1; } function compareEnvironmentLocation(a, b, workspacePath) { const aHeuristic = getEnvLocationHeuristic(a, workspacePath); const bHeuristic = getEnvLocationHeuristic(b, workspacePath); return Math.sign(aHeuristic - bHeuristic); } function getEnvLocationHeuristic(environment, workspacePath) { if (workspacePath.length > 0 && ((environment.envPath && (0, externalDependencies_1.isParentPath)(environment.envPath, workspacePath)) || (environment.path && (0, externalDependencies_1.isParentPath)(environment.path, workspacePath)))) { return EnvLocationHeuristic.Local; } return EnvLocationHeuristic.Global; } exports.getEnvLocationHeuristic = getEnvLocationHeuristic; function compareEnvironmentType(a, b) { const envTypeByPriority = getPrioritizedEnvironmentType(); return Math.sign(envTypeByPriority.indexOf(a.envType) - envTypeByPriority.indexOf(b.envType)); } function compareEnvironmentTypeV2(a, b) { const envTypeByPriority = getPrioritizedEnvironmentType(); return Math.sign(envTypeByPriority.indexOf((0, utils_1.getEnvironmentType)(a)) - envTypeByPriority.indexOf((0, utils_1.getEnvironmentType)(b))); } function getPrioritizedEnvironmentType() { return [ info_1.EnvironmentType.Poetry, info_1.EnvironmentType.Pipenv, info_1.EnvironmentType.VirtualEnvWrapper, info_1.EnvironmentType.Venv, info_1.EnvironmentType.VirtualEnv, info_1.EnvironmentType.ActiveState, info_1.EnvironmentType.Conda, info_1.EnvironmentType.Pyenv, info_1.EnvironmentType.MicrosoftStore, info_1.EnvironmentType.Global, info_1.EnvironmentType.System, info_1.EnvironmentType.Unknown, ]; } /***/ }), /***/ "./src/client/interpreter/configuration/interpreterSelector/commands/base.ts": /*!***********************************************************************************!*\ !*** ./src/client/interpreter/configuration/interpreterSelector/commands/base.ts ***! \***********************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BaseInterpreterSelectorCommand = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const path = __webpack_require__(/*! path */ "path"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const localize_1 = __webpack_require__(/*! ../../../../common/utils/localize */ "./src/client/common/utils/localize.ts"); let BaseInterpreterSelectorCommand = class BaseInterpreterSelectorCommand { constructor(commandManager, applicationShell, workspaceService, pathUtils, configurationService) { this.commandManager = commandManager; this.applicationShell = applicationShell; this.workspaceService = workspaceService; this.pathUtils = pathUtils; this.configurationService = configurationService; this.supportedWorkspaceTypes = { untrustedWorkspace: false, virtualWorkspace: true }; this.disposables = []; this.disposables.push(this); } dispose() { this.disposables.forEach((disposable) => disposable.dispose()); } async getConfigTargets(options) { const workspaceFolders = this.workspaceService.workspaceFolders; if (workspaceFolders === undefined || workspaceFolders.length === 0) { return [ { folderUri: undefined, configTarget: vscode_1.ConfigurationTarget.Global, }, ]; } if (workspaceFolders.length === 1) { return [ { folderUri: workspaceFolders[0].uri, configTarget: vscode_1.ConfigurationTarget.WorkspaceFolder, }, ]; } let quickPickItems = (options === null || options === void 0 ? void 0 : options.resetTarget) ? [ { label: localize_1.Common.clearAll, }, ] : []; quickPickItems.push(...workspaceFolders.map((w) => { const selectedInterpreter = this.pathUtils.getDisplayName(this.configurationService.getSettings(w.uri).pythonPath, w.uri.fsPath); return { label: w.name, description: this.pathUtils.getDisplayName(path.dirname(w.uri.fsPath)), uri: w.uri, detail: selectedInterpreter, }; }), { label: (options === null || options === void 0 ? void 0 : options.resetTarget) ? localize_1.Interpreters.clearAtWorkspace : localize_1.Interpreters.entireWorkspace, uri: workspaceFolders[0].uri, }); const selection = await this.applicationShell.showQuickPick(quickPickItems, { placeHolder: (options === null || options === void 0 ? void 0 : options.resetTarget) ? 'Select the workspace folder to clear the interpreter for' : 'Select the workspace folder to set the interpreter', }); if ((selection === null || selection === void 0 ? void 0 : selection.label) === localize_1.Common.clearAll) { const folderTargets = workspaceFolders.map((w) => ({ folderUri: w.uri, configTarget: vscode_1.ConfigurationTarget.WorkspaceFolder, })); return [ ...folderTargets, { folderUri: workspaceFolders[0].uri, configTarget: vscode_1.ConfigurationTarget.Workspace }, ]; } return selection ? selection.label === localize_1.Interpreters.entireWorkspace || selection.label === localize_1.Interpreters.clearAtWorkspace ? [{ folderUri: selection.uri, configTarget: vscode_1.ConfigurationTarget.Workspace }] : [{ folderUri: selection.uri, configTarget: vscode_1.ConfigurationTarget.WorkspaceFolder }] : undefined; } }; BaseInterpreterSelectorCommand = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.unmanaged)()), __param(1, (0, inversify_1.unmanaged)()), __param(2, (0, inversify_1.unmanaged)()), __param(3, (0, inversify_1.unmanaged)()), __param(4, (0, inversify_1.unmanaged)()) ], BaseInterpreterSelectorCommand); exports.BaseInterpreterSelectorCommand = BaseInterpreterSelectorCommand; /***/ }), /***/ "./src/client/interpreter/configuration/interpreterSelector/commands/setInterpreter.ts": /*!*********************************************************************************************!*\ !*** ./src/client/interpreter/configuration/interpreterSelector/commands/setInterpreter.ts ***! \*********************************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SetInterpreterCommand = exports.EnvGroups = void 0; const python_extension_1 = __webpack_require__(/*! @vscode/python-extension */ "./node_modules/@vscode/python-extension/out/main.js"); const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const lodash_1 = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const types_1 = __webpack_require__(/*! ../../../../common/application/types */ "./src/client/common/application/types.ts"); const constants_1 = __webpack_require__(/*! ../../../../common/constants */ "./src/client/common/constants.ts"); const fs_paths_1 = __webpack_require__(/*! ../../../../common/platform/fs-paths */ "./src/client/common/platform/fs-paths.ts"); const types_2 = __webpack_require__(/*! ../../../../common/platform/types */ "./src/client/common/platform/types.ts"); const types_3 = __webpack_require__(/*! ../../../../common/types */ "./src/client/common/types.ts"); const localize_1 = __webpack_require__(/*! ../../../../common/utils/localize */ "./src/client/common/utils/localize.ts"); const misc_1 = __webpack_require__(/*! ../../../../common/utils/misc */ "./src/client/common/utils/misc.ts"); const multiStepInput_1 = __webpack_require__(/*! ../../../../common/utils/multiStepInput */ "./src/client/common/utils/multiStepInput.ts"); const systemVariables_1 = __webpack_require__(/*! ../../../../common/variables/systemVariables */ "./src/client/common/variables/systemVariables.ts"); const info_1 = __webpack_require__(/*! ../../../../pythonEnvironments/info */ "./src/client/pythonEnvironments/info/index.ts"); const telemetry_1 = __webpack_require__(/*! ../../../../telemetry */ "./src/client/telemetry/index.ts"); const constants_2 = __webpack_require__(/*! ../../../../telemetry/constants */ "./src/client/telemetry/constants.ts"); const contracts_1 = __webpack_require__(/*! ../../../contracts */ "./src/client/interpreter/contracts.ts"); const types_4 = __webpack_require__(/*! ../../types */ "./src/client/interpreter/configuration/types.ts"); const base_1 = __webpack_require__(/*! ./base */ "./src/client/interpreter/configuration/interpreterSelector/commands/base.ts"); const utils_1 = __webpack_require__(/*! ../../../../../environments/utils */ "./src/environments/utils.ts"); function isInterpreterQuickPickItem(item) { return 'interpreter' in item; } function isSpecialQuickPickItem(item) { return 'alwaysShow' in item; } function isSeparatorItem(item) { return 'kind' in item && item.kind === vscode_1.QuickPickItemKind.Separator; } var EnvGroups; (function (EnvGroups) { EnvGroups.Workspace = localize_1.InterpreterQuickPickList.workspaceGroupName; EnvGroups.Conda = 'Conda'; EnvGroups.Global = localize_1.InterpreterQuickPickList.globalGroupName; EnvGroups.VirtualEnv = 'VirtualEnv'; EnvGroups.PipEnv = 'PipEnv'; EnvGroups.Pyenv = 'Pyenv'; EnvGroups.Venv = 'Venv'; EnvGroups.Poetry = 'Poetry'; EnvGroups.VirtualEnvWrapper = 'VirtualEnvWrapper'; EnvGroups.ActiveState = 'ActiveState'; EnvGroups.Recommended = localize_1.Common.recommended; })(EnvGroups = exports.EnvGroups || (exports.EnvGroups = {})); let SetInterpreterCommand = class SetInterpreterCommand extends base_1.BaseInterpreterSelectorCommand { constructor(applicationShell, pathUtils, configurationService, commandManager, multiStepFactory, platformService, interpreterSelector, workspaceService, interpreterService) { super(commandManager, applicationShell, workspaceService, pathUtils, configurationService); this.multiStepFactory = multiStepFactory; this.platformService = platformService; this.interpreterSelector = interpreterSelector; this.interpreterService = interpreterService; this.manualEntrySuggestion = { label: `${constants_1.Octicons.Add} ${localize_1.InterpreterQuickPickList.enterPath.label}`, alwaysShow: true, }; this.refreshButton = { iconPath: new vscode_1.ThemeIcon(constants_1.ThemeIcons.Refresh), tooltip: localize_1.InterpreterQuickPickList.refreshInterpreterList, }; this.noPythonInstalled = { label: `${constants_1.Octicons.Error} ${localize_1.InterpreterQuickPickList.noPythonInstalled}`, detail: localize_1.InterpreterQuickPickList.clickForInstructions, alwaysShow: true, }; this.wasNoPythonInstalledItemClicked = false; this.tipToReloadWindow = { label: `${constants_1.Octicons.Lightbulb} Reload the window if you installed Python but don't see it`, detail: `Click to run \`Developer: Reload Window\` command`, alwaysShow: true, }; this.isBusyLoadingPythonEnvs = false; this.isBusyLoadingPythonEnvs = true; python_extension_1.PythonExtension.api().then((api) => { this.api = api; api.environments.refreshEnvironments().finally(() => { this.isBusyLoadingPythonEnvs = false; }); }); } async activate() { } async _pickInterpreter(input, state, filter, params) { var _a, _b; const api = await python_extension_1.PythonExtension.api(); const preserveOrderWhenFiltering = this.isBusyLoadingPythonEnvs; const suggestions = this._getItems(api, state.workspace, filter, params); state.path = undefined; const currentInterpreterPathDisplay = this.pathUtils.getDisplayName(this.configurationService.getSettings(state.workspace).pythonPath, state.workspace ? state.workspace.fsPath : undefined); const placeholder = (params === null || params === void 0 ? void 0 : params.placeholder) === null ? undefined : (_a = params === null || params === void 0 ? void 0 : params.placeholder) !== null && _a !== void 0 ? _a : vscode_1.l10n.t('Selected Interpreter: {0}', currentInterpreterPathDisplay); const title = (params === null || params === void 0 ? void 0 : params.title) === null ? undefined : (_b = params === null || params === void 0 ? void 0 : params.title) !== null && _b !== void 0 ? _b : localize_1.InterpreterQuickPickList.browsePath.openButtonLabel; const buttons = [ { button: this.refreshButton, callback: (quickpickInput) => { this.refreshCallback(quickpickInput, { isButton: true, showBackButton: params === null || params === void 0 ? void 0 : params.showBackButton }); }, }, ]; if (params === null || params === void 0 ? void 0 : params.showBackButton) { buttons.push({ button: vscode_1.QuickInputButtons.Back, callback: () => { }, }); } const selection = await input.showQuickPick({ placeholder, items: suggestions, sortByLabel: !preserveOrderWhenFiltering, keepScrollPosition: true, activeItem: this.getActiveItem(state.workspace, suggestions), matchOnDetail: true, matchOnDescription: true, title, customButtonSetups: buttons, initialize: (quickPick) => { if (this.api.environments.known.length === 0) { this.refreshCallback(quickPick, { showBackButton: params === null || params === void 0 ? void 0 : params.showBackButton }); } else { this.refreshCallback(quickPick, { ifNotTriggerredAlready: true, showBackButton: params === null || params === void 0 ? void 0 : params.showBackButton, }); } }, onChangeItem: { event: this.api.environments.onDidChangeEnvironments, callback: (event, quickPick) => { if (this.isBusyLoadingPythonEnvs) { quickPick.busy = true; this.api.environments.refreshEnvironments().then(() => { quickPick.busy = false; this.updateQuickPickItems(api, quickPick, undefined, state.workspace, filter, params); }); } this.updateQuickPickItems(api, quickPick, event, state.workspace, filter, params); }, }, }); if (selection === undefined) { (0, telemetry_1.sendTelemetryEvent)(constants_2.EventName.SELECT_INTERPRETER_SELECTED, undefined, { action: 'escape' }); } else if (selection.label === this.manualEntrySuggestion.label) { (0, telemetry_1.sendTelemetryEvent)(constants_2.EventName.SELECT_INTERPRETER_ENTER_OR_FIND); return this._enterOrBrowseInterpreterPath.bind(this); } else if (selection.label === this.noPythonInstalled.label) { this.commandManager.executeCommand(constants_1.Commands.InstallPython).then(misc_1.noop, misc_1.noop); this.wasNoPythonInstalledItemClicked = true; } else if (selection.label === this.tipToReloadWindow.label) { this.commandManager.executeCommand('workbench.action.reloadWindow').then(misc_1.noop, misc_1.noop); } else { (0, telemetry_1.sendTelemetryEvent)(constants_2.EventName.SELECT_INTERPRETER_SELECTED, undefined, { action: 'selected' }); state.path = selection.path; } return undefined; } _getItems(api, resource, filter, params) { const suggestions = [this.manualEntrySuggestion]; const defaultInterpreterPathSuggestion = this.getDefaultInterpreterPathSuggestion(resource); if (defaultInterpreterPathSuggestion) { suggestions.push(defaultInterpreterPathSuggestion); } const interpreterSuggestions = this.getSuggestions(api, resource, filter, params); this.finalizeItems(api, interpreterSuggestions, resource, params); suggestions.push(...interpreterSuggestions); return suggestions; } getSuggestions(api, resource, filter, params) { var _a; const workspaceFolder = this.workspaceService.getWorkspaceFolder(resource); const items = this.interpreterSelector .getSuggestions(api, resource, this.isBusyLoadingPythonEnvs) .filter((i) => !filter || filter(i.interpreter)); if (this.isBusyLoadingPythonEnvs) { return items; } const itemsWithFullName = this.interpreterSelector .getSuggestions(api, resource, true) .filter((i) => !filter || filter(i.interpreter)); let recommended; if (!(params === null || params === void 0 ? void 0 : params.skipRecommended)) { recommended = this.interpreterSelector.getRecommendedSuggestion(itemsWithFullName, (_a = this.workspaceService.getWorkspaceFolder(resource)) === null || _a === void 0 ? void 0 : _a.uri); } if (recommended && items[0].interpreter.id === recommended.interpreter.id) { items.shift(); } return getGroupedQuickPickItems(items, recommended, workspaceFolder === null || workspaceFolder === void 0 ? void 0 : workspaceFolder.uri.fsPath); } async getActiveItem(resource, suggestions) { const interpreter = await this.interpreterService.getActiveInterpreter(resource); const activeInterpreterItem = suggestions.find((i) => isInterpreterQuickPickItem(i) && i.interpreter.id === (interpreter === null || interpreter === void 0 ? void 0 : interpreter.id)); if (activeInterpreterItem) { return activeInterpreterItem; } const firstInterpreterSuggestion = suggestions.find((s) => isInterpreterQuickPickItem(s)); if (firstInterpreterSuggestion) { return firstInterpreterSuggestion; } const noPythonInstalledItem = suggestions.find((i) => isSpecialQuickPickItem(i) && i.label === this.noPythonInstalled.label); return noPythonInstalledItem !== null && noPythonInstalledItem !== void 0 ? noPythonInstalledItem : suggestions[0]; } getDefaultInterpreterPathSuggestion(resource) { const config = this.workspaceService.getConfiguration('python', resource); const systemVariables = new systemVariables_1.SystemVariables(resource, undefined, this.workspaceService); const defaultInterpreterPathValue = systemVariables.resolveAny(config.get('defaultInterpreterPath')); if (defaultInterpreterPathValue && defaultInterpreterPathValue !== 'python') { return { label: `${constants_1.Octicons.Gear} ${localize_1.InterpreterQuickPickList.defaultInterpreterPath.label}`, description: this.pathUtils.getDisplayName(defaultInterpreterPathValue, resource ? resource.fsPath : undefined), path: defaultInterpreterPathValue, alwaysShow: true, }; } return undefined; } updateQuickPickItems(api, quickPick, event, resource, filter, params) { const activeItemBeforeUpdate = quickPick.activeItems.length > 0 ? quickPick.activeItems[0] : undefined; quickPick.items = this.getUpdatedItems(api, quickPick.items, event, resource, filter, params); const activeItem = activeItemBeforeUpdate ? quickPick.items.find((item) => { if (isInterpreterQuickPickItem(item) && isInterpreterQuickPickItem(activeItemBeforeUpdate)) { return item.interpreter.id === activeItemBeforeUpdate.interpreter.id; } if (isSpecialQuickPickItem(item) && isSpecialQuickPickItem(activeItemBeforeUpdate)) { return item.label === activeItemBeforeUpdate.label; } return false; }) : undefined; quickPick.activeItems = activeItem ? [activeItem] : []; } getUpdatedItems(_api, _items, _event, _resource, _filter, _params) { return []; } finalizeItems(api, items, resource, params) { const interpreterSuggestions = this.interpreterSelector.getSuggestions(api, resource, true); if (!this.isBusyLoadingPythonEnvs) { if (interpreterSuggestions.length) { if (!(params === null || params === void 0 ? void 0 : params.skipRecommended)) { this.setRecommendedItem(interpreterSuggestions, items, resource); } items.forEach((item, i) => { if (isInterpreterQuickPickItem(item) && (0, utils_1.isNonPythonCondaEnvironment)(item.interpreter)) { if (!items[i].label.includes(constants_1.Octicons.Warning)) { items[i].label = `${constants_1.Octicons.Warning} ${items[i].label}`; items[i].tooltip = localize_1.InterpreterQuickPickList.condaEnvWithoutPythonTooltip; } } }); } else { if (!items.some((i) => isSpecialQuickPickItem(i) && i.label === this.noPythonInstalled.label)) { items.push(this.noPythonInstalled); } if (this.wasNoPythonInstalledItemClicked && !items.some((i) => isSpecialQuickPickItem(i) && i.label === this.tipToReloadWindow.label)) { items.push(this.tipToReloadWindow); } } } } setRecommendedItem(interpreterSuggestions, items, resource) { var _a, _b; const suggestion = this.interpreterSelector.getRecommendedSuggestion(interpreterSuggestions, (_a = this.workspaceService.getWorkspaceFolder(resource)) === null || _a === void 0 ? void 0 : _a.uri); if (!suggestion) { return; } const areItemsGrouped = items.find((item) => isSeparatorItem(item) && item.label === EnvGroups.Recommended); const recommended = (0, lodash_1.cloneDeep)(suggestion); recommended.label = `${constants_1.Octicons.Star} ${recommended.label}`; recommended.description = areItemsGrouped ? recommended.description : `${(_b = recommended.description) !== null && _b !== void 0 ? _b : ''} - ${localize_1.Common.recommended}`; const index = items.findIndex((item) => isInterpreterQuickPickItem(item) && item.interpreter.id === recommended.interpreter.id); if (index !== -1) { items[index] = recommended; } } refreshCallback(input, options) { input.buttons = this.getButtons(options); input.busy = true; this.api.environments .refreshEnvironments({}) .finally(() => { input.busy = false; input.buttons = this.getButtons({ isButton: false, showBackButton: options === null || options === void 0 ? void 0 : options.showBackButton }); }) .ignoreErrors(); } getButtons(options) { const buttons = []; if (options === null || options === void 0 ? void 0 : options.showBackButton) { buttons.push(vscode_1.QuickInputButtons.Back); } if (options === null || options === void 0 ? void 0 : options.isButton) { buttons.push({ iconPath: new vscode_1.ThemeIcon(constants_1.ThemeIcons.SpinningLoader), tooltip: localize_1.InterpreterQuickPickList.refreshingInterpreterList, }); } else { buttons.push(this.refreshButton); } return buttons; } async _enterOrBrowseInterpreterPath(input, state) { const items = [ { label: localize_1.InterpreterQuickPickList.browsePath.label, detail: localize_1.InterpreterQuickPickList.browsePath.detail, }, ]; const selection = await input.showQuickPick({ placeholder: localize_1.InterpreterQuickPickList.enterPath.placeholder, items, acceptFilterBoxTextAsSelection: true, }); if (typeof selection === 'string') { (0, telemetry_1.sendTelemetryEvent)(constants_2.EventName.SELECT_INTERPRETER_ENTER_CHOICE, undefined, { choice: 'enter' }); state.path = selection; } else if (selection && selection.label === localize_1.InterpreterQuickPickList.browsePath.label) { (0, telemetry_1.sendTelemetryEvent)(constants_2.EventName.SELECT_INTERPRETER_ENTER_CHOICE, undefined, { choice: 'browse' }); const filtersKey = 'Executables'; const filtersObject = {}; filtersObject[filtersKey] = ['exe']; const uris = await this.applicationShell.showOpenDialog({ filters: this.platformService.isWindows ? filtersObject : undefined, openLabel: localize_1.InterpreterQuickPickList.browsePath.openButtonLabel, canSelectMany: false, title: localize_1.InterpreterQuickPickList.browsePath.title, }); if (uris && uris.length > 0) { state.path = uris[0].fsPath; } else { return Promise.reject(multiStepInput_1.InputFlowAction.resume); } } return Promise.resolve(); } async setInterpreter() { const targetConfig = await this.getConfigTargets(); if (!targetConfig) { return; } const wkspace = targetConfig[0].folderUri; const interpreterState = { path: undefined, workspace: wkspace }; const multiStep = this.multiStepFactory.create(); await multiStep.run((input, s) => this._pickInterpreter(input, s, undefined), interpreterState); } async getInterpreterViaQuickPick(workspace, filter, params) { const interpreterState = { path: undefined, workspace }; const multiStep = this.multiStepFactory.create(); await multiStep.run((input, s) => this._pickInterpreter(input, s, filter, params), interpreterState); return interpreterState.path; } }; SetInterpreterCommand = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_1.IApplicationShell)), __param(1, (0, inversify_1.inject)(types_3.IPathUtils)), __param(2, (0, inversify_1.inject)(types_3.IConfigurationService)), __param(3, (0, inversify_1.inject)(types_1.ICommandManager)), __param(4, (0, inversify_1.inject)(multiStepInput_1.IMultiStepInputFactory)), __param(5, (0, inversify_1.inject)(types_2.IPlatformService)), __param(6, (0, inversify_1.inject)(types_4.IInterpreterSelector)), __param(7, (0, inversify_1.inject)(types_1.IWorkspaceService)), __param(8, (0, inversify_1.inject)(contracts_1.IInterpreterService)) ], SetInterpreterCommand); exports.SetInterpreterCommand = SetInterpreterCommand; function getGroupedQuickPickItems(items, recommended, workspacePath) { const updatedItems = []; if (recommended) { updatedItems.push({ label: EnvGroups.Recommended, kind: vscode_1.QuickPickItemKind.Separator }, recommended); } let previousGroup = EnvGroups.Recommended; for (const item of items) { previousGroup = addSeparatorIfApplicable(updatedItems, item, workspacePath, previousGroup); updatedItems.push(item); } return updatedItems; } function addSeparatorIfApplicable(items, newItem, workspacePath, previousGroup) { if (!previousGroup) { const lastItem = items.length ? items[items.length - 1] : undefined; previousGroup = lastItem && isInterpreterQuickPickItem(lastItem) ? getGroup(lastItem, workspacePath) : undefined; } const currentGroup = getGroup(newItem, workspacePath); if (!previousGroup || currentGroup !== previousGroup) { const separatorItem = { label: currentGroup, kind: vscode_1.QuickPickItemKind.Separator }; items.push(separatorItem); previousGroup = currentGroup; } return previousGroup; } function getGroup(item, workspacePath) { if (workspacePath && (0, fs_paths_1.isParentPath)(item.path, workspacePath)) { return EnvGroups.Workspace; } const envType = (0, utils_1.getEnvironmentType)(item.interpreter); switch (envType) { case info_1.EnvironmentType.Global: case info_1.EnvironmentType.System: case info_1.EnvironmentType.Unknown: case info_1.EnvironmentType.MicrosoftStore: return EnvGroups.Global; default: return EnvGroups[envType]; } } /***/ }), /***/ "./src/client/interpreter/configuration/interpreterSelector/interpreterSelector.ts": /*!*****************************************************************************************!*\ !*** ./src/client/interpreter/configuration/interpreterSelector/interpreterSelector.ts ***! \*****************************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InterpreterSelector = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const path_1 = __webpack_require__(/*! path */ "path"); const types_1 = __webpack_require__(/*! ../../../common/types */ "./src/client/common/types.ts"); const types_2 = __webpack_require__(/*! ../types */ "./src/client/interpreter/configuration/types.ts"); let InterpreterSelector = class InterpreterSelector { constructor(envTypeComparer, pathUtils) { this.envTypeComparer = envTypeComparer; this.pathUtils = pathUtils; this.disposables = []; } dispose() { this.disposables.forEach((disposable) => disposable.dispose()); } getSuggestions(api, resource, useFullDisplayName = false) { const interpreters = api.environments.known.slice(); interpreters.sort(this.envTypeComparer.compareV2.bind(this.envTypeComparer)); return interpreters.map((item) => this.suggestionToQuickPickItem(item, resource, useFullDisplayName)); } suggestionToQuickPickItem(interpreter, workspaceUri, _useDetailedName = false) { var _a, _b, _c, _d, _e, _f, _g; const path = ((_b = (_a = interpreter.environment) === null || _a === void 0 ? void 0 : _a.folderUri) === null || _b === void 0 ? void 0 : _b.fsPath) || ((_d = (_c = interpreter.executable) === null || _c === void 0 ? void 0 : _c.uri) === null || _d === void 0 ? void 0 : _d.fsPath) || interpreter.path; const detail = this.pathUtils.getDisplayName(path, workspaceUri ? workspaceUri.fsPath : undefined); const version = ((_e = interpreter.version) === null || _e === void 0 ? void 0 : _e.major) ? `${interpreter.version.major}.${interpreter.version.minor}.${interpreter.version.micro}` : ''; const displayVersion = version ? ` (${version})` : ''; const pythonDisplayName = `Python${displayVersion}`; const envName = ((_f = interpreter.environment) === null || _f === void 0 ? void 0 : _f.name) || (((_g = interpreter.environment) === null || _g === void 0 ? void 0 : _g.folderUri) ? (0, path_1.dirname)(interpreter.environment.folderUri.fsPath) : undefined); return { label: envName ? `${envName} (${pythonDisplayName})` : pythonDisplayName, description: detail || '', path, interpreter, }; } getRecommendedSuggestion(_suggestions, _resource) { return undefined; } }; InterpreterSelector = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_2.IInterpreterComparer)), __param(1, (0, inversify_1.inject)(types_1.IPathUtils)) ], InterpreterSelector); exports.InterpreterSelector = InterpreterSelector; /***/ }), /***/ "./src/client/interpreter/configuration/types.ts": /*!*******************************************************!*\ !*** ./src/client/interpreter/configuration/types.ts ***! \*******************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.IInterpreterQuickPick = exports.IInterpreterComparer = exports.IInterpreterSelector = void 0; exports.IInterpreterSelector = Symbol('IInterpreterSelector'); exports.IInterpreterComparer = Symbol('IInterpreterComparer'); exports.IInterpreterQuickPick = Symbol('IInterpreterQuickPick'); /***/ }), /***/ "./src/client/interpreter/contracts.ts": /*!*********************************************!*\ !*** ./src/client/interpreter/contracts.ts ***! \*********************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.IActivatedEnvironmentLaunch = exports.IInterpreterStatusbarVisibilityFilter = exports.IInterpreterHelper = exports.IInterpreterService = exports.ICondaService = exports.IComponentAdapter = void 0; exports.IComponentAdapter = Symbol('IComponentAdapter'); exports.ICondaService = Symbol('ICondaService'); exports.IInterpreterService = Symbol('IInterpreterService'); exports.IInterpreterHelper = Symbol('IInterpreterHelper'); exports.IInterpreterStatusbarVisibilityFilter = Symbol('IInterpreterStatusbarVisibilityFilter'); exports.IActivatedEnvironmentLaunch = Symbol('IActivatedEnvironmentLaunch'); /***/ }), /***/ "./src/client/interpreter/helpers.ts": /*!*******************************************!*\ !*** ./src/client/interpreter/helpers.ts ***! \*******************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InterpreterHelper = exports.isInterpreterLocatedInWorkspace = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const types_1 = __webpack_require__(/*! ../common/application/types */ "./src/client/common/application/types.ts"); const fs_paths_1 = __webpack_require__(/*! ../common/platform/fs-paths */ "./src/client/common/platform/fs-paths.ts"); const types_2 = __webpack_require__(/*! ../ioc/types */ "./src/client/ioc/types.ts"); const pythonVersion_1 = __webpack_require__(/*! ../pythonEnvironments/base/info/pythonVersion */ "./src/client/pythonEnvironments/base/info/pythonVersion.ts"); const info_1 = __webpack_require__(/*! ../pythonEnvironments/info */ "./src/client/pythonEnvironments/info/index.ts"); const contracts_1 = __webpack_require__(/*! ./contracts */ "./src/client/interpreter/contracts.ts"); function isInterpreterLocatedInWorkspace(interpreter, activeWorkspaceUri) { const fileSystemPaths = fs_paths_1.FileSystemPaths.withDefaults(); const interpreterPath = fileSystemPaths.normCase(interpreter.path); const resourcePath = fileSystemPaths.normCase(activeWorkspaceUri.fsPath); return interpreterPath.startsWith(resourcePath); } exports.isInterpreterLocatedInWorkspace = isInterpreterLocatedInWorkspace; function sortInterpreters(interpreters) { if (interpreters.length === 0) { return []; } if (interpreters.length === 1) { return [interpreters[0]]; } const sorted = interpreters.slice(); sorted.sort((a, b) => (a.version && b.version ? (0, pythonVersion_1.compareSemVerLikeVersions)(a.version, b.version) : 0)); return sorted; } let InterpreterHelper = class InterpreterHelper { constructor(serviceContainer, pyenvs) { this.serviceContainer = serviceContainer; this.pyenvs = pyenvs; } getActiveWorkspaceUri(resource) { var _a; const workspaceService = this.serviceContainer.get(types_1.IWorkspaceService); const hasWorkspaceFolders = (((_a = workspaceService.workspaceFolders) === null || _a === void 0 ? void 0 : _a.length) || 0) > 0; if (!hasWorkspaceFolders) { return; } if (Array.isArray(workspaceService.workspaceFolders) && workspaceService.workspaceFolders.length === 1) { return { folderUri: workspaceService.workspaceFolders[0].uri, configTarget: vscode_1.ConfigurationTarget.Workspace }; } if (resource) { const workspaceFolder = workspaceService.getWorkspaceFolder(resource); if (workspaceFolder) { return { configTarget: vscode_1.ConfigurationTarget.WorkspaceFolder, folderUri: workspaceFolder.uri }; } } const documentManager = this.serviceContainer.get(types_1.IDocumentManager); if (documentManager.activeTextEditor) { const workspaceFolder = workspaceService.getWorkspaceFolder(documentManager.activeTextEditor.document.uri); if (workspaceFolder) { return { configTarget: vscode_1.ConfigurationTarget.WorkspaceFolder, folderUri: workspaceFolder.uri }; } } } async getInterpreterInformation(pythonPath) { return this.pyenvs.getInterpreterInformation(pythonPath); } async getInterpreters({ resource, source } = {}) { const interpreters = await this.pyenvs.getInterpreters(resource, source); return sortInterpreters(interpreters); } async getInterpreterPath(pythonPath) { const interpreterInfo = await this.getInterpreterInformation(pythonPath); if (interpreterInfo) { return interpreterInfo.path; } else { return pythonPath; } } async isMacDefaultPythonPath(pythonPath) { return this.pyenvs.isMacDefaultPythonPath(pythonPath); } getInterpreterTypeDisplayName(interpreterType) { return (0, info_1.getEnvironmentTypeName)(interpreterType); } getBestInterpreter(interpreters) { if (!Array.isArray(interpreters) || interpreters.length === 0) { return; } const sorted = sortInterpreters(interpreters); return sorted[sorted.length - 1]; } }; InterpreterHelper = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_2.IServiceContainer)), __param(1, (0, inversify_1.inject)(contracts_1.IComponentAdapter)) ], InterpreterHelper); exports.InterpreterHelper = InterpreterHelper; /***/ }), /***/ "./src/client/interpreter/interpreterService.ts": /*!******************************************************!*\ !*** ./src/client/interpreter/interpreterService.ts ***! \******************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InterpreterService = void 0; const python_extension_1 = __webpack_require__(/*! @vscode/python-extension */ "./node_modules/@vscode/python-extension/out/main.js"); const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); __webpack_require__(/*! ../common/extensions */ "./src/client/common/extensions.ts"); const contracts_1 = __webpack_require__(/*! ./contracts */ "./src/client/interpreter/contracts.ts"); let InterpreterService = class InterpreterService { constructor(pyenvs) { this.pyenvs = pyenvs; this.didChangeInterpreterEmitter = new vscode_1.EventEmitter(); python_extension_1.PythonExtension.api().then((api) => api.environments.onDidChangeActiveEnvironmentPath((e) => { var _a; this.didChangeInterpreterEmitter.fire((_a = e.resource) === null || _a === void 0 ? void 0 : _a.uri); })); } get onDidChangeInterpreter() { return this.didChangeInterpreterEmitter.event; } getInterpreters(resource) { return this.pyenvs.getInterpreters(resource); } dispose() { this.didChangeInterpreterEmitter.dispose(); } async getActiveInterpreter(resource) { const api = await python_extension_1.PythonExtension.api(); const pythonPath = await api.environments.getActiveEnvironmentPath(resource); return pythonPath ? this.getInterpreterDetails(pythonPath.path) : undefined; } async getInterpreterDetails(pythonPath) { return this.pyenvs.getInterpreterDetails(pythonPath); } }; InterpreterService = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(contracts_1.IComponentAdapter)) ], InterpreterService); exports.InterpreterService = InterpreterService; /***/ }), /***/ "./src/client/interpreter/serviceRegistry.ts": /*!***************************************************!*\ !*** ./src/client/interpreter/serviceRegistry.ts ***! \***************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.registerTypes = void 0; const service_1 = __webpack_require__(/*! ./activation/service */ "./src/client/interpreter/activation/service.ts"); const types_1 = __webpack_require__(/*! ./activation/types */ "./src/client/interpreter/activation/types.ts"); const environmentTypeComparer_1 = __webpack_require__(/*! ./configuration/environmentTypeComparer */ "./src/client/interpreter/configuration/environmentTypeComparer.ts"); const setInterpreter_1 = __webpack_require__(/*! ./configuration/interpreterSelector/commands/setInterpreter */ "./src/client/interpreter/configuration/interpreterSelector/commands/setInterpreter.ts"); const interpreterSelector_1 = __webpack_require__(/*! ./configuration/interpreterSelector/interpreterSelector */ "./src/client/interpreter/configuration/interpreterSelector/interpreterSelector.ts"); const types_2 = __webpack_require__(/*! ./configuration/types */ "./src/client/interpreter/configuration/types.ts"); const contracts_1 = __webpack_require__(/*! ./contracts */ "./src/client/interpreter/contracts.ts"); const helpers_1 = __webpack_require__(/*! ./helpers */ "./src/client/interpreter/helpers.ts"); const interpreterService_1 = __webpack_require__(/*! ./interpreterService */ "./src/client/interpreter/interpreterService.ts"); function registerInterpreterTypes(serviceManager) { serviceManager.addSingleton(contracts_1.IInterpreterService, interpreterService_1.InterpreterService); serviceManager.addSingleton(types_2.IInterpreterSelector, interpreterSelector_1.InterpreterSelector); serviceManager.addSingleton(types_2.IInterpreterQuickPick, setInterpreter_1.SetInterpreterCommand); serviceManager.addSingleton(contracts_1.IInterpreterHelper, helpers_1.InterpreterHelper); serviceManager.addSingleton(types_2.IInterpreterComparer, environmentTypeComparer_1.EnvironmentTypeComparer); } function registerTypes(serviceManager) { registerInterpreterTypes(serviceManager); serviceManager.addSingleton(service_1.EnvironmentActivationService, service_1.EnvironmentActivationService); serviceManager.addSingleton(types_1.IEnvironmentActivationService, service_1.EnvironmentActivationService); } exports.registerTypes = registerTypes; /***/ }), /***/ "./src/client/ioc/container.ts": /*!*************************************!*\ !*** ./src/client/ioc/container.ts ***! \*************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ServiceContainer = void 0; const events_1 = __webpack_require__(/*! events */ "events"); const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const logging_1 = __webpack_require__(/*! ../logging */ "./src/client/logging/index.ts"); try { (0, inversify_1.decorate)((0, inversify_1.injectable)(), events_1.EventEmitter); } catch (ex) { (0, logging_1.traceWarn)('Failed to decorate EventEmitter for DI (possibly already decorated by another Extension)', ex); } let ServiceContainer = class ServiceContainer { constructor(container) { this.container = container; } get(serviceIdentifier, name) { return name ? this.container.getNamed(serviceIdentifier, name) : this.container.get(serviceIdentifier); } getAll(serviceIdentifier, name) { return name ? this.container.getAllNamed(serviceIdentifier, name) : this.container.getAll(serviceIdentifier); } tryGet(serviceIdentifier, name) { try { return name ? this.container.getNamed(serviceIdentifier, name) : this.container.get(serviceIdentifier); } catch (_a) { } return undefined; } }; ServiceContainer = __decorate([ (0, inversify_1.injectable)() ], ServiceContainer); exports.ServiceContainer = ServiceContainer; /***/ }), /***/ "./src/client/ioc/serviceManager.ts": /*!******************************************!*\ !*** ./src/client/ioc/serviceManager.ts ***! \******************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ServiceManager = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); let ServiceManager = class ServiceManager { constructor(container) { this.container = container; } add(serviceIdentifier, constructor, name, bindings) { if (name) { this.container.bind(serviceIdentifier).to(constructor).whenTargetNamed(name); } else { this.container.bind(serviceIdentifier).to(constructor); } if (bindings) { bindings.forEach((binding) => { this.addBinding(serviceIdentifier, binding); }); } } addFactory(factoryIdentifier, factoryMethod) { this.container.bind(factoryIdentifier).toFactory(factoryMethod); } addBinding(from, to) { this.container.bind(to).toService(from); } addSingleton(serviceIdentifier, constructor, name, bindings) { if (name) { this.container.bind(serviceIdentifier).to(constructor).inSingletonScope().whenTargetNamed(name); } else { this.container.bind(serviceIdentifier).to(constructor).inSingletonScope(); } if (bindings) { bindings.forEach((binding) => { this.addBinding(serviceIdentifier, binding); }); } } addSingletonInstance(serviceIdentifier, instance, name) { if (name) { this.container.bind(serviceIdentifier).toConstantValue(instance).whenTargetNamed(name); } else { this.container.bind(serviceIdentifier).toConstantValue(instance); } } get(serviceIdentifier, name) { return name ? this.container.getNamed(serviceIdentifier, name) : this.container.get(serviceIdentifier); } tryGet(serviceIdentifier, name) { try { return name ? this.container.getNamed(serviceIdentifier, name) : this.container.get(serviceIdentifier); } catch (_a) { } return undefined; } getAll(serviceIdentifier, name) { return name ? this.container.getAllNamed(serviceIdentifier, name) : this.container.getAll(serviceIdentifier); } rebind(serviceIdentifier, constructor, name) { if (name) { this.container.rebind(serviceIdentifier).to(constructor).whenTargetNamed(name); } else { this.container.rebind(serviceIdentifier).to(constructor); } } rebindSingleton(serviceIdentifier, constructor, name) { if (name) { this.container.rebind(serviceIdentifier).to(constructor).inSingletonScope().whenTargetNamed(name); } else { this.container.rebind(serviceIdentifier).to(constructor).inSingletonScope(); } } rebindInstance(serviceIdentifier, instance, name) { if (name) { this.container.rebind(serviceIdentifier).toConstantValue(instance).whenTargetNamed(name); } else { this.container.rebind(serviceIdentifier).toConstantValue(instance); } } dispose() { this.container.unbindAll(); this.container.unload(); } }; ServiceManager = __decorate([ (0, inversify_1.injectable)() ], ServiceManager); exports.ServiceManager = ServiceManager; /***/ }), /***/ "./src/client/ioc/types.ts": /*!*********************************!*\ !*** ./src/client/ioc/types.ts ***! \*********************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.IServiceContainer = exports.IServiceManager = void 0; exports.IServiceManager = Symbol('IServiceManager'); exports.IServiceContainer = Symbol('IServiceContainer'); /***/ }), /***/ "./src/client/logging/index.ts": /*!*************************************!*\ !*** ./src/client/logging/index.ts ***! \*************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.logTo = exports.traceDecoratorWarn = exports.traceDecoratorInfo = exports.traceDecoratorError = exports.traceDecoratorVerbose = exports.traceVerbose = exports.traceInfo = exports.traceWarn = exports.traceError = exports.traceLog = exports.registerLogger = void 0; const internal_compatibility_1 = __webpack_require__(/*! rxjs/internal-compatibility */ "./node_modules/rxjs/_esm5/internal-compatibility/index.js"); const stopWatch_1 = __webpack_require__(/*! ../common/utils/stopWatch */ "./src/client/common/utils/stopWatch.ts"); const telemetry_1 = __webpack_require__(/*! ../telemetry */ "./src/client/telemetry/index.ts"); const types_1 = __webpack_require__(/*! ./types */ "./src/client/logging/types.ts"); const util_1 = __webpack_require__(/*! ./util */ "./src/client/logging/util.ts"); const DEFAULT_OPTS = types_1.TraceOptions.Arguments | types_1.TraceOptions.ReturnValue; let loggers = []; function registerLogger(logger) { loggers.push(logger); return { dispose: () => { loggers = loggers.filter((l) => l !== logger); }, }; } exports.registerLogger = registerLogger; function traceLog(...args) { loggers.forEach((l) => l.traceLog(...args)); } exports.traceLog = traceLog; function traceError(...args) { loggers.forEach((l) => l.traceError(...args)); } exports.traceError = traceError; function traceWarn(...args) { loggers.forEach((l) => l.traceWarn(...args)); } exports.traceWarn = traceWarn; function traceInfo(...args) { loggers.forEach((l) => l.traceInfo(...args)); } exports.traceInfo = traceInfo; function traceVerbose(...args) { loggers.forEach((l) => l.traceVerbose(...args)); } exports.traceVerbose = traceVerbose; function traceDecoratorVerbose(message, opts = DEFAULT_OPTS) { return createTracingDecorator({ message, opts, level: types_1.LogLevel.Debug }); } exports.traceDecoratorVerbose = traceDecoratorVerbose; function traceDecoratorError(message) { return createTracingDecorator({ message, opts: DEFAULT_OPTS, level: types_1.LogLevel.Error }); } exports.traceDecoratorError = traceDecoratorError; function traceDecoratorInfo(message) { return createTracingDecorator({ message, opts: DEFAULT_OPTS, level: types_1.LogLevel.Info }); } exports.traceDecoratorInfo = traceDecoratorInfo; function traceDecoratorWarn(message) { return createTracingDecorator({ message, opts: DEFAULT_OPTS, level: types_1.LogLevel.Warning }); } exports.traceDecoratorWarn = traceDecoratorWarn; function traceDecorator(log) { return function (_, __, descriptor) { const originalMethod = descriptor.value; descriptor.value = function (...args) { const call = { kind: 'Class', name: _ && _.constructor ? _.constructor.name : '', args, }; const scope = this; return tracing((t) => log(call, t), () => originalMethod.apply(scope, args)); }; return descriptor; }; } function tracing(log, run) { const timer = new stopWatch_1.StopWatch(); try { const result = run(); if ((0, internal_compatibility_1.isPromise)(result)) { result .then((data) => { log({ elapsed: timer.elapsedTime, returnValue: data }); return data; }) .catch((ex) => { log({ elapsed: timer.elapsedTime, err: ex }); }); } else { log({ elapsed: timer.elapsedTime, returnValue: result }); } return result; } catch (ex) { log({ elapsed: timer.elapsedTime, err: ex }); throw ex; } } function createTracingDecorator(logInfo) { return traceDecorator((call, traced) => logResult(logInfo, traced, call)); } function normalizeCall(call) { let { kind, name, args } = call; if (!kind || kind === '') { kind = 'Function'; } if (!name || name === '') { name = ''; } if (!args) { args = []; } return { kind, name, args }; } function formatMessages(logInfo, traced, call) { call = normalizeCall(call); const messages = [logInfo.message]; messages.push(`${call.kind} name = ${call.name}`.trim(), `completed in ${traced.elapsed}ms`, `has a ${traced.returnValue ? 'truthy' : 'falsy'} return value`); if ((logInfo.opts & types_1.TraceOptions.Arguments) === types_1.TraceOptions.Arguments) { messages.push((0, util_1.argsToLogString)(call.args)); } if ((logInfo.opts & types_1.TraceOptions.ReturnValue) === types_1.TraceOptions.ReturnValue) { messages.push((0, util_1.returnValueToLogString)(traced.returnValue)); } return messages.join(', '); } function logResult(logInfo, traced, call) { const formatted = formatMessages(logInfo, traced, call); if (traced.err === undefined) { if (!logInfo.level || logInfo.level > types_1.LogLevel.Error) { logTo(types_1.LogLevel.Info, [formatted]); } } else { logTo(types_1.LogLevel.Error, [formatted, traced.err]); (0, telemetry_1.sendTelemetryEvent)('ERROR', undefined, undefined, traced.err); } } function logTo(logLevel, ...args) { switch (logLevel) { case types_1.LogLevel.Error: traceError(...args); break; case types_1.LogLevel.Warning: traceWarn(...args); break; case types_1.LogLevel.Info: traceInfo(...args); break; case types_1.LogLevel.Debug: traceVerbose(...args); break; default: break; } } exports.logTo = logTo; /***/ }), /***/ "./src/client/logging/outputChannelLogger.ts": /*!***************************************************!*\ !*** ./src/client/logging/outputChannelLogger.ts ***! \***************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OutputChannelLogger = void 0; const util = __webpack_require__(/*! util */ "util"); class OutputChannelLogger { constructor(channel) { this.channel = channel; } traceLog(...data) { this.channel.appendLine(util.format(...data)); } traceError(...data) { this.channel.appendLine(`Error: ${util.format(...data)}`); } traceWarn(...data) { this.channel.appendLine(`Warn: ${util.format(...data)}`); } traceInfo(...data) { this.channel.appendLine(`Info: ${util.format(...data)}`); } traceVerbose(...data) { this.channel.appendLine(`Debug: ${util.format(...data)}`); } } exports.OutputChannelLogger = OutputChannelLogger; /***/ }), /***/ "./src/client/logging/types.ts": /*!*************************************!*\ !*** ./src/client/logging/types.ts ***! \*************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TraceOptions = exports.LogLevel = void 0; var LogLevel; (function (LogLevel) { LogLevel[LogLevel["Off"] = 0] = "Off"; LogLevel[LogLevel["Trace"] = 1] = "Trace"; LogLevel[LogLevel["Debug"] = 2] = "Debug"; LogLevel[LogLevel["Info"] = 3] = "Info"; LogLevel[LogLevel["Warning"] = 4] = "Warning"; LogLevel[LogLevel["Error"] = 5] = "Error"; })(LogLevel = exports.LogLevel || (exports.LogLevel = {})); var TraceOptions; (function (TraceOptions) { TraceOptions[TraceOptions["None"] = 0] = "None"; TraceOptions[TraceOptions["Arguments"] = 1] = "Arguments"; TraceOptions[TraceOptions["ReturnValue"] = 2] = "ReturnValue"; })(TraceOptions = exports.TraceOptions || (exports.TraceOptions = {})); /***/ }), /***/ "./src/client/logging/util.ts": /*!************************************!*\ !*** ./src/client/logging/util.ts ***! \************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.returnValueToLogString = exports.argsToLogString = void 0; function valueToLogString(value, kind) { if (value === undefined) { return 'undefined'; } if (value === null) { return 'null'; } try { if (value && value.fsPath) { return ``; } return JSON.stringify(value); } catch (_a) { return `<${kind} cannot be serialized for logging>`; } } function argsToLogString(args) { if (!args) { return ''; } try { const argStrings = args.map((item, index) => { const valueString = valueToLogString(item, 'argument'); return `Arg ${index + 1}: ${valueString}`; }); return argStrings.join(', '); } catch (_a) { return ''; } } exports.argsToLogString = argsToLogString; function returnValueToLogString(returnValue) { const valueString = valueToLogString(returnValue, 'Return value'); return `Return Value: ${valueString}`; } exports.returnValueToLogString = returnValueToLogString; /***/ }), /***/ "./src/client/pythonEnvironments/api.ts": /*!**********************************************!*\ !*** ./src/client/pythonEnvironments/api.ts ***! \**********************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createPythonEnvironments = void 0; class PythonEnvironments { constructor(getLocator) { this.getLocator = getLocator; } async activate() { this.locator = await this.getLocator(); } get onProgress() { return this.locator.onProgress; } get refreshState() { return this.locator.refreshState; } getRefreshPromise(options) { return this.locator.getRefreshPromise(options); } get onChanged() { return this.locator.onChanged; } getEnvs(query) { return this.locator.getEnvs(query); } async resolveEnv(env) { return this.locator.resolveEnv(env); } async triggerRefresh(query, options) { return this.locator.triggerRefresh(query, options); } } async function createPythonEnvironments(getLocator) { const api = new PythonEnvironments(getLocator); await api.activate(); return api; } exports.createPythonEnvironments = createPythonEnvironments; /***/ }), /***/ "./src/client/pythonEnvironments/base/info/env.ts": /*!********************************************************!*\ !*** ./src/client/pythonEnvironments/base/info/env.ts ***! \********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.comparePythonVersionSpecificity = exports.areSameEnv = exports.getEnvID = exports.getEnvPath = exports.setEnvDisplayString = exports.copyEnvInfo = exports.areEnvsDeepEqual = exports.buildEnvInfo = void 0; const lodash_1 = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js"); const path = __webpack_require__(/*! path */ "path"); const registry_1 = __webpack_require__(/*! ../../../common/platform/registry */ "./src/client/common/platform/registry.ts"); const platform_1 = __webpack_require__(/*! ../../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const externalDependencies_1 = __webpack_require__(/*! ../../common/externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const envKind_1 = __webpack_require__(/*! ./envKind */ "./src/client/pythonEnvironments/base/info/envKind.ts"); const pythonVersion_1 = __webpack_require__(/*! ./pythonVersion */ "./src/client/pythonEnvironments/base/info/pythonVersion.ts"); const _1 = __webpack_require__(/*! . */ "./src/client/pythonEnvironments/base/info/index.ts"); function buildEnvInfo(init) { var _a, _b, _c, _d, _e, _f, _g, _h, _j; const env = { name: (_a = init === null || init === void 0 ? void 0 : init.name) !== null && _a !== void 0 ? _a : '', location: '', kind: _1.PythonEnvKind.Unknown, executable: { filename: '', sysPrefix: (_b = init === null || init === void 0 ? void 0 : init.sysPrefix) !== null && _b !== void 0 ? _b : '', ctime: (_d = (_c = init === null || init === void 0 ? void 0 : init.fileInfo) === null || _c === void 0 ? void 0 : _c.ctime) !== null && _d !== void 0 ? _d : -1, mtime: (_f = (_e = init === null || init === void 0 ? void 0 : init.fileInfo) === null || _e === void 0 ? void 0 : _e.mtime) !== null && _f !== void 0 ? _f : -1, }, searchLocation: undefined, display: init === null || init === void 0 ? void 0 : init.display, version: { major: -1, minor: -1, micro: -1, release: { level: _1.PythonReleaseLevel.Final, serial: 0, }, }, arch: (_g = init === null || init === void 0 ? void 0 : init.arch) !== null && _g !== void 0 ? _g : platform_1.Architecture.Unknown, distro: { org: (_h = init === null || init === void 0 ? void 0 : init.org) !== null && _h !== void 0 ? _h : '', }, source: (_j = init === null || init === void 0 ? void 0 : init.source) !== null && _j !== void 0 ? _j : [], }; if (init !== undefined) { updateEnv(env, init); } env.id = getEnvID(env.executable.filename, env.location); return env; } exports.buildEnvInfo = buildEnvInfo; function areEnvsDeepEqual(env1, env2) { var _a, _b, _c, _d, _e, _f, _g, _h; const env1Clone = (0, lodash_1.cloneDeep)(env1); const env2Clone = (0, lodash_1.cloneDeep)(env2); delete env1Clone.searchLocation; delete env2Clone.searchLocation; env1Clone.source = env1Clone.source.sort(); env2Clone.source = env2Clone.source.sort(); const searchLocation1 = (_b = (_a = env1.searchLocation) === null || _a === void 0 ? void 0 : _a.fsPath) !== null && _b !== void 0 ? _b : ''; const searchLocation2 = (_d = (_c = env2.searchLocation) === null || _c === void 0 ? void 0 : _c.fsPath) !== null && _d !== void 0 ? _d : ''; const searchLocation1Scheme = (_f = (_e = env1.searchLocation) === null || _e === void 0 ? void 0 : _e.scheme) !== null && _f !== void 0 ? _f : ''; const searchLocation2Scheme = (_h = (_g = env2.searchLocation) === null || _g === void 0 ? void 0 : _g.scheme) !== null && _h !== void 0 ? _h : ''; return ((0, lodash_1.isEqual)(env1Clone, env2Clone) && (0, externalDependencies_1.arePathsSame)(searchLocation1, searchLocation2) && searchLocation1Scheme === searchLocation2Scheme); } exports.areEnvsDeepEqual = areEnvsDeepEqual; function copyEnvInfo(env, updates) { const copied = (0, lodash_1.cloneDeep)(env); if (updates !== undefined) { updateEnv(copied, updates); } return copied; } exports.copyEnvInfo = copyEnvInfo; function updateEnv(env, updates) { if (updates.kind !== undefined) { env.kind = updates.kind; } if (updates.executable !== undefined) { env.executable.filename = updates.executable; } if (updates.location !== undefined) { env.location = updates.location; } if (updates.version !== undefined) { env.version = updates.version; } if (updates.searchLocation !== undefined) { env.searchLocation = updates.searchLocation; } if (updates.type !== undefined) { env.type = updates.type; } } function setEnvDisplayString(env) { env.display = buildEnvDisplayString(env); env.detailedDisplayName = buildEnvDisplayString(env, true); } exports.setEnvDisplayString = setEnvDisplayString; function buildEnvDisplayString(env, getAllDetails = false) { const shouldDisplayKind = getAllDetails || env.searchLocation || _1.globallyInstalledEnvKinds.includes(env.kind); const shouldDisplayArch = !_1.virtualEnvKinds.includes(env.kind); const displayNameParts = ['Python']; if (env.version && !(0, pythonVersion_1.isVersionEmpty)(env.version)) { displayNameParts.push((0, pythonVersion_1.getVersionDisplayString)(env.version)); } if (shouldDisplayArch) { const archName = (0, registry_1.getArchitectureDisplayName)(env.arch); if (archName !== '') { displayNameParts.push(archName); } } const envSuffixParts = []; if (env.name && env.name !== '') { envSuffixParts.push(`'${env.name}'`); } if (shouldDisplayKind) { const kindName = (0, envKind_1.getKindDisplayName)(env.kind); if (kindName !== '') { envSuffixParts.push(kindName); } } const envSuffix = envSuffixParts.length === 0 ? '' : `(${envSuffixParts.join(': ')})`; return `${displayNameParts.join(' ')} ${envSuffix}`.trim(); } function getMinimalPartialInfo(env) { if (typeof env === 'string') { if (env === '') { return undefined; } return { id: '', executable: { filename: env, sysPrefix: '', ctime: -1, mtime: -1, }, }; } if ('executablePath' in env) { return { id: '', executable: { filename: env.executablePath, sysPrefix: '', ctime: -1, mtime: -1, }, location: env.envPath, kind: env.kind, source: env.source, }; } return env; } function getEnvPath(interpreterPath, envFolderPath) { let envPath = { path: interpreterPath, pathType: 'interpreterPath' }; if (envFolderPath && !(0, externalDependencies_1.isParentPath)(interpreterPath, envFolderPath)) { envPath = { path: envFolderPath, pathType: 'envFolderPath' }; } return envPath; } exports.getEnvPath = getEnvPath; function getEnvID(interpreterPath, envFolderPath) { return (0, externalDependencies_1.normCasePath)(getEnvPath(interpreterPath, envFolderPath).path); } exports.getEnvID = getEnvID; function areSameEnv(left, right, allowPartialMatch = true) { const leftInfo = getMinimalPartialInfo(left); const rightInfo = getMinimalPartialInfo(right); if (leftInfo === undefined || rightInfo === undefined) { return undefined; } const leftFilename = leftInfo.executable.filename; const rightFilename = rightInfo.executable.filename; if (leftInfo.id && leftInfo.id === rightInfo.id) { return true; } if (getEnvID(leftFilename, leftInfo.location) === getEnvID(rightFilename, rightInfo.location)) { return true; } if (allowPartialMatch) { const isSameDirectory = leftFilename !== 'python' && rightFilename !== 'python' && (0, externalDependencies_1.arePathsSame)(path.dirname(leftFilename), path.dirname(rightFilename)); if (isSameDirectory) { const leftVersion = typeof left === 'string' ? undefined : leftInfo.version; const rightVersion = typeof right === 'string' ? undefined : rightInfo.version; if (leftVersion && rightVersion) { if ((0, pythonVersion_1.areIdenticalVersion)(leftVersion, rightVersion) || (0, pythonVersion_1.areSimilarVersions)(leftVersion, rightVersion)) { return true; } } } } return false; } exports.areSameEnv = areSameEnv; function getPythonVersionSpecificity(version) { var _a, _b; let infoLevel = 0; if (version.major > 0) { infoLevel += 20; } if (version.minor >= 0) { infoLevel += 10; } if (version.micro >= 0) { infoLevel += 5; } if ((_a = version.release) === null || _a === void 0 ? void 0 : _a.level) { infoLevel += 3; } if (((_b = version.release) === null || _b === void 0 ? void 0 : _b.serial) || version.sysVersion) { infoLevel += 1; } return infoLevel; } function comparePythonVersionSpecificity(versionA, versionB) { return Math.sign(getPythonVersionSpecificity(versionA) - getPythonVersionSpecificity(versionB)); } exports.comparePythonVersionSpecificity = comparePythonVersionSpecificity; /***/ }), /***/ "./src/client/pythonEnvironments/base/info/envKind.ts": /*!************************************************************!*\ !*** ./src/client/pythonEnvironments/base/info/envKind.ts ***! \************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getPrioritizedEnvKinds = exports.getKindDisplayName = void 0; const _1 = __webpack_require__(/*! . */ "./src/client/pythonEnvironments/base/info/index.ts"); function getKindDisplayName(kind) { for (const [candidate, value] of [ [_1.PythonEnvKind.System, 'system'], [_1.PythonEnvKind.MicrosoftStore, 'microsoft store'], [_1.PythonEnvKind.Pyenv, 'pyenv'], [_1.PythonEnvKind.Poetry, 'poetry'], [_1.PythonEnvKind.Custom, 'custom'], [_1.PythonEnvKind.Venv, 'venv'], [_1.PythonEnvKind.VirtualEnv, 'virtualenv'], [_1.PythonEnvKind.VirtualEnvWrapper, 'virtualenv'], [_1.PythonEnvKind.Pipenv, 'pipenv'], [_1.PythonEnvKind.Conda, 'conda'], [_1.PythonEnvKind.ActiveState, 'ActiveState'], ]) { if (kind === candidate) { return value; } } return ''; } exports.getKindDisplayName = getKindDisplayName; function getPrioritizedEnvKinds() { return [ _1.PythonEnvKind.Pyenv, _1.PythonEnvKind.Conda, _1.PythonEnvKind.MicrosoftStore, _1.PythonEnvKind.Pipenv, _1.PythonEnvKind.Poetry, _1.PythonEnvKind.Venv, _1.PythonEnvKind.VirtualEnvWrapper, _1.PythonEnvKind.VirtualEnv, _1.PythonEnvKind.ActiveState, _1.PythonEnvKind.OtherVirtual, _1.PythonEnvKind.OtherGlobal, _1.PythonEnvKind.System, _1.PythonEnvKind.Custom, _1.PythonEnvKind.Unknown, ]; } exports.getPrioritizedEnvKinds = getPrioritizedEnvKinds; /***/ }), /***/ "./src/client/pythonEnvironments/base/info/environmentInfoService.ts": /*!***************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/info/environmentInfoService.ts ***! \***************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEnvironmentInfoService = exports.EnvironmentInfoServiceQueuePriority = void 0; const async_1 = __webpack_require__(/*! ../../../common/utils/async */ "./src/client/common/utils/async.ts"); const workerPool_1 = __webpack_require__(/*! ../../../common/utils/workerPool */ "./src/client/common/utils/workerPool.ts"); const interpreter_1 = __webpack_require__(/*! ./interpreter */ "./src/client/pythonEnvironments/base/info/interpreter.ts"); const exec_1 = __webpack_require__(/*! ../../exec */ "./src/client/pythonEnvironments/exec.ts"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); const conda_1 = __webpack_require__(/*! ../../common/environmentManagers/conda */ "./src/client/pythonEnvironments/common/environmentManagers/conda.ts"); const _1 = __webpack_require__(/*! . */ "./src/client/pythonEnvironments/base/info/index.ts"); const externalDependencies_1 = __webpack_require__(/*! ../../common/externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const scripts_1 = __webpack_require__(/*! ../../../common/process/internal/scripts */ "./src/client/common/process/internal/scripts/index.ts"); const platform_1 = __webpack_require__(/*! ../../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const pythonVersion_1 = __webpack_require__(/*! ./pythonVersion */ "./src/client/pythonEnvironments/base/info/pythonVersion.ts"); var EnvironmentInfoServiceQueuePriority; (function (EnvironmentInfoServiceQueuePriority) { EnvironmentInfoServiceQueuePriority[EnvironmentInfoServiceQueuePriority["Default"] = 0] = "Default"; EnvironmentInfoServiceQueuePriority[EnvironmentInfoServiceQueuePriority["High"] = 1] = "High"; })(EnvironmentInfoServiceQueuePriority = exports.EnvironmentInfoServiceQueuePriority || (exports.EnvironmentInfoServiceQueuePriority = {})); async function buildEnvironmentInfo(env, useIsolated = true) { const python = [env.executable.filename]; if (useIsolated) { python.push(...['-I', scripts_1.OUTPUT_MARKER_SCRIPT]); } else { python.push(...[scripts_1.OUTPUT_MARKER_SCRIPT]); } const interpreterInfo = await (0, interpreter_1.getInterpreterInfo)((0, exec_1.buildPythonExecInfo)(python, undefined, env.executable.filename)); return interpreterInfo; } async function buildEnvironmentInfoUsingCondaRun(env) { const conda = await conda_1.Conda.getConda(); const path = env.location.length ? env.location : env.executable.filename; const condaEnv = await (conda === null || conda === void 0 ? void 0 : conda.getCondaEnvironment(path)); if (!condaEnv) { return undefined; } const python = await (conda === null || conda === void 0 ? void 0 : conda.getRunPythonArgs(condaEnv, true, true)); if (!python) { return undefined; } const interpreterInfo = await (0, interpreter_1.getInterpreterInfo)((0, exec_1.buildPythonExecInfo)(python, undefined, env.executable.filename), conda_1.CONDA_ACTIVATION_TIMEOUT); return interpreterInfo; } class EnvironmentInfoService { constructor() { this.cache = new Map(); } dispose() { if (this.workerPool !== undefined) { this.workerPool.stop(); this.workerPool = undefined; } if (this.condaRunWorkerPool !== undefined) { this.condaRunWorkerPool.stop(); this.condaRunWorkerPool = undefined; } } async getEnvironmentInfo(env, priority) { const interpreterPath = env.executable.filename; const result = this.cache.get((0, externalDependencies_1.normCasePath)(interpreterPath)); if (result !== undefined) { return result.promise; } const deferred = (0, async_1.createDeferred)(); this.cache.set((0, externalDependencies_1.normCasePath)(interpreterPath), deferred); this._getEnvironmentInfo(env, priority) .then((r) => { deferred.resolve(r); }) .catch((ex) => { deferred.reject(ex); }); return deferred.promise; } async _getEnvironmentInfo(env, priority, retryOnce = true) { if (env.kind === _1.PythonEnvKind.Conda && env.executable.filename === 'python') { const emptyInterpreterInfo = { arch: platform_1.Architecture.Unknown, executable: { filename: 'python', ctime: -1, mtime: -1, sysPrefix: '', }, version: (0, pythonVersion_1.getEmptyVersion)(), }; return emptyInterpreterInfo; } if (this.workerPool === undefined) { this.workerPool = (0, workerPool_1.createRunningWorkerPool)(buildEnvironmentInfo); } let reason; let r = await addToQueue(this.workerPool, env, priority).catch((err) => { reason = err; return undefined; }); if (r === undefined) { const isCondaEnv = env.kind === _1.PythonEnvKind.Conda || (await (0, conda_1.isCondaEnvironment)(env.executable.filename)); if (isCondaEnv) { (0, logging_1.traceVerbose)(`Validating ${env.executable.filename} normally failed with error, falling back to using conda run: (${reason})`); if (this.condaRunWorkerPool === undefined) { this.condaRunWorkerPool = (0, workerPool_1.createRunningWorkerPool)(buildEnvironmentInfoUsingCondaRun); } r = await addToQueue(this.condaRunWorkerPool, env, priority).catch((err) => { (0, logging_1.traceError)(err); return undefined; }); } else if (reason) { if (reason.message.includes('Unknown option: -I') || reason.message.includes("ModuleNotFoundError: No module named 'encodings'")) { (0, logging_1.traceWarn)(reason); if (reason.message.includes('Unknown option: -I')) { (0, logging_1.traceError)('Support for Python 2.7 has been dropped by the Python extension so certain features may not work, upgrade to using Python 3.'); } return buildEnvironmentInfo(env, false).catch((err) => { (0, logging_1.traceError)(err); return undefined; }); } (0, logging_1.traceError)(reason); } } if (r === undefined && retryOnce) { return (0, async_1.sleep)(2000).then(() => this._getEnvironmentInfo(env, priority, false)); } return r; } resetInfo(searchLocation) { const searchLocationPath = searchLocation.fsPath; const keys = Array.from(this.cache.keys()); keys.forEach((key) => { if (key.startsWith((0, externalDependencies_1.normCasePath)(searchLocationPath))) { this.cache.delete(key); } }); } } function addToQueue(workerPool, env, priority) { return priority === EnvironmentInfoServiceQueuePriority.High ? workerPool.addToQueue(env, workerPool_1.QueuePosition.Front) : workerPool.addToQueue(env, workerPool_1.QueuePosition.Back); } let envInfoService; function getEnvironmentInfoService(disposables) { if (envInfoService === undefined) { const service = new EnvironmentInfoService(); disposables === null || disposables === void 0 ? void 0 : disposables.push({ dispose: () => { service.dispose(); envInfoService = undefined; }, }); envInfoService = service; } return envInfoService; } exports.getEnvironmentInfoService = getEnvironmentInfoService; /***/ }), /***/ "./src/client/pythonEnvironments/base/info/executable.ts": /*!***************************************************************!*\ !*** ./src/client/pythonEnvironments/base/info/executable.ts ***! \***************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseVersionFromExecutable = void 0; const path = __webpack_require__(/*! path */ "path"); const platform_1 = __webpack_require__(/*! ../../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const pythonVersion_1 = __webpack_require__(/*! ./pythonVersion */ "./src/client/pythonEnvironments/base/info/pythonVersion.ts"); const externalDependencies_1 = __webpack_require__(/*! ../../common/externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); function parseVersionFromExecutable(filename) { const version = parseBasename(path.basename(filename)); if (version.major === 2 && version.minor === -1) { version.minor = 7; } return version; } exports.parseVersionFromExecutable = parseVersionFromExecutable; function parseBasename(basename) { basename = (0, externalDependencies_1.normCasePath)(basename); if ((0, platform_1.getOSType)() === platform_1.OSType.Windows) { if (basename === 'python.exe') { return (0, pythonVersion_1.getEmptyVersion)(); } } else if (basename === 'python') { return (0, pythonVersion_1.parseVersion)('2.7'); } if (!basename.startsWith('python')) { throw Error(`not a Python executable (expected "python..", got "${basename}")`); } return (0, pythonVersion_1.parseVersion)(basename); } /***/ }), /***/ "./src/client/pythonEnvironments/base/info/index.ts": /*!**********************************************************!*\ !*** ./src/client/pythonEnvironments/base/info/index.ts ***! \**********************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UNKNOWN_PYTHON_VERSION = exports.PythonReleaseLevel = exports.PythonEnvSource = exports.globallyInstalledEnvKinds = exports.virtualEnvKinds = exports.PythonEnvType = exports.PythonEnvKind = void 0; var PythonEnvKind; (function (PythonEnvKind) { PythonEnvKind["Unknown"] = "unknown"; PythonEnvKind["System"] = "global-system"; PythonEnvKind["MicrosoftStore"] = "global-microsoft-store"; PythonEnvKind["Pyenv"] = "global-pyenv"; PythonEnvKind["Poetry"] = "poetry"; PythonEnvKind["ActiveState"] = "activestate"; PythonEnvKind["Custom"] = "global-custom"; PythonEnvKind["OtherGlobal"] = "global-other"; PythonEnvKind["Venv"] = "virt-venv"; PythonEnvKind["VirtualEnv"] = "virt-virtualenv"; PythonEnvKind["VirtualEnvWrapper"] = "virt-virtualenvwrapper"; PythonEnvKind["Pipenv"] = "virt-pipenv"; PythonEnvKind["Conda"] = "virt-conda"; PythonEnvKind["OtherVirtual"] = "virt-other"; })(PythonEnvKind = exports.PythonEnvKind || (exports.PythonEnvKind = {})); var PythonEnvType; (function (PythonEnvType) { PythonEnvType["Conda"] = "Conda"; PythonEnvType["Virtual"] = "Virtual"; })(PythonEnvType = exports.PythonEnvType || (exports.PythonEnvType = {})); exports.virtualEnvKinds = [ PythonEnvKind.Poetry, PythonEnvKind.Pipenv, PythonEnvKind.Venv, PythonEnvKind.VirtualEnvWrapper, PythonEnvKind.Conda, PythonEnvKind.VirtualEnv, ]; exports.globallyInstalledEnvKinds = [ PythonEnvKind.OtherGlobal, PythonEnvKind.Unknown, PythonEnvKind.MicrosoftStore, PythonEnvKind.System, PythonEnvKind.Custom, ]; var PythonEnvSource; (function (PythonEnvSource) { PythonEnvSource["PathEnvVar"] = "path env var"; PythonEnvSource["WindowsRegistry"] = "windows registry"; })(PythonEnvSource = exports.PythonEnvSource || (exports.PythonEnvSource = {})); var PythonReleaseLevel; (function (PythonReleaseLevel) { PythonReleaseLevel["Alpha"] = "alpha"; PythonReleaseLevel["Beta"] = "beta"; PythonReleaseLevel["Candidate"] = "candidate"; PythonReleaseLevel["Final"] = "final"; })(PythonReleaseLevel = exports.PythonReleaseLevel || (exports.PythonReleaseLevel = {})); exports.UNKNOWN_PYTHON_VERSION = { major: -1, minor: -1, micro: -1, release: { level: PythonReleaseLevel.Final, serial: -1 }, sysVersion: undefined, }; Object.freeze(exports.UNKNOWN_PYTHON_VERSION); /***/ }), /***/ "./src/client/pythonEnvironments/base/info/interpreter.ts": /*!****************************************************************!*\ !*** ./src/client/pythonEnvironments/base/info/interpreter.ts ***! \****************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getInterpreterInfo = void 0; const constants_1 = __webpack_require__(/*! ../../../common/constants */ "./src/client/common/constants.ts"); const scripts_1 = __webpack_require__(/*! ../../../common/process/internal/scripts */ "./src/client/common/process/internal/scripts/index.ts"); const platform_1 = __webpack_require__(/*! ../../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); const externalDependencies_1 = __webpack_require__(/*! ../../common/externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const exec_1 = __webpack_require__(/*! ../../exec */ "./src/client/pythonEnvironments/exec.ts"); const pythonVersion_1 = __webpack_require__(/*! ./pythonVersion */ "./src/client/pythonEnvironments/base/info/pythonVersion.ts"); function extractInterpreterInfo(python, raw) { let rawVersion = `${raw.versionInfo.slice(0, 3).join('.')}`; if (raw.versionInfo[3] !== undefined && ['final', 'alpha', 'beta', 'candidate'].includes(raw.versionInfo[3])) { rawVersion = `${rawVersion}-${raw.versionInfo[3]}`; if (raw.versionInfo[4] !== undefined) { let serial = -1; try { serial = parseInt(`${raw.versionInfo[4]}`, 10); } catch (ex) { serial = -1; } rawVersion = serial >= 0 ? `${rawVersion}${serial}` : rawVersion; } } return { arch: raw.is64Bit ? platform_1.Architecture.x64 : platform_1.Architecture.x86, executable: { filename: python, sysPrefix: raw.sysPrefix, mtime: -1, ctime: -1, }, version: { ...(0, pythonVersion_1.parseVersion)(rawVersion), sysVersion: raw.sysVersion, }, }; } async function getInterpreterInfo(python, timeout) { const [args, parse] = (0, scripts_1.interpreterInfo)(); const info = (0, exec_1.copyPythonExecInfo)(python, args); const argv = [info.command, ...info.args]; const quoted = argv.reduce((p, c) => (p ? `${p} ${c.toCommandArgumentForPythonMgrExt()}` : `${c.toCommandArgumentForPythonMgrExt()}`), ''); const standardTimeout = constants_1.isCI ? 30000 : 15000; const result = await (0, externalDependencies_1.shellExecute)(quoted, { timeout: timeout !== null && timeout !== void 0 ? timeout : standardTimeout }); if (result.stderr) { (0, logging_1.traceError)(`Stderr when executing script with >> ${quoted} << stderr: ${result.stderr}, still attempting to parse output`); } let json; try { json = parse(result.stdout); } catch (ex) { (0, logging_1.traceError)(`Failed to parse interpreter information for >> ${quoted} << with ${ex}`); return undefined; } (0, logging_1.traceVerbose)(`Found interpreter for >> ${quoted} <<: ${JSON.stringify(json)}`); return extractInterpreterInfo(python.pythonExecutable, json); } exports.getInterpreterInfo = getInterpreterInfo; /***/ }), /***/ "./src/client/pythonEnvironments/base/info/pythonVersion.ts": /*!******************************************************************!*\ !*** ./src/client/pythonEnvironments/base/info/pythonVersion.ts ***! \******************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.compareSemVerLikeVersions = exports.toSemverLikeVersion = exports.areSimilarVersions = exports.areIdenticalVersion = exports.getShortVersionString = exports.getVersionDisplayString = exports.isVersionEmpty = exports.getEmptyVersion = exports.parseBasicVersion = exports.parseRelease = exports.parseVersion = exports.getPythonVersionFromPath = void 0; const lodash_1 = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js"); const path = __webpack_require__(/*! path */ "path"); const basic = __webpack_require__(/*! ../../../common/utils/version */ "./src/client/common/utils/version.ts"); const _1 = __webpack_require__(/*! . */ "./src/client/pythonEnvironments/base/info/index.ts"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); function getPythonVersionFromPath(exe) { let version = _1.UNKNOWN_PYTHON_VERSION; try { version = parseVersion(path.basename(exe)); } catch (ex) { (0, logging_1.traceError)(`Failed to parse version from path: ${exe}`, ex); } return version; } exports.getPythonVersionFromPath = getPythonVersionFromPath; function parseVersion(versionStr) { const [version, after] = parseBasicVersion(versionStr); if (version.micro === -1) { return version; } const [release] = parseRelease(after); version.release = release; return version; } exports.parseVersion = parseVersion; function parseRelease(text) { let after; let alpha; let beta; let rc; let fin; let serialStr; let match = text.match(/^(?:-?final|\.final(?:\.0)?)(.*)$/); if (match) { [, after] = match; fin = 'final'; serialStr = '0'; } else { for (const regex of [ /^(?:(a)|(b)|(rc))([1-9]\d*)(.*)$/, /^-(?:(?:(alpha)|(beta)|(candidate))([1-9]\d*))(.*)$/, /^\.(?:(?:(alpha)|(beta)|(candidate))\.([1-9]\d*))(.*)$/, ]) { match = text.match(regex); if (match) { [, alpha, beta, rc, serialStr, after] = match; break; } } } let level; if (fin) { level = _1.PythonReleaseLevel.Final; } else if (rc) { level = _1.PythonReleaseLevel.Candidate; } else if (beta) { level = _1.PythonReleaseLevel.Beta; } else if (alpha) { level = _1.PythonReleaseLevel.Alpha; } else { return [undefined, text]; } const serial = parseInt(serialStr, 10); return [{ level, serial }, after]; } exports.parseRelease = parseRelease; function parseBasicVersion(versionStr) { const parsed = basic.parseBasicVersionInfo(`ignored-${versionStr}`); if (!parsed) { if (versionStr === '') { return [getEmptyVersion(), '']; } throw Error(`invalid version ${versionStr}`); } const { version, after } = parsed; version.release = undefined; if (version.minor === -1) { if (version.major > 9) { const numdigits = version.major.toString().length - 1; const factor = 10 ** numdigits; version.minor = version.major % factor; version.major = Math.floor(version.major / factor); } } return [version, after]; } exports.parseBasicVersion = parseBasicVersion; function getEmptyVersion() { return (0, lodash_1.cloneDeep)(basic.EMPTY_VERSION); } exports.getEmptyVersion = getEmptyVersion; function isVersionEmpty(version) { return basic.isVersionInfoEmpty(version); } exports.isVersionEmpty = isVersionEmpty; function getVersionDisplayString(ver) { if (isVersionEmpty(ver)) { return ''; } if (ver.micro !== -1) { return getShortVersionString(ver); } return `${getShortVersionString(ver)}.x`; } exports.getVersionDisplayString = getVersionDisplayString; function getShortVersionString(ver) { let verStr = basic.getVersionString(ver); if (ver.release === undefined) { return verStr; } if (ver.release.level === _1.PythonReleaseLevel.Final) { return verStr; } if (ver.release.level === _1.PythonReleaseLevel.Candidate) { verStr = `${verStr}rc${ver.release.serial}`; } else if (ver.release.level === _1.PythonReleaseLevel.Beta) { verStr = `${verStr}b${ver.release.serial}`; } else if (ver.release.level === _1.PythonReleaseLevel.Alpha) { verStr = `${verStr}a${ver.release.serial}`; } else { throw Error(`unsupported release level ${ver.release.level}`); } return verStr; } exports.getShortVersionString = getShortVersionString; function areIdenticalVersion(left, right) { return basic.areIdenticalVersion(left, right, compareVersionRelease); } exports.areIdenticalVersion = areIdenticalVersion; function areSimilarVersions(left, right) { if (!basic.areSimilarVersions(left, right, compareVersionRelease)) { return false; } if (left.major === 2) { return true; } return left.minor > -1 && right.minor > -1; } exports.areSimilarVersions = areSimilarVersions; function compareVersionRelease(left, right) { if (left.release === undefined) { if (right.release === undefined) { return [0, '']; } return [1, 'level']; } if (right.release === undefined) { return [-1, 'level']; } if (left.release.level < right.release.level) { return [1, 'level']; } if (left.release.level > right.release.level) { return [-1, 'level']; } if (left.release.level === _1.PythonReleaseLevel.Final) { return [0, '']; } if (left.release.serial < right.release.serial) { return [1, 'serial']; } if (left.release.serial > right.release.serial) { return [-1, 'serial']; } return [0, '']; } function toSemverLikeVersion(version) { const versionPrefix = basic.getVersionString(version); let preRelease = []; if (version.release) { preRelease = version.release.serial < 0 ? [`${version.release.level}`] : [`${version.release.level}`, `${version.release.serial}`]; } return { raw: versionPrefix, major: version.major, minor: version.minor, patch: version.micro, build: [], prerelease: preRelease, }; } exports.toSemverLikeVersion = toSemverLikeVersion; function compareSemVerLikeVersions(v1, v2) { if (v1.major === v2.major) { if (v1.minor === v2.minor) { if (v1.patch === v2.patch) { return 0; } return v1.patch > v2.patch ? 1 : -1; } return v1.minor > v2.minor ? 1 : -1; } return v1.major > v2.major ? 1 : -1; } exports.compareSemVerLikeVersions = compareSemVerLikeVersions; /***/ }), /***/ "./src/client/pythonEnvironments/base/locator.ts": /*!*******************************************************!*\ !*** ./src/client/pythonEnvironments/base/locator.ts ***! \*******************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Locator = exports.NOOP_ITERATOR = exports.isProgressEvent = exports.ProgressReportStage = void 0; const async_1 = __webpack_require__(/*! ../../common/utils/async */ "./src/client/common/utils/async.ts"); const watcher_1 = __webpack_require__(/*! ./watcher */ "./src/client/pythonEnvironments/base/watcher.ts"); var ProgressReportStage; (function (ProgressReportStage) { ProgressReportStage["discoveryStarted"] = "discoveryStarted"; ProgressReportStage["allPathsDiscovered"] = "allPathsDiscovered"; ProgressReportStage["discoveryFinished"] = "discoveryFinished"; })(ProgressReportStage = exports.ProgressReportStage || (exports.ProgressReportStage = {})); function isProgressEvent(event) { return 'stage' in event; } exports.isProgressEvent = isProgressEvent; exports.NOOP_ITERATOR = (0, async_1.iterEmpty)(); class LocatorBase { constructor(watcher) { this.emitter = watcher; this.onChanged = watcher.onChanged; } } class Locator extends LocatorBase { constructor() { super(new watcher_1.PythonEnvsWatcher()); } } exports.Locator = Locator; /***/ }), /***/ "./src/client/pythonEnvironments/base/locatorUtils.ts": /*!************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locatorUtils.ts ***! \************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEnvs = exports.getQueryFilter = void 0; const async_1 = __webpack_require__(/*! ../../common/utils/async */ "./src/client/common/utils/async.ts"); const misc_1 = __webpack_require__(/*! ../../common/utils/misc */ "./src/client/common/utils/misc.ts"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const locator_1 = __webpack_require__(/*! ./locator */ "./src/client/pythonEnvironments/base/locator.ts"); function getQueryFilter(query) { var _a; const kinds = query.kinds !== undefined && query.kinds.length > 0 ? query.kinds : undefined; const includeNonRooted = !((_a = query.searchLocations) === null || _a === void 0 ? void 0 : _a.doNotIncludeNonRooted); const locationFilters = getSearchLocationFilters(query); function checkKind(env) { if (kinds === undefined) { return true; } return kinds.includes(env.kind); } function checkSearchLocation(env) { if (env.searchLocation === undefined) { return includeNonRooted; } const loc = env.searchLocation; if (locationFilters !== undefined) { return locationFilters.some((filter) => filter(loc)); } return true; } return (env) => { if (!checkKind(env)) { return false; } if (!checkSearchLocation(env)) { return false; } return true; }; } exports.getQueryFilter = getQueryFilter; function getSearchLocationFilters(query) { if (query.searchLocations === undefined) { return undefined; } if (query.searchLocations.roots.length === 0) { return []; } return query.searchLocations.roots.map((loc) => (0, misc_1.getURIFilter)(loc, { checkParent: true, })); } async function getEnvs(iterator) { const envs = []; const updatesDone = (0, async_1.createDeferred)(); if (iterator.onUpdated === undefined) { updatesDone.resolve(); } else { const listener = iterator.onUpdated((event) => { if ((0, locator_1.isProgressEvent)(event)) { if (event.stage !== locator_1.ProgressReportStage.discoveryFinished) { return; } updatesDone.resolve(); listener.dispose(); } else { const { index, update } = event; if (envs[index] === undefined) { const json = JSON.stringify(update); (0, logging_1.traceVerbose)(`Updates sent for an env which was classified as invalid earlier, currently not expected, ${json}`); } envs[index] = update; } }); } let itemIndex = 0; for await (const env of iterator) { if (envs[itemIndex] === undefined) { envs[itemIndex] = env; } itemIndex += 1; } await updatesDone.promise; return envs.filter((e) => e !== undefined).map((e) => e); } exports.getEnvs = getEnvs; /***/ }), /***/ "./src/client/pythonEnvironments/base/locators.ts": /*!********************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators.ts ***! \********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Locators = exports.combineIterators = void 0; const async_1 = __webpack_require__(/*! ../../common/utils/async */ "./src/client/common/utils/async.ts"); const resourceLifecycle_1 = __webpack_require__(/*! ../../common/utils/resourceLifecycle */ "./src/client/common/utils/resourceLifecycle.ts"); const locator_1 = __webpack_require__(/*! ./locator */ "./src/client/pythonEnvironments/base/locator.ts"); const watchers_1 = __webpack_require__(/*! ./watchers */ "./src/client/pythonEnvironments/base/watchers.ts"); function combineIterators(iterators) { const result = (0, async_1.chain)(iterators); const events = iterators.map((it) => it.onUpdated).filter((v) => v); if (!events || events.length === 0) { return result; } result.onUpdated = (handleEvent) => { const disposables = new resourceLifecycle_1.Disposables(); let numActive = events.length; events.forEach((event) => { const disposable = event((e) => { if ((0, locator_1.isProgressEvent)(e)) { if (e.stage === locator_1.ProgressReportStage.discoveryFinished) { numActive -= 1; if (numActive === 0) { handleEvent({ stage: locator_1.ProgressReportStage.discoveryFinished }); } } else { handleEvent({ stage: e.stage }); } } else { handleEvent(e); } }); disposables.push(disposable); }); return disposables; }; return result; } exports.combineIterators = combineIterators; class Locators extends watchers_1.PythonEnvsWatchers { constructor(locators) { super(locators); this.locators = locators; this.providerId = locators.map((loc) => loc.providerId).join('+'); } iterEnvs(query) { const iterators = this.locators.map((loc) => loc.iterEnvs(query)); return combineIterators(iterators); } } exports.Locators = Locators; /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/common/resourceBasedLocator.ts": /*!************************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/common/resourceBasedLocator.ts ***! \************************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LazyResourceBasedLocator = void 0; const async_1 = __webpack_require__(/*! ../../../../common/utils/async */ "./src/client/common/utils/async.ts"); const resourceLifecycle_1 = __webpack_require__(/*! ../../../../common/utils/resourceLifecycle */ "./src/client/common/utils/resourceLifecycle.ts"); const logging_1 = __webpack_require__(/*! ../../../../logging */ "./src/client/logging/index.ts"); const externalDependencies_1 = __webpack_require__(/*! ../../../common/externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const env_1 = __webpack_require__(/*! ../../info/env */ "./src/client/pythonEnvironments/base/info/env.ts"); const locator_1 = __webpack_require__(/*! ../../locator */ "./src/client/pythonEnvironments/base/locator.ts"); class LazyResourceBasedLocator extends locator_1.Locator { constructor() { super(...arguments); this.disposables = new resourceLifecycle_1.Disposables(); } async activate() { await this.ensureResourcesReady(); this.ensureWatchersReady().ignoreErrors(); } async dispose() { await this.disposables.dispose(); } async *iterEnvs(query) { await this.activate(); const iterator = this.doIterEnvs(query); if (query === null || query === void 0 ? void 0 : query.envPath) { let result = await iterator.next(); while (!result.done) { const currEnv = result.value; const { path } = (0, env_1.getEnvPath)(currEnv.executablePath, currEnv.envPath); if ((0, externalDependencies_1.arePathsSame)(path, query.envPath)) { yield currEnv; break; } result = await iterator.next(); } } else { yield* iterator; } } async initResources() { } async initWatchers() { } async ensureResourcesReady() { if (this.resourcesReady !== undefined) { await this.resourcesReady.promise; return; } this.resourcesReady = (0, async_1.createDeferred)(); await this.initResources().catch((ex) => { var _a; (0, logging_1.traceError)(ex); (_a = this.resourcesReady) === null || _a === void 0 ? void 0 : _a.reject(ex); }); this.resourcesReady.resolve(); } async ensureWatchersReady() { if (this.watchersReady !== undefined) { await this.watchersReady.promise; return; } this.watchersReady = (0, async_1.createDeferred)(); if (!(0, externalDependencies_1.isVirtualWorkspace)()) { await this.initWatchers().catch((ex) => { var _a; (0, logging_1.traceError)(ex); (_a = this.watchersReady) === null || _a === void 0 ? void 0 : _a.reject(ex); }); } this.watchersReady.resolve(); } } exports.LazyResourceBasedLocator = LazyResourceBasedLocator; /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/composite/envsCollectionCache.ts": /*!**************************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/composite/envsCollectionCache.ts ***! \**************************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createCollectionCache = exports.PythonEnvInfoCache = void 0; const constants_1 = __webpack_require__(/*! ../../../../common/constants */ "./src/client/common/constants.ts"); const logging_1 = __webpack_require__(/*! ../../../../logging */ "./src/client/logging/index.ts"); const externalDependencies_1 = __webpack_require__(/*! ../../../common/externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const info_1 = __webpack_require__(/*! ../../info */ "./src/client/pythonEnvironments/base/info/index.ts"); const env_1 = __webpack_require__(/*! ../../info/env */ "./src/client/pythonEnvironments/base/info/env.ts"); const watcher_1 = __webpack_require__(/*! ../../watcher */ "./src/client/pythonEnvironments/base/watcher.ts"); const conda_1 = __webpack_require__(/*! ../../../common/environmentManagers/conda */ "./src/client/pythonEnvironments/common/environmentManagers/conda.ts"); class PythonEnvInfoCache extends watcher_1.PythonEnvsWatcher { constructor(persistentStorage) { super(); this.persistentStorage = persistentStorage; this.envs = []; this.validatedEnvs = new Set(); this.flushedEnvs = new Set(); } async validateCache(envs, isCompleteList) { const areEnvsValid = await Promise.all(this.envs.map(async (cachedEnv) => { const { path } = (0, env_1.getEnvPath)(cachedEnv.executable.filename, cachedEnv.location); if (await (0, externalDependencies_1.pathExists)(path)) { if (envs && isCompleteList) { if (cachedEnv.searchLocation) { return true; } if (envs.some((env) => cachedEnv.id === env.id)) { return true; } if (Array.from(this.validatedEnvs.keys()).some((envId) => cachedEnv.id === envId)) { return true; } } else { return true; } } return false; })); const invalidIndexes = areEnvsValid .map((isValid, index) => (isValid ? -1 : index)) .filter((i) => i !== -1) .reverse(); invalidIndexes.forEach((index) => { const env = this.envs.splice(index, 1)[0]; (0, logging_1.traceVerbose)(`Removing invalid env from cache ${env.id}`); this.fire({ old: env, new: undefined }); }); if (envs) { envs.forEach((env) => { const cachedEnv = this.envs.find((e) => e.id === env.id); if (cachedEnv && !(0, env_1.areEnvsDeepEqual)(cachedEnv, env)) { this.updateEnv(cachedEnv, env, true); } }); } } getAllEnvs() { return this.envs; } addEnv(env, hasLatestInfo) { const found = this.envs.find((e) => (0, env_1.areSameEnv)(e, env)); if (!found) { this.envs.push(env); this.fire({ new: env }); } else if (hasLatestInfo && !this.validatedEnvs.has(env.id)) { this.updateEnv(found, env, true); } if (hasLatestInfo) { (0, logging_1.traceVerbose)(`Flushing env to cache ${env.id}`); this.validatedEnvs.add(env.id); this.flush(env).ignoreErrors(); } } updateEnv(oldValue, newValue, forceUpdate = false) { if (this.flushedEnvs.has(oldValue.id) && !forceUpdate) { return; } const index = this.envs.findIndex((e) => (0, env_1.areSameEnv)(e, oldValue)); if (index !== -1) { if (newValue === undefined) { this.envs.splice(index, 1); } else { this.envs[index] = newValue; } this.fire({ old: oldValue, new: newValue }); } } async getLatestInfo(path) { var _a; const env = (_a = this.envs.find((e) => (0, externalDependencies_1.arePathsSame)(e.location, path))) !== null && _a !== void 0 ? _a : this.envs.find((e) => (0, env_1.areSameEnv)(e, path)); if ((env === null || env === void 0 ? void 0 : env.kind) === info_1.PythonEnvKind.Conda && (0, env_1.getEnvPath)(env.executable.filename, env.location).pathType === 'envFolderPath') { if (await (0, externalDependencies_1.pathExists)((0, conda_1.getCondaInterpreterPath)(env.location))) { this.validatedEnvs.delete(env.id); return undefined; } this.validatedEnvs.add(env.id); return env; } if (env) { if (this.validatedEnvs.has(env.id)) { (0, logging_1.traceVerbose)(`Found cached env for ${path}`); return env; } if (await this.validateInfo(env)) { (0, logging_1.traceVerbose)(`Needed to validate ${path} with latest info`); this.validatedEnvs.add(env.id); return env; } } (0, logging_1.traceVerbose)(`No cached env found for ${path}`); return undefined; } clearAndReloadFromStorage() { this.envs = this.persistentStorage.get(); this.markAllEnvsAsFlushed(); } async flush(env) { if (env) { const envs = this.persistentStorage.get(); const index = envs.findIndex((e) => e.id === env.id); envs[index] = env; this.flushedEnvs.add(env.id); await this.persistentStorage.store(envs); return; } (0, logging_1.traceVerbose)('Environments added to cache', JSON.stringify(this.envs)); this.markAllEnvsAsFlushed(); await this.persistentStorage.store(this.envs); } markAllEnvsAsFlushed() { this.envs.forEach((e) => { this.flushedEnvs.add(e.id); }); } async validateInfo(env) { if (!this.flushedEnvs.has(env.id)) { return false; } const { ctime, mtime } = await (0, externalDependencies_1.getFileInfo)(env.executable.filename); if (ctime !== -1 && mtime !== -1 && ctime === env.executable.ctime && mtime === env.executable.mtime) { return true; } env.executable.ctime = ctime; env.executable.mtime = mtime; return false; } } exports.PythonEnvInfoCache = PythonEnvInfoCache; async function createCollectionCache(storage) { const cache = new PythonEnvInfoCache(storage); cache.clearAndReloadFromStorage(); await validateCache(cache); return cache; } exports.createCollectionCache = createCollectionCache; async function validateCache(cache) { if ((0, constants_1.isTestExecution)()) { return cache.validateCache(); } return cache.validateCache().ignoreErrors(); } /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/composite/envsCollectionService.ts": /*!****************************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/composite/envsCollectionService.ts ***! \****************************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EnvsCollectionService = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); __webpack_require__(/*! ../../../../common/extensions */ "./src/client/common/extensions.ts"); const async_1 = __webpack_require__(/*! ../../../../common/utils/async */ "./src/client/common/utils/async.ts"); const stopWatch_1 = __webpack_require__(/*! ../../../../common/utils/stopWatch */ "./src/client/common/utils/stopWatch.ts"); const logging_1 = __webpack_require__(/*! ../../../../logging */ "./src/client/logging/index.ts"); const telemetry_1 = __webpack_require__(/*! ../../../../telemetry */ "./src/client/telemetry/index.ts"); const constants_1 = __webpack_require__(/*! ../../../../telemetry/constants */ "./src/client/telemetry/constants.ts"); const externalDependencies_1 = __webpack_require__(/*! ../../../common/externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const env_1 = __webpack_require__(/*! ../../info/env */ "./src/client/pythonEnvironments/base/info/env.ts"); const locator_1 = __webpack_require__(/*! ../../locator */ "./src/client/pythonEnvironments/base/locator.ts"); const locatorUtils_1 = __webpack_require__(/*! ../../locatorUtils */ "./src/client/pythonEnvironments/base/locatorUtils.ts"); const watcher_1 = __webpack_require__(/*! ../../watcher */ "./src/client/pythonEnvironments/base/watcher.ts"); class EnvsCollectionService extends watcher_1.PythonEnvsWatcher { constructor(cache, locator) { super(); this.cache = cache; this.locator = locator; this.refreshesPerQuery = new Map(); this.scheduledRefreshesPerQuery = new Map(); this.progressPromises = new Map(); this.hasRefreshFinishedForQuery = new Map(); this.progress = new vscode_1.EventEmitter(); this.refreshState = locator_1.ProgressReportStage.discoveryFinished; this.locator.onChanged((event) => { const query = event.providerId ? { providerId: event.providerId, envPath: event.envPath } : undefined; let scheduledRefresh = this.scheduledRefreshesPerQuery.get(query); if (!scheduledRefresh) { scheduledRefresh = this.scheduleNewRefresh(query); } scheduledRefresh.then(() => { this.fire(event); }); }); this.cache.onChanged((e) => { this.fire(e); }); this.onProgress((event) => { var _a; this.refreshState = event.stage; (_a = this.progressPromises.get(event.stage)) === null || _a === void 0 ? void 0 : _a.resolve(); this.progressPromises.delete(event.stage); }); } get onProgress() { return this.progress.event; } getRefreshPromise(options) { var _a, _b; const stage = (_a = options === null || options === void 0 ? void 0 : options.stage) !== null && _a !== void 0 ? _a : locator_1.ProgressReportStage.discoveryFinished; return (_b = this.progressPromises.get(stage)) === null || _b === void 0 ? void 0 : _b.promise; } async resolveEnv(path) { path = (0, externalDependencies_1.normalizePath)(path); const cachedEnv = await this.cache.getLatestInfo(path); if (cachedEnv) { (0, logging_1.traceVerbose)(`Resolved ${path} from cache: ${JSON.stringify(cachedEnv)}`); return cachedEnv; } const resolved = await this.locator.resolveEnv(path).catch((ex) => { (0, logging_1.traceError)(`Failed to resolve ${path}`, ex); return undefined; }); (0, logging_1.traceVerbose)(`Resolved ${path} to ${JSON.stringify(resolved)}`); if (resolved) { this.cache.addEnv(resolved, true); } return resolved; } getEnvs(query) { const cachedEnvs = this.cache.getAllEnvs(); return query ? cachedEnvs.filter((0, locatorUtils_1.getQueryFilter)(query)) : cachedEnvs; } triggerRefresh(query, options) { const stopWatch = new stopWatch_1.StopWatch(); let refreshPromise = this.getRefreshPromiseForQuery(query); if (!refreshPromise) { if ((options === null || options === void 0 ? void 0 : options.ifNotTriggerredAlready) && this.hasRefreshFinished(query)) { return Promise.resolve(); } refreshPromise = this.startRefresh(query); } return refreshPromise.then(() => this.sendTelemetry(query, stopWatch)); } startRefresh(query) { this.createProgressStates(query); const promise = this.addEnvsToCacheForQuery(query); return promise .then(async () => { this.resolveProgressStates(query); }) .catch((ex) => { this.rejectProgressStates(query, ex); }); } async addEnvsToCacheForQuery(query) { const iterator = this.locator.iterEnvs(query); const seen = []; const state = { done: false, pending: 0, }; const updatesDone = (0, async_1.createDeferred)(); if (iterator.onUpdated !== undefined) { const listener = iterator.onUpdated(async (event) => { if ((0, locator_1.isProgressEvent)(event)) { switch (event.stage) { case locator_1.ProgressReportStage.discoveryFinished: state.done = true; listener.dispose(); break; case locator_1.ProgressReportStage.allPathsDiscovered: if (!query) { this.progress.fire(event); } break; default: this.progress.fire(event); } } else { state.pending += 1; this.cache.updateEnv(seen[event.index], event.update); if (event.update) { seen[event.index] = event.update; } state.pending -= 1; } if (state.done && state.pending === 0) { updatesDone.resolve(); } }); } else { this.progress.fire({ stage: locator_1.ProgressReportStage.discoveryStarted }); updatesDone.resolve(); } for await (const env of iterator) { seen.push(env); this.cache.addEnv(env); } await updatesDone.promise; await this.cache.validateCache(seen, query === undefined); this.cache.flush().ignoreErrors(); } getRefreshPromiseForQuery(query) { var _a, _b, _c; return (_b = (_a = this.refreshesPerQuery.get(query)) === null || _a === void 0 ? void 0 : _a.promise) !== null && _b !== void 0 ? _b : (_c = this.refreshesPerQuery.get(undefined)) === null || _c === void 0 ? void 0 : _c.promise; } hasRefreshFinished(query) { var _a; return (_a = this.hasRefreshFinishedForQuery.get(query)) !== null && _a !== void 0 ? _a : this.hasRefreshFinishedForQuery.get(undefined); } async scheduleNewRefresh(query) { const refreshPromise = this.getRefreshPromiseForQuery(query); let nextRefreshPromise; if (!refreshPromise) { nextRefreshPromise = this.startRefresh(query); } else { nextRefreshPromise = refreshPromise.then(() => { this.scheduledRefreshesPerQuery.delete(query); this.startRefresh(query); }); this.scheduledRefreshesPerQuery.set(query, nextRefreshPromise); } return nextRefreshPromise; } createProgressStates(query) { this.refreshesPerQuery.set(query, (0, async_1.createDeferred)()); Object.values(locator_1.ProgressReportStage).forEach((stage) => { this.progressPromises.set(stage, (0, async_1.createDeferred)()); }); if (locator_1.ProgressReportStage.allPathsDiscovered && query) { this.progressPromises.delete(locator_1.ProgressReportStage.allPathsDiscovered); } } rejectProgressStates(query, ex) { var _a; (_a = this.refreshesPerQuery.get(query)) === null || _a === void 0 ? void 0 : _a.reject(ex); this.refreshesPerQuery.delete(query); Object.values(locator_1.ProgressReportStage).forEach((stage) => { var _a; (_a = this.progressPromises.get(stage)) === null || _a === void 0 ? void 0 : _a.reject(ex); this.progressPromises.delete(stage); }); } resolveProgressStates(query) { var _a; (_a = this.refreshesPerQuery.get(query)) === null || _a === void 0 ? void 0 : _a.resolve(); this.refreshesPerQuery.delete(query); const isRefreshComplete = Array.from(this.refreshesPerQuery.values()).every((d) => d.completed); if (isRefreshComplete) { this.progress.fire({ stage: locator_1.ProgressReportStage.discoveryFinished }); } } sendTelemetry(query, stopWatch) { if (!query && !this.hasRefreshFinished(query)) { (0, telemetry_1.sendTelemetryEvent)(constants_1.EventName.PYTHON_INTERPRETER_DISCOVERY, stopWatch.elapsedTime, { interpreters: this.cache.getAllEnvs().length, environmentsWithoutPython: this.cache .getAllEnvs() .filter((e) => (0, env_1.getEnvPath)(e.executable.filename, e.location).pathType === 'envFolderPath').length, }); } this.hasRefreshFinishedForQuery.set(query, true); } } exports.EnvsCollectionService = EnvsCollectionService; /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/composite/envsReducer.ts": /*!******************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/composite/envsReducer.ts ***! \******************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PythonEnvsReducer = void 0; const lodash_1 = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const logging_1 = __webpack_require__(/*! ../../../../logging */ "./src/client/logging/index.ts"); const env_1 = __webpack_require__(/*! ../../info/env */ "./src/client/pythonEnvironments/base/info/env.ts"); const envKind_1 = __webpack_require__(/*! ../../info/envKind */ "./src/client/pythonEnvironments/base/info/envKind.ts"); const locator_1 = __webpack_require__(/*! ../../locator */ "./src/client/pythonEnvironments/base/locator.ts"); class PythonEnvsReducer { constructor(parentLocator) { this.parentLocator = parentLocator; } get onChanged() { return this.parentLocator.onChanged; } iterEnvs(query) { const didUpdate = new vscode_1.EventEmitter(); const incomingIterator = this.parentLocator.iterEnvs(query); const iterator = iterEnvsIterator(incomingIterator, didUpdate); iterator.onUpdated = didUpdate.event; return iterator; } } exports.PythonEnvsReducer = PythonEnvsReducer; async function* iterEnvsIterator(iterator, didUpdate) { const state = { done: false, pending: 0, }; const seen = []; if (iterator.onUpdated !== undefined) { const listener = iterator.onUpdated((event) => { state.pending += 1; if ((0, locator_1.isProgressEvent)(event)) { if (event.stage === locator_1.ProgressReportStage.discoveryFinished) { state.done = true; listener.dispose(); } else { didUpdate.fire(event); } } else if (event.update === undefined) { throw new Error('Unsupported behavior: `undefined` environment updates are not supported from downstream locators in reducer'); } else if (seen[event.index] !== undefined) { const oldEnv = seen[event.index]; seen[event.index] = event.update; didUpdate.fire({ index: event.index, old: oldEnv, update: event.update }); } else { (0, logging_1.traceVerbose)(`Expected already iterated env, got ${event.old} (#${event.index})`); } state.pending -= 1; checkIfFinishedAndNotify(state, didUpdate); }); } else { didUpdate.fire({ stage: locator_1.ProgressReportStage.discoveryStarted }); } let result = await iterator.next(); while (!result.done) { const currEnv = result.value; const oldIndex = seen.findIndex((s) => (0, env_1.areSameEnv)(s, currEnv)); if (oldIndex !== -1) { resolveDifferencesInBackground(oldIndex, currEnv, state, didUpdate, seen).ignoreErrors(); } else { yield currEnv; seen.push(currEnv); } result = await iterator.next(); } if (iterator.onUpdated === undefined) { state.done = true; checkIfFinishedAndNotify(state, didUpdate); } } async function resolveDifferencesInBackground(oldIndex, newEnv, state, didUpdate, seen) { state.pending += 1; const oldEnv = seen[oldIndex]; const merged = resolveEnvCollision(oldEnv, newEnv); if (!(0, lodash_1.isEqual)(oldEnv, merged)) { seen[oldIndex] = merged; didUpdate.fire({ index: oldIndex, old: oldEnv, update: merged }); } state.pending -= 1; checkIfFinishedAndNotify(state, didUpdate); } function checkIfFinishedAndNotify(state, didUpdate) { if (state.done && state.pending === 0) { didUpdate.fire({ stage: locator_1.ProgressReportStage.discoveryFinished }); didUpdate.dispose(); (0, logging_1.traceVerbose)(`Finished with environment reducer`); } } function resolveEnvCollision(oldEnv, newEnv) { var _a, _b; const [env] = sortEnvInfoByPriority(oldEnv, newEnv); const merged = (0, lodash_1.cloneDeep)(env); merged.source = (0, lodash_1.uniq)(((_a = oldEnv.source) !== null && _a !== void 0 ? _a : []).concat((_b = newEnv.source) !== null && _b !== void 0 ? _b : [])); return merged; } function sortEnvInfoByPriority(...envs) { const envKindByPriority = (0, envKind_1.getPrioritizedEnvKinds)(); return envs.sort((a, b) => envKindByPriority.indexOf(a.kind) - envKindByPriority.indexOf(b.kind)); } /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/composite/envsResolver.ts": /*!*******************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/composite/envsResolver.ts ***! \*******************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PythonEnvsResolver = void 0; const lodash_1 = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const environmentIdentifier_1 = __webpack_require__(/*! ../../../common/environmentIdentifier */ "./src/client/pythonEnvironments/common/environmentIdentifier.ts"); const env_1 = __webpack_require__(/*! ../../info/env */ "./src/client/pythonEnvironments/base/info/env.ts"); const locator_1 = __webpack_require__(/*! ../../locator */ "./src/client/pythonEnvironments/base/locator.ts"); const resolverUtils_1 = __webpack_require__(/*! ./resolverUtils */ "./src/client/pythonEnvironments/base/locators/composite/resolverUtils.ts"); const logging_1 = __webpack_require__(/*! ../../../../logging */ "./src/client/logging/index.ts"); const commonUtils_1 = __webpack_require__(/*! ../../../common/commonUtils */ "./src/client/pythonEnvironments/common/commonUtils.ts"); const pythonVersion_1 = __webpack_require__(/*! ../../info/pythonVersion */ "./src/client/pythonEnvironments/base/info/pythonVersion.ts"); class PythonEnvsResolver { constructor(parentLocator, environmentInfoService) { this.parentLocator = parentLocator; this.environmentInfoService = environmentInfoService; this.parentLocator.onChanged((event) => { if (event.type && event.searchLocation !== undefined) { this.environmentInfoService.resetInfo(event.searchLocation); } }); } get onChanged() { return this.parentLocator.onChanged; } async resolveEnv(path) { const [executablePath, envPath] = await getExecutablePathAndEnvPath(path); path = executablePath.length ? executablePath : envPath; const kind = await (0, environmentIdentifier_1.identifyEnvironment)(path); const environment = await (0, resolverUtils_1.resolveBasicEnv)({ kind, executablePath, envPath }); const info = await this.environmentInfoService.getEnvironmentInfo(environment); (0, logging_1.traceVerbose)(`Environment resolver resolved ${path} for ${JSON.stringify(environment)} to ${JSON.stringify(info)}`); if (!info) { return undefined; } return getResolvedEnv(info, environment); } iterEnvs(query) { const didUpdate = new vscode_1.EventEmitter(); const incomingIterator = this.parentLocator.iterEnvs(query); const iterator = this.iterEnvsIterator(incomingIterator, didUpdate); iterator.onUpdated = didUpdate.event; return iterator; } async *iterEnvsIterator(iterator, didUpdate) { const environmentKinds = new Map(); const state = { done: false, pending: 0, }; const seen = []; if (iterator.onUpdated !== undefined) { const listener = iterator.onUpdated(async (event) => { state.pending += 1; if ((0, locator_1.isProgressEvent)(event)) { if (event.stage === locator_1.ProgressReportStage.discoveryFinished) { didUpdate.fire({ stage: locator_1.ProgressReportStage.allPathsDiscovered }); state.done = true; listener.dispose(); } else { didUpdate.fire(event); } } else if (event.update === undefined) { throw new Error('Unsupported behavior: `undefined` environment updates are not supported from downstream locators in resolver'); } else if (seen[event.index] !== undefined) { const old = seen[event.index]; await setKind(event.update, environmentKinds); seen[event.index] = await (0, resolverUtils_1.resolveBasicEnv)(event.update); didUpdate.fire({ old, index: event.index, update: seen[event.index] }); this.resolveInBackground(event.index, state, didUpdate, seen).ignoreErrors(); } else { (0, logging_1.traceVerbose)(`Expected already iterated env, got ${event.old} (#${event.index})`); } state.pending -= 1; checkIfFinishedAndNotify(state, didUpdate); }); } else { didUpdate.fire({ stage: locator_1.ProgressReportStage.discoveryStarted }); } let result = await iterator.next(); while (!result.done) { await setKind(result.value, environmentKinds); const currEnv = await (0, resolverUtils_1.resolveBasicEnv)(result.value); seen.push(currEnv); yield currEnv; this.resolveInBackground(seen.indexOf(currEnv), state, didUpdate, seen).ignoreErrors(); result = await iterator.next(); } if (iterator.onUpdated === undefined) { state.done = true; checkIfFinishedAndNotify(state, didUpdate); } } async resolveInBackground(envIndex, state, didUpdate, seen) { state.pending += 1; const info = await this.environmentInfoService.getEnvironmentInfo(seen[envIndex]); const old = seen[envIndex]; if (info) { const resolvedEnv = getResolvedEnv(info, seen[envIndex]); seen[envIndex] = resolvedEnv; didUpdate.fire({ old, index: envIndex, update: resolvedEnv }); } else { didUpdate.fire({ old, index: envIndex, update: undefined }); } state.pending -= 1; checkIfFinishedAndNotify(state, didUpdate); } } exports.PythonEnvsResolver = PythonEnvsResolver; async function setKind(env, environmentKinds) { const { path } = (0, env_1.getEnvPath)(env.executablePath, env.envPath); let kind = environmentKinds.get(path); if (!kind) { kind = await (0, environmentIdentifier_1.identifyEnvironment)(path); environmentKinds.set(path, kind); } env.kind = kind; } function checkIfFinishedAndNotify(state, didUpdate) { if (state.done && state.pending === 0) { didUpdate.fire({ stage: locator_1.ProgressReportStage.discoveryFinished }); didUpdate.dispose(); (0, logging_1.traceVerbose)(`Finished with environment resolver`); } } function getResolvedEnv(interpreterInfo, environment) { const resolvedEnv = (0, lodash_1.cloneDeep)(environment); resolvedEnv.executable.sysPrefix = interpreterInfo.executable.sysPrefix; const isEnvLackingPython = (0, env_1.getEnvPath)(resolvedEnv.executable.filename, resolvedEnv.location).pathType === 'envFolderPath'; if (isEnvLackingPython) { resolvedEnv.version = (0, pythonVersion_1.getEmptyVersion)(); } else { resolvedEnv.version = interpreterInfo.version; } resolvedEnv.arch = interpreterInfo.arch; (0, env_1.setEnvDisplayString)(resolvedEnv); return resolvedEnv; } async function getExecutablePathAndEnvPath(path) { var _a; let executablePath; let envPath; const isPathAnExecutable = await (0, commonUtils_1.isPythonExecutable)(path).catch((ex) => { (0, logging_1.traceWarn)('Failed to check if', path, 'is an executable', ex); return true; }); if (isPathAnExecutable) { executablePath = path; envPath = (0, commonUtils_1.getEnvironmentDirFromPath)(executablePath); } else { envPath = path; executablePath = (_a = (await (0, commonUtils_1.getInterpreterPathFromDir)(envPath))) !== null && _a !== void 0 ? _a : ''; } return [executablePath, envPath]; } /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/composite/resolverUtils.ts": /*!********************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/composite/resolverUtils.ts ***! \********************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveBasicEnv = void 0; const path = __webpack_require__(/*! path */ "path"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const lodash_1 = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js"); const info_1 = __webpack_require__(/*! ../../info */ "./src/client/pythonEnvironments/base/info/index.ts"); const env_1 = __webpack_require__(/*! ../../info/env */ "./src/client/pythonEnvironments/base/info/env.ts"); const commonUtils_1 = __webpack_require__(/*! ../../../common/commonUtils */ "./src/client/pythonEnvironments/common/commonUtils.ts"); const externalDependencies_1 = __webpack_require__(/*! ../../../common/externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const conda_1 = __webpack_require__(/*! ../../../common/environmentManagers/conda */ "./src/client/pythonEnvironments/common/environmentManagers/conda.ts"); const pyenv_1 = __webpack_require__(/*! ../../../common/environmentManagers/pyenv */ "./src/client/pythonEnvironments/common/environmentManagers/pyenv.ts"); const platform_1 = __webpack_require__(/*! ../../../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const pythonVersion_1 = __webpack_require__(/*! ../../info/pythonVersion */ "./src/client/pythonEnvironments/base/info/pythonVersion.ts"); const windowsUtils_1 = __webpack_require__(/*! ../../../common/windowsUtils */ "./src/client/pythonEnvironments/common/windowsUtils.ts"); const executable_1 = __webpack_require__(/*! ../../info/executable */ "./src/client/pythonEnvironments/base/info/executable.ts"); const logging_1 = __webpack_require__(/*! ../../../../logging */ "./src/client/logging/index.ts"); const simplevirtualenvs_1 = __webpack_require__(/*! ../../../common/environmentManagers/simplevirtualenvs */ "./src/client/pythonEnvironments/common/environmentManagers/simplevirtualenvs.ts"); const workspaceApis_1 = __webpack_require__(/*! ../../../../common/vscodeApis/workspaceApis */ "./src/client/common/vscodeApis/workspaceApis.ts"); const activestate_1 = __webpack_require__(/*! ../../../common/environmentManagers/activestate */ "./src/client/pythonEnvironments/common/environmentManagers/activestate.ts"); function getResolvers() { const resolvers = new Map(); Object.values(info_1.PythonEnvKind).forEach((k) => { resolvers.set(k, resolveGloballyInstalledEnv); }); info_1.virtualEnvKinds.forEach((k) => { resolvers.set(k, resolveSimpleEnv); }); resolvers.set(info_1.PythonEnvKind.Conda, resolveCondaEnv); resolvers.set(info_1.PythonEnvKind.MicrosoftStore, resolveMicrosoftStoreEnv); resolvers.set(info_1.PythonEnvKind.Pyenv, resolvePyenvEnv); resolvers.set(info_1.PythonEnvKind.ActiveState, resolveActiveStateEnv); return resolvers; } async function resolveBasicEnv(env) { var _a; const { kind, source } = env; const resolvers = getResolvers(); const resolverForKind = resolvers.get(kind); const resolvedEnv = await resolverForKind(env); resolvedEnv.searchLocation = getSearchLocation(resolvedEnv); resolvedEnv.source = (0, lodash_1.uniq)(resolvedEnv.source.concat(source !== null && source !== void 0 ? source : [])); if ((0, platform_1.getOSType)() === platform_1.OSType.Windows && ((_a = resolvedEnv.source) === null || _a === void 0 ? void 0 : _a.includes(info_1.PythonEnvSource.WindowsRegistry))) { await updateEnvUsingRegistry(resolvedEnv); } (0, env_1.setEnvDisplayString)(resolvedEnv); const { ctime, mtime } = await (0, externalDependencies_1.getFileInfo)(resolvedEnv.executable.filename); resolvedEnv.executable.ctime = ctime; resolvedEnv.executable.mtime = mtime; const type = await getEnvType(resolvedEnv); if (type) { resolvedEnv.type = type; } return resolvedEnv; } exports.resolveBasicEnv = resolveBasicEnv; async function getEnvType(env) { if (env.type) { return env.type; } if (await (0, simplevirtualenvs_1.isVirtualEnvironment)(env.executable.filename)) { return info_1.PythonEnvType.Virtual; } if (await (0, conda_1.isCondaEnvironment)(env.executable.filename)) { return info_1.PythonEnvType.Conda; } return undefined; } function getSearchLocation(env) { const folders = (0, workspaceApis_1.getWorkspaceFolderPaths)(); const isRootedEnv = folders.some((f) => (0, externalDependencies_1.isParentPath)(env.executable.filename, f) || (0, externalDependencies_1.isParentPath)(env.location, f)); if (isRootedEnv) { return vscode_1.Uri.file(env.location); } return undefined; } async function updateEnvUsingRegistry(env) { var _a, _b, _c; let interpreters = (0, windowsUtils_1.getRegistryInterpretersSync)(); if (!interpreters) { (0, logging_1.traceError)('Expected registry interpreter cache to be initialized already'); interpreters = await (0, windowsUtils_1.getRegistryInterpreters)(); } const data = interpreters.find((i) => (0, externalDependencies_1.arePathsSame)(i.interpreterPath, env.executable.filename)); if (data) { const versionStr = (_b = (_a = data.versionStr) !== null && _a !== void 0 ? _a : data.sysVersionStr) !== null && _b !== void 0 ? _b : data.interpreterPath; let version; try { version = (0, pythonVersion_1.parseVersion)(versionStr); } catch (ex) { version = info_1.UNKNOWN_PYTHON_VERSION; } env.kind = env.kind === info_1.PythonEnvKind.Unknown ? info_1.PythonEnvKind.OtherGlobal : env.kind; env.version = (0, env_1.comparePythonVersionSpecificity)(version, env.version) > 0 ? version : env.version; env.distro.defaultDisplayName = data.companyDisplayName; env.arch = data.bitnessStr === '32bit' ? platform_1.Architecture.x86 : platform_1.Architecture.x64; env.distro.org = (_c = data.distroOrgName) !== null && _c !== void 0 ? _c : env.distro.org; env.source = (0, lodash_1.uniq)(env.source.concat(info_1.PythonEnvSource.WindowsRegistry)); } else { (0, logging_1.traceWarn)('Expected registry to find the interpreter as source was set'); } } async function resolveGloballyInstalledEnv(env) { const { executablePath } = env; let version; try { version = (0, executable_1.parseVersionFromExecutable)(executablePath); } catch (_a) { version = info_1.UNKNOWN_PYTHON_VERSION; } const envInfo = (0, env_1.buildEnvInfo)({ kind: env.kind, version, executable: executablePath, }); return envInfo; } async function resolveSimpleEnv(env) { const { executablePath, kind } = env; const envInfo = (0, env_1.buildEnvInfo)({ kind, version: await (0, commonUtils_1.getPythonVersionFromPath)(executablePath), executable: executablePath, type: info_1.PythonEnvType.Virtual, }); const location = (0, commonUtils_1.getEnvironmentDirFromPath)(executablePath); envInfo.location = location; envInfo.name = path.basename(location); return envInfo; } async function resolveCondaEnv(env) { var _a; const { executablePath } = env; const conda = await conda_1.Conda.getConda(); if (conda === undefined) { (0, logging_1.traceWarn)(`${executablePath} identified as Conda environment even though Conda is not found`); env.kind = info_1.PythonEnvKind.Unknown; const envInfo = await resolveSimpleEnv(env); envInfo.type = info_1.PythonEnvType.Conda; envInfo.name = ''; return envInfo; } const envPath = (_a = env.envPath) !== null && _a !== void 0 ? _a : (0, commonUtils_1.getEnvironmentDirFromPath)(env.executablePath); let executable; if (env.executablePath.length > 0) { executable = env.executablePath; } else { executable = await conda.getInterpreterPathForEnvironment({ prefix: envPath }); } const info = (0, env_1.buildEnvInfo)({ executable, kind: info_1.PythonEnvKind.Conda, org: conda_1.AnacondaCompanyName, location: envPath, source: [], version: executable ? await (0, commonUtils_1.getPythonVersionFromPath)(executable) : undefined, type: info_1.PythonEnvType.Conda, }); const name = await (conda === null || conda === void 0 ? void 0 : conda.getName(envPath)); if (name) { info.name = name; } if (env.envPath && path.basename(executable) === executable) { const predictedExecutable = (0, conda_1.getCondaInterpreterPath)(env.envPath); info.id = (0, env_1.getEnvID)(predictedExecutable, env.envPath); } return info; } async function resolvePyenvEnv(env) { const { executablePath } = env; const location = (0, commonUtils_1.getEnvironmentDirFromPath)(executablePath); const name = path.basename(location); const versionStrings = (0, pyenv_1.parsePyenvVersion)(name); const envInfo = (0, env_1.buildEnvInfo)({ kind: info_1.PythonEnvKind.Pyenv, executable: executablePath, source: [], location, version: await (0, commonUtils_1.getPythonVersionFromPath)(executablePath, versionStrings === null || versionStrings === void 0 ? void 0 : versionStrings.pythonVer), org: versionStrings && versionStrings.distro ? versionStrings.distro : '', }); if (await isBaseCondaPyenvEnvironment(executablePath)) { envInfo.name = 'base'; } else { envInfo.name = name; } return envInfo; } async function resolveActiveStateEnv(env) { const info = (0, env_1.buildEnvInfo)({ kind: env.kind, executable: env.executablePath, }); const projects = await activestate_1.ActiveState.getState().then((v) => v === null || v === void 0 ? void 0 : v.getProjects()); if (projects) { for (const project of projects) { for (const dir of project.executables) { if ((0, externalDependencies_1.arePathsSame)(dir, path.dirname(env.executablePath))) { info.name = `${project.organization}/${project.name}`; return info; } } } } return info; } async function isBaseCondaPyenvEnvironment(executablePath) { if (!(await (0, conda_1.isCondaEnvironment)(executablePath))) { return false; } const location = (0, commonUtils_1.getEnvironmentDirFromPath)(executablePath); const pyenvVersionDir = (0, pyenv_1.getPyenvVersionsDir)(); return (0, externalDependencies_1.arePathsSame)(path.dirname(location), pyenvVersionDir); } async function resolveMicrosoftStoreEnv(env) { const { executablePath } = env; return (0, env_1.buildEnvInfo)({ kind: info_1.PythonEnvKind.MicrosoftStore, executable: executablePath, version: (0, pythonVersion_1.getPythonVersionFromPath)(executablePath), org: 'Microsoft', arch: platform_1.Architecture.x64, source: [info_1.PythonEnvSource.PathEnvVar], }); } /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/lowLevel/activeStateLocator.ts": /*!************************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/lowLevel/activeStateLocator.ts ***! \************************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ActiveStateLocator = void 0; const activestate_1 = __webpack_require__(/*! ../../../common/environmentManagers/activestate */ "./src/client/pythonEnvironments/common/environmentManagers/activestate.ts"); const info_1 = __webpack_require__(/*! ../../info */ "./src/client/pythonEnvironments/base/info/index.ts"); const logging_1 = __webpack_require__(/*! ../../../../logging */ "./src/client/logging/index.ts"); const resourceBasedLocator_1 = __webpack_require__(/*! ../common/resourceBasedLocator */ "./src/client/pythonEnvironments/base/locators/common/resourceBasedLocator.ts"); const commonUtils_1 = __webpack_require__(/*! ../../../common/commonUtils */ "./src/client/pythonEnvironments/common/commonUtils.ts"); class ActiveStateLocator extends resourceBasedLocator_1.LazyResourceBasedLocator { constructor() { super(...arguments); this.providerId = 'activestate'; } async *doIterEnvs() { const state = await activestate_1.ActiveState.getState(); if (state === undefined) { (0, logging_1.traceVerbose)(`Couldn't locate the state binary.`); return; } (0, logging_1.traceVerbose)(`Searching for active state environments`); const projects = await state.getProjects(); if (projects === undefined) { (0, logging_1.traceVerbose)(`Couldn't fetch State Tool projects.`); return; } for (const project of projects) { if (project.executables) { for (const dir of project.executables) { try { (0, logging_1.traceVerbose)(`Looking for Python in: ${project.name}`); for await (const exe of (0, commonUtils_1.findInterpretersInDir)(dir)) { (0, logging_1.traceVerbose)(`Found Python executable: ${exe.filename}`); yield { kind: info_1.PythonEnvKind.ActiveState, executablePath: exe.filename }; } } catch (ex) { (0, logging_1.traceError)(`Failed to process State Tool project: ${JSON.stringify(project)}`, ex); } } } } (0, logging_1.traceVerbose)(`Finished searching for active state environments`); } } exports.ActiveStateLocator = ActiveStateLocator; /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/lowLevel/condaLocator.ts": /*!******************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/lowLevel/condaLocator.ts ***! \******************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CondaEnvironmentLocator = void 0; __webpack_require__(/*! ../../../../common/extensions */ "./src/client/common/extensions.ts"); const info_1 = __webpack_require__(/*! ../../info */ "./src/client/pythonEnvironments/base/info/index.ts"); const conda_1 = __webpack_require__(/*! ../../../common/environmentManagers/conda */ "./src/client/pythonEnvironments/common/environmentManagers/conda.ts"); const logging_1 = __webpack_require__(/*! ../../../../logging */ "./src/client/logging/index.ts"); const fsWatchingLocator_1 = __webpack_require__(/*! ./fsWatchingLocator */ "./src/client/pythonEnvironments/base/locators/lowLevel/fsWatchingLocator.ts"); class CondaEnvironmentLocator extends fsWatchingLocator_1.FSWatchingLocator { constructor() { super(() => (0, conda_1.getCondaEnvironmentsTxt)(), async () => info_1.PythonEnvKind.Conda, { isFile: true }); this.providerId = 'conda-envs'; } async *doIterEnvs() { const conda = await conda_1.Conda.getConda(); if (conda === undefined) { (0, logging_1.traceVerbose)(`Couldn't locate the conda binary.`); return; } (0, logging_1.traceVerbose)(`Searching for conda environments using ${conda.command}`); const envs = await conda.getEnvList(); for (const env of envs) { try { (0, logging_1.traceVerbose)(`Looking into conda env for executable: ${JSON.stringify(env)}`); const executablePath = await conda.getInterpreterPathForEnvironment(env); (0, logging_1.traceVerbose)(`Found conda executable: ${executablePath}`); yield { kind: info_1.PythonEnvKind.Conda, executablePath, envPath: env.prefix }; } catch (ex) { (0, logging_1.traceError)(`Failed to process conda env: ${JSON.stringify(env)}`, ex); } } (0, logging_1.traceVerbose)(`Finished searching for conda environments`); } } exports.CondaEnvironmentLocator = CondaEnvironmentLocator; /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/lowLevel/customVirtualEnvLocator.ts": /*!*****************************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/lowLevel/customVirtualEnvLocator.ts ***! \*****************************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CustomVirtualEnvironmentLocator = exports.VENVFOLDERS_SETTING_KEY = exports.VENVPATH_SETTING_KEY = void 0; const lodash_1 = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js"); const path = __webpack_require__(/*! path */ "path"); const async_1 = __webpack_require__(/*! ../../../../common/utils/async */ "./src/client/common/utils/async.ts"); const platform_1 = __webpack_require__(/*! ../../../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const info_1 = __webpack_require__(/*! ../../info */ "./src/client/pythonEnvironments/base/info/index.ts"); const fsWatchingLocator_1 = __webpack_require__(/*! ./fsWatchingLocator */ "./src/client/pythonEnvironments/base/locators/lowLevel/fsWatchingLocator.ts"); const commonUtils_1 = __webpack_require__(/*! ../../../common/commonUtils */ "./src/client/pythonEnvironments/common/commonUtils.ts"); const externalDependencies_1 = __webpack_require__(/*! ../../../common/externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const pipenv_1 = __webpack_require__(/*! ../../../common/environmentManagers/pipenv */ "./src/client/pythonEnvironments/common/environmentManagers/pipenv.ts"); const simplevirtualenvs_1 = __webpack_require__(/*! ../../../common/environmentManagers/simplevirtualenvs */ "./src/client/pythonEnvironments/common/environmentManagers/simplevirtualenvs.ts"); __webpack_require__(/*! ../../../../common/extensions */ "./src/client/common/extensions.ts"); const arrayUtils_1 = __webpack_require__(/*! ../../../../common/utils/arrayUtils */ "./src/client/common/utils/arrayUtils.ts"); const logging_1 = __webpack_require__(/*! ../../../../logging */ "./src/client/logging/index.ts"); const DEFAULT_SEARCH_DEPTH = 2; exports.VENVPATH_SETTING_KEY = 'venvPath'; exports.VENVFOLDERS_SETTING_KEY = 'venvFolders'; async function getCustomVirtualEnvDirs() { var _a; const venvDirs = []; const venvPath = (0, externalDependencies_1.getPythonSetting)(exports.VENVPATH_SETTING_KEY); if (venvPath) { venvDirs.push((0, externalDependencies_1.untildify)(venvPath)); } const venvFolders = (_a = (0, externalDependencies_1.getPythonSetting)(exports.VENVFOLDERS_SETTING_KEY)) !== null && _a !== void 0 ? _a : []; const homeDir = (0, platform_1.getUserHomeDir)(); if (homeDir && (await (0, externalDependencies_1.pathExists)(homeDir))) { venvFolders.map((item) => path.join(homeDir, item)).forEach((d) => venvDirs.push(d)); } return (0, arrayUtils_1.asyncFilter)((0, lodash_1.uniq)(venvDirs), externalDependencies_1.pathExists); } async function getVirtualEnvKind(interpreterPath) { if (await (0, pipenv_1.isPipenvEnvironment)(interpreterPath)) { return info_1.PythonEnvKind.Pipenv; } if (await (0, simplevirtualenvs_1.isVirtualenvwrapperEnvironment)(interpreterPath)) { return info_1.PythonEnvKind.VirtualEnvWrapper; } if (await (0, simplevirtualenvs_1.isVenvEnvironment)(interpreterPath)) { return info_1.PythonEnvKind.Venv; } if (await (0, simplevirtualenvs_1.isVirtualenvEnvironment)(interpreterPath)) { return info_1.PythonEnvKind.VirtualEnv; } return info_1.PythonEnvKind.Unknown; } class CustomVirtualEnvironmentLocator extends fsWatchingLocator_1.FSWatchingLocator { constructor() { super(getCustomVirtualEnvDirs, getVirtualEnvKind, { delayOnCreated: 1000, }); this.providerId = 'custom-virtual-envs'; } async initResources() { this.disposables.push((0, externalDependencies_1.onDidChangePythonSetting)(exports.VENVPATH_SETTING_KEY, () => this.emitter.fire({}))); this.disposables.push((0, externalDependencies_1.onDidChangePythonSetting)(exports.VENVFOLDERS_SETTING_KEY, () => this.emitter.fire({}))); } doIterEnvs() { async function* iterator() { const envRootDirs = await getCustomVirtualEnvDirs(); const envGenerators = envRootDirs.map((envRootDir) => { async function* generator() { (0, logging_1.traceVerbose)(`Searching for custom virtual envs in: ${envRootDir}`); const executables = (0, commonUtils_1.findInterpretersInDir)(envRootDir, DEFAULT_SEARCH_DEPTH); for await (const entry of executables) { const { filename } = entry; if (await (0, commonUtils_1.looksLikeBasicVirtualPython)(entry)) { try { const kind = await getVirtualEnvKind(filename); yield { kind, executablePath: filename }; (0, logging_1.traceVerbose)(`Custom Virtual Environment: [added] ${filename}`); } catch (ex) { (0, logging_1.traceError)(`Failed to process environment: ${filename}`, ex); } } else { (0, logging_1.traceVerbose)(`Custom Virtual Environment: [skipped] ${filename}`); } } } return generator(); }); yield* (0, async_1.iterable)((0, async_1.chain)(envGenerators)); (0, logging_1.traceVerbose)(`Finished searching for custom virtual envs`); } return iterator(); } } exports.CustomVirtualEnvironmentLocator = CustomVirtualEnvironmentLocator; /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/lowLevel/filesLocator.ts": /*!******************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/lowLevel/filesLocator.ts ***! \******************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DirFilesLocator = void 0; const commonUtils_1 = __webpack_require__(/*! ../../../common/commonUtils */ "./src/client/pythonEnvironments/common/commonUtils.ts"); const watcher_1 = __webpack_require__(/*! ../../watcher */ "./src/client/pythonEnvironments/base/watcher.ts"); class FoundFilesLocator { constructor(kind, getExecutables, source) { this.kind = kind; this.getExecutables = getExecutables; this.source = source; this.watcher = new watcher_1.PythonEnvsWatcher(); this.onChanged = this.watcher.onChanged; } iterEnvs(_query) { const executables = this.getExecutables(); async function* generator(kind, source) { for await (const executablePath of executables) { yield { executablePath, kind, source }; } } const iterator = generator(this.kind, this.source); return iterator; } } class DirFilesLocator extends FoundFilesLocator { constructor(dirname, defaultKind, getExecutables = getExecutablesDefault, source) { super(defaultKind, () => getExecutables(dirname), source); this.providerId = `dir-files-${dirname}`; } } exports.DirFilesLocator = DirFilesLocator; async function* getExecutablesDefault(dirname) { for await (const entry of (0, commonUtils_1.iterPythonExecutablesInDir)(dirname)) { yield entry.filename; } } /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/lowLevel/fsWatchingLocator.ts": /*!***********************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/lowLevel/fsWatchingLocator.ts ***! \***********************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FSWatchingLocator = exports.FSWatcherKind = void 0; const fs = __webpack_require__(/*! fs */ "fs"); const path = __webpack_require__(/*! path */ "path"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const fileSystemWatcher_1 = __webpack_require__(/*! ../../../../common/platform/fileSystemWatcher */ "./src/client/common/platform/fileSystemWatcher.ts"); const async_1 = __webpack_require__(/*! ../../../../common/utils/async */ "./src/client/common/utils/async.ts"); const logging_1 = __webpack_require__(/*! ../../../../logging */ "./src/client/logging/index.ts"); const commonUtils_1 = __webpack_require__(/*! ../../../common/commonUtils */ "./src/client/pythonEnvironments/common/commonUtils.ts"); const pythonBinariesWatcher_1 = __webpack_require__(/*! ../../../common/pythonBinariesWatcher */ "./src/client/pythonEnvironments/common/pythonBinariesWatcher.ts"); const resourceBasedLocator_1 = __webpack_require__(/*! ../common/resourceBasedLocator */ "./src/client/pythonEnvironments/base/locators/common/resourceBasedLocator.ts"); var FSWatcherKind; (function (FSWatcherKind) { FSWatcherKind[FSWatcherKind["Global"] = 0] = "Global"; FSWatcherKind[FSWatcherKind["Workspace"] = 1] = "Workspace"; })(FSWatcherKind = exports.FSWatcherKind || (exports.FSWatcherKind = {})); function checkDirWatchable(dirname) { let names; try { names = fs.readdirSync(dirname); } catch (err) { const exception = err; (0, logging_1.traceError)('Reading directory to watch failed', exception); if (exception.code === 'ENOENT') { return 'directory does not exist'; } throw err; } if (names.length > 200) { return 'too many files'; } return undefined; } class FSWatchingLocator extends resourceBasedLocator_1.LazyResourceBasedLocator { constructor(getRoots, getKind, creationOptions = {}, watcherKind = FSWatcherKind.Global) { super(); this.getRoots = getRoots; this.getKind = getKind; this.creationOptions = creationOptions; this.watcherKind = watcherKind; this.activate().ignoreErrors(); } async initWatchers() { if (this.watcherKind === FSWatcherKind.Global && !isWatchingAFile(this.creationOptions)) { return; } (0, logging_1.traceVerbose)('Getting roots'); let roots = await this.getRoots(); (0, logging_1.traceVerbose)('Found roots'); if (typeof roots === 'string') { roots = [roots]; } const promises = roots.map(async (root) => { if (isWatchingAFile(this.creationOptions)) { return root; } const unwatchable = await checkDirWatchable(root); if (unwatchable) { (0, logging_1.traceError)(`Dir "${root}" is not watchable (${unwatchable})`); return undefined; } return root; }); const watchableRoots = (await Promise.all(promises)).filter((root) => !!root); watchableRoots.forEach((root) => this.startWatchers(root)); } startWatchers(root) { const opts = this.creationOptions; if (isWatchingAFile(opts)) { (0, logging_1.traceVerbose)('Start watching file for changes', root); this.disposables.push((0, fileSystemWatcher_1.watchLocationForPattern)(path.dirname(root), path.basename(root), () => { (0, logging_1.traceVerbose)('Detected change in file: ', root, 'initiating a refresh'); this.emitter.fire({ providerId: this.providerId }); })); return; } const callback = async (type, executable) => { var _a; if (type === fileSystemWatcher_1.FileChangeType.Created) { if (opts.delayOnCreated !== undefined) { await (0, async_1.sleep)(opts.delayOnCreated); } } const kind = await this.getKind(executable).catch(() => undefined); const searchLocation = vscode_1.Uri.file((_a = opts.searchLocation) !== null && _a !== void 0 ? _a : path.dirname((0, commonUtils_1.getEnvironmentDirFromPath)(executable))); (0, logging_1.traceVerbose)('Fired event ', JSON.stringify({ type, kind, searchLocation }), 'from locator'); this.emitter.fire({ type, kind, searchLocation, providerId: this.providerId, envPath: executable }); }; const globs = (0, pythonBinariesWatcher_1.resolvePythonExeGlobs)(opts.baseGlob, opts.envStructure); (0, logging_1.traceVerbose)('Start watching root', root, 'for globs', JSON.stringify(globs)); const watchers = globs.map((g) => (0, pythonBinariesWatcher_1.watchLocationForPythonBinaries)(root, callback, g)); this.disposables.push(...watchers); } } exports.FSWatchingLocator = FSWatchingLocator; function isWatchingAFile(options) { return 'isFile' in options && options.isFile; } /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/lowLevel/globalVirtualEnvronmentLocator.ts": /*!************************************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/lowLevel/globalVirtualEnvronmentLocator.ts ***! \************************************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GlobalVirtualEnvironmentLocator = void 0; const lodash_1 = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js"); const path = __webpack_require__(/*! path */ "path"); const async_1 = __webpack_require__(/*! ../../../../common/utils/async */ "./src/client/common/utils/async.ts"); const platform_1 = __webpack_require__(/*! ../../../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const info_1 = __webpack_require__(/*! ../../info */ "./src/client/pythonEnvironments/base/info/index.ts"); const fsWatchingLocator_1 = __webpack_require__(/*! ./fsWatchingLocator */ "./src/client/pythonEnvironments/base/locators/lowLevel/fsWatchingLocator.ts"); const commonUtils_1 = __webpack_require__(/*! ../../../common/commonUtils */ "./src/client/pythonEnvironments/common/commonUtils.ts"); const externalDependencies_1 = __webpack_require__(/*! ../../../common/externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const pipenv_1 = __webpack_require__(/*! ../../../common/environmentManagers/pipenv */ "./src/client/pythonEnvironments/common/environmentManagers/pipenv.ts"); const simplevirtualenvs_1 = __webpack_require__(/*! ../../../common/environmentManagers/simplevirtualenvs */ "./src/client/pythonEnvironments/common/environmentManagers/simplevirtualenvs.ts"); __webpack_require__(/*! ../../../../common/extensions */ "./src/client/common/extensions.ts"); const arrayUtils_1 = __webpack_require__(/*! ../../../../common/utils/arrayUtils */ "./src/client/common/utils/arrayUtils.ts"); const logging_1 = __webpack_require__(/*! ../../../../logging */ "./src/client/logging/index.ts"); const DEFAULT_SEARCH_DEPTH = 2; async function getGlobalVirtualEnvDirs() { const venvDirs = []; let workOnHome = (0, platform_1.getEnvironmentVariable)('WORKON_HOME'); if (workOnHome) { workOnHome = (0, externalDependencies_1.untildify)(workOnHome); if (await (0, externalDependencies_1.pathExists)(workOnHome)) { venvDirs.push(workOnHome); } } const homeDir = (0, platform_1.getUserHomeDir)(); if (homeDir && (await (0, externalDependencies_1.pathExists)(homeDir))) { const subDirs = ['Envs', '.direnv', '.venvs', '.virtualenvs', path.join('.local', 'share', 'virtualenvs')]; if ((0, platform_1.getOSType)() !== platform_1.OSType.Windows) { subDirs.push('envs'); } const filtered = await (0, arrayUtils_1.asyncFilter)(subDirs.map((d) => path.join(homeDir, d)), externalDependencies_1.pathExists); filtered.forEach((d) => venvDirs.push(d)); } return (0, lodash_1.uniq)(venvDirs); } async function getVirtualEnvKind(interpreterPath) { if (await (0, pipenv_1.isPipenvEnvironment)(interpreterPath)) { return info_1.PythonEnvKind.Pipenv; } if (await (0, simplevirtualenvs_1.isVirtualenvwrapperEnvironment)(interpreterPath)) { return info_1.PythonEnvKind.VirtualEnvWrapper; } if (await (0, simplevirtualenvs_1.isVenvEnvironment)(interpreterPath)) { return info_1.PythonEnvKind.Venv; } if (await (0, simplevirtualenvs_1.isVirtualenvEnvironment)(interpreterPath)) { return info_1.PythonEnvKind.VirtualEnv; } return info_1.PythonEnvKind.Unknown; } class GlobalVirtualEnvironmentLocator extends fsWatchingLocator_1.FSWatchingLocator { constructor(searchDepth) { super(getGlobalVirtualEnvDirs, getVirtualEnvKind, { delayOnCreated: 1000, }); this.searchDepth = searchDepth; this.providerId = 'global-virtual-env'; } doIterEnvs() { var _a; const searchDepth = (_a = this.searchDepth) !== null && _a !== void 0 ? _a : DEFAULT_SEARCH_DEPTH; async function* iterator() { const envRootDirs = await getGlobalVirtualEnvDirs(); const envGenerators = envRootDirs.map((envRootDir) => { async function* generator() { (0, logging_1.traceVerbose)(`Searching for global virtual envs in: ${envRootDir}`); const executables = (0, commonUtils_1.findInterpretersInDir)(envRootDir, searchDepth); for await (const entry of executables) { const { filename } = entry; if (await (0, commonUtils_1.looksLikeBasicVirtualPython)(entry)) { const kind = await getVirtualEnvKind(filename); try { yield { kind, executablePath: filename }; (0, logging_1.traceVerbose)(`Global Virtual Environment: [added] ${filename}`); } catch (ex) { (0, logging_1.traceError)(`Failed to process environment: ${filename}`, ex); } } else { (0, logging_1.traceVerbose)(`Global Virtual Environment: [skipped] ${filename}`); } } } return generator(); }); yield* (0, async_1.iterable)((0, async_1.chain)(envGenerators)); (0, logging_1.traceVerbose)(`Finished searching for global virtual envs`); } return iterator(); } } exports.GlobalVirtualEnvironmentLocator = GlobalVirtualEnvironmentLocator; /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/lowLevel/microsoftStoreLocator.ts": /*!***************************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/lowLevel/microsoftStoreLocator.ts ***! \***************************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MicrosoftStoreLocator = exports.getMicrosoftStorePythonExes = void 0; const fsapi = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const minimatch = __webpack_require__(/*! minimatch */ "./node_modules/minimatch/minimatch.js"); const path = __webpack_require__(/*! path */ "path"); const info_1 = __webpack_require__(/*! ../../info */ "./src/client/pythonEnvironments/base/info/index.ts"); const fsWatchingLocator_1 = __webpack_require__(/*! ./fsWatchingLocator */ "./src/client/pythonEnvironments/base/locators/lowLevel/fsWatchingLocator.ts"); const pythonBinariesWatcher_1 = __webpack_require__(/*! ../../../common/pythonBinariesWatcher */ "./src/client/pythonEnvironments/common/pythonBinariesWatcher.ts"); const microsoftStoreEnv_1 = __webpack_require__(/*! ../../../common/environmentManagers/microsoftStoreEnv */ "./src/client/pythonEnvironments/common/environmentManagers/microsoftStoreEnv.ts"); const logging_1 = __webpack_require__(/*! ../../../../logging */ "./src/client/logging/index.ts"); const pythonExeGlob = 'python3.{[0-9],[0-9][0-9]}.exe'; function isMicrosoftStorePythonExePattern(interpreterPath) { return minimatch(path.basename(interpreterPath), pythonExeGlob, { nocase: true }); } async function getMicrosoftStorePythonExes() { if (await (0, microsoftStoreEnv_1.isStorePythonInstalled)()) { const windowsAppsRoot = (0, microsoftStoreEnv_1.getMicrosoftStoreAppsRoot)(); const files = await fsapi.readdir(windowsAppsRoot); return files .map((filename) => path.join(windowsAppsRoot, filename)) .filter(isMicrosoftStorePythonExePattern); } return []; } exports.getMicrosoftStorePythonExes = getMicrosoftStorePythonExes; class MicrosoftStoreLocator extends fsWatchingLocator_1.FSWatchingLocator { constructor() { super(microsoftStoreEnv_1.getMicrosoftStoreAppsRoot, async () => this.kind, { baseGlob: pythonExeGlob, searchLocation: (0, microsoftStoreEnv_1.getMicrosoftStoreAppsRoot)(), envStructure: pythonBinariesWatcher_1.PythonEnvStructure.Flat, }); this.providerId = 'microsoft-store'; this.kind = info_1.PythonEnvKind.MicrosoftStore; } doIterEnvs() { const iterator = async function* (kind) { (0, logging_1.traceVerbose)('Searching for windows store envs'); const exes = await getMicrosoftStorePythonExes(); yield* exes.map(async (executablePath) => ({ kind, executablePath, })); (0, logging_1.traceVerbose)(`Finished searching for windows store envs`); }; return iterator(this.kind); } } exports.MicrosoftStoreLocator = MicrosoftStoreLocator; /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/lowLevel/poetryLocator.ts": /*!*******************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/lowLevel/poetryLocator.ts ***! \*******************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PoetryLocator = void 0; const path = __webpack_require__(/*! path */ "path"); const async_1 = __webpack_require__(/*! ../../../../common/utils/async */ "./src/client/common/utils/async.ts"); const info_1 = __webpack_require__(/*! ../../info */ "./src/client/pythonEnvironments/base/info/index.ts"); const commonUtils_1 = __webpack_require__(/*! ../../../common/commonUtils */ "./src/client/pythonEnvironments/common/commonUtils.ts"); const externalDependencies_1 = __webpack_require__(/*! ../../../common/externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const poetry_1 = __webpack_require__(/*! ../../../common/environmentManagers/poetry */ "./src/client/pythonEnvironments/common/environmentManagers/poetry.ts"); __webpack_require__(/*! ../../../../common/extensions */ "./src/client/common/extensions.ts"); const arrayUtils_1 = __webpack_require__(/*! ../../../../common/utils/arrayUtils */ "./src/client/common/utils/arrayUtils.ts"); const logging_1 = __webpack_require__(/*! ../../../../logging */ "./src/client/logging/index.ts"); const resourceBasedLocator_1 = __webpack_require__(/*! ../common/resourceBasedLocator */ "./src/client/pythonEnvironments/base/locators/common/resourceBasedLocator.ts"); async function getVirtualEnvDirs(root) { const envDirs = [path.join(root, poetry_1.localPoetryEnvDirName)]; const poetry = await poetry_1.Poetry.getPoetry(root); const virtualenvs = await (poetry === null || poetry === void 0 ? void 0 : poetry.getEnvList()); if (virtualenvs) { envDirs.push(...virtualenvs); } return (0, arrayUtils_1.asyncFilter)(envDirs, externalDependencies_1.pathExists); } async function getVirtualEnvKind(interpreterPath) { if (await (0, poetry_1.isPoetryEnvironment)(interpreterPath)) { return info_1.PythonEnvKind.Poetry; } return info_1.PythonEnvKind.Unknown; } class PoetryLocator extends resourceBasedLocator_1.LazyResourceBasedLocator { constructor(root) { super(); this.root = root; this.providerId = 'poetry'; } doIterEnvs() { async function* iterator(root) { const envDirs = await getVirtualEnvDirs(root); const envGenerators = envDirs.map((envDir) => { async function* generator() { (0, logging_1.traceVerbose)(`Searching for poetry virtual envs in: ${envDir}`); const filename = await (0, commonUtils_1.getInterpreterPathFromDir)(envDir); if (filename !== undefined) { const kind = await getVirtualEnvKind(filename); try { yield { executablePath: filename, kind }; (0, logging_1.traceVerbose)(`Poetry Virtual Environment: [added] ${filename}`); } catch (ex) { (0, logging_1.traceError)(`Failed to process environment: ${filename}`, ex); } } } return generator(); }); yield* (0, async_1.iterable)((0, async_1.chain)(envGenerators)); (0, logging_1.traceVerbose)(`Finished searching for poetry envs`); } return iterator(this.root); } } exports.PoetryLocator = PoetryLocator; /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/lowLevel/posixKnownPathsLocator.ts": /*!****************************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/lowLevel/posixKnownPathsLocator.ts ***! \****************************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PosixKnownPathsLocator = void 0; const os = __webpack_require__(/*! os */ "os"); const semver_1 = __webpack_require__(/*! semver */ "./node_modules/semver/semver.js"); const info_1 = __webpack_require__(/*! ../../info */ "./src/client/pythonEnvironments/base/info/index.ts"); const locator_1 = __webpack_require__(/*! ../../locator */ "./src/client/pythonEnvironments/base/locator.ts"); const posixUtils_1 = __webpack_require__(/*! ../../../common/posixUtils */ "./src/client/pythonEnvironments/common/posixUtils.ts"); const pyenv_1 = __webpack_require__(/*! ../../../common/environmentManagers/pyenv */ "./src/client/pythonEnvironments/common/environmentManagers/pyenv.ts"); const platform_1 = __webpack_require__(/*! ../../../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const macDefault_1 = __webpack_require__(/*! ../../../common/environmentManagers/macDefault */ "./src/client/pythonEnvironments/common/environmentManagers/macDefault.ts"); const logging_1 = __webpack_require__(/*! ../../../../logging */ "./src/client/logging/index.ts"); class PosixKnownPathsLocator extends locator_1.Locator { constructor() { super(...arguments); this.providerId = 'posixKnownPaths'; this.kind = info_1.PythonEnvKind.OtherGlobal; } iterEnvs() { let isMacPython2Deprecated = false; if ((0, platform_1.getOSType)() === platform_1.OSType.OSX && (0, semver_1.gte)(os.release(), '21.0.0')) { isMacPython2Deprecated = true; } const iterator = async function* (kind) { (0, logging_1.traceVerbose)('Searching for interpreters in posix paths locator'); try { const knownDirs = (await (0, posixUtils_1.commonPosixBinPaths)()).filter((dirname) => !(0, pyenv_1.isPyenvShimDir)(dirname)); let pythonBinaries = await (0, posixUtils_1.getPythonBinFromPosixPaths)(knownDirs); (0, logging_1.traceVerbose)(`Found ${pythonBinaries.length} python binaries in posix paths`); if (isMacPython2Deprecated) { pythonBinaries = pythonBinaries.filter((binary) => !(0, macDefault_1.isMacDefaultPythonPath)(binary)); } for (const bin of pythonBinaries) { try { yield { executablePath: bin, kind, source: [info_1.PythonEnvSource.PathEnvVar] }; } catch (ex) { (0, logging_1.traceError)(`Failed to process environment: ${bin}`, ex); } } } catch (ex) { (0, logging_1.traceError)('Failed to process posix paths', ex); } (0, logging_1.traceVerbose)('Finished searching for interpreters in posix paths locator'); }; return iterator(this.kind); } } exports.PosixKnownPathsLocator = PosixKnownPathsLocator; /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/lowLevel/pyenvLocator.ts": /*!******************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/lowLevel/pyenvLocator.ts ***! \******************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PyenvLocator = void 0; const info_1 = __webpack_require__(/*! ../../info */ "./src/client/pythonEnvironments/base/info/index.ts"); const fsWatchingLocator_1 = __webpack_require__(/*! ./fsWatchingLocator */ "./src/client/pythonEnvironments/base/locators/lowLevel/fsWatchingLocator.ts"); const commonUtils_1 = __webpack_require__(/*! ../../../common/commonUtils */ "./src/client/pythonEnvironments/common/commonUtils.ts"); const externalDependencies_1 = __webpack_require__(/*! ../../../common/externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const pyenv_1 = __webpack_require__(/*! ../../../common/environmentManagers/pyenv */ "./src/client/pythonEnvironments/common/environmentManagers/pyenv.ts"); const logging_1 = __webpack_require__(/*! ../../../../logging */ "./src/client/logging/index.ts"); async function* getPyenvEnvironments() { (0, logging_1.traceVerbose)('Searching for pyenv environments'); const pyenvVersionDir = (0, pyenv_1.getPyenvVersionsDir)(); const subDirs = (0, externalDependencies_1.getSubDirs)(pyenvVersionDir, { resolveSymlinks: true }); for await (const subDirPath of subDirs) { const interpreterPath = await (0, commonUtils_1.getInterpreterPathFromDir)(subDirPath); if (interpreterPath) { try { yield { kind: info_1.PythonEnvKind.Pyenv, executablePath: interpreterPath, }; } catch (ex) { (0, logging_1.traceError)(`Failed to process environment: ${interpreterPath}`, ex); } } } (0, logging_1.traceVerbose)('Finished searching for pyenv environments'); } class PyenvLocator extends fsWatchingLocator_1.FSWatchingLocator { constructor() { super(pyenv_1.getPyenvVersionsDir, async () => info_1.PythonEnvKind.Pyenv); this.providerId = 'pyenv'; } doIterEnvs() { return getPyenvEnvironments(); } } exports.PyenvLocator = PyenvLocator; /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/lowLevel/windowsKnownPathsLocator.ts": /*!******************************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/lowLevel/windowsKnownPathsLocator.ts ***! \******************************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WindowsPathEnvVarLocator = void 0; const exec_1 = __webpack_require__(/*! ../../../../common/utils/exec */ "./src/client/common/utils/exec.ts"); const resourceLifecycle_1 = __webpack_require__(/*! ../../../../common/utils/resourceLifecycle */ "./src/client/common/utils/resourceLifecycle.ts"); const commonUtils_1 = __webpack_require__(/*! ../../../common/commonUtils */ "./src/client/pythonEnvironments/common/commonUtils.ts"); const pyenv_1 = __webpack_require__(/*! ../../../common/environmentManagers/pyenv */ "./src/client/pythonEnvironments/common/environmentManagers/pyenv.ts"); const microsoftStoreEnv_1 = __webpack_require__(/*! ../../../common/environmentManagers/microsoftStoreEnv */ "./src/client/pythonEnvironments/common/environmentManagers/microsoftStoreEnv.ts"); const info_1 = __webpack_require__(/*! ../../info */ "./src/client/pythonEnvironments/base/info/index.ts"); const locators_1 = __webpack_require__(/*! ../../locators */ "./src/client/pythonEnvironments/base/locators.ts"); const locatorUtils_1 = __webpack_require__(/*! ../../locatorUtils */ "./src/client/pythonEnvironments/base/locatorUtils.ts"); const filesLocator_1 = __webpack_require__(/*! ./filesLocator */ "./src/client/pythonEnvironments/base/locators/lowLevel/filesLocator.ts"); const logging_1 = __webpack_require__(/*! ../../../../logging */ "./src/client/logging/index.ts"); class WindowsPathEnvVarLocator { constructor() { this.providerId = 'windows-path-env-var-locator'; this.disposables = new resourceLifecycle_1.Disposables(); const dirLocators = (0, exec_1.getSearchPathEntries)() .filter((dirname) => !(0, microsoftStoreEnv_1.isMicrosoftStoreDir)(dirname) && !(0, pyenv_1.isPyenvShimDir)(dirname)) .map((dirname) => getDirFilesLocator(dirname, info_1.PythonEnvKind.System, [info_1.PythonEnvSource.PathEnvVar])); this.disposables.push(...dirLocators); this.locators = new locators_1.Locators(dirLocators); this.onChanged = this.locators.onChanged; } async dispose() { this.locators.dispose(); await this.disposables.dispose(); } iterEnvs(query) { return this.locators.iterEnvs(query); } } exports.WindowsPathEnvVarLocator = WindowsPathEnvVarLocator; async function* getExecutables(dirname) { for await (const entry of (0, commonUtils_1.iterPythonExecutablesInDir)(dirname)) { if (await (0, commonUtils_1.looksLikeBasicGlobalPython)(entry)) { yield entry.filename; } } } function getDirFilesLocator(dirname, kind, source) { const locator = new filesLocator_1.DirFilesLocator(dirname, kind, getExecutables, source); const dispose = async () => undefined; async function* iterEnvs(query) { (0, logging_1.traceVerbose)('Searching for windows path interpreters'); yield* await (0, locatorUtils_1.getEnvs)(locator.iterEnvs(query)).then((res) => { (0, logging_1.traceVerbose)('Finished searching for windows path interpreters'); return res; }); } return { providerId: locator.providerId, iterEnvs, dispose, onChanged: locator.onChanged, }; } /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/lowLevel/windowsRegistryLocator.ts": /*!****************************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/lowLevel/windowsRegistryLocator.ts ***! \****************************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WindowsRegistryLocator = void 0; const info_1 = __webpack_require__(/*! ../../info */ "./src/client/pythonEnvironments/base/info/index.ts"); const locator_1 = __webpack_require__(/*! ../../locator */ "./src/client/pythonEnvironments/base/locator.ts"); const windowsUtils_1 = __webpack_require__(/*! ../../../common/windowsUtils */ "./src/client/pythonEnvironments/common/windowsUtils.ts"); const logging_1 = __webpack_require__(/*! ../../../../logging */ "./src/client/logging/index.ts"); const microsoftStoreEnv_1 = __webpack_require__(/*! ../../../common/environmentManagers/microsoftStoreEnv */ "./src/client/pythonEnvironments/common/environmentManagers/microsoftStoreEnv.ts"); class WindowsRegistryLocator extends locator_1.Locator { constructor() { super(...arguments); this.providerId = 'windows-registry'; } iterEnvs() { const iterator = async function* () { (0, logging_1.traceVerbose)('Searching for windows registry interpreters'); const interpreters = await (0, windowsUtils_1.getRegistryInterpreters)(); for (const interpreter of interpreters) { try { if ((0, microsoftStoreEnv_1.isMicrosoftStoreDir)(interpreter.interpreterPath)) { continue; } const env = { kind: info_1.PythonEnvKind.OtherGlobal, executablePath: interpreter.interpreterPath, source: [info_1.PythonEnvSource.WindowsRegistry], }; yield env; } catch (ex) { (0, logging_1.traceError)(`Failed to process environment: ${interpreter}`, ex); } } (0, logging_1.traceVerbose)('Finished searching for windows registry interpreters'); }; return iterator(); } } exports.WindowsRegistryLocator = WindowsRegistryLocator; /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/lowLevel/workspaceVirtualEnvLocator.ts": /*!********************************************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/lowLevel/workspaceVirtualEnvLocator.ts ***! \********************************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WorkspaceVirtualEnvironmentLocator = void 0; const path = __webpack_require__(/*! path */ "path"); const async_1 = __webpack_require__(/*! ../../../../common/utils/async */ "./src/client/common/utils/async.ts"); const commonUtils_1 = __webpack_require__(/*! ../../../common/commonUtils */ "./src/client/pythonEnvironments/common/commonUtils.ts"); const externalDependencies_1 = __webpack_require__(/*! ../../../common/externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const pipenv_1 = __webpack_require__(/*! ../../../common/environmentManagers/pipenv */ "./src/client/pythonEnvironments/common/environmentManagers/pipenv.ts"); const simplevirtualenvs_1 = __webpack_require__(/*! ../../../common/environmentManagers/simplevirtualenvs */ "./src/client/pythonEnvironments/common/environmentManagers/simplevirtualenvs.ts"); const info_1 = __webpack_require__(/*! ../../info */ "./src/client/pythonEnvironments/base/info/index.ts"); const fsWatchingLocator_1 = __webpack_require__(/*! ./fsWatchingLocator */ "./src/client/pythonEnvironments/base/locators/lowLevel/fsWatchingLocator.ts"); __webpack_require__(/*! ../../../../common/extensions */ "./src/client/common/extensions.ts"); const arrayUtils_1 = __webpack_require__(/*! ../../../../common/utils/arrayUtils */ "./src/client/common/utils/arrayUtils.ts"); const logging_1 = __webpack_require__(/*! ../../../../logging */ "./src/client/logging/index.ts"); const DEFAULT_SEARCH_DEPTH = 2; function getWorkspaceVirtualEnvDirs(root) { return (0, arrayUtils_1.asyncFilter)([root, path.join(root, '.direnv')], externalDependencies_1.pathExists); } async function getVirtualEnvKind(interpreterPath) { if (await (0, pipenv_1.isPipenvEnvironment)(interpreterPath)) { return info_1.PythonEnvKind.Pipenv; } if (await (0, simplevirtualenvs_1.isVenvEnvironment)(interpreterPath)) { return info_1.PythonEnvKind.Venv; } if (await (0, simplevirtualenvs_1.isVirtualenvEnvironment)(interpreterPath)) { return info_1.PythonEnvKind.VirtualEnv; } return info_1.PythonEnvKind.Unknown; } class WorkspaceVirtualEnvironmentLocator extends fsWatchingLocator_1.FSWatchingLocator { constructor(root) { super(() => getWorkspaceVirtualEnvDirs(this.root), getVirtualEnvKind, { delayOnCreated: 1000, }, fsWatchingLocator_1.FSWatcherKind.Workspace); this.root = root; this.providerId = 'workspaceVirtualEnvLocator'; } doIterEnvs() { async function* iterator(root) { const envRootDirs = await getWorkspaceVirtualEnvDirs(root); const envGenerators = envRootDirs.map((envRootDir) => { async function* generator() { (0, logging_1.traceVerbose)(`Searching for workspace virtual envs in: ${envRootDir}`); const executables = (0, commonUtils_1.findInterpretersInDir)(envRootDir, DEFAULT_SEARCH_DEPTH); for await (const entry of executables) { const { filename } = entry; if (await (0, commonUtils_1.looksLikeBasicVirtualPython)(entry)) { const kind = await getVirtualEnvKind(filename); yield { kind, executablePath: filename }; (0, logging_1.traceVerbose)(`Workspace Virtual Environment: [added] ${filename}`); } else { (0, logging_1.traceVerbose)(`Workspace Virtual Environment: [skipped] ${filename}`); } } } return generator(); }); yield* (0, async_1.iterable)((0, async_1.chain)(envGenerators)); (0, logging_1.traceVerbose)(`Finished searching for workspace virtual envs`); } return iterator(this.root); } } exports.WorkspaceVirtualEnvironmentLocator = WorkspaceVirtualEnvironmentLocator; /***/ }), /***/ "./src/client/pythonEnvironments/base/locators/wrappers.ts": /*!*****************************************************************!*\ !*** ./src/client/pythonEnvironments/base/locators/wrappers.ts ***! \*****************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WorkspaceLocators = exports.ExtensionLocators = void 0; const async_1 = __webpack_require__(/*! ../../../common/utils/async */ "./src/client/common/utils/async.ts"); const misc_1 = __webpack_require__(/*! ../../../common/utils/misc */ "./src/client/common/utils/misc.ts"); const resourceLifecycle_1 = __webpack_require__(/*! ../../../common/utils/resourceLifecycle */ "./src/client/common/utils/resourceLifecycle.ts"); const locators_1 = __webpack_require__(/*! ../locators */ "./src/client/pythonEnvironments/base/locators.ts"); const resourceBasedLocator_1 = __webpack_require__(/*! ./common/resourceBasedLocator */ "./src/client/pythonEnvironments/base/locators/common/resourceBasedLocator.ts"); class ExtensionLocators extends locators_1.Locators { constructor(nonWorkspace, workspace) { super([...nonWorkspace, workspace]); this.nonWorkspace = nonWorkspace; this.workspace = workspace; } iterEnvs(query) { var _a; const iterators = [this.workspace.iterEnvs(query)]; if (!((_a = query === null || query === void 0 ? void 0 : query.searchLocations) === null || _a === void 0 ? void 0 : _a.doNotIncludeNonRooted)) { const nonWorkspace = (query === null || query === void 0 ? void 0 : query.providerId) ? this.nonWorkspace.filter((locator) => query.providerId === locator.providerId) : this.nonWorkspace; iterators.push(...nonWorkspace.map((loc) => loc.iterEnvs(query))); } return (0, locators_1.combineIterators)(iterators); } } exports.ExtensionLocators = ExtensionLocators; class WorkspaceLocators extends resourceBasedLocator_1.LazyResourceBasedLocator { constructor(watchRoots, factories) { super(); this.watchRoots = watchRoots; this.factories = factories; this.providerId = 'workspace-locators'; this.locators = {}; this.roots = {}; this.activate().ignoreErrors(); } async dispose() { await super.dispose(); const roots = Object.keys(this.roots).map((key) => this.roots[key]); roots.forEach((root) => this.removeRoot(root)); } doIterEnvs(query) { const iterators = Object.keys(this.locators).map((key) => { if ((query === null || query === void 0 ? void 0 : query.searchLocations) !== undefined) { const root = this.roots[key]; const filter = (0, misc_1.getURIFilter)(root, { checkParent: true, checkChild: true }); if (!query.searchLocations.roots.some(filter)) { return (0, async_1.iterEmpty)(); } if (query.providerId && query.providerId !== this.providerId) { return (0, async_1.iterEmpty)(); } } const [locator] = this.locators[key]; return locator.iterEnvs(query); }); return (0, locators_1.combineIterators)(iterators); } async initResources() { const disposable = this.watchRoots({ initRoot: (root) => this.addRoot(root), addRoot: (root) => { this.removeRoot(root); this.addRoot(root); this.emitter.fire({ searchLocation: root }); }, removeRoot: (root) => { this.removeRoot(root); this.emitter.fire({ searchLocation: root }); }, }); this.disposables.push(disposable); } addRoot(root) { const locators = []; const disposables = new resourceLifecycle_1.Disposables(); this.factories.forEach((create) => { create(root).forEach((loc) => { locators.push(loc); if (loc.dispose !== undefined) { disposables.push(loc); } }); }); const locator = new locators_1.Locators(locators); const key = root.toString(); this.locators[key] = [locator, disposables]; this.roots[key] = root; disposables.push(locator.onChanged((e) => { if (e.searchLocation === undefined) { e.searchLocation = root; } this.emitter.fire(e); })); } removeRoot(root) { const key = root.toString(); const found = this.locators[key]; if (found === undefined) { return; } const [, disposables] = found; delete this.locators[key]; delete this.roots[key]; disposables.dispose(); } } exports.WorkspaceLocators = WorkspaceLocators; /***/ }), /***/ "./src/client/pythonEnvironments/base/watcher.ts": /*!*******************************************************!*\ !*** ./src/client/pythonEnvironments/base/watcher.ts ***! \*******************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PythonEnvsWatcher = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); class PythonEnvsWatcher { constructor() { this.didChange = new vscode_1.EventEmitter(); this.onChanged = this.didChange.event; } fire(event) { this.didChange.fire(event); } } exports.PythonEnvsWatcher = PythonEnvsWatcher; /***/ }), /***/ "./src/client/pythonEnvironments/base/watchers.ts": /*!********************************************************!*\ !*** ./src/client/pythonEnvironments/base/watchers.ts ***! \********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PythonEnvsWatchers = void 0; const resourceLifecycle_1 = __webpack_require__(/*! ../../common/utils/resourceLifecycle */ "./src/client/common/utils/resourceLifecycle.ts"); const watcher_1 = __webpack_require__(/*! ./watcher */ "./src/client/pythonEnvironments/base/watcher.ts"); class PythonEnvsWatchers { constructor(watchers) { this.watcher = new watcher_1.PythonEnvsWatcher(); this.disposables = new resourceLifecycle_1.Disposables(); this.onChanged = this.watcher.onChanged; watchers.forEach((w) => { const disposable = w.onChanged((e) => this.watcher.fire(e)); this.disposables.push(disposable); }); } async dispose() { await this.disposables.dispose(); } } exports.PythonEnvsWatchers = PythonEnvsWatchers; /***/ }), /***/ "./src/client/pythonEnvironments/common/commonUtils.ts": /*!*************************************************************!*\ !*** ./src/client/pythonEnvironments/common/commonUtils.ts ***! \*************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEnvironmentDirFromPath = exports.getInterpreterPathFromDir = exports.looksLikeBasicVirtualPython = exports.looksLikeBasicGlobalPython = exports.getPythonVersionFromPath = exports.iterPythonExecutablesInDir = exports.findInterpretersInDir = exports.isPythonExecutable = void 0; const fs = __webpack_require__(/*! fs */ "fs"); const path = __webpack_require__(/*! path */ "path"); const filesystem_1 = __webpack_require__(/*! ../../common/utils/filesystem */ "./src/client/common/utils/filesystem.ts"); const platform_1 = __webpack_require__(/*! ../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const info_1 = __webpack_require__(/*! ../base/info */ "./src/client/pythonEnvironments/base/info/index.ts"); const env_1 = __webpack_require__(/*! ../base/info/env */ "./src/client/pythonEnvironments/base/info/env.ts"); const pythonVersion_1 = __webpack_require__(/*! ../base/info/pythonVersion */ "./src/client/pythonEnvironments/base/info/pythonVersion.ts"); const conda_1 = __webpack_require__(/*! ./environmentManagers/conda */ "./src/client/pythonEnvironments/common/environmentManagers/conda.ts"); const simplevirtualenvs_1 = __webpack_require__(/*! ./environmentManagers/simplevirtualenvs */ "./src/client/pythonEnvironments/common/environmentManagers/simplevirtualenvs.ts"); const externalDependencies_1 = __webpack_require__(/*! ./externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const posix = __webpack_require__(/*! ./posixUtils */ "./src/client/pythonEnvironments/common/posixUtils.ts"); const windows = __webpack_require__(/*! ./windowsUtils */ "./src/client/pythonEnvironments/common/windowsUtils.ts"); const matchStandardPythonBinFilename = (0, platform_1.getOSType)() === platform_1.OSType.Windows ? windows.matchPythonBinFilename : posix.matchPythonBinFilename; async function isPythonExecutable(filePath) { const isMatch = matchStandardPythonBinFilename(filePath); if (isMatch && (0, platform_1.getOSType)() === platform_1.OSType.Windows) { return true; } if (await (0, externalDependencies_1.isFile)(filePath)) { return true; } return false; } exports.isPythonExecutable = isPythonExecutable; async function* findInterpretersInDir(root, recurseLevel, filterSubDir, ignoreErrors = true) { const checkBin = (0, platform_1.getOSType)() === platform_1.OSType.Windows ? windows.matchPythonBinFilename : posix.matchPythonBinFilename; const cfg = { ignoreErrors, filterSubDir, filterFile: checkBin, maxDepth: recurseLevel || 0, }; for await (const entry of walkSubTree(root, 1, cfg)) { const { filename, filetype } = entry; if (filetype === filesystem_1.FileType.File || filetype === filesystem_1.FileType.SymbolicLink) { if (matchFile(filename, checkBin, ignoreErrors)) { yield entry; } } } } exports.findInterpretersInDir = findInterpretersInDir; async function* iterPythonExecutablesInDir(dirname, opts = { ignoreErrors: true }) { const readDirOpts = { ...opts, filterFile: matchStandardPythonBinFilename, }; const entries = await readDirEntries(dirname, readDirOpts); for (const entry of entries) { const { filetype } = entry; if (filetype === filesystem_1.FileType.File || filetype === filesystem_1.FileType.SymbolicLink) { yield entry; } } } exports.iterPythonExecutablesInDir = iterPythonExecutablesInDir; async function* walkSubTree(subRoot, currentDepth, cfg) { const entries = await readDirEntries(subRoot, cfg); for (const entry of entries) { yield entry; const { filename, filetype } = entry; if (filetype === filesystem_1.FileType.Directory) { if (cfg.maxDepth < 0 || currentDepth <= cfg.maxDepth) { if (matchFile(filename, cfg.filterSubDir, cfg.ignoreErrors)) { yield* walkSubTree(filename, currentDepth + 1, cfg); } } } } } async function readDirEntries(dirname, opts = { ignoreErrors: true }) { const ignoreErrors = opts.ignoreErrors || false; if (opts.filterFilename && (0, platform_1.getOSType)() === platform_1.OSType.Windows) { let basenames; try { basenames = await fs.promises.readdir(dirname); } catch (err) { const exception = err; if (exception.code === 'ENOENT') { return []; } if (ignoreErrors) { (0, logging_1.traceError)(`readdir() failed for "${dirname}" (${err})`); return []; } throw err; } const filenames = basenames .map((b) => path.join(dirname, b)) .filter((f) => matchFile(f, opts.filterFilename, ignoreErrors)); return Promise.all(filenames.map(async (filename) => { const filetype = (await (0, filesystem_1.getFileType)(filename, opts)) || filesystem_1.FileType.Unknown; return { filename, filetype }; })); } let raw; try { raw = await fs.promises.readdir(dirname, { withFileTypes: true }); } catch (err) { const exception = err; if (exception.code === 'ENOENT') { return []; } if (ignoreErrors) { (0, logging_1.traceError)(`readdir() failed for "${dirname}" (${err})`); return []; } throw err; } const entries = raw.map((entry) => { const filename = path.join(dirname, entry.name); const filetype = (0, filesystem_1.convertFileType)(entry); return { filename, filetype }; }); if (opts.filterFilename) { return entries.filter((e) => matchFile(e.filename, opts.filterFilename, ignoreErrors)); } return entries; } function matchFile(filename, filterFile, ignoreErrors = true) { if (filterFile === undefined) { return true; } try { return filterFile(filename); } catch (err) { if (ignoreErrors) { (0, logging_1.traceError)(`filter failed for "${filename}" (${err})`); return false; } throw err; } } async function getPythonVersionFromNearByFiles(interpreterPath) { const root = path.dirname(interpreterPath); let version = info_1.UNKNOWN_PYTHON_VERSION; for await (const entry of findInterpretersInDir(root)) { const { filename } = entry; try { const curVersion = (0, pythonVersion_1.parseVersion)(path.basename(filename)); if ((0, env_1.comparePythonVersionSpecificity)(curVersion, version) > 0) { version = curVersion; } } catch (ex) { } } return version; } async function getPythonVersionFromPath(interpreterPath, hint) { let versionA; try { versionA = hint ? (0, pythonVersion_1.parseVersion)(hint) : info_1.UNKNOWN_PYTHON_VERSION; } catch (ex) { versionA = info_1.UNKNOWN_PYTHON_VERSION; } const versionB = interpreterPath ? await getPythonVersionFromNearByFiles(interpreterPath) : info_1.UNKNOWN_PYTHON_VERSION; const versionC = interpreterPath ? await (0, simplevirtualenvs_1.getPythonVersionFromPyvenvCfg)(interpreterPath) : info_1.UNKNOWN_PYTHON_VERSION; const versionD = interpreterPath ? await (0, conda_1.getPythonVersionFromConda)(interpreterPath) : info_1.UNKNOWN_PYTHON_VERSION; let version = info_1.UNKNOWN_PYTHON_VERSION; for (const v of [versionA, versionB, versionC, versionD]) { version = (0, env_1.comparePythonVersionSpecificity)(version, v) > 0 ? version : v; } return version; } exports.getPythonVersionFromPath = getPythonVersionFromPath; async function checkPythonExecutable(executable, opts) { const matchFilename = opts.matchFilename || matchStandardPythonBinFilename; const filename = typeof executable === 'string' ? executable : executable.filename; if (!matchFilename(filename)) { return false; } if (opts.filterFile && !(await opts.filterFile(executable))) { return false; } return true; } const filterGlobalExecutable = (0, filesystem_1.getFileFilter)({ ignoreFileType: filesystem_1.FileType.SymbolicLink }); async function looksLikeBasicGlobalPython(executable) { const matchBasic = (0, platform_1.getOSType)() === platform_1.OSType.Windows ? windows.matchBasicPythonBinFilename : posix.matchBasicPythonBinFilename; const matchFilename = matchBasic; const filterFile = filterGlobalExecutable; return checkPythonExecutable(executable, { matchFilename, filterFile }); } exports.looksLikeBasicGlobalPython = looksLikeBasicGlobalPython; async function looksLikeBasicVirtualPython(executable) { const matchBasic = (0, platform_1.getOSType)() === platform_1.OSType.Windows ? windows.matchBasicPythonBinFilename : posix.matchBasicPythonBinFilename; const matchFilename = matchBasic; const filterFile = undefined; return checkPythonExecutable(executable, { matchFilename, filterFile }); } exports.looksLikeBasicVirtualPython = looksLikeBasicVirtualPython; async function getInterpreterPathFromDir(envDir, opts = {}) { const recurseLevel = 2; function filterDir(dirname) { const lower = path.basename(dirname).toLowerCase(); return ['bin', 'scripts'].includes(lower); } const matchExecutable = opts.global ? looksLikeBasicGlobalPython : looksLikeBasicVirtualPython; const executables = findInterpretersInDir(envDir, recurseLevel, filterDir, opts.ignoreErrors); for await (const entry of executables) { if (await matchExecutable(entry)) { return entry.filename; } } return undefined; } exports.getInterpreterPathFromDir = getInterpreterPathFromDir; function getEnvironmentDirFromPath(interpreterPath) { const skipDirs = ['bin', 'scripts']; const dir = path.basename(path.dirname(interpreterPath)); if (!skipDirs.map((e) => (0, externalDependencies_1.normCasePath)(e)).includes((0, externalDependencies_1.normCasePath)(dir))) { return path.dirname(interpreterPath); } return path.dirname(path.dirname(interpreterPath)); } exports.getEnvironmentDirFromPath = getEnvironmentDirFromPath; /***/ }), /***/ "./src/client/pythonEnvironments/common/environmentIdentifier.ts": /*!***********************************************************************!*\ !*** ./src/client/pythonEnvironments/common/environmentIdentifier.ts ***! \***********************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.identifyEnvironment = void 0; const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const info_1 = __webpack_require__(/*! ../base/info */ "./src/client/pythonEnvironments/base/info/index.ts"); const envKind_1 = __webpack_require__(/*! ../base/info/envKind */ "./src/client/pythonEnvironments/base/info/envKind.ts"); const conda_1 = __webpack_require__(/*! ./environmentManagers/conda */ "./src/client/pythonEnvironments/common/environmentManagers/conda.ts"); const globalInstalledEnvs_1 = __webpack_require__(/*! ./environmentManagers/globalInstalledEnvs */ "./src/client/pythonEnvironments/common/environmentManagers/globalInstalledEnvs.ts"); const pipenv_1 = __webpack_require__(/*! ./environmentManagers/pipenv */ "./src/client/pythonEnvironments/common/environmentManagers/pipenv.ts"); const poetry_1 = __webpack_require__(/*! ./environmentManagers/poetry */ "./src/client/pythonEnvironments/common/environmentManagers/poetry.ts"); const pyenv_1 = __webpack_require__(/*! ./environmentManagers/pyenv */ "./src/client/pythonEnvironments/common/environmentManagers/pyenv.ts"); const simplevirtualenvs_1 = __webpack_require__(/*! ./environmentManagers/simplevirtualenvs */ "./src/client/pythonEnvironments/common/environmentManagers/simplevirtualenvs.ts"); const microsoftStoreEnv_1 = __webpack_require__(/*! ./environmentManagers/microsoftStoreEnv */ "./src/client/pythonEnvironments/common/environmentManagers/microsoftStoreEnv.ts"); const activestate_1 = __webpack_require__(/*! ./environmentManagers/activestate */ "./src/client/pythonEnvironments/common/environmentManagers/activestate.ts"); function getIdentifiers() { const notImplemented = () => Promise.resolve(false); const defaultTrue = () => Promise.resolve(true); const identifier = new Map(); Object.values(info_1.PythonEnvKind).forEach((k) => { identifier.set(k, notImplemented); }); identifier.set(info_1.PythonEnvKind.Conda, conda_1.isCondaEnvironment); identifier.set(info_1.PythonEnvKind.MicrosoftStore, microsoftStoreEnv_1.isMicrosoftStoreEnvironment); identifier.set(info_1.PythonEnvKind.Pipenv, pipenv_1.isPipenvEnvironment); identifier.set(info_1.PythonEnvKind.Pyenv, pyenv_1.isPyenvEnvironment); identifier.set(info_1.PythonEnvKind.Poetry, poetry_1.isPoetryEnvironment); identifier.set(info_1.PythonEnvKind.Venv, simplevirtualenvs_1.isVenvEnvironment); identifier.set(info_1.PythonEnvKind.VirtualEnvWrapper, simplevirtualenvs_1.isVirtualenvwrapperEnvironment); identifier.set(info_1.PythonEnvKind.VirtualEnv, simplevirtualenvs_1.isVirtualenvEnvironment); identifier.set(info_1.PythonEnvKind.ActiveState, activestate_1.isActiveStateEnvironment); identifier.set(info_1.PythonEnvKind.Unknown, defaultTrue); identifier.set(info_1.PythonEnvKind.OtherGlobal, globalInstalledEnvs_1.isGloballyInstalledEnv); return identifier; } async function identifyEnvironment(path) { const identifiers = getIdentifiers(); const prioritizedEnvTypes = (0, envKind_1.getPrioritizedEnvKinds)(); for (const e of prioritizedEnvTypes) { const identifier = identifiers.get(e); if (identifier && (await identifier(path).catch((ex) => { (0, logging_1.traceWarn)(`Identifier for ${e} failed to identify ${path}`, ex); return false; }))) { return e; } } return info_1.PythonEnvKind.Unknown; } exports.identifyEnvironment = identifyEnvironment; /***/ }), /***/ "./src/client/pythonEnvironments/common/environmentManagers/activestate.ts": /*!*********************************************************************************!*\ !*** ./src/client/pythonEnvironments/common/environmentManagers/activestate.ts ***! \*********************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isActiveStateEnvironmentForWorkspace = exports.ActiveState = exports.isActiveStateEnvironment = exports.ACTIVESTATETOOLPATH_SETTING_KEY = void 0; const path = __webpack_require__(/*! path */ "path"); const path_1 = __webpack_require__(/*! path */ "path"); const externalDependencies_1 = __webpack_require__(/*! ../externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const decorators_1 = __webpack_require__(/*! ../../../common/utils/decorators */ "./src/client/common/utils/decorators.ts"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); const platform_1 = __webpack_require__(/*! ../../../common/utils/platform */ "./src/client/common/utils/platform.ts"); exports.ACTIVESTATETOOLPATH_SETTING_KEY = 'activeStateToolPath'; const STATE_GENERAL_TIMEOUT = 5000; async function isActiveStateEnvironment(interpreterPath) { const execDir = path.dirname(interpreterPath); const runtimeDir = path.dirname(execDir); return (0, externalDependencies_1.pathExists)(path.join(runtimeDir, '_runtime_store')); } exports.isActiveStateEnvironment = isActiveStateEnvironment; class ActiveState { constructor() { (0, externalDependencies_1.onDidChangePythonSetting)(exports.ACTIVESTATETOOLPATH_SETTING_KEY, () => { ActiveState.statePromise = undefined; }); } static async getState() { if (ActiveState.statePromise === undefined) { ActiveState.statePromise = ActiveState.locate(); } return ActiveState.statePromise; } static getStateToolDir() { const home = (0, platform_1.getUserHomeDir)(); if (!home) { return undefined; } return (0, platform_1.getOSType)() === platform_1.OSType.Windows ? path.join(home, 'AppData', 'Local', 'ActiveState', 'StateTool') : path.join(home, '.local', 'ActiveState', 'StateTool'); } static async locate() { var _a; const stateToolDir = this.getStateToolDir(); const stateCommand = (_a = (0, externalDependencies_1.getPythonSetting)(exports.ACTIVESTATETOOLPATH_SETTING_KEY)) !== null && _a !== void 0 ? _a : ActiveState.defaultStateCommand; if (stateToolDir && ((await (0, externalDependencies_1.pathExists)(stateToolDir)) || stateCommand !== this.defaultStateCommand)) { return new ActiveState(); } return undefined; } async getProjects() { return this.getProjectsCached(); } async getProjectsCached() { var _a; try { const stateCommand = (_a = (0, externalDependencies_1.getPythonSetting)(exports.ACTIVESTATETOOLPATH_SETTING_KEY)) !== null && _a !== void 0 ? _a : ActiveState.defaultStateCommand; const result = await (0, externalDependencies_1.shellExecute)(`${stateCommand} projects -o editor`, { timeout: STATE_GENERAL_TIMEOUT, }); if (!result) { return undefined; } let output = result.stdout.trimEnd(); if (output[output.length - 1] === '\0') { output = output.substring(0, output.length - 1); } (0, logging_1.traceVerbose)(`${stateCommand} projects -o editor: ${output}`); const projects = JSON.parse(output); ActiveState.setCachedProjectInfo(projects); return projects; } catch (ex) { (0, logging_1.traceError)(ex); return undefined; } } static getCachedProjectInfo() { return this.cachedProjectInfo; } static setCachedProjectInfo(projects) { this.cachedProjectInfo = projects; } } ActiveState.defaultStateCommand = 'state'; ActiveState.cachedProjectInfo = []; __decorate([ (0, decorators_1.cache)(30000, true, 10000) ], ActiveState.prototype, "getProjectsCached", null); exports.ActiveState = ActiveState; function isActiveStateEnvironmentForWorkspace(interpreterPath, workspacePath) { const interpreterDir = (0, path_1.dirname)(interpreterPath); for (const project of ActiveState.getCachedProjectInfo()) { if (project.executables) { for (const [i, dir] of project.executables.entries()) { if ((0, externalDependencies_1.arePathsSame)(dir, interpreterDir) && (0, externalDependencies_1.arePathsSame)(workspacePath, project.local_checkouts[i])) { return true; } } } } return false; } exports.isActiveStateEnvironmentForWorkspace = isActiveStateEnvironmentForWorkspace; /***/ }), /***/ "./src/client/pythonEnvironments/common/environmentManagers/conda.ts": /*!***************************************************************************!*\ !*** ./src/client/pythonEnvironments/common/environmentManagers/conda.ts ***! \***************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Conda = exports.CONDA_ACTIVATION_TIMEOUT = exports.CONDA_RUN_VERSION = exports.getCondaInterpreterPath = exports.getPythonVersionFromConda = exports.getCondaEnvironmentsTxt = exports.isCondaEnvironment = exports.getCondaMetaPaths = exports.parseCondaInfo = exports.CONDAPATH_SETTING_KEY = exports.AnacondaCompanyName = void 0; const fsapi = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const path = __webpack_require__(/*! path */ "path"); const semver_1 = __webpack_require__(/*! semver */ "./node_modules/semver/semver.js"); const platform_1 = __webpack_require__(/*! ../../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const externalDependencies_1 = __webpack_require__(/*! ../externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const info_1 = __webpack_require__(/*! ../../base/info */ "./src/client/pythonEnvironments/base/info/index.ts"); const pythonVersion_1 = __webpack_require__(/*! ../../base/info/pythonVersion */ "./src/client/pythonEnvironments/base/info/pythonVersion.ts"); const windowsUtils_1 = __webpack_require__(/*! ../windowsUtils */ "./src/client/pythonEnvironments/common/windowsUtils.ts"); const info_2 = __webpack_require__(/*! ../../info */ "./src/client/pythonEnvironments/info/index.ts"); const decorators_1 = __webpack_require__(/*! ../../../common/utils/decorators */ "./src/client/common/utils/decorators.ts"); const constants_1 = __webpack_require__(/*! ../../../common/constants */ "./src/client/common/constants.ts"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); const scripts_1 = __webpack_require__(/*! ../../../common/process/internal/scripts */ "./src/client/common/process/internal/scripts/index.ts"); const stringUtils_1 = __webpack_require__(/*! ../../../common/stringUtils */ "./src/client/common/stringUtils.ts"); exports.AnacondaCompanyName = 'Anaconda, Inc.'; exports.CONDAPATH_SETTING_KEY = 'condaPath'; async function parseCondaInfo(info, getPythonPath, fileExists, getPythonInfo) { const envs = Array.isArray(info.envs) ? info.envs : []; if (info.default_prefix && info.default_prefix.length > 0) { envs.push(info.default_prefix); } const promises = envs.map(async (envPath) => { const pythonPath = getPythonPath(envPath); if (!(await fileExists(pythonPath))) { return undefined; } const details = await getPythonInfo(pythonPath); if (!details) { return undefined; } return { ...details, path: pythonPath, companyDisplayName: exports.AnacondaCompanyName, envType: info_2.EnvironmentType.Conda, envPath, }; }); return Promise.all(promises) .then((interpreters) => interpreters.filter((interpreter) => interpreter !== null && interpreter !== undefined)) .then((interpreters) => interpreters.map((interpreter) => interpreter)); } exports.parseCondaInfo = parseCondaInfo; function getCondaMetaPaths(interpreterPathOrEnvPath) { const condaMetaDir = 'conda-meta'; const condaEnvDir1 = path.join(path.dirname(interpreterPathOrEnvPath), condaMetaDir); const condaEnvDir2 = path.join(path.dirname(path.dirname(interpreterPathOrEnvPath)), condaMetaDir); const condaEnvDir3 = path.join(interpreterPathOrEnvPath, condaMetaDir); return [condaEnvDir1, condaEnvDir2, condaEnvDir3]; } exports.getCondaMetaPaths = getCondaMetaPaths; async function isCondaEnvironment(interpreterPathOrEnvPath) { const condaMetaPaths = getCondaMetaPaths(interpreterPathOrEnvPath); for (const condaMeta of condaMetaPaths) { if (await (0, externalDependencies_1.pathExists)(condaMeta)) { return true; } } return false; } exports.isCondaEnvironment = isCondaEnvironment; async function getCondaEnvironmentsTxt() { const homeDir = (0, platform_1.getUserHomeDir)(); if (!homeDir) { return []; } const environmentsTxt = path.join(homeDir, '.conda', 'environments.txt'); return [environmentsTxt]; } exports.getCondaEnvironmentsTxt = getCondaEnvironmentsTxt; async function getPythonVersionFromConda(interpreterPath) { const configPaths = getCondaMetaPaths(interpreterPath).map((p) => path.join(p, 'history')); const pattern = /\:python-(([\d\.a-z]?)+)/; for (const configPath of configPaths) { if (await (0, externalDependencies_1.pathExists)(configPath)) { try { const lines = (0, stringUtils_1.splitLines)(await (0, externalDependencies_1.readFile)(configPath)); const pythonVersionStrings = lines .map((line) => { const matches = pattern.exec(line); return matches ? matches[1] : ''; }) .filter((v) => v.length > 0); if (pythonVersionStrings.length > 0) { const last = pythonVersionStrings.length - 1; return (0, pythonVersion_1.parseVersion)(pythonVersionStrings[last].trim()); } } catch (ex) { return info_1.UNKNOWN_PYTHON_VERSION; } } } return info_1.UNKNOWN_PYTHON_VERSION; } exports.getPythonVersionFromConda = getPythonVersionFromConda; function getCondaInterpreterPath(condaEnvironmentPath) { const relativePath = (0, platform_1.getOSType)() === platform_1.OSType.Windows ? 'python.exe' : path.join('bin', 'python'); const filePath = path.join(condaEnvironmentPath, relativePath); return filePath; } exports.getCondaInterpreterPath = getCondaInterpreterPath; exports.CONDA_RUN_VERSION = '4.9.0'; exports.CONDA_ACTIVATION_TIMEOUT = 45000; const CONDA_GENERAL_TIMEOUT = 50000; class Conda { constructor(command, shellCommand, shellPath) { this.command = command; this.shellPath = shellPath; this.condaInfoCached = new Map(); this.shellCommand = shellCommand !== null && shellCommand !== void 0 ? shellCommand : command; (0, externalDependencies_1.onDidChangePythonSetting)(exports.CONDAPATH_SETTING_KEY, () => { Conda.condaPromise = new Map(); }); } static async getConda(shellPath) { if (Conda.condaPromise.get(shellPath) === undefined || (0, constants_1.isTestExecution)()) { Conda.condaPromise.set(shellPath, Conda.locate(shellPath)); } return Conda.condaPromise.get(shellPath); } static async locate(shellPath) { (0, logging_1.traceVerbose)(`Searching for conda.`); const home = (0, platform_1.getUserHomeDir)(); const customCondaPath = (0, externalDependencies_1.getPythonSetting)(exports.CONDAPATH_SETTING_KEY); const suffix = (0, platform_1.getOSType)() === platform_1.OSType.Windows ? 'Scripts\\conda.exe' : 'bin/conda'; async function* getCandidates() { if (customCondaPath && customCondaPath !== 'conda') { yield customCondaPath; } yield 'conda'; if ((0, platform_1.getOSType)() === platform_1.OSType.Windows) { yield* getCandidatesFromRegistry(); } yield* getCandidatesFromKnownPaths(); yield* getCandidatesFromEnvironmentsTxt(); } async function* getCandidatesFromRegistry() { const interps = await (0, windowsUtils_1.getRegistryInterpreters)(); const candidates = interps .filter((interp) => interp.interpreterPath && interp.distroOrgName === 'ContinuumAnalytics') .map((interp) => path.join(path.win32.dirname(interp.interpreterPath), suffix)); yield* candidates; } async function* getCandidatesFromKnownPaths() { const prefixes = []; if ((0, platform_1.getOSType)() === platform_1.OSType.Windows) { const programData = (0, platform_1.getEnvironmentVariable)('PROGRAMDATA') || 'C:\\ProgramData'; prefixes.push(programData); if (home) { const localAppData = (0, platform_1.getEnvironmentVariable)('LOCALAPPDATA') || path.join(home, 'AppData', 'Local'); prefixes.push(home, path.join(localAppData, 'Continuum')); } } else { prefixes.push('/usr/share', '/usr/local/share', '/opt'); if (home) { prefixes.push(home, path.join(home, 'opt')); } } for (const prefix of prefixes) { let items; try { items = await fsapi.readdir(prefix); } catch (ex) { items = undefined; } if (items !== undefined) { yield* items .filter((fileName) => fileName.toLowerCase().includes('conda')) .map((fileName) => path.join(prefix, fileName, suffix)); } } } async function* getCandidatesFromEnvironmentsTxt() { if (!home) { return; } let contents; try { contents = await fsapi.readFile(path.join(home, '.conda', 'environments.txt'), 'utf8'); } catch (ex) { contents = ''; } yield* contents .split(/\r?\n/g) .map((line) => line.trim()) .filter((line) => line !== '' && !line.startsWith('#')) .map((line) => path.join(line, suffix)); } async function getCondaBatFile(file) { const fileDir = path.dirname(file); const possibleBatch = path.join(fileDir, '..', 'condabin', 'conda.bat'); if (await (0, externalDependencies_1.pathExists)(possibleBatch)) { return possibleBatch; } return undefined; } for await (const condaPath of getCandidates()) { (0, logging_1.traceVerbose)(`Probing conda binary: ${condaPath}`); let conda = new Conda(condaPath, undefined, shellPath); try { await conda.getInfo(); if ((0, platform_1.getOSType)() === platform_1.OSType.Windows && ((0, constants_1.isTestExecution)() || condaPath !== customCondaPath)) { const condaBatFile = await getCondaBatFile(condaPath); try { if (condaBatFile) { const condaBat = new Conda(condaBatFile, undefined, shellPath); await condaBat.getInfo(); conda = new Conda(condaPath, condaBatFile, shellPath); } } catch (ex) { (0, logging_1.traceVerbose)('Failed to spawn conda bat file', condaBatFile, ex); } } (0, logging_1.traceVerbose)(`Found conda via filesystem probing: ${condaPath}`); return conda; } catch (ex) { (0, logging_1.traceVerbose)('Failed to spawn conda binary', condaPath, ex); } } (0, logging_1.traceVerbose)("Couldn't locate the conda binary."); return undefined; } async getInfo(useCache) { let condaInfoCached = this.condaInfoCached.get(this.shellPath); if (!useCache || !condaInfoCached) { condaInfoCached = this.getInfoImpl(this.command, this.shellPath); this.condaInfoCached.set(this.shellPath, condaInfoCached); } return condaInfoCached; } async getInfoImpl(command, shellPath) { const options = { timeout: CONDA_GENERAL_TIMEOUT }; if (shellPath) { options.shell = shellPath; } const result = await (0, externalDependencies_1.exec)(command, ['info', '--json'], options); (0, logging_1.traceVerbose)(`${command} info --json: ${result.stdout}`); return JSON.parse(result.stdout); } async getEnvList() { const info = await this.getInfo(); const { envs } = info; if (envs === undefined) { return []; } return Promise.all(envs.map(async (prefix) => ({ prefix, name: await this.getName(prefix, info), }))); } async getName(prefix, info) { info = info !== null && info !== void 0 ? info : (await this.getInfo(true)); if (info.root_prefix && (0, externalDependencies_1.arePathsSame)(prefix, info.root_prefix)) { return 'base'; } const parentDir = path.dirname(prefix); if (info.envs_dirs !== undefined) { for (const envsDir of info.envs_dirs) { if ((0, externalDependencies_1.arePathsSame)(parentDir, envsDir)) { return path.basename(prefix); } } } return undefined; } async getCondaEnvironment(executableOrEnvPath) { const envList = await this.getEnvList(); const condaEnv = envList.find((e) => (0, externalDependencies_1.arePathsSame)(executableOrEnvPath, e.prefix)); if (condaEnv) { return condaEnv; } return envList.find((e) => (0, externalDependencies_1.isParentPath)(executableOrEnvPath, e.prefix)); } async getInterpreterPathForEnvironment(condaEnv) { const executablePath = getCondaInterpreterPath(condaEnv.prefix); if (await (0, externalDependencies_1.pathExists)(executablePath)) { (0, logging_1.traceVerbose)('Found executable within conda env', JSON.stringify(condaEnv)); return executablePath; } (0, logging_1.traceVerbose)('Executable does not exist within conda env, assume the executable to be `python`', JSON.stringify(condaEnv)); return 'python'; } async getRunPythonArgs(env, forShellExecution, isolatedFlag = false) { const condaVersion = await this.getCondaVersion(); if (condaVersion && (0, semver_1.lt)(condaVersion, exports.CONDA_RUN_VERSION)) { (0, logging_1.traceError)('`conda run` is not supported for conda version', condaVersion.raw); return undefined; } const args = []; if (env.name) { args.push('-n', env.name); } else { args.push('-p', env.prefix); } const python = [ forShellExecution ? this.shellCommand : this.command, 'run', ...args, '--no-capture-output', 'python', ]; if (isolatedFlag) { python.push('-I'); } return [...python, scripts_1.OUTPUT_MARKER_SCRIPT]; } async getCondaVersion() { const info = await this.getInfo(true).catch(() => undefined); let versionString; if (info && info.conda_version) { versionString = info.conda_version; } else { const stdOut = await (0, externalDependencies_1.exec)(this.command, ['--version'], { timeout: CONDA_GENERAL_TIMEOUT }) .then((result) => result.stdout.trim()) .catch(() => undefined); versionString = stdOut && stdOut.startsWith('conda ') ? stdOut.substring('conda '.length).trim() : stdOut; } if (!versionString) { return undefined; } const pattern = /(?\d+)\.(?\d+)\.(?\d+)(?:.*)?/; const match = versionString.match(pattern); if (match && match.groups) { const versionStringParsed = match.groups.major.concat('.', match.groups.minor, '.', match.groups.micro); const semVarVersion = new semver_1.SemVer(versionStringParsed); if (semVarVersion) { return semVarVersion; } } (0, logging_1.traceError)(`Unable to parse version of Conda, ${versionString}`); return new semver_1.SemVer('0.0.1'); } async isCondaRunSupported() { const condaVersion = await this.getCondaVersion(); if (condaVersion && (0, semver_1.lt)(condaVersion, exports.CONDA_RUN_VERSION)) { return false; } return true; } } Conda.condaPromise = new Map(); __decorate([ (0, decorators_1.cache)(30000, true, 10000) ], Conda.prototype, "getInfoImpl", null); __decorate([ (0, decorators_1.cache)(30000, true, 10000) ], Conda.prototype, "getEnvList", null); __decorate([ (0, decorators_1.cache)(-1, true) ], Conda.prototype, "getCondaVersion", null); exports.Conda = Conda; /***/ }), /***/ "./src/client/pythonEnvironments/common/environmentManagers/condaService.ts": /*!**********************************************************************************!*\ !*** ./src/client/pythonEnvironments/common/environmentManagers/condaService.ts ***! \**********************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CondaService = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const path = __webpack_require__(/*! path */ "path"); const types_1 = __webpack_require__(/*! ../../../common/platform/types */ "./src/client/common/platform/types.ts"); const decorators_1 = __webpack_require__(/*! ../../../common/utils/decorators */ "./src/client/common/utils/decorators.ts"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); const conda_1 = __webpack_require__(/*! ./conda */ "./src/client/pythonEnvironments/common/environmentManagers/conda.ts"); let CondaService = class CondaService { constructor(platform, fileSystem) { this.platform = platform; this.fileSystem = fileSystem; } async getActivationScriptFromInterpreter(interpreterPath, envName) { const condaPath = await this.getCondaFileFromInterpreter(interpreterPath, envName); const activatePath = (condaPath ? path.join(path.dirname(condaPath), 'activate') : 'activate').fileToCommandArgumentForPythonMgrExt(); if (this.platform.isLinux || this.platform.isMac) { const condaInfo = await this.getCondaInfo(); if (condaInfo === null || condaInfo === void 0 ? void 0 : condaInfo.root_prefix) { const globalActivatePath = path .join(condaInfo.root_prefix, this.platform.virtualEnvBinName, 'activate') .fileToCommandArgumentForPythonMgrExt(); if (activatePath === globalActivatePath || !(await this.fileSystem.fileExists(activatePath))) { return { path: globalActivatePath, type: 'global', }; } } } return { path: activatePath, type: 'local' }; } async getCondaFile(forShellExecution) { return conda_1.Conda.getConda().then((conda) => { const command = forShellExecution ? conda === null || conda === void 0 ? void 0 : conda.shellCommand : conda === null || conda === void 0 ? void 0 : conda.command; return command !== null && command !== void 0 ? command : 'conda'; }); } async getInterpreterPathForEnvironment(condaEnv) { const conda = await conda_1.Conda.getConda(); return conda === null || conda === void 0 ? void 0 : conda.getInterpreterPathForEnvironment({ name: condaEnv.name, prefix: condaEnv.path }); } async isCondaAvailable() { if (typeof this.isAvailable === 'boolean') { return this.isAvailable; } return this.getCondaVersion() .then((version) => (this.isAvailable = version !== undefined)) .catch(() => (this.isAvailable = false)); } async getCondaVersion() { return conda_1.Conda.getConda().then((conda) => conda === null || conda === void 0 ? void 0 : conda.getCondaVersion()); } async getCondaFileFromInterpreter(interpreterPath, envName) { const condaExe = this.platform.isWindows ? 'conda.exe' : 'conda'; const scriptsDir = this.platform.isWindows ? 'Scripts' : 'bin'; const interpreterDir = interpreterPath ? path.dirname(interpreterPath) : ''; const envsPos = envName ? interpreterDir.indexOf(path.join('envs', envName)) : -1; if (envsPos > 0) { const originalPath = interpreterDir.slice(0, envsPos); let condaPath1 = path.join(originalPath, condaExe); if (await this.fileSystem.fileExists(condaPath1)) { return condaPath1; } condaPath1 = path.join(originalPath, scriptsDir, condaExe); if (await this.fileSystem.fileExists(condaPath1)) { return condaPath1; } } let condaPath2 = path.join(interpreterDir, condaExe); if (await this.fileSystem.fileExists(condaPath2)) { return condaPath2; } condaPath2 = path.join(interpreterDir, scriptsDir, condaExe); if (await this.fileSystem.fileExists(condaPath2)) { return condaPath2; } return this.getCondaFile(); } async getCondaInfo() { const conda = await conda_1.Conda.getConda(); return conda === null || conda === void 0 ? void 0 : conda.getInfo(); } }; __decorate([ (0, logging_1.traceDecoratorVerbose)('Get Conda File from interpreter'), (0, decorators_1.cache)(120000) ], CondaService.prototype, "getCondaFileFromInterpreter", null); __decorate([ (0, decorators_1.cache)(60000) ], CondaService.prototype, "getCondaInfo", null); CondaService = __decorate([ (0, inversify_1.injectable)(), __param(0, (0, inversify_1.inject)(types_1.IPlatformService)), __param(1, (0, inversify_1.inject)(types_1.IFileSystem)) ], CondaService); exports.CondaService = CondaService; /***/ }), /***/ "./src/client/pythonEnvironments/common/environmentManagers/globalInstalledEnvs.ts": /*!*****************************************************************************************!*\ !*** ./src/client/pythonEnvironments/common/environmentManagers/globalInstalledEnvs.ts ***! \*****************************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isGloballyInstalledEnv = void 0; const exec_1 = __webpack_require__(/*! ../../../common/utils/exec */ "./src/client/common/utils/exec.ts"); const platform_1 = __webpack_require__(/*! ../../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const externalDependencies_1 = __webpack_require__(/*! ../externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const posixUtils_1 = __webpack_require__(/*! ../posixUtils */ "./src/client/pythonEnvironments/common/posixUtils.ts"); const pyenv_1 = __webpack_require__(/*! ./pyenv */ "./src/client/pythonEnvironments/common/environmentManagers/pyenv.ts"); async function isGloballyInstalledEnv(executablePath) { return isFoundInPathEnvVar(executablePath); } exports.isGloballyInstalledEnv = isGloballyInstalledEnv; async function isFoundInPathEnvVar(executablePath) { let searchPathEntries = []; if ((0, platform_1.getOSType)() === platform_1.OSType.Windows) { searchPathEntries = (0, exec_1.getSearchPathEntries)(); } else { searchPathEntries = await (0, posixUtils_1.commonPosixBinPaths)(); } searchPathEntries = searchPathEntries.filter((dirname) => !(0, pyenv_1.isPyenvShimDir)(dirname)); for (const searchPath of searchPathEntries) { if ((0, externalDependencies_1.isParentPath)(executablePath, searchPath)) { return true; } } return false; } /***/ }), /***/ "./src/client/pythonEnvironments/common/environmentManagers/macDefault.ts": /*!********************************************************************************!*\ !*** ./src/client/pythonEnvironments/common/environmentManagers/macDefault.ts ***! \********************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isMacDefaultPythonPath = void 0; const platform_1 = __webpack_require__(/*! ../../../common/utils/platform */ "./src/client/common/utils/platform.ts"); function isMacDefaultPythonPath(pythonPath) { if ((0, platform_1.getOSType)() !== platform_1.OSType.OSX) { return false; } const defaultPaths = ['/usr/bin/python']; return defaultPaths.includes(pythonPath) || pythonPath.startsWith('/usr/bin/python2'); } exports.isMacDefaultPythonPath = isMacDefaultPythonPath; /***/ }), /***/ "./src/client/pythonEnvironments/common/environmentManagers/microsoftStoreEnv.ts": /*!***************************************************************************************!*\ !*** ./src/client/pythonEnvironments/common/environmentManagers/microsoftStoreEnv.ts ***! \***************************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isMicrosoftStoreEnvironment = exports.isStorePythonInstalled = exports.isMicrosoftStoreDir = exports.getMicrosoftStoreAppsRoot = void 0; const path = __webpack_require__(/*! path */ "path"); const platform_1 = __webpack_require__(/*! ../../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); const externalDependencies_1 = __webpack_require__(/*! ../externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); function getMicrosoftStoreAppsRoot() { const localAppData = (0, platform_1.getEnvironmentVariable)('LOCALAPPDATA') || ''; return path.join(localAppData, 'Microsoft', 'WindowsApps'); } exports.getMicrosoftStoreAppsRoot = getMicrosoftStoreAppsRoot; function isForbiddenStorePath(absPath) { const programFilesStorePath = path .join((0, platform_1.getEnvironmentVariable)('ProgramFiles') || 'Program Files', 'WindowsApps') .normalize() .toUpperCase(); return path.normalize(absPath).toUpperCase().includes(programFilesStorePath); } function isMicrosoftStoreDir(dirPath) { const storeRootPath = path.normalize(getMicrosoftStoreAppsRoot()).toUpperCase(); return path.normalize(dirPath).toUpperCase().includes(storeRootPath) || isForbiddenStorePath(dirPath); } exports.isMicrosoftStoreDir = isMicrosoftStoreDir; async function isStorePythonInstalled(interpreterPath) { let results = await Promise.all([ (0, externalDependencies_1.pathExists)(path.join(getMicrosoftStoreAppsRoot(), 'idle.exe')), (0, externalDependencies_1.pathExists)(path.join(getMicrosoftStoreAppsRoot(), 'pip.exe')), ]); if (results.includes(true)) { return true; } if (interpreterPath) { results = await Promise.all([ (0, externalDependencies_1.pathExists)(path.join(path.dirname(interpreterPath), 'idle.exe')), (0, externalDependencies_1.pathExists)(path.join(path.dirname(interpreterPath), 'pip.exe')), ]); return results.includes(true); } return false; } exports.isStorePythonInstalled = isStorePythonInstalled; async function isMicrosoftStoreEnvironment(interpreterPath) { if (await isStorePythonInstalled(interpreterPath)) { const pythonPathToCompare = path.normalize(interpreterPath).toUpperCase(); const localAppDataStorePath = path.normalize(getMicrosoftStoreAppsRoot()).toUpperCase(); if (pythonPathToCompare.includes(localAppDataStorePath)) { return true; } if (isForbiddenStorePath(pythonPathToCompare)) { (0, logging_1.traceWarn)('isMicrosoftStoreEnvironment called with Program Files store path.'); return true; } } return false; } exports.isMicrosoftStoreEnvironment = isMicrosoftStoreEnvironment; /***/ }), /***/ "./src/client/pythonEnvironments/common/environmentManagers/pipenv.ts": /*!****************************************************************************!*\ !*** ./src/client/pythonEnvironments/common/environmentManagers/pipenv.ts ***! \****************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isPipenvEnvironmentRelatedToFolder = exports.isPipenvEnvironment = exports._getAssociatedPipfile = void 0; const path = __webpack_require__(/*! path */ "path"); const platform_1 = __webpack_require__(/*! ../../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); const externalDependencies_1 = __webpack_require__(/*! ../externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); function getSearchHeight() { const maxDepthStr = (0, platform_1.getEnvironmentVariable)('PIPENV_MAX_DEPTH'); if (maxDepthStr === undefined) { return 3; } const maxDepth = parseInt(maxDepthStr, 10); if (isNaN(maxDepth)) { (0, logging_1.traceError)(`PIPENV_MAX_DEPTH is incorrectly set. Converting value '${maxDepthStr}' to number results in NaN`); return 1; } return maxDepth; } async function _getAssociatedPipfile(searchDir, options) { const pipFileName = (0, platform_1.getEnvironmentVariable)('PIPENV_PIPFILE') || 'Pipfile'; let heightToSearch = options.lookIntoParentDirectories ? getSearchHeight() : 1; while (heightToSearch > 0 && !(0, externalDependencies_1.arePathsSame)(searchDir, path.dirname(searchDir))) { const pipFile = path.join(searchDir, pipFileName); if (await (0, externalDependencies_1.pathExists)(pipFile)) { return pipFile; } searchDir = path.dirname(searchDir); heightToSearch -= 1; } return undefined; } exports._getAssociatedPipfile = _getAssociatedPipfile; async function getPipfileIfLocal(interpreterPath) { const venvFolder = path.dirname(path.dirname(interpreterPath)); if (path.basename(venvFolder) !== '.venv') { return undefined; } const directoryWhereVenvResides = path.dirname(venvFolder); return _getAssociatedPipfile(directoryWhereVenvResides, { lookIntoParentDirectories: false }); } async function getProjectDir(envFolder) { const dotProjectFile = path.join(envFolder, '.project'); if (!(await (0, externalDependencies_1.pathExists)(dotProjectFile))) { return undefined; } const projectDir = (await (0, externalDependencies_1.readFile)(dotProjectFile)).trim(); if (!(await (0, externalDependencies_1.pathExists)(projectDir))) { (0, logging_1.traceError)(`The .project file inside environment folder: ${envFolder} doesn't contain a valid path to the project`); return undefined; } return projectDir; } async function getPipfileIfGlobal(interpreterPath) { const envFolder = path.dirname(path.dirname(interpreterPath)); const projectDir = await getProjectDir(envFolder); if (projectDir === undefined) { return undefined; } const envFolderName = path.basename((0, externalDependencies_1.normCasePath)(envFolder)); if (!envFolderName.startsWith(`${path.basename((0, externalDependencies_1.normCasePath)(projectDir))}-`)) { return undefined; } return _getAssociatedPipfile(projectDir, { lookIntoParentDirectories: false }); } async function isPipenvEnvironment(interpreterPath) { if (await getPipfileIfLocal(interpreterPath)) { return true; } if (await getPipfileIfGlobal(interpreterPath)) { return true; } return false; } exports.isPipenvEnvironment = isPipenvEnvironment; async function isPipenvEnvironmentRelatedToFolder(interpreterPath, folder) { const pipFileAssociatedWithEnvironment = await getPipfileIfGlobal(interpreterPath); if (!pipFileAssociatedWithEnvironment) { return false; } const lookIntoParentDirectories = (0, platform_1.getEnvironmentVariable)('PIPENV_NO_INHERIT') === undefined; const pipFileAssociatedWithFolder = await _getAssociatedPipfile(folder, { lookIntoParentDirectories }); if (!pipFileAssociatedWithFolder) { return false; } return (0, externalDependencies_1.arePathsSame)(pipFileAssociatedWithEnvironment, pipFileAssociatedWithFolder); } exports.isPipenvEnvironmentRelatedToFolder = isPipenvEnvironmentRelatedToFolder; /***/ }), /***/ "./src/client/pythonEnvironments/common/environmentManagers/poetry.ts": /*!****************************************************************************!*\ !*** ./src/client/pythonEnvironments/common/environmentManagers/poetry.ts ***! \****************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isPoetryEnvironmentRelatedToFolder = exports.Poetry = exports.isPoetryEnvironment = exports.localPoetryEnvDirName = void 0; const path = __webpack_require__(/*! path */ "path"); const platform_1 = __webpack_require__(/*! ../../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const externalDependencies_1 = __webpack_require__(/*! ../externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const commonUtils_1 = __webpack_require__(/*! ../commonUtils */ "./src/client/pythonEnvironments/common/commonUtils.ts"); const simplevirtualenvs_1 = __webpack_require__(/*! ./simplevirtualenvs */ "./src/client/pythonEnvironments/common/environmentManagers/simplevirtualenvs.ts"); const stopWatch_1 = __webpack_require__(/*! ../../../common/utils/stopWatch */ "./src/client/common/utils/stopWatch.ts"); const decorators_1 = __webpack_require__(/*! ../../../common/utils/decorators */ "./src/client/common/utils/decorators.ts"); const constants_1 = __webpack_require__(/*! ../../../common/constants */ "./src/client/common/constants.ts"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); const stringUtils_1 = __webpack_require__(/*! ../../../common/stringUtils */ "./src/client/common/stringUtils.ts"); const globalPoetryEnvDirRegex = /^(.+)-(.+)-py(\d).(\d){1,2}$/; async function isGlobalPoetryEnvironment(interpreterPath) { const envDir = (0, commonUtils_1.getEnvironmentDirFromPath)(interpreterPath); return globalPoetryEnvDirRegex.test(path.basename(envDir)) ? (0, simplevirtualenvs_1.isVirtualenvEnvironment)(interpreterPath) : false; } exports.localPoetryEnvDirName = '.venv'; async function isLocalPoetryEnvironment(interpreterPath) { const envDir = (0, commonUtils_1.getEnvironmentDirFromPath)(interpreterPath); if (path.basename(envDir) !== exports.localPoetryEnvDirName) { return false; } const project = path.dirname(envDir); if (!hasValidPyprojectToml(project)) { return false; } return true; } async function isPoetryEnvironment(interpreterPath) { if (await isGlobalPoetryEnvironment(interpreterPath)) { return true; } if (await isLocalPoetryEnvironment(interpreterPath)) { return true; } return false; } exports.isPoetryEnvironment = isPoetryEnvironment; const POETRY_TIMEOUT = 50000; class Poetry { constructor(command, cwd) { this.command = command; this.cwd = cwd; this.fixCwd(); } static async getPoetry(cwd) { if (!hasValidPyprojectToml(cwd)) { return undefined; } if (Poetry.poetryPromise.get(cwd) === undefined || (0, constants_1.isTestExecution)()) { Poetry.poetryPromise.set(cwd, Poetry.locate(cwd)); } return Poetry.poetryPromise.get(cwd); } static async locate(cwd) { (0, logging_1.traceVerbose)(`Getting poetry for cwd ${cwd}`); function* getCandidates() { try { const customPoetryPath = (0, externalDependencies_1.getPythonSetting)('poetryPath'); if (customPoetryPath && customPoetryPath !== 'poetry') { yield customPoetryPath; } } catch (ex) { (0, logging_1.traceError)(`Failed to get poetry setting`, ex); } yield 'poetry'; const home = (0, platform_1.getUserHomeDir)(); if (home) { const defaultPoetryPath = path.join(home, '.poetry', 'bin', 'poetry'); if ((0, externalDependencies_1.pathExistsSync)(defaultPoetryPath)) { yield defaultPoetryPath; } } } for (const poetryPath of getCandidates()) { (0, logging_1.traceVerbose)(`Probing poetry binary for ${cwd}: ${poetryPath}`); const poetry = new Poetry(poetryPath, cwd); const virtualenvs = await poetry.getEnvList(); if (virtualenvs !== undefined) { (0, logging_1.traceVerbose)(`Found poetry via filesystem probing for ${cwd}: ${poetryPath}`); return poetry; } (0, logging_1.traceVerbose)(`Failed to find poetry for ${cwd}: ${poetryPath}`); } (0, logging_1.traceVerbose)(`No poetry binary found for ${cwd}`); return undefined; } static async getVersion(cwd) { (0, logging_1.traceVerbose)(`Getting poetry version`); function* getCandidates() { try { const customPoetryPath = (0, externalDependencies_1.getPythonSetting)('poetryPath'); if (customPoetryPath && customPoetryPath !== 'poetry') { yield customPoetryPath; } } catch (ex) { (0, logging_1.traceError)(`Failed to get poetry setting`, ex); } yield 'poetry'; const home = (0, platform_1.getUserHomeDir)(); if (home) { const defaultPoetryPath = path.join(home, '.poetry', 'bin', 'poetry'); if ((0, externalDependencies_1.pathExistsSync)(defaultPoetryPath)) { yield defaultPoetryPath; } } } for (const poetryPath of getCandidates()) { (0, logging_1.traceVerbose)(`Getting poetry version for ${poetryPath}`); const poetry = new Poetry(poetryPath, cwd); const version = await poetry.getVersionCached(); if (version) { (0, logging_1.traceVerbose)(`Found version ${version} for ${poetryPath}`); return version; } (0, logging_1.traceVerbose)(`Failed to find poetry for ${poetryPath}`); } (0, logging_1.traceVerbose)(`No poetry binary found for ${cwd}`); return undefined; } async getVersionCached() { const result = await this.safeShellExecute(`${this.command} --version`); if (!result) { return undefined; } const lines = (0, stringUtils_1.splitLines)(result.stdout).map((line) => { if (line.startsWith('Poetry (version')) { line = line.substring('Poetry (version'.length).trim(); } if (line.endsWith(')')) { line = line.substring(0, line.length - 1).trim(); } return line; }); return lines.length ? lines[0] : ''; } async getEnvList() { return this.getEnvListCached(this.cwd); } async getEnvListCached(_cwd) { const result = await this.safeShellExecute(`${this.command} env list --full-path`); if (!result) { return undefined; } const activated = '(Activated)'; const res = await Promise.all((0, stringUtils_1.splitLines)(result.stdout).map(async (line) => { if (line.endsWith(activated)) { line = line.slice(0, -activated.length); } const folder = line.trim(); return (await (0, externalDependencies_1.pathExists)(folder)) ? folder : undefined; })); return res.filter((r) => r !== undefined).map((r) => r); } async getActiveEnvPath() { return this.getActiveEnvPathCached(this.cwd); } async getActiveEnvPathCached(_cwd) { const result = await this.safeShellExecute(`${this.command} env info -p`, true); if (!result) { return undefined; } return result.stdout.trim(); } async getVirtualenvsPathSetting() { const result = await this.safeShellExecute(`${this.command} config virtualenvs.path`); if (!result) { return undefined; } return result.stdout.trim(); } fixCwd() { if ((0, platform_1.getOSType)() === platform_1.OSType.Windows) { if (/^[a-z]:/.test(this.cwd)) { const a = this.cwd.split(':'); a[0] = a[0].toUpperCase(); this.cwd = a.join(':'); } } } async safeShellExecute(command, logVerbose = false) { const stopWatch = new stopWatch_1.StopWatch(); const result = await (0, externalDependencies_1.shellExecute)(command, { cwd: this.cwd, throwOnStdErr: true, timeout: POETRY_TIMEOUT, }).catch((ex) => { if (logVerbose) { (0, logging_1.traceVerbose)(ex); } else { (0, logging_1.traceError)(ex); } return undefined; }); (0, logging_1.traceVerbose)(`Time taken to run ${command} in ms`, stopWatch.elapsedTime); return result; } } Poetry.poetryPromise = new Map(); __decorate([ (0, decorators_1.cache)(30000, true, 10000) ], Poetry.prototype, "getVersionCached", null); __decorate([ (0, decorators_1.cache)(30000, true, 10000) ], Poetry.prototype, "getEnvListCached", null); __decorate([ (0, decorators_1.cache)(20000, true, 10000) ], Poetry.prototype, "getActiveEnvPathCached", null); exports.Poetry = Poetry; async function isPoetryEnvironmentRelatedToFolder(interpreterPath, folder, poetryPath) { const poetry = poetryPath ? new Poetry(poetryPath, folder) : await Poetry.getPoetry(folder); const pathToEnv = await (poetry === null || poetry === void 0 ? void 0 : poetry.getActiveEnvPath()); if (!pathToEnv) { return false; } return (0, externalDependencies_1.isParentPath)(interpreterPath, pathToEnv); } exports.isPoetryEnvironmentRelatedToFolder = isPoetryEnvironmentRelatedToFolder; function hasValidPyprojectToml(folder) { const pyprojectToml = path.join(folder, 'pyproject.toml'); if (!(0, externalDependencies_1.pathExistsSync)(pyprojectToml)) { return false; } const content = (0, externalDependencies_1.readFileSync)(pyprojectToml); if (!content.includes('[tool.poetry]')) { return false; } return true; } /***/ }), /***/ "./src/client/pythonEnvironments/common/environmentManagers/pyenv.ts": /*!***************************************************************************!*\ !*** ./src/client/pythonEnvironments/common/environmentManagers/pyenv.ts ***! \***************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parsePyenvVersion = exports.isPyenvEnvironment = exports.isPyenvShimDir = exports.getPyenvVersionsDir = exports.getPyenvDir = void 0; const path = __webpack_require__(/*! path */ "path"); const platform_1 = __webpack_require__(/*! ../../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const externalDependencies_1 = __webpack_require__(/*! ../externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); function getPyenvDir() { var _a; let pyenvDir = (_a = (0, platform_1.getEnvironmentVariable)('PYENV_ROOT')) !== null && _a !== void 0 ? _a : (0, platform_1.getEnvironmentVariable)('PYENV'); if (!pyenvDir) { const homeDir = (0, platform_1.getUserHomeDir)() || ''; pyenvDir = (0, platform_1.getOSType)() === platform_1.OSType.Windows ? path.join(homeDir, '.pyenv', 'pyenv-win') : path.join(homeDir, '.pyenv'); } return pyenvDir; } exports.getPyenvDir = getPyenvDir; function getPyenvVersionsDir() { return path.join(getPyenvDir(), 'versions'); } exports.getPyenvVersionsDir = getPyenvVersionsDir; function isPyenvShimDir(dirPath) { const shimPath = path.join(getPyenvDir(), 'shims'); return (0, externalDependencies_1.arePathsSame)(shimPath, dirPath) || (0, externalDependencies_1.arePathsSame)(`${shimPath}${path.sep}`, dirPath); } exports.isPyenvShimDir = isPyenvShimDir; async function isPyenvEnvironment(interpreterPath) { const pathToCheck = interpreterPath; const pyenvDir = getPyenvDir(); if (!(await (0, externalDependencies_1.pathExists)(pyenvDir))) { return false; } return (0, externalDependencies_1.isParentPath)(pathToCheck, pyenvDir); } exports.isPyenvEnvironment = isPyenvEnvironment; function getKnownPyenvVersionParsers() { function pythonOnly(str) { return { pythonVer: str, distro: undefined, distroVer: undefined, }; } function distroOnly(str) { const parts = str.split('-'); if (parts.length === 3) { return { pythonVer: undefined, distroVer: `${parts[1]}-${parts[2]}`, distro: parts[0], }; } if (parts.length === 2) { return { pythonVer: undefined, distroVer: parts[1], distro: parts[0], }; } return { pythonVer: undefined, distroVer: undefined, distro: str, }; } function pypyParser(str) { const pattern = /[0-9\.]+/; const parts = str.split('-'); const pythonVer = parts[0].search(pattern) > 0 ? parts[0].substr('pypy'.length) : undefined; if (parts.length === 2) { return { pythonVer, distroVer: parts[1], distro: 'pypy', }; } if (parts.length === 3 && (parts[2].startsWith('src') || parts[2].startsWith('beta') || parts[2].startsWith('alpha') || parts[2].startsWith('win64'))) { const part1 = parts[1].startsWith('v') ? parts[1].substr(1) : parts[1]; return { pythonVer, distroVer: `${part1}-${parts[2]}`, distro: 'pypy', }; } if (parts.length === 3 && parts[1] === 'stm') { return { pythonVer, distroVer: parts[2], distro: `${parts[0]}-${parts[1]}`, }; } if (parts.length === 4 && parts[1] === 'c') { return { pythonVer, distroVer: parts[3], distro: `pypy-${parts[1]}-${parts[2]}`, }; } if (parts.length === 4 && parts[3].startsWith('src')) { return { pythonVer, distroVer: `${parts[1]}-${parts[2]}-${parts[3]}`, distro: 'pypy', }; } return { pythonVer, distroVer: undefined, distro: 'pypy', }; } const parsers = new Map(); parsers.set('activepython', distroOnly); parsers.set('anaconda', distroOnly); parsers.set('graalpython', distroOnly); parsers.set('ironpython', distroOnly); parsers.set('jython', distroOnly); parsers.set('micropython', distroOnly); parsers.set('miniconda', distroOnly); parsers.set('miniforge', distroOnly); parsers.set('pypy', pypyParser); parsers.set('pyston', distroOnly); parsers.set('stackless', distroOnly); parsers.set('3', pythonOnly); parsers.set('2', pythonOnly); return parsers; } function parsePyenvVersion(str) { const allParsers = getKnownPyenvVersionParsers(); const knownPrefixes = Array.from(allParsers.keys()); const parsers = knownPrefixes .filter((k) => str.startsWith(k)) .map((p) => allParsers.get(p)) .filter((p) => p !== undefined); if (parsers.length > 0 && parsers[0]) { return parsers[0](str); } return undefined; } exports.parsePyenvVersion = parsePyenvVersion; /***/ }), /***/ "./src/client/pythonEnvironments/common/environmentManagers/simplevirtualenvs.ts": /*!***************************************************************************************!*\ !*** ./src/client/pythonEnvironments/common/environmentManagers/simplevirtualenvs.ts ***! \***************************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getPythonVersionFromPyvenvCfg = exports.isVirtualenvwrapperEnvironment = exports.isVirtualenvEnvironment = exports.isVenvEnvironment = exports.isVirtualEnvironment = void 0; const fsapi = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const path = __webpack_require__(/*! path */ "path"); __webpack_require__(/*! ../../../common/extensions */ "./src/client/common/extensions.ts"); const stringUtils_1 = __webpack_require__(/*! ../../../common/stringUtils */ "./src/client/common/stringUtils.ts"); const platform_1 = __webpack_require__(/*! ../../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const info_1 = __webpack_require__(/*! ../../base/info */ "./src/client/pythonEnvironments/base/info/index.ts"); const env_1 = __webpack_require__(/*! ../../base/info/env */ "./src/client/pythonEnvironments/base/info/env.ts"); const pythonVersion_1 = __webpack_require__(/*! ../../base/info/pythonVersion */ "./src/client/pythonEnvironments/base/info/pythonVersion.ts"); const externalDependencies_1 = __webpack_require__(/*! ../externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); function getPyvenvConfigPathsFrom(interpreterPath) { const pyvenvConfigFile = 'pyvenv.cfg'; const venvPath1 = path.join(path.dirname(path.dirname(interpreterPath)), pyvenvConfigFile); const venvPath2 = path.join(path.dirname(interpreterPath), pyvenvConfigFile); return [venvPath1, venvPath2]; } async function isVirtualEnvironment(interpreterPath) { return isVenvEnvironment(interpreterPath); } exports.isVirtualEnvironment = isVirtualEnvironment; async function isVenvEnvironment(interpreterPath) { const venvPaths = getPyvenvConfigPathsFrom(interpreterPath); for (const venvPath of venvPaths) { if (await (0, externalDependencies_1.pathExists)(venvPath)) { return true; } } return false; } exports.isVenvEnvironment = isVenvEnvironment; async function isVirtualenvEnvironment(interpreterPath) { const directory = path.dirname(interpreterPath); const files = await fsapi.readdir(directory); const regex = /^activate(\.([A-z]|\d)+)?$/i; return files.find((file) => regex.test(file)) !== undefined; } exports.isVirtualenvEnvironment = isVirtualenvEnvironment; async function getDefaultVirtualenvwrapperDir() { const homeDir = (0, platform_1.getUserHomeDir)() || ''; if ((0, platform_1.getOSType)() === platform_1.OSType.Windows) { const envs = path.join(homeDir, 'Envs'); if (await (0, externalDependencies_1.pathExists)(envs)) { return envs; } } return path.join(homeDir, '.virtualenvs'); } function getWorkOnHome() { const workOnHome = (0, platform_1.getEnvironmentVariable)('WORKON_HOME'); if (workOnHome) { return Promise.resolve(workOnHome); } return getDefaultVirtualenvwrapperDir(); } async function isVirtualenvwrapperEnvironment(interpreterPath) { const workOnHomeDir = await getWorkOnHome(); return ((await (0, externalDependencies_1.pathExists)(workOnHomeDir)) && (0, externalDependencies_1.isParentPath)(interpreterPath, workOnHomeDir) && isVirtualenvEnvironment(interpreterPath)); } exports.isVirtualenvwrapperEnvironment = isVirtualenvwrapperEnvironment; async function getPythonVersionFromPyvenvCfg(interpreterPath) { const configPaths = getPyvenvConfigPathsFrom(interpreterPath); let version = info_1.UNKNOWN_PYTHON_VERSION; for (const configPath of configPaths) { if (await (0, externalDependencies_1.pathExists)(configPath)) { try { const lines = (0, stringUtils_1.splitLines)(await (0, externalDependencies_1.readFile)(configPath)); const pythonVersions = lines .map((line) => { const parts = line.split('='); if (parts.length === 2) { const name = parts[0].toLowerCase().trim(); const value = parts[1].trim(); if (name === 'version') { try { return (0, pythonVersion_1.parseVersion)(value); } catch (ex) { return undefined; } } else if (name === 'version_info') { try { return parseVersionInfo(value); } catch (ex) { return undefined; } } } return undefined; }) .filter((v) => v !== undefined) .map((v) => v); if (pythonVersions.length > 0) { for (const v of pythonVersions) { if ((0, env_1.comparePythonVersionSpecificity)(v, version) > 0) { version = v; } } } } catch (ex) { return info_1.UNKNOWN_PYTHON_VERSION; } } } return version; } exports.getPythonVersionFromPyvenvCfg = getPythonVersionFromPyvenvCfg; function parseVersionInfo(versionInfoStr) { let version; let after; try { [version, after] = (0, pythonVersion_1.parseBasicVersion)(versionInfoStr); } catch (_a) { return info_1.UNKNOWN_PYTHON_VERSION; } if (version.micro !== -1 && after.startsWith('.')) { [version.release] = (0, pythonVersion_1.parseRelease)(after); } return version; } /***/ }), /***/ "./src/client/pythonEnvironments/common/externalDependencies.ts": /*!**********************************************************************!*\ !*** ./src/client/pythonEnvironments/common/externalDependencies.ts ***! \**********************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.onDidChangePythonSetting = exports.getPythonSetting = exports.getSubDirs = exports.isFile = exports.getFileInfo = exports.resolveSymbolicLink = exports.arePathsSame = exports.normCasePath = exports.resolvePath = exports.normalizePath = exports.isDirectory = exports.isParentPath = exports.untildify = exports.readFileSync = exports.readFile = exports.pathExistsSync = exports.pathExists = exports.isVirtualWorkspace = exports.exec = exports.shellExecute = exports.initializeExternalDependencies = void 0; const fsapi = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const path = __webpack_require__(/*! path */ "path"); const vscode = __webpack_require__(/*! vscode */ "vscode"); const types_1 = __webpack_require__(/*! ../../common/application/types */ "./src/client/common/application/types.ts"); const types_2 = __webpack_require__(/*! ../../common/process/types */ "./src/client/common/process/types.ts"); const types_3 = __webpack_require__(/*! ../../common/types */ "./src/client/common/types.ts"); const async_1 = __webpack_require__(/*! ../../common/utils/async */ "./src/client/common/utils/async.ts"); const platform_1 = __webpack_require__(/*! ../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); let internalServiceContainer; function initializeExternalDependencies(serviceContainer) { internalServiceContainer = serviceContainer; } exports.initializeExternalDependencies = initializeExternalDependencies; async function shellExecute(command, options = {}) { const service = await internalServiceContainer.get(types_2.IProcessServiceFactory).create(); return service.shellExec(command, options); } exports.shellExecute = shellExecute; async function exec(file, args, options = {}) { const service = await internalServiceContainer.get(types_2.IProcessServiceFactory).create(); return service.exec(file, args, options); } exports.exec = exec; function isVirtualWorkspace() { const service = internalServiceContainer.get(types_1.IWorkspaceService); return service.isVirtualWorkspace; } exports.isVirtualWorkspace = isVirtualWorkspace; function pathExists(absPath) { return fsapi.pathExists(absPath); } exports.pathExists = pathExists; function pathExistsSync(absPath) { return fsapi.pathExistsSync(absPath); } exports.pathExistsSync = pathExistsSync; function readFile(filePath) { return fsapi.readFile(filePath, 'utf-8'); } exports.readFile = readFile; function readFileSync(filePath) { return fsapi.readFileSync(filePath, 'utf-8'); } exports.readFileSync = readFileSync; exports.untildify = __webpack_require__(/*! untildify */ "./node_modules/untildify/index.js"); function isParentPath(filePath, parentPath) { if (!parentPath.endsWith(path.sep)) { parentPath += path.sep; } if (!filePath.endsWith(path.sep)) { filePath += path.sep; } return normCasePath(filePath).startsWith(normCasePath(parentPath)); } exports.isParentPath = isParentPath; async function isDirectory(filename) { const stat = await fsapi.lstat(filename); return stat.isDirectory(); } exports.isDirectory = isDirectory; function normalizePath(filename) { return path.normalize(filename); } exports.normalizePath = normalizePath; function resolvePath(filename) { return path.resolve(filename); } exports.resolvePath = resolvePath; function normCasePath(filePath) { return (0, platform_1.getOSType)() === platform_1.OSType.Windows ? path.normalize(filePath).toUpperCase() : path.normalize(filePath); } exports.normCasePath = normCasePath; function arePathsSame(path1, path2) { return normCasePath(path1) === normCasePath(path2); } exports.arePathsSame = arePathsSame; async function resolveSymbolicLink(absPath, stats, count) { stats = stats !== null && stats !== void 0 ? stats : (await fsapi.lstat(absPath)); if (stats.isSymbolicLink()) { if (count && count > 5) { (0, logging_1.traceError)(`Detected a potential symbolic link loop at ${absPath}, terminating resolution.`); return absPath; } const link = await fsapi.readlink(absPath); const absLinkPath = path.isAbsolute(link) ? link : path.resolve(path.dirname(absPath), link); count = count ? count + 1 : 1; return resolveSymbolicLink(absLinkPath, undefined, count); } return absPath; } exports.resolveSymbolicLink = resolveSymbolicLink; async function getFileInfo(filePath) { try { const data = await fsapi.lstat(filePath); return { ctime: data.ctime.valueOf(), mtime: data.mtime.valueOf(), }; } catch (ex) { (0, logging_1.traceVerbose)(`Failed to get file info for ${filePath}`, ex); return { ctime: -1, mtime: -1 }; } } exports.getFileInfo = getFileInfo; async function isFile(filePath) { const stats = await fsapi.lstat(filePath); if (stats.isSymbolicLink()) { const resolvedPath = await resolveSymbolicLink(filePath, stats); const resolvedStats = await fsapi.lstat(resolvedPath); return resolvedStats.isFile(); } return stats.isFile(); } exports.isFile = isFile; async function* getSubDirs(root, options) { const dirContents = await fsapi.promises.readdir(root, { withFileTypes: true }); const generators = dirContents.map((item) => { async function* generator() { const fullPath = path.join(root, item.name); if (item.isDirectory()) { yield fullPath; } else if ((options === null || options === void 0 ? void 0 : options.resolveSymlinks) && item.isSymbolicLink()) { const resolvedPath = await resolveSymbolicLink(fullPath); const resolvedPathStat = await fsapi.lstat(resolvedPath); if (resolvedPathStat.isDirectory()) { yield resolvedPath; } } } return generator(); }); yield* (0, async_1.iterable)((0, async_1.chain)(generators)); } exports.getSubDirs = getSubDirs; function getPythonSetting(name) { const settings = internalServiceContainer.get(types_3.IConfigurationService).getSettings(); return settings[name]; } exports.getPythonSetting = getPythonSetting; function onDidChangePythonSetting(name, callback) { return vscode.workspace.onDidChangeConfiguration((event) => { if (event.affectsConfiguration(`python.${name}`)) { callback(); } }); } exports.onDidChangePythonSetting = onDidChangePythonSetting; /***/ }), /***/ "./src/client/pythonEnvironments/common/posixUtils.ts": /*!************************************************************!*\ !*** ./src/client/pythonEnvironments/common/posixUtils.ts ***! \************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getPythonBinFromPosixPaths = exports.commonPosixBinPaths = exports.matchPythonBinFilename = exports.matchBasicPythonBinFilename = void 0; const fs = __webpack_require__(/*! fs */ "fs"); const fsapi = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const path = __webpack_require__(/*! path */ "path"); const lodash_1 = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js"); const exec_1 = __webpack_require__(/*! ../../common/utils/exec */ "./src/client/common/utils/exec.ts"); const externalDependencies_1 = __webpack_require__(/*! ./externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); function matchBasicPythonBinFilename(filename) { return path.basename(filename) === 'python'; } exports.matchBasicPythonBinFilename = matchBasicPythonBinFilename; function matchPythonBinFilename(filename) { const posixPythonBinPattern = /^python(\d+(\.\d+)?)?$/; return posixPythonBinPattern.test(path.basename(filename)); } exports.matchPythonBinFilename = matchPythonBinFilename; async function commonPosixBinPaths() { const searchPaths = (0, exec_1.getSearchPathEntries)(); const paths = Array.from(new Set([ '/bin', '/etc', '/lib', '/lib/x86_64-linux-gnu', '/lib64', '/sbin', '/snap/bin', '/usr/bin', '/usr/games', '/usr/include', '/usr/lib', '/usr/lib/x86_64-linux-gnu', '/usr/lib64', '/usr/libexec', '/usr/local', '/usr/local/bin', '/usr/local/etc', '/usr/local/games', '/usr/local/lib', '/usr/local/sbin', '/usr/sbin', '/usr/share', '~/.local/bin', ].concat(searchPaths))); const exists = await Promise.all(paths.map((p) => fsapi.pathExists(p))); return paths.filter((_, index) => exists[index]); } exports.commonPosixBinPaths = commonPosixBinPaths; async function findPythonBinariesInDir(searchDir) { return (await fs.promises.readdir(searchDir, { withFileTypes: true })) .filter((dirent) => !dirent.isDirectory()) .map((dirent) => path.join(searchDir, dirent.name)) .filter(matchPythonBinFilename); } function pickShortestPath(pythonPaths) { let shortestLen = pythonPaths[0].length; let shortestPath = pythonPaths[0]; for (const p of pythonPaths) { if (p.length <= shortestLen) { shortestLen = p.length; shortestPath = p; } } return shortestPath; } async function getPythonBinFromPosixPaths(searchDirs) { var _a; const binToLinkMap = new Map(); for (const searchDir of searchDirs) { const paths = await findPythonBinariesInDir(searchDir).catch((ex) => { (0, logging_1.traceWarn)('Looking for python binaries within', searchDir, 'failed with', ex); return []; }); for (const filepath of paths) { try { (0, logging_1.traceVerbose)(`Attempting to resolve symbolic link: ${filepath}`); const resolvedBin = await (0, externalDependencies_1.resolveSymbolicLink)(filepath); if (binToLinkMap.has(resolvedBin)) { (_a = binToLinkMap.get(resolvedBin)) === null || _a === void 0 ? void 0 : _a.push(filepath); } else { binToLinkMap.set(resolvedBin, [filepath]); } (0, logging_1.traceInfo)(`Found: ${filepath} --> ${resolvedBin}`); } catch (ex) { (0, logging_1.traceError)('Failed to resolve symbolic link: ', ex); } } } const keys = Array.from(binToLinkMap.keys()); const pythonPaths = keys.map((key) => { var _a; return pickShortestPath([key, ...((_a = binToLinkMap.get(key)) !== null && _a !== void 0 ? _a : [])]); }); return (0, lodash_1.uniq)(pythonPaths); } exports.getPythonBinFromPosixPaths = getPythonBinFromPosixPaths; /***/ }), /***/ "./src/client/pythonEnvironments/common/pythonBinariesWatcher.ts": /*!***********************************************************************!*\ !*** ./src/client/pythonEnvironments/common/pythonBinariesWatcher.ts ***! \***********************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolvePythonExeGlobs = exports.PythonEnvStructure = exports.watchLocationForPythonBinaries = void 0; const minimatch = __webpack_require__(/*! minimatch */ "./node_modules/minimatch/minimatch.js"); const path = __webpack_require__(/*! path */ "path"); const fileSystemWatcher_1 = __webpack_require__(/*! ../../common/platform/fileSystemWatcher */ "./src/client/common/platform/fileSystemWatcher.ts"); const platform_1 = __webpack_require__(/*! ../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const [executable, binName] = (0, platform_1.getOSType)() === platform_1.OSType.Windows ? ['python.exe', 'Scripts'] : ['python', 'bin']; function watchLocationForPythonBinaries(baseDir, callback, executableGlob = executable) { const resolvedGlob = path.posix.normalize(executableGlob); const [baseGlob] = resolvedGlob.split('/').slice(-1); function callbackClosure(type, e) { (0, logging_1.traceVerbose)('Received event', type, JSON.stringify(e), 'for baseglob', baseGlob); const isMatch = minimatch(path.basename(e), baseGlob, { nocase: (0, platform_1.getOSType)() === platform_1.OSType.Windows }); if (!isMatch) { return; } callback(type, e); } return (0, fileSystemWatcher_1.watchLocationForPattern)(baseDir, resolvedGlob, callbackClosure); } exports.watchLocationForPythonBinaries = watchLocationForPythonBinaries; var PythonEnvStructure; (function (PythonEnvStructure) { PythonEnvStructure["Standard"] = "standard"; PythonEnvStructure["Flat"] = "flat"; })(PythonEnvStructure = exports.PythonEnvStructure || (exports.PythonEnvStructure = {})); function resolvePythonExeGlobs(basenameGlob = executable, structure = PythonEnvStructure.Standard) { if (path.posix.normalize(basenameGlob).includes('/')) { throw Error(`invalid basename glob "${basenameGlob}"`); } const globs = []; if (structure === PythonEnvStructure.Standard) { globs.push(basenameGlob, `*/${basenameGlob}`, `*/${binName}/${basenameGlob}`); } else if (structure === PythonEnvStructure.Flat) { globs.push(basenameGlob); } return globs; } exports.resolvePythonExeGlobs = resolvePythonExeGlobs; /***/ }), /***/ "./src/client/pythonEnvironments/common/windowsRegistry.ts": /*!*****************************************************************!*\ !*** ./src/client/pythonEnvironments/common/windowsRegistry.ts ***! \*****************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readRegistryKeys = exports.readRegistryValues = exports.REG_SZ = exports.HKLM = exports.HKCU = void 0; const winreg_1 = __webpack_require__(/*! winreg */ "./node_modules/winreg/lib/registry.js"); Object.defineProperty(exports, "HKCU", ({ enumerable: true, get: function () { return winreg_1.HKCU; } })); Object.defineProperty(exports, "HKLM", ({ enumerable: true, get: function () { return winreg_1.HKLM; } })); Object.defineProperty(exports, "REG_SZ", ({ enumerable: true, get: function () { return winreg_1.REG_SZ; } })); const async_1 = __webpack_require__(/*! ../../common/utils/async */ "./src/client/common/utils/async.ts"); async function readRegistryValues(options) { const WinReg = __webpack_require__(/*! winreg */ "./node_modules/winreg/lib/registry.js"); const regKey = new WinReg(options); const deferred = (0, async_1.createDeferred)(); regKey.values((err, res) => { if (err) { deferred.reject(err); } deferred.resolve(res); }); return deferred.promise; } exports.readRegistryValues = readRegistryValues; async function readRegistryKeys(options) { const WinReg = __webpack_require__(/*! winreg */ "./node_modules/winreg/lib/registry.js"); const regKey = new WinReg(options); const deferred = (0, async_1.createDeferred)(); regKey.keys((err, res) => { if (err) { deferred.reject(err); } deferred.resolve(res); }); return deferred.promise; } exports.readRegistryKeys = readRegistryKeys; /***/ }), /***/ "./src/client/pythonEnvironments/common/windowsUtils.ts": /*!**************************************************************!*\ !*** ./src/client/pythonEnvironments/common/windowsUtils.ts ***! \**************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRegistryInterpreters = exports.getRegistryInterpretersSync = exports.getInterpreterDataFromRegistry = exports.matchPythonBinFilename = exports.matchBasicPythonBinFilename = void 0; const lodash_1 = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js"); const path = __webpack_require__(/*! path */ "path"); const constants_1 = __webpack_require__(/*! ../../common/constants */ "./src/client/common/constants.ts"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const windowsRegistry_1 = __webpack_require__(/*! ./windowsRegistry */ "./src/client/pythonEnvironments/common/windowsRegistry.ts"); function matchBasicPythonBinFilename(filename) { return path.basename(filename).toLowerCase() === 'python.exe'; } exports.matchBasicPythonBinFilename = matchBasicPythonBinFilename; function matchPythonBinFilename(filename) { const windowsPythonExes = /^python(\d+(.\d+)?)?\.exe$/; return windowsPythonExes.test(path.basename(filename)); } exports.matchPythonBinFilename = matchPythonBinFilename; async function getInterpreterDataFromKey({ arch, hive, key }, distroOrgName) { const result = { interpreterPath: '', distroOrgName, }; const values = await (0, windowsRegistry_1.readRegistryValues)({ arch, hive, key }); for (const value of values) { switch (value.name) { case 'SysArchitecture': result.bitnessStr = value.value; break; case 'SysVersion': result.sysVersionStr = value.value; break; case 'Version': result.versionStr = value.value; break; case 'DisplayName': result.companyDisplayName = value.value; break; default: break; } } const subKeys = await (0, windowsRegistry_1.readRegistryKeys)({ arch, hive, key }); const subKey = subKeys.map((s) => s.key).find((s) => s.endsWith('InstallPath')); if (subKey) { const subKeyValues = await (0, windowsRegistry_1.readRegistryValues)({ arch, hive, key: subKey }); const value = subKeyValues.find((v) => v.name === 'ExecutablePath'); if (value) { result.interpreterPath = value.value; if (value.type !== windowsRegistry_1.REG_SZ) { (0, logging_1.traceVerbose)(`Registry interpreter path type [${value.type}]: ${value.value}`); } } } if (result.interpreterPath.length > 0) { return result; } return undefined; } async function getInterpreterDataFromRegistry(arch, hive, key) { const subKeys = await (0, windowsRegistry_1.readRegistryKeys)({ arch, hive, key }); const distroOrgName = key.substr(key.lastIndexOf('\\') + 1); const allData = await Promise.all(subKeys.map((subKey) => getInterpreterDataFromKey(subKey, distroOrgName))); return (allData.filter((data) => data !== undefined) || []); } exports.getInterpreterDataFromRegistry = getInterpreterDataFromRegistry; let registryInterpretersCache; function getRegistryInterpretersSync() { return !(0, constants_1.isTestExecution)() ? registryInterpretersCache : undefined; } exports.getRegistryInterpretersSync = getRegistryInterpretersSync; let registryInterpretersPromise; async function getRegistryInterpreters() { if (!(0, constants_1.isTestExecution)() && registryInterpretersPromise !== undefined) { return registryInterpretersPromise; } registryInterpretersPromise = getRegistryInterpretersImpl(); return registryInterpretersPromise; } exports.getRegistryInterpreters = getRegistryInterpreters; async function getRegistryInterpretersImpl() { let registryData = []; for (const arch of ['x64', 'x86']) { for (const hive of [windowsRegistry_1.HKLM, windowsRegistry_1.HKCU]) { const root = '\\SOFTWARE\\Python'; let keys = []; try { keys = (await (0, windowsRegistry_1.readRegistryKeys)({ arch, hive, key: root })).map((k) => k.key); } catch (ex) { (0, logging_1.traceError)(`Failed to access Registry: ${arch}\\${hive}\\${root}`, ex); } for (const key of keys) { registryData = registryData.concat(await getInterpreterDataFromRegistry(arch, hive, key)); } } } registryInterpretersCache = (0, lodash_1.uniqBy)(registryData, (r) => r.interpreterPath); return registryInterpretersCache; } /***/ }), /***/ "./src/client/pythonEnvironments/creation/common/commonUtils.ts": /*!**********************************************************************!*\ !*** ./src/client/pythonEnvironments/creation/common/commonUtils.ts ***! \**********************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getVenvExecutable = exports.hasVenv = exports.getVenvPath = exports.showErrorMessageWithLogs = void 0; const fs = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const path = __webpack_require__(/*! path */ "path"); const constants_1 = __webpack_require__(/*! ../../../common/constants */ "./src/client/common/constants.ts"); const localize_1 = __webpack_require__(/*! ../../../common/utils/localize */ "./src/client/common/utils/localize.ts"); const commandApis_1 = __webpack_require__(/*! ../../../common/vscodeApis/commandApis */ "./src/client/common/vscodeApis/commandApis.ts"); const windowApis_1 = __webpack_require__(/*! ../../../common/vscodeApis/windowApis */ "./src/client/common/vscodeApis/windowApis.ts"); const platformService_1 = __webpack_require__(/*! ../../../common/platform/platformService */ "./src/client/common/platform/platformService.ts"); async function showErrorMessageWithLogs(message) { const result = await (0, windowApis_1.showErrorMessage)(message, localize_1.Common.openOutputPanel, localize_1.Common.selectPythonInterpreter); if (result === localize_1.Common.openOutputPanel) { await (0, commandApis_1.executeCommand)(constants_1.Commands.ViewOutput); } else if (result === localize_1.Common.selectPythonInterpreter) { await (0, commandApis_1.executeCommand)(constants_1.Commands.Set_Interpreter); } } exports.showErrorMessageWithLogs = showErrorMessageWithLogs; function getVenvPath(workspaceFolder) { return path.join(workspaceFolder.uri.fsPath, '.venv'); } exports.getVenvPath = getVenvPath; async function hasVenv(workspaceFolder) { return fs.pathExists(getVenvPath(workspaceFolder)); } exports.hasVenv = hasVenv; function getVenvExecutable(workspaceFolder) { if ((0, platformService_1.isWindows)()) { return path.join(getVenvPath(workspaceFolder), 'Scripts', 'python.exe'); } return path.join(getVenvPath(workspaceFolder), 'bin', 'python'); } exports.getVenvExecutable = getVenvExecutable; /***/ }), /***/ "./src/client/pythonEnvironments/creation/common/workspaceSelection.ts": /*!*****************************************************************************!*\ !*** ./src/client/pythonEnvironments/creation/common/workspaceSelection.ts ***! \*****************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.pickWorkspaceFolder = void 0; const fsapi = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const path = __webpack_require__(/*! path */ "path"); const windowApis_1 = __webpack_require__(/*! ../../../common/vscodeApis/windowApis */ "./src/client/common/vscodeApis/windowApis.ts"); const workspaceApis_1 = __webpack_require__(/*! ../../../common/vscodeApis/workspaceApis */ "./src/client/common/vscodeApis/workspaceApis.ts"); const localize_1 = __webpack_require__(/*! ../../../common/utils/localize */ "./src/client/common/utils/localize.ts"); const commandApis_1 = __webpack_require__(/*! ../../../common/vscodeApis/commandApis */ "./src/client/common/vscodeApis/commandApis.ts"); function hasVirtualEnv(workspace) { return Promise.race([ fsapi.pathExists(path.join(workspace.uri.fsPath, '.venv')), fsapi.pathExists(path.join(workspace.uri.fsPath, '.conda')), ]); } async function getWorkspacesForQuickPick(workspaces) { const items = []; for (const workspace of workspaces) { items.push({ label: workspace.name, detail: workspace.uri.fsPath, description: (await hasVirtualEnv(workspace)) ? localize_1.CreateEnv.hasVirtualEnv : undefined, }); } return items; } async function pickWorkspaceFolder(options, context) { const workspaces = (0, workspaceApis_1.getWorkspaceFolders)(); if (!workspaces || workspaces.length === 0) { if (context === windowApis_1.MultiStepAction.Back) { throw windowApis_1.MultiStepAction.Back; } const result = await (0, windowApis_1.showErrorMessage)(localize_1.CreateEnv.noWorkspace, localize_1.Common.openFolder); if (result === localize_1.Common.openFolder) { await (0, commandApis_1.executeCommand)('vscode.openFolder'); } return undefined; } if (workspaces.length === 1) { if (context === windowApis_1.MultiStepAction.Back) { throw windowApis_1.MultiStepAction.Back; } return workspaces[0]; } const selected = await (0, windowApis_1.showQuickPickWithBack)(await getWorkspacesForQuickPick(workspaces), { placeHolder: localize_1.CreateEnv.pickWorkspacePlaceholder, ignoreFocusOut: true, canPickMany: options === null || options === void 0 ? void 0 : options.allowMultiSelect, matchOnDescription: true, matchOnDetail: true, }, options === null || options === void 0 ? void 0 : options.token); if (selected) { if (Array.isArray(selected)) { const details = selected.map((s) => s.detail).filter((s) => s !== undefined); return workspaces.filter((w) => details.includes(w.uri.fsPath)); } return workspaces.filter((w) => w.uri.fsPath === selected.detail)[0]; } return undefined; } exports.pickWorkspaceFolder = pickWorkspaceFolder; /***/ }), /***/ "./src/client/pythonEnvironments/creation/createEnvApi.ts": /*!****************************************************************!*\ !*** ./src/client/pythonEnvironments/creation/createEnvApi.ts ***! \****************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var _a; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildEnvironmentCreationApi = exports.registerCreateEnvironmentFeatures = exports.isCreatingEnvironment = exports.onCreateEnvironmentExited = exports.onCreateEnvironmentStarted = exports.registerCreateEnvironmentProvider = exports._createEnvironmentProviders = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const constants_1 = __webpack_require__(/*! ../../common/constants */ "./src/client/common/constants.ts"); const commandApis_1 = __webpack_require__(/*! ../../common/vscodeApis/commandApis */ "./src/client/common/vscodeApis/commandApis.ts"); const createEnvironment_1 = __webpack_require__(/*! ./createEnvironment */ "./src/client/pythonEnvironments/creation/createEnvironment.ts"); const condaCreationProvider_1 = __webpack_require__(/*! ./provider/condaCreationProvider */ "./src/client/pythonEnvironments/creation/provider/condaCreationProvider.ts"); const venvCreationProvider_1 = __webpack_require__(/*! ./provider/venvCreationProvider */ "./src/client/pythonEnvironments/creation/provider/venvCreationProvider.ts"); const telemetry_1 = __webpack_require__(/*! ../../telemetry */ "./src/client/telemetry/index.ts"); const constants_2 = __webpack_require__(/*! ../../telemetry/constants */ "./src/client/telemetry/constants.ts"); class CreateEnvironmentProviders { constructor() { this._createEnvProviders = []; this._createEnvProviders = []; } add(provider) { if (this._createEnvProviders.filter((p) => p.id === provider.id).length > 0) { throw new Error(`Create Environment provider with id ${provider.id} already registered`); } this._createEnvProviders.push(provider); } remove(provider) { this._createEnvProviders = this._createEnvProviders.filter((p) => p !== provider); } getAll() { return this._createEnvProviders; } } exports._createEnvironmentProviders = new CreateEnvironmentProviders(); function registerCreateEnvironmentProvider(provider) { exports._createEnvironmentProviders.add(provider); return new vscode_1.Disposable(() => { exports._createEnvironmentProviders.remove(provider); }); } exports.registerCreateEnvironmentProvider = registerCreateEnvironmentProvider; _a = (0, createEnvironment_1.getCreationEvents)(), exports.onCreateEnvironmentStarted = _a.onCreateEnvironmentStarted, exports.onCreateEnvironmentExited = _a.onCreateEnvironmentExited, exports.isCreatingEnvironment = _a.isCreatingEnvironment; function registerCreateEnvironmentFeatures(disposables, interpreterQuickPick) { disposables.push((0, commandApis_1.registerCommand)(constants_1.Commands.Create_Environment, (options) => { const providers = exports._createEnvironmentProviders.getAll(); return (0, createEnvironment_1.handleCreateEnvironmentCommand)(providers, options); }), (0, commandApis_1.registerCommand)(constants_1.Commands.Create_Environment_Button, async () => { (0, telemetry_1.sendTelemetryEvent)(constants_2.EventName.ENVIRONMENT_BUTTON, undefined, undefined); await (0, commandApis_1.executeCommand)(constants_1.Commands.Create_Environment); }), registerCreateEnvironmentProvider(new venvCreationProvider_1.VenvCreationProvider(interpreterQuickPick)), registerCreateEnvironmentProvider((0, condaCreationProvider_1.condaCreationProvider)())); } exports.registerCreateEnvironmentFeatures = registerCreateEnvironmentFeatures; function buildEnvironmentCreationApi() { return { onWillCreateEnvironment: exports.onCreateEnvironmentStarted, onDidCreateEnvironment: exports.onCreateEnvironmentExited, createEnvironment: async (options) => { const providers = exports._createEnvironmentProviders.getAll(); try { return await (0, createEnvironment_1.handleCreateEnvironmentCommand)(providers, options); } catch (err) { return { path: undefined, workspaceFolder: undefined, action: undefined, error: err }; } }, registerCreateEnvironmentProvider: (provider) => registerCreateEnvironmentProvider(provider), }; } exports.buildEnvironmentCreationApi = buildEnvironmentCreationApi; /***/ }), /***/ "./src/client/pythonEnvironments/creation/createEnvButtonContext.ts": /*!**************************************************************************!*\ !*** ./src/client/pythonEnvironments/creation/createEnvButtonContext.ts ***! \**************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.registerCreateEnvironmentButtonFeatures = void 0; const commandApis_1 = __webpack_require__(/*! ../../common/vscodeApis/commandApis */ "./src/client/common/vscodeApis/commandApis.ts"); const workspaceApis_1 = __webpack_require__(/*! ../../common/vscodeApis/workspaceApis */ "./src/client/common/vscodeApis/workspaceApis.ts"); async function setShowCreateEnvButtonContextKey() { const config = (0, workspaceApis_1.getConfiguration)('python'); const showCreateEnvButton = config.get('createEnvironment.contentButton', 'show') === 'show'; await (0, commandApis_1.executeCommand)('setContext', 'showCreateEnvButton', showCreateEnvButton); } function registerCreateEnvironmentButtonFeatures(disposables) { disposables.push((0, workspaceApis_1.onDidChangeConfiguration)(async () => { await setShowCreateEnvButtonContextKey(); })); setShowCreateEnvButtonContextKey(); } exports.registerCreateEnvironmentButtonFeatures = registerCreateEnvironmentButtonFeatures; /***/ }), /***/ "./src/client/pythonEnvironments/creation/createEnvironment.ts": /*!*********************************************************************!*\ !*** ./src/client/pythonEnvironments/creation/createEnvironment.ts ***! \*********************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.handleCreateEnvironmentCommand = exports.getCreationEvents = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const localize_1 = __webpack_require__(/*! ../../common/utils/localize */ "./src/client/common/utils/localize.ts"); const windowApis_1 = __webpack_require__(/*! ../../common/vscodeApis/windowApis */ "./src/client/common/vscodeApis/windowApis.ts"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const onCreateEnvironmentStartedEvent = new vscode_1.EventEmitter(); const onCreateEnvironmentExitedEvent = new vscode_1.EventEmitter(); let startedEventCount = 0; function isBusyCreatingEnvironment() { return startedEventCount > 0; } function fireStartedEvent(options) { onCreateEnvironmentStartedEvent.fire({ options }); startedEventCount += 1; } function fireExitedEvent(result, options, error) { startedEventCount -= 1; if (result) { onCreateEnvironmentExitedEvent.fire({ options, ...result }); } else if (error) { onCreateEnvironmentExitedEvent.fire({ options, error }); } } function getCreationEvents() { return { onCreateEnvironmentStarted: onCreateEnvironmentStartedEvent.event, onCreateEnvironmentExited: onCreateEnvironmentExitedEvent.event, isCreatingEnvironment: isBusyCreatingEnvironment, }; } exports.getCreationEvents = getCreationEvents; async function createEnvironment(provider, options) { let result; let err; try { fireStartedEvent(options); result = await provider.createEnvironment(options); } catch (ex) { if (ex === vscode_1.QuickInputButtons.Back) { (0, logging_1.traceVerbose)('Create Env: User clicked back button during environment creation'); if (!options.showBackButton) { return undefined; } } err = ex; throw err; } finally { fireExitedEvent(result, options, err); } return result; } async function showCreateEnvironmentQuickPick(providers, options) { const items = providers.map((p) => ({ label: p.name, description: p.description, id: p.id, })); let selectedItem; if (options === null || options === void 0 ? void 0 : options.showBackButton) { selectedItem = await (0, windowApis_1.showQuickPickWithBack)(items, { placeHolder: localize_1.CreateEnv.providersQuickPickPlaceholder, matchOnDescription: true, ignoreFocusOut: true, }); } else { selectedItem = await (0, windowApis_1.showQuickPick)(items, { placeHolder: localize_1.CreateEnv.providersQuickPickPlaceholder, matchOnDescription: true, ignoreFocusOut: true, }); } if (selectedItem) { const selected = Array.isArray(selectedItem) ? selectedItem[0] : selectedItem; if (selected) { const selections = providers.filter((p) => p.id === selected.id); if (selections.length > 0) { return selections[0]; } } } return undefined; } function getOptionsWithDefaults(options) { return { installPackages: true, ignoreSourceControl: true, showBackButton: false, selectEnvironment: true, ...options, }; } async function handleCreateEnvironmentCommand(providers, options) { const optionsWithDefaults = getOptionsWithDefaults(options); if (!optionsWithDefaults.showBackButton && providers.length === 1) { optionsWithDefaults.showBackButton = false; } let selectedProvider = providers.length === 1 ? providers[0] : undefined; const envTypeStep = new windowApis_1.MultiStepNode(undefined, async (context) => { if (providers.length > 0) { try { selectedProvider = await showCreateEnvironmentQuickPick(providers, optionsWithDefaults); } catch (ex) { if (ex === windowApis_1.MultiStepAction.Back || ex === windowApis_1.MultiStepAction.Cancel) { return ex; } throw ex; } if (!selectedProvider) { return windowApis_1.MultiStepAction.Cancel; } } else { (0, logging_1.traceError)('No Environment Creation providers were registered.'); if (context === windowApis_1.MultiStepAction.Back) { return windowApis_1.MultiStepAction.Back; } } return windowApis_1.MultiStepAction.Continue; }, undefined); let result; const createStep = new windowApis_1.MultiStepNode(providers.length === 1 ? undefined : envTypeStep, async (context) => { if (context === windowApis_1.MultiStepAction.Back) { return windowApis_1.MultiStepAction.Back; } if (selectedProvider) { try { result = await createEnvironment(selectedProvider, optionsWithDefaults); } catch (ex) { if (ex === windowApis_1.MultiStepAction.Back || ex === windowApis_1.MultiStepAction.Cancel) { return ex; } throw ex; } } return windowApis_1.MultiStepAction.Continue; }, undefined); envTypeStep.next = createStep; const action = await windowApis_1.MultiStepNode.run(providers.length === 1 ? createStep : envTypeStep); if (options === null || options === void 0 ? void 0 : options.showBackButton) { if (action === windowApis_1.MultiStepAction.Back || action === windowApis_1.MultiStepAction.Cancel) { result = { action, workspaceFolder: undefined, path: undefined, error: undefined }; } } if (result) { return Object.freeze(result); } return undefined; } exports.handleCreateEnvironmentCommand = handleCreateEnvironmentCommand; /***/ }), /***/ "./src/client/pythonEnvironments/creation/provider/condaCreationProvider.ts": /*!**********************************************************************************!*\ !*** ./src/client/pythonEnvironments/creation/provider/condaCreationProvider.ts ***! \**********************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.condaCreationProvider = void 0; const fs_extra_1 = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const path = __webpack_require__(/*! path */ "path"); const constants_1 = __webpack_require__(/*! ../../../common/constants */ "./src/client/common/constants.ts"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); const workspaceSelection_1 = __webpack_require__(/*! ../common/workspaceSelection */ "./src/client/pythonEnvironments/creation/common/workspaceSelection.ts"); const rawProcessApis_1 = __webpack_require__(/*! ../../../common/process/rawProcessApis */ "./src/client/common/process/rawProcessApis.ts"); const async_1 = __webpack_require__(/*! ../../../common/utils/async */ "./src/client/common/utils/async.ts"); const platform_1 = __webpack_require__(/*! ../../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const scripts_1 = __webpack_require__(/*! ../../../common/process/internal/scripts */ "./src/client/common/process/internal/scripts/index.ts"); const localize_1 = __webpack_require__(/*! ../../../common/utils/localize */ "./src/client/common/utils/localize.ts"); const condaUtils_1 = __webpack_require__(/*! ./condaUtils */ "./src/client/pythonEnvironments/creation/provider/condaUtils.ts"); const commonUtils_1 = __webpack_require__(/*! ../common/commonUtils */ "./src/client/pythonEnvironments/creation/common/commonUtils.ts"); const windowApis_1 = __webpack_require__(/*! ../../../common/vscodeApis/windowApis */ "./src/client/common/vscodeApis/windowApis.ts"); const constants_2 = __webpack_require__(/*! ../../../telemetry/constants */ "./src/client/telemetry/constants.ts"); const telemetry_1 = __webpack_require__(/*! ../../../telemetry */ "./src/client/telemetry/index.ts"); const condaProgressAndTelemetry_1 = __webpack_require__(/*! ./condaProgressAndTelemetry */ "./src/client/pythonEnvironments/creation/provider/condaProgressAndTelemetry.ts"); const stringUtils_1 = __webpack_require__(/*! ../../../common/stringUtils */ "./src/client/common/stringUtils.ts"); function generateCommandArgs(version, options, name) { let addGitIgnore = true; let installPackages = true; if (options) { addGitIgnore = (options === null || options === void 0 ? void 0 : options.ignoreSourceControl) !== undefined ? options.ignoreSourceControl : true; installPackages = (options === null || options === void 0 ? void 0 : options.installPackages) !== undefined ? options.installPackages : true; } const command = [(0, scripts_1.createCondaScript)()]; if (addGitIgnore) { command.push('--git-ignore'); } if (name && (name || '').trim().length) { command.push('--name', name.toCommandArgumentForPythonMgrExt()); } if (installPackages) { command.push('--install'); } if (version) { command.push('--python'); command.push(version); } return command; } function getCondaEnvFromOutput(output) { try { const envPath = output .split(/\r?\n/g) .map((s) => s.trim()) .filter((s) => s.startsWith(condaProgressAndTelemetry_1.CONDA_ENV_CREATED_MARKER) || s.startsWith(condaProgressAndTelemetry_1.CONDA_ENV_EXISTING_MARKER))[0]; if (envPath.includes(condaProgressAndTelemetry_1.CONDA_ENV_CREATED_MARKER)) { return envPath.substring(condaProgressAndTelemetry_1.CONDA_ENV_CREATED_MARKER.length); } return envPath.substring(condaProgressAndTelemetry_1.CONDA_ENV_EXISTING_MARKER.length); } catch (ex) { (0, logging_1.traceError)('Parsing out environment path failed.'); return undefined; } } async function createCondaEnv(workspace, command, args, progress, token) { progress.report({ message: localize_1.CreateEnv.Conda.creating, }); const deferred = (0, async_1.createDeferred)(); let pathEnv = (0, platform_1.getEnvironmentVariable)('PATH') || (0, platform_1.getEnvironmentVariable)('Path') || ''; if ((0, platform_1.getOSType)() === platform_1.OSType.Windows) { const root = path.dirname(command); const libPath1 = path.join(root, 'Library', 'bin'); const libPath2 = path.join(root, 'Library', 'mingw-w64', 'bin'); const libPath3 = path.join(root, 'Library', 'usr', 'bin'); const libPath4 = path.join(root, 'bin'); const libPath5 = path.join(root, 'Scripts'); const libPath = [libPath1, libPath2, libPath3, libPath4, libPath5].join(path.delimiter); pathEnv = `${libPath}${path.delimiter}${pathEnv}`; } (0, logging_1.traceLog)('Running Conda Env creation script: ', [command, ...args]); const { proc, out, dispose } = (0, rawProcessApis_1.execObservable)(command, args, { mergeStdOutErr: true, token, cwd: workspace.uri.fsPath, env: { PATH: pathEnv, }, }); const progressAndTelemetry = new condaProgressAndTelemetry_1.CondaProgressAndTelemetry(progress); let condaEnvPath; out.subscribe((value) => { const output = (0, stringUtils_1.splitLines)(value.out).join('\r\n'); (0, logging_1.traceLog)(output); if (output.includes(condaProgressAndTelemetry_1.CONDA_ENV_CREATED_MARKER) || output.includes(condaProgressAndTelemetry_1.CONDA_ENV_EXISTING_MARKER)) { condaEnvPath = getCondaEnvFromOutput(output); } progressAndTelemetry.process(output); }, async (error) => { (0, logging_1.traceError)('Error while running conda env creation script: ', error); deferred.reject(error); }, () => { dispose(); if ((proc === null || proc === void 0 ? void 0 : proc.exitCode) !== 0) { (0, logging_1.traceError)('Error while running venv creation script: ', progressAndTelemetry.getLastError()); deferred.reject(progressAndTelemetry.getLastError() || `Conda env creation failed with exitCode: ${proc === null || proc === void 0 ? void 0 : proc.exitCode}`); } else { deferred.resolve(condaEnvPath); } }); return deferred.promise; } function getExecutableCommand(condaBaseEnvPath) { if ((0, platform_1.getOSType)() === platform_1.OSType.Windows) { return path.join(condaBaseEnvPath, 'python.exe'); } return path.join(condaBaseEnvPath, 'bin', 'python'); } async function createEnvironment(options) { const conda = await (0, condaUtils_1.getCondaBaseEnv)(); if (!conda) { return undefined; } let workspace; const workspaceStep = new windowApis_1.MultiStepNode(undefined, async (context) => { try { workspace = (await (0, workspaceSelection_1.pickWorkspaceFolder)(undefined, context)); } catch (ex) { if (ex === windowApis_1.MultiStepAction.Back || ex === windowApis_1.MultiStepAction.Cancel) { return ex; } throw ex; } if (workspace === undefined) { (0, logging_1.traceError)('Workspace was not selected or found for creating conda environment.'); return windowApis_1.MultiStepAction.Cancel; } (0, logging_1.traceInfo)(`Selected workspace ${workspace.uri.fsPath} for creating conda environment.`); return windowApis_1.MultiStepAction.Continue; }, undefined); let version; const versionStep = new windowApis_1.MultiStepNode(workspaceStep, async () => { try { version = await (0, condaUtils_1.pickPythonVersion)(); } catch (ex) { if (ex === windowApis_1.MultiStepAction.Back || ex === windowApis_1.MultiStepAction.Cancel) { return ex; } throw ex; } if (version === undefined) { (0, logging_1.traceError)('Python version was not selected for creating conda environment.'); return windowApis_1.MultiStepAction.Cancel; } (0, logging_1.traceInfo)(`Selected Python version ${version} for creating conda environment.`); return windowApis_1.MultiStepAction.Continue; }, undefined); workspaceStep.next = versionStep; let name = '.conda'; const nameStep = new windowApis_1.MultiStepNode(versionStep, async () => new Promise((resolve) => { const input = vscode_1.window.createInputBox(); input.title = 'Environment Name'; input.value = '.conda'; input.buttons = [vscode_1.QuickInputButtons.Back]; input.onDidTriggerButton((e) => { if (e === vscode_1.QuickInputButtons.Back) { resolve(windowApis_1.MultiStepAction.Back); input.hide(); } }); input.onDidHide(() => { resolve(windowApis_1.MultiStepAction.Cancel); input.hide(); }); input.onDidAccept(async () => { const envName = input.value.trim(); if (!envName.length) { input.validationMessage = 'Enter a valid name'; return; } if (workspace) { const fullPath = vscode_1.Uri.joinPath(workspace.uri, envName); if (await (0, fs_extra_1.pathExists)(fullPath.fsPath)) { input.validationMessage = 'Environment with the same name already exists'; return; } } name = envName; input.validationMessage = ''; resolve(windowApis_1.MultiStepAction.Continue); input.hide(); }); input.show(); }), undefined); versionStep.next = nameStep; const action = await windowApis_1.MultiStepNode.run(workspaceStep); if (action === windowApis_1.MultiStepAction.Back || action === windowApis_1.MultiStepAction.Cancel) { throw action; } return (0, windowApis_1.withProgress)({ location: vscode_1.ProgressLocation.Notification, title: `${localize_1.CreateEnv.statusTitle} ([${localize_1.Common.showLogs}](command:${constants_1.Commands.ViewOutput}))`, cancellable: true, }, async (progress, token) => { progress.report({ message: localize_1.CreateEnv.statusStarting, }); let envPath; try { (0, telemetry_1.sendTelemetryEvent)(constants_2.EventName.ENVIRONMENT_CREATING, undefined, { environmentType: 'conda', pythonVersion: version, }); if (workspace) { envPath = await createCondaEnv(workspace, getExecutableCommand(conda), generateCommandArgs(version, options, name), progress, token); if (envPath) { return { path: envPath, workspaceFolder: workspace }; } throw new Error('Failed to create conda environment. See Output > Python for more info.'); } else { throw new Error('A workspace is needed to create conda environment'); } } catch (ex) { (0, logging_1.traceError)(ex); (0, commonUtils_1.showErrorMessageWithLogs)(localize_1.CreateEnv.Conda.errorCreatingEnvironment); return { error: ex }; } }); } function condaCreationProvider() { return { createEnvironment, name: 'Conda', description: localize_1.CreateEnv.Conda.providerDescription, id: `${constants_1.PVSC_EXTENSION_ID}:conda`, tools: ['Conda'], }; } exports.condaCreationProvider = condaCreationProvider; /***/ }), /***/ "./src/client/pythonEnvironments/creation/provider/condaProgressAndTelemetry.ts": /*!**************************************************************************************!*\ !*** ./src/client/pythonEnvironments/creation/provider/condaProgressAndTelemetry.ts ***! \**************************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CondaProgressAndTelemetry = exports.CREATE_FAILED_INSTALL_YML = exports.CREATE_CONDA_INSTALLED_YML = exports.CREATE_CONDA_FAILED_MARKER = exports.CONDA_INSTALLING_YML = exports.CONDA_ENV_EXISTING_MARKER = exports.CONDA_ENV_CREATED_MARKER = void 0; const localize_1 = __webpack_require__(/*! ../../../common/utils/localize */ "./src/client/common/utils/localize.ts"); const telemetry_1 = __webpack_require__(/*! ../../../telemetry */ "./src/client/telemetry/index.ts"); const constants_1 = __webpack_require__(/*! ../../../telemetry/constants */ "./src/client/telemetry/constants.ts"); exports.CONDA_ENV_CREATED_MARKER = 'CREATED_CONDA_ENV:'; exports.CONDA_ENV_EXISTING_MARKER = 'EXISTING_CONDA_ENV:'; exports.CONDA_INSTALLING_YML = 'CONDA_INSTALLING_YML:'; exports.CREATE_CONDA_FAILED_MARKER = 'CREATE_CONDA.ENV_FAILED_CREATION'; exports.CREATE_CONDA_INSTALLED_YML = 'CREATE_CONDA.INSTALLED_YML'; exports.CREATE_FAILED_INSTALL_YML = 'CREATE_CONDA.FAILED_INSTALL_YML'; class CondaProgressAndTelemetry { constructor(progress) { this.progress = progress; this.condaCreatedReported = false; this.condaFailedReported = false; this.condaInstallingPackagesReported = false; this.condaInstallingPackagesFailedReported = false; this.condaInstalledPackagesReported = false; this.lastError = undefined; } process(output) { if (!this.condaCreatedReported && output.includes(exports.CONDA_ENV_CREATED_MARKER)) { this.condaCreatedReported = true; this.progress.report({ message: localize_1.CreateEnv.Conda.created, }); (0, telemetry_1.sendTelemetryEvent)(constants_1.EventName.ENVIRONMENT_CREATED, undefined, { environmentType: 'conda', reason: 'created', }); } else if (!this.condaCreatedReported && output.includes(exports.CONDA_ENV_EXISTING_MARKER)) { this.condaCreatedReported = true; this.progress.report({ message: localize_1.CreateEnv.Conda.created, }); (0, telemetry_1.sendTelemetryEvent)(constants_1.EventName.ENVIRONMENT_CREATED, undefined, { environmentType: 'conda', reason: 'existing', }); } else if (!this.condaFailedReported && output.includes(exports.CREATE_CONDA_FAILED_MARKER)) { this.condaFailedReported = true; (0, telemetry_1.sendTelemetryEvent)(constants_1.EventName.ENVIRONMENT_FAILED, undefined, { environmentType: 'conda', reason: 'other', }); this.lastError = exports.CREATE_CONDA_FAILED_MARKER; } else if (!this.condaInstallingPackagesReported && output.includes(exports.CONDA_INSTALLING_YML)) { this.condaInstallingPackagesReported = true; this.progress.report({ message: localize_1.CreateEnv.Conda.installingPackages, }); (0, telemetry_1.sendTelemetryEvent)(constants_1.EventName.ENVIRONMENT_INSTALLING_PACKAGES, undefined, { environmentType: 'conda', using: 'environment.yml', }); } else if (!this.condaInstallingPackagesFailedReported && output.includes(exports.CREATE_FAILED_INSTALL_YML)) { this.condaInstallingPackagesFailedReported = true; (0, telemetry_1.sendTelemetryEvent)(constants_1.EventName.ENVIRONMENT_INSTALLING_PACKAGES_FAILED, undefined, { environmentType: 'conda', using: 'environment.yml', }); this.lastError = exports.CREATE_FAILED_INSTALL_YML; } else if (!this.condaInstalledPackagesReported && output.includes(exports.CREATE_CONDA_INSTALLED_YML)) { this.condaInstalledPackagesReported = true; (0, telemetry_1.sendTelemetryEvent)(constants_1.EventName.ENVIRONMENT_INSTALLED_PACKAGES, undefined, { environmentType: 'conda', using: 'environment.yml', }); } } getLastError() { return this.lastError; } } exports.CondaProgressAndTelemetry = CondaProgressAndTelemetry; /***/ }), /***/ "./src/client/pythonEnvironments/creation/provider/condaUtils.ts": /*!***********************************************************************!*\ !*** ./src/client/pythonEnvironments/creation/provider/condaUtils.ts ***! \***********************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.pickPythonVersion = exports.getCondaBaseEnv = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const constants_1 = __webpack_require__(/*! ../../../common/constants */ "./src/client/common/constants.ts"); const localize_1 = __webpack_require__(/*! ../../../common/utils/localize */ "./src/client/common/utils/localize.ts"); const commandApis_1 = __webpack_require__(/*! ../../../common/vscodeApis/commandApis */ "./src/client/common/vscodeApis/commandApis.ts"); const windowApis_1 = __webpack_require__(/*! ../../../common/vscodeApis/windowApis */ "./src/client/common/vscodeApis/windowApis.ts"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); const conda_1 = __webpack_require__(/*! ../../common/environmentManagers/conda */ "./src/client/pythonEnvironments/common/environmentManagers/conda.ts"); const RECOMMENDED_CONDA_PYTHON = '3.10'; async function getCondaBaseEnv() { const conda = await conda_1.Conda.getConda(); if (!conda) { const response = await (0, windowApis_1.showErrorMessage)(localize_1.CreateEnv.Conda.condaMissing, localize_1.Common.learnMore); if (response === localize_1.Common.learnMore) { await (0, commandApis_1.executeCommand)('vscode.open', vscode_1.Uri.parse('https://docs.anaconda.com/anaconda/install/')); } return undefined; } const envs = (await conda.getEnvList()).filter((e) => e.name === 'base'); if (envs.length === 1) { return envs[0].prefix; } if (envs.length > 1) { (0, logging_1.traceLog)('Multiple conda base envs detected: ', envs.map((e) => e.prefix)); return undefined; } return undefined; } exports.getCondaBaseEnv = getCondaBaseEnv; async function pickPythonVersion(token) { const items = ['3.10', '3.11', '3.9', '3.8', '3.7'].map((v) => ({ label: v === RECOMMENDED_CONDA_PYTHON ? `${constants_1.Octicons.Star} Python` : 'Python', description: v, })); const selection = await (0, windowApis_1.showQuickPickWithBack)(items, { placeHolder: localize_1.CreateEnv.Conda.selectPythonQuickPickPlaceholder, matchOnDescription: true, ignoreFocusOut: true, }, token); if (selection) { return selection.description; } return undefined; } exports.pickPythonVersion = pickPythonVersion; /***/ }), /***/ "./src/client/pythonEnvironments/creation/provider/venvCreationProvider.ts": /*!*********************************************************************************!*\ !*** ./src/client/pythonEnvironments/creation/provider/venvCreationProvider.ts ***! \*********************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.canCreateVenv = exports.VenvCreationProvider = void 0; const os = __webpack_require__(/*! os */ "os"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const constants_1 = __webpack_require__(/*! ../../../common/constants */ "./src/client/common/constants.ts"); const scripts_1 = __webpack_require__(/*! ../../../common/process/internal/scripts */ "./src/client/common/process/internal/scripts/index.ts"); const rawProcessApis_1 = __webpack_require__(/*! ../../../common/process/rawProcessApis */ "./src/client/common/process/rawProcessApis.ts"); const async_1 = __webpack_require__(/*! ../../../common/utils/async */ "./src/client/common/utils/async.ts"); const localize_1 = __webpack_require__(/*! ../../../common/utils/localize */ "./src/client/common/utils/localize.ts"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); const workspaceSelection_1 = __webpack_require__(/*! ../common/workspaceSelection */ "./src/client/pythonEnvironments/creation/common/workspaceSelection.ts"); const info_1 = __webpack_require__(/*! ../../info */ "./src/client/pythonEnvironments/info/index.ts"); const windowApis_1 = __webpack_require__(/*! ../../../common/vscodeApis/windowApis */ "./src/client/common/vscodeApis/windowApis.ts"); const telemetry_1 = __webpack_require__(/*! ../../../telemetry */ "./src/client/telemetry/index.ts"); const constants_2 = __webpack_require__(/*! ../../../telemetry/constants */ "./src/client/telemetry/constants.ts"); const venvProgressAndTelemetry_1 = __webpack_require__(/*! ./venvProgressAndTelemetry */ "./src/client/pythonEnvironments/creation/provider/venvProgressAndTelemetry.ts"); const commonUtils_1 = __webpack_require__(/*! ../common/commonUtils */ "./src/client/pythonEnvironments/creation/common/commonUtils.ts"); const venvUtils_1 = __webpack_require__(/*! ./venvUtils */ "./src/client/pythonEnvironments/creation/provider/venvUtils.ts"); const multiStepInput_1 = __webpack_require__(/*! ../../../common/utils/multiStepInput */ "./src/client/common/utils/multiStepInput.ts"); const utils_1 = __webpack_require__(/*! ../../../../environments/utils */ "./src/environments/utils.ts"); function generateCommandArgs(installInfo, addGitIgnore) { var _a; const command = [(0, scripts_1.createVenvScript)()]; if (addGitIgnore) { command.push('--git-ignore'); } if (installInfo) { if (installInfo.some((i) => i.installType === 'toml')) { const source = (_a = installInfo.find((i) => i.installType === 'toml')) === null || _a === void 0 ? void 0 : _a.source; command.push('--toml', (source === null || source === void 0 ? void 0 : source.fileToCommandArgumentForPythonMgrExt()) || 'pyproject.toml'); } const extras = installInfo.filter((i) => i.installType === 'toml').map((i) => i.installItem); extras.forEach((r) => { if (r) { command.push('--extras', r); } }); const requirements = installInfo.filter((i) => i.installType === 'requirements').map((i) => i.installItem); requirements.forEach((r) => { if (r) { command.push('--requirements', r); } }); } return command; } function getVenvFromOutput(output) { try { const envPath = output .split(/\r?\n/g) .map((s) => s.trim()) .filter((s) => s.startsWith(venvProgressAndTelemetry_1.VENV_CREATED_MARKER) || s.startsWith(venvProgressAndTelemetry_1.VENV_EXISTING_MARKER))[0]; if (envPath.includes(venvProgressAndTelemetry_1.VENV_CREATED_MARKER)) { return envPath.substring(venvProgressAndTelemetry_1.VENV_CREATED_MARKER.length); } return envPath.substring(venvProgressAndTelemetry_1.VENV_EXISTING_MARKER.length); } catch (ex) { (0, logging_1.traceError)('Parsing out environment path failed.'); return undefined; } } async function createVenv(workspace, command, args, progress, token) { progress.report({ message: localize_1.CreateEnv.Venv.creating, }); (0, telemetry_1.sendTelemetryEvent)(constants_2.EventName.ENVIRONMENT_CREATING, undefined, { environmentType: 'venv', pythonVersion: undefined, }); const deferred = (0, async_1.createDeferred)(); (0, logging_1.traceLog)('Running Env creation script: ', [command, ...args]); const { proc, out, dispose } = (0, rawProcessApis_1.execObservable)(command, args, { mergeStdOutErr: true, token, cwd: workspace.uri.fsPath, }); const progressAndTelemetry = new venvProgressAndTelemetry_1.VenvProgressAndTelemetry(progress); let venvPath; out.subscribe((value) => { const output = value.out.split(/\r?\n/g).join(os.EOL); (0, logging_1.traceLog)(output); if (output.includes(venvProgressAndTelemetry_1.VENV_CREATED_MARKER) || output.includes(venvProgressAndTelemetry_1.VENV_EXISTING_MARKER)) { venvPath = getVenvFromOutput(output); } progressAndTelemetry.process(output); }, (error) => { (0, logging_1.traceError)('Error while running venv creation script: ', error); deferred.reject(error); }, () => { dispose(); if ((proc === null || proc === void 0 ? void 0 : proc.exitCode) !== 0) { (0, logging_1.traceError)('Error while running venv creation script: ', progressAndTelemetry.getLastError()); deferred.reject(progressAndTelemetry.getLastError() || `Failed to create virtual environment with exitCode: ${proc === null || proc === void 0 ? void 0 : proc.exitCode}`); } else { deferred.resolve(venvPath); } }); return deferred.promise; } class VenvCreationProvider { constructor(interpreterQuickPick) { this.interpreterQuickPick = interpreterQuickPick; this.name = 'Venv'; this.description = localize_1.CreateEnv.Venv.providerDescription; this.id = `${constants_1.PVSC_EXTENSION_ID}:venv`; this.tools = ['Venv']; } async createEnvironment(options) { let workspace; const workspaceStep = new windowApis_1.MultiStepNode(undefined, async (context) => { try { workspace = (await (0, workspaceSelection_1.pickWorkspaceFolder)(undefined, context)); } catch (ex) { if (ex === windowApis_1.MultiStepAction.Back || ex === windowApis_1.MultiStepAction.Cancel) { return ex; } throw ex; } if (workspace === undefined) { (0, logging_1.traceError)('Workspace was not selected or found for creating virtual environment.'); return windowApis_1.MultiStepAction.Cancel; } (0, logging_1.traceInfo)(`Selected workspace ${workspace.uri.fsPath} for creating virtual environment.`); return windowApis_1.MultiStepAction.Continue; }, undefined); let existingVenvAction; const existingEnvStep = new windowApis_1.MultiStepNode(workspaceStep, async (context) => { if (workspace && context === windowApis_1.MultiStepAction.Continue) { try { existingVenvAction = await (0, venvUtils_1.pickExistingVenvAction)(workspace); return windowApis_1.MultiStepAction.Continue; } catch (ex) { if (ex === windowApis_1.MultiStepAction.Back || ex === windowApis_1.MultiStepAction.Cancel) { return ex; } throw ex; } } else if (context === windowApis_1.MultiStepAction.Back) { return windowApis_1.MultiStepAction.Back; } return windowApis_1.MultiStepAction.Continue; }, undefined); workspaceStep.next = existingEnvStep; let interpreter; const interpreterStep = new windowApis_1.MultiStepNode(existingEnvStep, async (context) => { if (workspace) { if (existingVenvAction === venvUtils_1.ExistingVenvAction.Recreate || existingVenvAction === venvUtils_1.ExistingVenvAction.Create) { try { interpreter = await this.interpreterQuickPick.getInterpreterViaQuickPick(workspace.uri, (i) => [ info_1.EnvironmentType.System, info_1.EnvironmentType.MicrosoftStore, info_1.EnvironmentType.Global, info_1.EnvironmentType.Pyenv, info_1.EnvironmentType.Unknown, ].includes((0, utils_1.getEnvironmentType)(i)), { skipRecommended: true, showBackButton: true, placeholder: localize_1.CreateEnv.Venv.selectPythonPlaceHolder, title: null, }); } catch (ex) { if (ex === multiStepInput_1.InputFlowAction.back) { return windowApis_1.MultiStepAction.Back; } interpreter = undefined; } } else if (existingVenvAction === venvUtils_1.ExistingVenvAction.UseExisting) { if (context === windowApis_1.MultiStepAction.Back) { return windowApis_1.MultiStepAction.Back; } interpreter = (0, commonUtils_1.getVenvExecutable)(workspace); } } if (!interpreter) { (0, logging_1.traceError)('Virtual env creation requires an interpreter.'); return windowApis_1.MultiStepAction.Cancel; } (0, logging_1.traceInfo)(`Selected interpreter ${interpreter} for creating virtual environment.`); return windowApis_1.MultiStepAction.Continue; }, undefined); existingEnvStep.next = interpreterStep; let addGitIgnore = true; let installPackages = true; if (options) { addGitIgnore = (options === null || options === void 0 ? void 0 : options.ignoreSourceControl) !== undefined ? options.ignoreSourceControl : true; installPackages = (options === null || options === void 0 ? void 0 : options.installPackages) !== undefined ? options.installPackages : true; } let installInfo; const packagesStep = new windowApis_1.MultiStepNode(interpreterStep, async (context) => { if (workspace && installPackages) { if (existingVenvAction !== venvUtils_1.ExistingVenvAction.UseExisting) { try { installInfo = await (0, venvUtils_1.pickPackagesToInstall)(workspace); } catch (ex) { if (ex === windowApis_1.MultiStepAction.Back || ex === windowApis_1.MultiStepAction.Cancel) { return ex; } throw ex; } if (!installInfo) { (0, logging_1.traceVerbose)('Virtual env creation exited during dependencies selection.'); return windowApis_1.MultiStepAction.Cancel; } } else if (context === windowApis_1.MultiStepAction.Back) { return windowApis_1.MultiStepAction.Back; } } return windowApis_1.MultiStepAction.Continue; }, undefined); interpreterStep.next = packagesStep; const action = await windowApis_1.MultiStepNode.run(workspaceStep); if (action === windowApis_1.MultiStepAction.Back || action === windowApis_1.MultiStepAction.Cancel) { throw action; } if (workspace) { if (existingVenvAction === venvUtils_1.ExistingVenvAction.Recreate) { (0, telemetry_1.sendTelemetryEvent)(constants_2.EventName.ENVIRONMENT_DELETE, undefined, { environmentType: 'venv', status: 'triggered', }); if (await (0, venvUtils_1.deleteEnvironment)(workspace, interpreter)) { (0, telemetry_1.sendTelemetryEvent)(constants_2.EventName.ENVIRONMENT_DELETE, undefined, { environmentType: 'venv', status: 'deleted', }); } else { (0, telemetry_1.sendTelemetryEvent)(constants_2.EventName.ENVIRONMENT_DELETE, undefined, { environmentType: 'venv', status: 'failed', }); throw windowApis_1.MultiStepAction.Cancel; } } else if (existingVenvAction === venvUtils_1.ExistingVenvAction.UseExisting) { (0, telemetry_1.sendTelemetryEvent)(constants_2.EventName.ENVIRONMENT_REUSE, undefined, { environmentType: 'venv', }); return { path: (0, commonUtils_1.getVenvExecutable)(workspace), workspaceFolder: workspace }; } } const args = generateCommandArgs(installInfo, addGitIgnore); return (0, windowApis_1.withProgress)({ location: vscode_1.ProgressLocation.Notification, title: `${localize_1.CreateEnv.statusTitle} ([${localize_1.Common.showLogs}](command:${constants_1.Commands.ViewOutput}))`, cancellable: true, }, async (progress, token) => { progress.report({ message: localize_1.CreateEnv.statusStarting, }); let envPath; try { if (interpreter && workspace) { envPath = await createVenv(workspace, interpreter, args, progress, token); if (envPath) { return { path: envPath, workspaceFolder: workspace }; } throw new Error('Failed to create virtual environment. See Output > Python for more info.'); } throw new Error('Failed to create virtual environment. Either interpreter or workspace is undefined.'); } catch (ex) { (0, logging_1.traceError)(ex); (0, commonUtils_1.showErrorMessageWithLogs)(localize_1.CreateEnv.Venv.errorCreatingEnvironment); return { error: ex }; } }); } } exports.VenvCreationProvider = VenvCreationProvider; function canCreateVenv(environments) { return environments.some((i) => [ info_1.EnvironmentType.System, info_1.EnvironmentType.MicrosoftStore, info_1.EnvironmentType.Global, info_1.EnvironmentType.Pyenv, info_1.EnvironmentType.Unknown, ].includes((0, utils_1.getEnvironmentType)(i))); } exports.canCreateVenv = canCreateVenv; /***/ }), /***/ "./src/client/pythonEnvironments/creation/provider/venvDeleteUtils.ts": /*!****************************************************************************!*\ !*** ./src/client/pythonEnvironments/creation/provider/venvDeleteUtils.ts ***! \****************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.deleteEnvironmentWindows = exports.deleteEnvironmentNonWindows = void 0; const fs = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const path = __webpack_require__(/*! path */ "path"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); const commonUtils_1 = __webpack_require__(/*! ../common/commonUtils */ "./src/client/pythonEnvironments/creation/common/commonUtils.ts"); const localize_1 = __webpack_require__(/*! ../../../common/utils/localize */ "./src/client/common/utils/localize.ts"); const async_1 = __webpack_require__(/*! ../../../common/utils/async */ "./src/client/common/utils/async.ts"); const venvSwitchPython_1 = __webpack_require__(/*! ./venvSwitchPython */ "./src/client/pythonEnvironments/creation/provider/venvSwitchPython.ts"); async function tryDeleteFile(file) { try { if (!(await fs.pathExists(file))) { return true; } await fs.unlink(file); return true; } catch (err) { (0, logging_1.traceError)(`Failed to delete file [${file}]:`, err); return false; } } async function tryDeleteDir(dir) { try { if (!(await fs.pathExists(dir))) { return true; } await fs.rmdir(dir, { recursive: true, maxRetries: 10, retryDelay: 200, }); return true; } catch (err) { (0, logging_1.traceError)(`Failed to delete directory [${dir}]:`, err); return false; } } async function deleteEnvironmentNonWindows(workspaceFolder) { const venvPath = (0, commonUtils_1.getVenvPath)(workspaceFolder); if (await tryDeleteDir(venvPath)) { (0, logging_1.traceInfo)(`Deleted venv dir: ${venvPath}`); return true; } (0, commonUtils_1.showErrorMessageWithLogs)(localize_1.CreateEnv.Venv.errorDeletingEnvironment); return false; } exports.deleteEnvironmentNonWindows = deleteEnvironmentNonWindows; async function deleteEnvironmentWindows(workspaceFolder, interpreter) { const venvPath = (0, commonUtils_1.getVenvPath)(workspaceFolder); const venvPythonPath = path.join(venvPath, 'Scripts', 'python.exe'); if (await tryDeleteFile(venvPythonPath)) { (0, logging_1.traceInfo)(`Deleted python executable: ${venvPythonPath}`); if (await tryDeleteDir(venvPath)) { (0, logging_1.traceInfo)(`Deleted ".venv" dir: ${venvPath}`); return true; } (0, logging_1.traceError)(`Failed to delete ".venv" dir: ${venvPath}`); (0, logging_1.traceError)('This happens if the virtual environment is still in use, or some binary in the venv is still running.'); (0, logging_1.traceError)(`Please delete the ".venv" manually: [${venvPath}]`); (0, commonUtils_1.showErrorMessageWithLogs)(localize_1.CreateEnv.Venv.errorDeletingEnvironment); return false; } (0, logging_1.traceError)(`Failed to delete python executable: ${venvPythonPath}`); (0, logging_1.traceError)('This happens if the virtual environment is still in use.'); if (interpreter) { (0, logging_1.traceError)('We will attempt to switch python temporarily to delete the ".venv"'); await (0, venvSwitchPython_1.switchSelectedPython)(interpreter, workspaceFolder.uri, 'temporarily to delete the ".venv"'); (0, logging_1.traceInfo)(`Attempting to delete ".venv" again: ${venvPath}`); const ms = 500; for (let i = 0; i < 5; i = i + 1) { (0, logging_1.traceInfo)(`Waiting for ${ms}ms to let processes exit, before a delete attempt.`); await (0, async_1.sleep)(ms); if (await tryDeleteDir(venvPath)) { (0, logging_1.traceInfo)(`Deleted ".venv" dir: ${venvPath}`); return true; } (0, logging_1.traceError)(`Failed to delete ".venv" dir [${venvPath}] (attempt ${i + 1}/5).`); } } else { (0, logging_1.traceError)(`Please delete the ".venv" dir manually: [${venvPath}]`); } (0, commonUtils_1.showErrorMessageWithLogs)(localize_1.CreateEnv.Venv.errorDeletingEnvironment); return false; } exports.deleteEnvironmentWindows = deleteEnvironmentWindows; /***/ }), /***/ "./src/client/pythonEnvironments/creation/provider/venvProgressAndTelemetry.ts": /*!*************************************************************************************!*\ !*** ./src/client/pythonEnvironments/creation/provider/venvProgressAndTelemetry.ts ***! \*************************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VenvProgressAndTelemetry = exports.VENV_EXISTING_MARKER = exports.VENV_CREATED_MARKER = void 0; const localize_1 = __webpack_require__(/*! ../../../common/utils/localize */ "./src/client/common/utils/localize.ts"); exports.VENV_CREATED_MARKER = 'CREATED_VENV:'; exports.VENV_EXISTING_MARKER = 'EXISTING_VENV:'; const INSTALLING_REQUIREMENTS = 'VENV_INSTALLING_REQUIREMENTS:'; const INSTALLING_PYPROJECT = 'VENV_INSTALLING_PYPROJECT:'; const PIP_NOT_INSTALLED_MARKER = 'CREATE_VENV.PIP_NOT_FOUND'; const VENV_NOT_INSTALLED_MARKER = 'CREATE_VENV.VENV_NOT_FOUND'; const INSTALL_REQUIREMENTS_FAILED_MARKER = 'CREATE_VENV.PIP_FAILED_INSTALL_REQUIREMENTS'; const INSTALL_PYPROJECT_FAILED_MARKER = 'CREATE_VENV.PIP_FAILED_INSTALL_PYPROJECT'; const CREATE_VENV_FAILED_MARKER = 'CREATE_VENV.VENV_FAILED_CREATION'; const VENV_ALREADY_EXISTS_MARKER = 'CREATE_VENV.VENV_ALREADY_EXISTS'; const INSTALLED_REQUIREMENTS_MARKER = 'CREATE_VENV.PIP_INSTALLED_REQUIREMENTS'; const INSTALLED_PYPROJECT_MARKER = 'CREATE_VENV.PIP_INSTALLED_PYPROJECT'; const UPGRADE_PIP_FAILED_MARKER = 'CREATE_VENV.UPGRADE_PIP_FAILED'; const UPGRADING_PIP_MARKER = 'CREATE_VENV.UPGRADING_PIP'; const UPGRADED_PIP_MARKER = 'CREATE_VENV.UPGRADED_PIP'; const CREATING_MICROVENV_MARKER = 'CREATE_MICROVENV.CREATING_MICROVENV'; const CREATE_MICROVENV_FAILED_MARKER = 'CREATE_VENV.MICROVENV_FAILED_CREATION'; const CREATE_MICROVENV_FAILED_MARKER2 = 'CREATE_MICROVENV.MICROVENV_FAILED_CREATION'; const MICROVENV_CREATED_MARKER = 'CREATE_MICROVENV.CREATED_MICROVENV'; const INSTALLING_PIP_MARKER = 'CREATE_VENV.INSTALLING_PIP'; const INSTALL_PIP_FAILED_MARKER = 'CREATE_VENV.INSTALL_PIP_FAILED'; const DOWNLOADING_PIP_MARKER = 'CREATE_VENV.DOWNLOADING_PIP'; const DOWNLOAD_PIP_FAILED_MARKER = 'CREATE_VENV.DOWNLOAD_PIP_FAILED'; const DISTUTILS_NOT_INSTALLED_MARKER = 'CREATE_VENV.DISTUTILS_NOT_INSTALLED'; class VenvProgressAndTelemetry { constructor(progress) { this.progress = progress; this.processed = new Set(); this.reportActions = new Map([ [ exports.VENV_CREATED_MARKER, (progress) => { progress.report({ message: localize_1.CreateEnv.Venv.created }); return undefined; }, ], [ exports.VENV_EXISTING_MARKER, (progress) => { progress.report({ message: localize_1.CreateEnv.Venv.existing }); return undefined; }, ], [ INSTALLING_REQUIREMENTS, (progress) => { progress.report({ message: localize_1.CreateEnv.Venv.installingPackages }); return undefined; }, ], [ INSTALLING_PYPROJECT, (progress) => { progress.report({ message: localize_1.CreateEnv.Venv.installingPackages }); return undefined; }, ], [ PIP_NOT_INSTALLED_MARKER, (_progress) => PIP_NOT_INSTALLED_MARKER, ], [ DISTUTILS_NOT_INSTALLED_MARKER, (_progress) => VENV_NOT_INSTALLED_MARKER, ], [ VENV_NOT_INSTALLED_MARKER, (_progress) => VENV_NOT_INSTALLED_MARKER, ], [ INSTALL_REQUIREMENTS_FAILED_MARKER, (_progress) => INSTALL_REQUIREMENTS_FAILED_MARKER, ], [ INSTALL_PYPROJECT_FAILED_MARKER, (_progress) => INSTALL_PYPROJECT_FAILED_MARKER, ], [ CREATE_VENV_FAILED_MARKER, (_progress) => CREATE_VENV_FAILED_MARKER, ], [ VENV_ALREADY_EXISTS_MARKER, (_progress) => undefined, ], [ INSTALLED_REQUIREMENTS_MARKER, (_progress) => undefined, ], [ INSTALLED_PYPROJECT_MARKER, (_progress) => undefined, ], [ UPGRADED_PIP_MARKER, (_progress) => undefined, ], [ UPGRADE_PIP_FAILED_MARKER, (_progress) => UPGRADE_PIP_FAILED_MARKER, ], [ DOWNLOADING_PIP_MARKER, (progress) => { progress.report({ message: localize_1.CreateEnv.Venv.downloadingPip }); return undefined; }, ], [ DOWNLOAD_PIP_FAILED_MARKER, (_progress) => DOWNLOAD_PIP_FAILED_MARKER, ], [ INSTALLING_PIP_MARKER, (progress) => { progress.report({ message: localize_1.CreateEnv.Venv.installingPip }); return undefined; }, ], [ INSTALL_PIP_FAILED_MARKER, (_progress) => INSTALL_PIP_FAILED_MARKER, ], [ CREATING_MICROVENV_MARKER, (progress) => { progress.report({ message: localize_1.CreateEnv.Venv.creatingMicrovenv }); return undefined; }, ], [ CREATE_MICROVENV_FAILED_MARKER, (_progress) => CREATE_MICROVENV_FAILED_MARKER, ], [ CREATE_MICROVENV_FAILED_MARKER2, (_progress) => CREATE_MICROVENV_FAILED_MARKER2, ], [ MICROVENV_CREATED_MARKER, (_progress) => undefined, ], [ UPGRADING_PIP_MARKER, (progress) => { progress.report({ message: localize_1.CreateEnv.Venv.upgradingPip }); return undefined; }, ], ]); this.lastError = undefined; } getLastError() { return this.lastError; } process(output) { const keys = Array.from(this.reportActions.keys()); for (const key of keys) { if (output.includes(key) && !this.processed.has(key)) { const action = this.reportActions.get(key); if (action) { const err = action(this.progress); if (err) { this.lastError = err; } } this.processed.add(key); } } } } exports.VenvProgressAndTelemetry = VenvProgressAndTelemetry; /***/ }), /***/ "./src/client/pythonEnvironments/creation/provider/venvSwitchPython.ts": /*!*****************************************************************************!*\ !*** ./src/client/pythonEnvironments/creation/provider/venvSwitchPython.ts ***! \*****************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.switchSelectedPython = void 0; const path = __webpack_require__(/*! path */ "path"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const python_extension_1 = __webpack_require__(/*! @vscode/python-extension */ "./node_modules/@vscode/python-extension/out/main.js"); const async_1 = __webpack_require__(/*! ../../../common/utils/async */ "./src/client/common/utils/async.ts"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); async function switchSelectedPython(interpreter, uri, purpose) { var _a; let dispose; try { const deferred = (0, async_1.createDeferred)(); const api = (_a = vscode_1.extensions.getExtension(python_extension_1.PVSC_EXTENSION_ID)) === null || _a === void 0 ? void 0 : _a.exports; if (!api) { throw new Error('Api not exported by Python extension'); } dispose = api.environments.onDidChangeActiveEnvironmentPath(async (e) => { if (path.normalize(e.path) === path.normalize(interpreter)) { (0, logging_1.traceInfo)(`Switched to interpreter ${purpose}: ${interpreter}`); deferred.resolve(); } }); api.environments.updateActiveEnvironmentPath(interpreter, uri); (0, logging_1.traceInfo)(`Switching interpreter ${purpose}: ${interpreter}`); await deferred.promise; } finally { dispose === null || dispose === void 0 ? void 0 : dispose.dispose(); } } exports.switchSelectedPython = switchSelectedPython; /***/ }), /***/ "./src/client/pythonEnvironments/creation/provider/venvUtils.ts": /*!**********************************************************************!*\ !*** ./src/client/pythonEnvironments/creation/provider/venvUtils.ts ***! \**********************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.pickExistingVenvAction = exports.ExistingVenvAction = exports.deleteEnvironment = exports.pickPackagesToInstall = exports.isPipInstallableToml = void 0; const tomljs = __webpack_require__(/*! @iarna/toml */ "./node_modules/@iarna/toml/toml.js"); const fs = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const lodash_1 = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js"); const path = __webpack_require__(/*! path */ "path"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const localize_1 = __webpack_require__(/*! ../../../common/utils/localize */ "./src/client/common/utils/localize.ts"); const windowApis_1 = __webpack_require__(/*! ../../../common/vscodeApis/windowApis */ "./src/client/common/vscodeApis/windowApis.ts"); const workspaceApis_1 = __webpack_require__(/*! ../../../common/vscodeApis/workspaceApis */ "./src/client/common/vscodeApis/workspaceApis.ts"); const logging_1 = __webpack_require__(/*! ../../../logging */ "./src/client/logging/index.ts"); const constants_1 = __webpack_require__(/*! ../../../common/constants */ "./src/client/common/constants.ts"); const platformService_1 = __webpack_require__(/*! ../../../common/platform/platformService */ "./src/client/common/platform/platformService.ts"); const commonUtils_1 = __webpack_require__(/*! ../common/commonUtils */ "./src/client/pythonEnvironments/creation/common/commonUtils.ts"); const venvDeleteUtils_1 = __webpack_require__(/*! ./venvDeleteUtils */ "./src/client/pythonEnvironments/creation/provider/venvDeleteUtils.ts"); const exclude = '**/{.venv*,.git,.nox,.tox,.conda,site-packages,__pypackages__}/**'; async function getPipRequirementsFiles(workspaceFolder, token) { const files = (0, lodash_1.flatten)(await Promise.all([ (0, workspaceApis_1.findFiles)(new vscode_1.RelativePattern(workspaceFolder, '**/*requirement*.txt'), exclude, undefined, token), (0, workspaceApis_1.findFiles)(new vscode_1.RelativePattern(workspaceFolder, '**/requirements/*.txt'), exclude, undefined, token), ])).map((u) => u.fsPath); return files; } function tomlParse(content) { try { return tomljs.parse(content); } catch (err) { (0, logging_1.traceError)('Failed to parse `pyproject.toml`:', err); } return {}; } function tomlHasBuildSystem(toml) { return toml['build-system'] !== undefined; } function getTomlOptionalDeps(toml) { const extras = []; if (toml.project && toml.project['optional-dependencies']) { const deps = toml.project['optional-dependencies']; for (const key of Object.keys(deps)) { extras.push(key); } } return extras; } async function pickTomlExtras(extras, token) { const items = extras.map((e) => ({ label: e })); const selection = await (0, windowApis_1.showQuickPickWithBack)(items, { placeHolder: localize_1.CreateEnv.Venv.tomlExtrasQuickPickTitle, canPickMany: true, ignoreFocusOut: true, }, token); if (selection && (0, lodash_1.isArray)(selection)) { return selection.map((s) => s.label); } return undefined; } async function pickRequirementsFiles(files, token) { const items = files .sort((a, b) => { const al = a.split(/[\\\/]/).length; const bl = b.split(/[\\\/]/).length; if (al === bl) { if (a.length === b.length) { return a.localeCompare(b); } return a.length - b.length; } return al - bl; }) .map((e) => ({ label: e })); const selection = await (0, windowApis_1.showQuickPickWithBack)(items, { placeHolder: localize_1.CreateEnv.Venv.requirementsQuickPickTitle, ignoreFocusOut: true, canPickMany: true, }, token); if (selection && (0, lodash_1.isArray)(selection)) { return selection.map((s) => s.label); } return undefined; } function isPipInstallableToml(tomlContent) { const toml = tomlParse(tomlContent); return tomlHasBuildSystem(toml); } exports.isPipInstallableToml = isPipInstallableToml; async function pickPackagesToInstall(workspaceFolder, token) { const tomlPath = path.join(workspaceFolder.uri.fsPath, 'pyproject.toml'); const packages = []; const tomlStep = new windowApis_1.MultiStepNode(undefined, async (context) => { (0, logging_1.traceVerbose)(`Looking for toml pyproject.toml with optional dependencies at: ${tomlPath}`); let extras = []; let hasBuildSystem = false; if (await fs.pathExists(tomlPath)) { const toml = tomlParse(await fs.readFile(tomlPath, 'utf-8')); extras = getTomlOptionalDeps(toml); hasBuildSystem = tomlHasBuildSystem(toml); if (!hasBuildSystem) { (0, logging_1.traceVerbose)('Create env: Found toml without build system. So we will not use editable install.'); } if (extras.length === 0) { (0, logging_1.traceVerbose)('Create env: Found toml without optional dependencies.'); } } else if (context === windowApis_1.MultiStepAction.Back) { return windowApis_1.MultiStepAction.Back; } if (hasBuildSystem) { if (extras.length > 0) { (0, logging_1.traceVerbose)('Create Env: Found toml with optional dependencies.'); try { const installList = await pickTomlExtras(extras, token); if (installList) { if (installList.length > 0) { installList.forEach((i) => { packages.push({ installType: 'toml', installItem: i, source: tomlPath }); }); } packages.push({ installType: 'toml', source: tomlPath }); } else { return windowApis_1.MultiStepAction.Cancel; } } catch (ex) { if (ex === windowApis_1.MultiStepAction.Back || ex === windowApis_1.MultiStepAction.Cancel) { return ex; } throw ex; } } else if (context === windowApis_1.MultiStepAction.Back) { return windowApis_1.MultiStepAction.Back; } else { packages.push({ installType: 'toml', source: tomlPath }); } } else if (context === windowApis_1.MultiStepAction.Back) { return windowApis_1.MultiStepAction.Back; } return windowApis_1.MultiStepAction.Continue; }, undefined); const requirementsStep = new windowApis_1.MultiStepNode(tomlStep, async (context) => { var _a; (0, logging_1.traceVerbose)('Looking for pip requirements.'); const requirementFiles = (_a = (await getPipRequirementsFiles(workspaceFolder, token))) === null || _a === void 0 ? void 0 : _a.map((p) => path.relative(workspaceFolder.uri.fsPath, p)); if (requirementFiles && requirementFiles.length > 0) { (0, logging_1.traceVerbose)('Found pip requirements.'); try { const result = await pickRequirementsFiles(requirementFiles, token); const installList = result === null || result === void 0 ? void 0 : result.map((p) => path.join(workspaceFolder.uri.fsPath, p)); if (installList) { installList.forEach((i) => { packages.push({ installType: 'requirements', installItem: i }); }); } else { return windowApis_1.MultiStepAction.Cancel; } } catch (ex) { if (ex === windowApis_1.MultiStepAction.Back || ex === windowApis_1.MultiStepAction.Cancel) { return ex; } throw ex; } } else if (context === windowApis_1.MultiStepAction.Back) { return windowApis_1.MultiStepAction.Back; } return windowApis_1.MultiStepAction.Continue; }, undefined); tomlStep.next = requirementsStep; const action = await windowApis_1.MultiStepNode.run(tomlStep); if (action === windowApis_1.MultiStepAction.Back || action === windowApis_1.MultiStepAction.Cancel) { throw action; } return packages; } exports.pickPackagesToInstall = pickPackagesToInstall; async function deleteEnvironment(workspaceFolder, interpreter) { const venvPath = (0, commonUtils_1.getVenvPath)(workspaceFolder); return (0, windowApis_1.withProgress)({ location: vscode_1.ProgressLocation.Notification, title: `${localize_1.CreateEnv.Venv.deletingEnvironmentProgress} ([${localize_1.Common.showLogs}](command:${constants_1.Commands.ViewOutput})): ${venvPath}`, cancellable: false, }, async () => { if ((0, platformService_1.isWindows)()) { return (0, venvDeleteUtils_1.deleteEnvironmentWindows)(workspaceFolder, interpreter); } return (0, venvDeleteUtils_1.deleteEnvironmentNonWindows)(workspaceFolder); }); } exports.deleteEnvironment = deleteEnvironment; var ExistingVenvAction; (function (ExistingVenvAction) { ExistingVenvAction[ExistingVenvAction["Recreate"] = 0] = "Recreate"; ExistingVenvAction[ExistingVenvAction["UseExisting"] = 1] = "UseExisting"; ExistingVenvAction[ExistingVenvAction["Create"] = 2] = "Create"; })(ExistingVenvAction = exports.ExistingVenvAction || (exports.ExistingVenvAction = {})); async function pickExistingVenvAction(workspaceFolder) { if (workspaceFolder) { if (await (0, commonUtils_1.hasVenv)(workspaceFolder)) { const items = [ { label: localize_1.CreateEnv.Venv.recreate, description: localize_1.CreateEnv.Venv.recreateDescription }, { label: localize_1.CreateEnv.Venv.useExisting, description: localize_1.CreateEnv.Venv.useExistingDescription, }, ]; const selection = (await (0, windowApis_1.showQuickPickWithBack)(items, { placeHolder: localize_1.CreateEnv.Venv.existingVenvQuickPickPlaceholder, ignoreFocusOut: true, }, undefined)); if ((selection === null || selection === void 0 ? void 0 : selection.label) === localize_1.CreateEnv.Venv.recreate) { return ExistingVenvAction.Recreate; } if ((selection === null || selection === void 0 ? void 0 : selection.label) === localize_1.CreateEnv.Venv.useExisting) { return ExistingVenvAction.UseExisting; } } else { return ExistingVenvAction.Create; } } throw windowApis_1.MultiStepAction.Cancel; } exports.pickExistingVenvAction = pickExistingVenvAction; /***/ }), /***/ "./src/client/pythonEnvironments/creation/registrations.ts": /*!*****************************************************************!*\ !*** ./src/client/pythonEnvironments/creation/registrations.ts ***! \*****************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.registerAllCreateEnvironmentFeatures = void 0; const createEnvApi_1 = __webpack_require__(/*! ./createEnvApi */ "./src/client/pythonEnvironments/creation/createEnvApi.ts"); const createEnvButtonContext_1 = __webpack_require__(/*! ./createEnvButtonContext */ "./src/client/pythonEnvironments/creation/createEnvButtonContext.ts"); function registerAllCreateEnvironmentFeatures(disposables, interpreterQuickPick) { (0, createEnvApi_1.registerCreateEnvironmentFeatures)(disposables, interpreterQuickPick); (0, createEnvButtonContext_1.registerCreateEnvironmentButtonFeatures)(disposables); } exports.registerAllCreateEnvironmentFeatures = registerAllCreateEnvironmentFeatures; /***/ }), /***/ "./src/client/pythonEnvironments/exec.ts": /*!***********************************************!*\ !*** ./src/client/pythonEnvironments/exec.ts ***! \***********************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.copyPythonExecInfo = exports.buildPythonExecInfo = void 0; function buildPythonExecInfo(python, pythonArgs, pythonExecutable) { if (Array.isArray(python)) { const args = python.slice(1); if (pythonArgs) { args.push(...pythonArgs); } return { args, command: python[0], python: [...python], pythonExecutable: pythonExecutable !== null && pythonExecutable !== void 0 ? pythonExecutable : python[python.length - 1], }; } return { command: python, args: pythonArgs || [], python: [python], pythonExecutable: python, }; } exports.buildPythonExecInfo = buildPythonExecInfo; function copyPythonExecInfo(orig, extraPythonArgs) { const info = { command: orig.command, args: [...orig.args], python: [...orig.python], pythonExecutable: orig.pythonExecutable, }; if (extraPythonArgs) { info.args.push(...extraPythonArgs); } if (info.pythonExecutable === undefined) { info.pythonExecutable = info.python[info.python.length - 1]; } return info; } exports.copyPythonExecInfo = copyPythonExecInfo; /***/ }), /***/ "./src/client/pythonEnvironments/index.ts": /*!************************************************!*\ !*** ./src/client/pythonEnvironments/index.ts ***! \************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.activate = exports.initialize = void 0; const vscode = __webpack_require__(/*! vscode */ "vscode"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const lodash_1 = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js"); const persistentState_1 = __webpack_require__(/*! ../common/persistentState */ "./src/client/common/persistentState.ts"); const platform_1 = __webpack_require__(/*! ../common/utils/platform */ "./src/client/common/utils/platform.ts"); const envsReducer_1 = __webpack_require__(/*! ./base/locators/composite/envsReducer */ "./src/client/pythonEnvironments/base/locators/composite/envsReducer.ts"); const envsResolver_1 = __webpack_require__(/*! ./base/locators/composite/envsResolver */ "./src/client/pythonEnvironments/base/locators/composite/envsResolver.ts"); const windowsKnownPathsLocator_1 = __webpack_require__(/*! ./base/locators/lowLevel/windowsKnownPathsLocator */ "./src/client/pythonEnvironments/base/locators/lowLevel/windowsKnownPathsLocator.ts"); const workspaceVirtualEnvLocator_1 = __webpack_require__(/*! ./base/locators/lowLevel/workspaceVirtualEnvLocator */ "./src/client/pythonEnvironments/base/locators/lowLevel/workspaceVirtualEnvLocator.ts"); const externalDependencies_1 = __webpack_require__(/*! ./common/externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const wrappers_1 = __webpack_require__(/*! ./base/locators/wrappers */ "./src/client/pythonEnvironments/base/locators/wrappers.ts"); const customVirtualEnvLocator_1 = __webpack_require__(/*! ./base/locators/lowLevel/customVirtualEnvLocator */ "./src/client/pythonEnvironments/base/locators/lowLevel/customVirtualEnvLocator.ts"); const condaLocator_1 = __webpack_require__(/*! ./base/locators/lowLevel/condaLocator */ "./src/client/pythonEnvironments/base/locators/lowLevel/condaLocator.ts"); const globalVirtualEnvronmentLocator_1 = __webpack_require__(/*! ./base/locators/lowLevel/globalVirtualEnvronmentLocator */ "./src/client/pythonEnvironments/base/locators/lowLevel/globalVirtualEnvronmentLocator.ts"); const posixKnownPathsLocator_1 = __webpack_require__(/*! ./base/locators/lowLevel/posixKnownPathsLocator */ "./src/client/pythonEnvironments/base/locators/lowLevel/posixKnownPathsLocator.ts"); const pyenvLocator_1 = __webpack_require__(/*! ./base/locators/lowLevel/pyenvLocator */ "./src/client/pythonEnvironments/base/locators/lowLevel/pyenvLocator.ts"); const windowsRegistryLocator_1 = __webpack_require__(/*! ./base/locators/lowLevel/windowsRegistryLocator */ "./src/client/pythonEnvironments/base/locators/lowLevel/windowsRegistryLocator.ts"); const microsoftStoreLocator_1 = __webpack_require__(/*! ./base/locators/lowLevel/microsoftStoreLocator */ "./src/client/pythonEnvironments/base/locators/lowLevel/microsoftStoreLocator.ts"); const environmentInfoService_1 = __webpack_require__(/*! ./base/info/environmentInfoService */ "./src/client/pythonEnvironments/base/info/environmentInfoService.ts"); const legacyIOC_1 = __webpack_require__(/*! ./legacyIOC */ "./src/client/pythonEnvironments/legacyIOC.ts"); const poetryLocator_1 = __webpack_require__(/*! ./base/locators/lowLevel/poetryLocator */ "./src/client/pythonEnvironments/base/locators/lowLevel/poetryLocator.ts"); const api_1 = __webpack_require__(/*! ./api */ "./src/client/pythonEnvironments/api.ts"); const envsCollectionCache_1 = __webpack_require__(/*! ./base/locators/composite/envsCollectionCache */ "./src/client/pythonEnvironments/base/locators/composite/envsCollectionCache.ts"); const envsCollectionService_1 = __webpack_require__(/*! ./base/locators/composite/envsCollectionService */ "./src/client/pythonEnvironments/base/locators/composite/envsCollectionService.ts"); const logging_1 = __webpack_require__(/*! ../logging */ "./src/client/logging/index.ts"); const activeStateLocator_1 = __webpack_require__(/*! ./base/locators/lowLevel/activeStateLocator */ "./src/client/pythonEnvironments/base/locators/lowLevel/activeStateLocator.ts"); async function initialize(ext) { (0, externalDependencies_1.initializeExternalDependencies)(ext.legacyIOC.serviceContainer); const api = await (0, api_1.createPythonEnvironments)(() => createLocator(ext)); (0, legacyIOC_1.registerNewDiscoveryForIOC)(ext.legacyIOC.serviceManager, api); return api; } exports.initialize = initialize; async function activate(api, ext) { const folders = vscode.workspace.workspaceFolders; const wasTriggered = (0, persistentState_1.getGlobalStorage)(ext.context, 'PYTHON_ENV_INFO_CACHE', []).get().length > 0; if (!wasTriggered) { api.triggerRefresh().ignoreErrors(); folders === null || folders === void 0 ? void 0 : folders.forEach(async (folder) => { const wasTriggeredForFolder = (0, persistentState_1.getGlobalStorage)(ext.context, `PYTHON_WAS_DISCOVERY_TRIGGERED_${(0, externalDependencies_1.normCasePath)(folder.uri.fsPath)}`, false); await wasTriggeredForFolder.set(true); }); } else { folders === null || folders === void 0 ? void 0 : folders.forEach(async (folder) => { const wasTriggeredForFolder = (0, persistentState_1.getGlobalStorage)(ext.context, `PYTHON_WAS_DISCOVERY_TRIGGERED_${(0, externalDependencies_1.normCasePath)(folder.uri.fsPath)}`, false); if (!wasTriggeredForFolder.get()) { api.triggerRefresh({ searchLocations: { roots: [folder.uri], doNotIncludeNonRooted: true }, }).ignoreErrors(); await wasTriggeredForFolder.set(true); } }); } return { fullyReady: Promise.resolve(), }; } exports.activate = activate; async function createLocator(ext) { const locators = new wrappers_1.ExtensionLocators(createNonWorkspaceLocators(ext), createWorkspaceLocator(ext)); const envInfoService = (0, environmentInfoService_1.getEnvironmentInfoService)(ext.disposables); const reducer = new envsReducer_1.PythonEnvsReducer(locators); const resolvingLocator = new envsResolver_1.PythonEnvsResolver(reducer, envInfoService); const caching = new envsCollectionService_1.EnvsCollectionService(await createCollectionCache(ext), resolvingLocator); return caching; } function createNonWorkspaceLocators(ext) { const locators = []; locators.push(new pyenvLocator_1.PyenvLocator(), new condaLocator_1.CondaEnvironmentLocator(), new activeStateLocator_1.ActiveStateLocator(), new globalVirtualEnvronmentLocator_1.GlobalVirtualEnvironmentLocator(), new customVirtualEnvLocator_1.CustomVirtualEnvironmentLocator()); if ((0, platform_1.getOSType)() === platform_1.OSType.Windows) { locators.push(new windowsRegistryLocator_1.WindowsRegistryLocator(), new microsoftStoreLocator_1.MicrosoftStoreLocator(), new windowsKnownPathsLocator_1.WindowsPathEnvVarLocator()); } else { locators.push(new posixKnownPathsLocator_1.PosixKnownPathsLocator()); } const disposables = locators.filter((d) => d.dispose !== undefined); ext.disposables.push(...disposables); return locators; } function watchRoots(args) { const { initRoot, addRoot, removeRoot } = args; const folders = vscode.workspace.workspaceFolders; if (folders) { folders.map((f) => f.uri).forEach(initRoot); } return vscode.workspace.onDidChangeWorkspaceFolders((event) => { for (const root of event.removed) { removeRoot(root.uri); } for (const root of event.added) { addRoot(root.uri); } }); } function createWorkspaceLocator(ext) { const locators = new wrappers_1.WorkspaceLocators(watchRoots, [ (root) => [new workspaceVirtualEnvLocator_1.WorkspaceVirtualEnvironmentLocator(root.fsPath), new poetryLocator_1.PoetryLocator(root.fsPath)], ]); ext.disposables.push(locators); return locators; } function getFromStorage(storage) { return storage.get().map((e) => { if (e.searchLocation) { if (typeof e.searchLocation === 'string') { e.searchLocation = vscode_1.Uri.parse(e.searchLocation); } else if ('scheme' in e.searchLocation && 'path' in e.searchLocation) { e.searchLocation = vscode_1.Uri.parse(`${e.searchLocation.scheme}://${e.searchLocation.path}`); } else { (0, logging_1.traceError)('Unexpected search location', JSON.stringify(e.searchLocation)); } } return e; }); } function putIntoStorage(storage, envs) { storage.set((0, lodash_1.cloneDeep)(envs).map((e) => { if (e.searchLocation) { e.searchLocation = e.searchLocation.toString(); } return e; })); return Promise.resolve(); } async function createCollectionCache(ext) { const storage = (0, persistentState_1.getGlobalStorage)(ext.context, 'PYTHON_ENV_INFO_CACHE', []); const cache = await (0, envsCollectionCache_1.createCollectionCache)({ get: () => getFromStorage(storage), store: async (e) => putIntoStorage(storage, e), }); return cache; } /***/ }), /***/ "./src/client/pythonEnvironments/info/executable.ts": /*!**********************************************************!*\ !*** ./src/client/pythonEnvironments/info/executable.ts ***! \**********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getExecutablePath = void 0; const python_1 = __webpack_require__(/*! ../../common/process/internal/python */ "./src/client/common/process/internal/python.ts"); const logging_1 = __webpack_require__(/*! ../../logging */ "./src/client/logging/index.ts"); const exec_1 = __webpack_require__(/*! ../exec */ "./src/client/pythonEnvironments/exec.ts"); async function getExecutablePath(python, shellExec) { try { const [args, parse] = (0, python_1.getExecutable)(); const info = (0, exec_1.copyPythonExecInfo)(python, args); const argv = [info.command, ...info.args]; const quoted = argv.reduce((p, c) => (p ? `${p} ${c.toCommandArgumentForPythonMgrExt()}` : `${c.toCommandArgumentForPythonMgrExt()}`), ''); const result = await shellExec(quoted, { timeout: 15000 }); const executable = parse(result.stdout.trim()); if (executable === '') { throw new Error(`${quoted} resulted in empty stdout`); } return executable; } catch (ex) { (0, logging_1.traceError)(ex); return undefined; } } exports.getExecutablePath = getExecutablePath; /***/ }), /***/ "./src/client/pythonEnvironments/info/index.ts": /*!*****************************************************!*\ !*** ./src/client/pythonEnvironments/info/index.ts ***! \*****************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEnvironmentTypeName = exports.ModuleInstallerType = exports.virtualEnvTypes = exports.EnvironmentType = void 0; var EnvironmentType; (function (EnvironmentType) { EnvironmentType["Unknown"] = "Unknown"; EnvironmentType["Conda"] = "Conda"; EnvironmentType["VirtualEnv"] = "VirtualEnv"; EnvironmentType["Pipenv"] = "PipEnv"; EnvironmentType["Pyenv"] = "Pyenv"; EnvironmentType["Venv"] = "Venv"; EnvironmentType["MicrosoftStore"] = "MicrosoftStore"; EnvironmentType["Poetry"] = "Poetry"; EnvironmentType["VirtualEnvWrapper"] = "VirtualEnvWrapper"; EnvironmentType["ActiveState"] = "ActiveState"; EnvironmentType["Global"] = "Global"; EnvironmentType["System"] = "System"; })(EnvironmentType = exports.EnvironmentType || (exports.EnvironmentType = {})); exports.virtualEnvTypes = [ EnvironmentType.Poetry, EnvironmentType.Pipenv, EnvironmentType.Venv, EnvironmentType.VirtualEnvWrapper, EnvironmentType.Conda, EnvironmentType.VirtualEnv, ]; var ModuleInstallerType; (function (ModuleInstallerType) { ModuleInstallerType["Unknown"] = "Unknown"; ModuleInstallerType["Conda"] = "Conda"; ModuleInstallerType["Pip"] = "Pip"; ModuleInstallerType["Poetry"] = "Poetry"; ModuleInstallerType["Pipenv"] = "Pipenv"; })(ModuleInstallerType = exports.ModuleInstallerType || (exports.ModuleInstallerType = {})); function getEnvironmentTypeName(environmentType) { switch (environmentType) { case EnvironmentType.Conda: { return 'conda'; } case EnvironmentType.Pipenv: { return 'pipenv'; } case EnvironmentType.Pyenv: { return 'pyenv'; } case EnvironmentType.Venv: { return 'venv'; } case EnvironmentType.VirtualEnv: { return 'virtualenv'; } case EnvironmentType.MicrosoftStore: { return 'microsoft store'; } case EnvironmentType.Poetry: { return 'poetry'; } case EnvironmentType.VirtualEnvWrapper: { return 'virtualenvwrapper'; } case EnvironmentType.ActiveState: { return 'activestate'; } default: { return ''; } } } exports.getEnvironmentTypeName = getEnvironmentTypeName; /***/ }), /***/ "./src/client/pythonEnvironments/info/interpreter.ts": /*!***********************************************************!*\ !*** ./src/client/pythonEnvironments/info/interpreter.ts ***! \***********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getInterpreterInfo = void 0; const semver_1 = __webpack_require__(/*! semver */ "./node_modules/semver/semver.js"); const scripts_1 = __webpack_require__(/*! ../../common/process/internal/scripts */ "./src/client/common/process/internal/scripts/index.ts"); const stringUtils_1 = __webpack_require__(/*! ../../common/stringUtils */ "./src/client/common/stringUtils.ts"); const platform_1 = __webpack_require__(/*! ../../common/utils/platform */ "./src/client/common/utils/platform.ts"); const exec_1 = __webpack_require__(/*! ../exec */ "./src/client/pythonEnvironments/exec.ts"); function extractInterpreterInfo(python, raw) { let rawVersion = `${raw.versionInfo.slice(0, 3).join('.')}`; if (raw.versionInfo[3] !== undefined && ['alpha', 'beta', 'candidate'].includes(raw.versionInfo[3])) { rawVersion = `${rawVersion}-${raw.versionInfo[3]}`; if (raw.versionInfo[4] !== undefined) { let serial = -1; try { serial = parseInt(`${raw.versionInfo[4]}`, 10); } catch (ex) { serial = -1; } rawVersion = serial >= 0 ? `${rawVersion}${serial}` : rawVersion; } } return { architecture: raw.is64Bit ? platform_1.Architecture.x64 : platform_1.Architecture.x86, path: python, version: new semver_1.SemVer(rawVersion), sysVersion: raw.sysVersion, sysPrefix: raw.sysPrefix, }; } async function getInterpreterInfo(python, shellExec, logger) { const [args, parse] = (0, scripts_1.interpreterInfo)(); const info = (0, exec_1.copyPythonExecInfo)(python, args); const argv = [info.command, ...info.args]; const quoted = argv.reduce((p, c) => (p ? `${p} "${c}"` : `"${(0, stringUtils_1.replaceAll)(c, '\\', '\\\\')}"`), ''); const result = await shellExec(quoted, { timeout: 15000 }); if (result.stderr) { if (logger) { logger.error(`Failed to parse interpreter information for ${argv} stderr: ${result.stderr}`); } } const json = parse(result.stdout); if (logger) { logger.verbose(`Found interpreter for ${argv}`); } if (!json) { return undefined; } return extractInterpreterInfo(python.pythonExecutable, json); } exports.getInterpreterInfo = getInterpreterInfo; /***/ }), /***/ "./src/client/pythonEnvironments/legacyIOC.ts": /*!****************************************************!*\ !*** ./src/client/pythonEnvironments/legacyIOC.ts ***! \****************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.registerNewDiscoveryForIOC = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const lodash_1 = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js"); const vscode = __webpack_require__(/*! vscode */ "vscode"); const fileSystemWatcher_1 = __webpack_require__(/*! ../common/platform/fileSystemWatcher */ "./src/client/common/platform/fileSystemWatcher.ts"); const contracts_1 = __webpack_require__(/*! ../interpreter/contracts */ "./src/client/interpreter/contracts.ts"); const info_1 = __webpack_require__(/*! ./base/info */ "./src/client/pythonEnvironments/base/info/index.ts"); const macDefault_1 = __webpack_require__(/*! ./common/environmentManagers/macDefault */ "./src/client/pythonEnvironments/common/environmentManagers/macDefault.ts"); const externalDependencies_1 = __webpack_require__(/*! ./common/externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const info_2 = __webpack_require__(/*! ./info */ "./src/client/pythonEnvironments/info/index.ts"); const pythonVersion_1 = __webpack_require__(/*! ./base/info/pythonVersion */ "./src/client/pythonEnvironments/base/info/pythonVersion.ts"); const async_1 = __webpack_require__(/*! ../common/utils/async */ "./src/client/common/utils/async.ts"); const arrayUtils_1 = __webpack_require__(/*! ../common/utils/arrayUtils */ "./src/client/common/utils/arrayUtils.ts"); const conda_1 = __webpack_require__(/*! ./common/environmentManagers/conda */ "./src/client/pythonEnvironments/common/environmentManagers/conda.ts"); const microsoftStoreEnv_1 = __webpack_require__(/*! ./common/environmentManagers/microsoftStoreEnv */ "./src/client/pythonEnvironments/common/environmentManagers/microsoftStoreEnv.ts"); const condaService_1 = __webpack_require__(/*! ./common/environmentManagers/condaService */ "./src/client/pythonEnvironments/common/environmentManagers/condaService.ts"); const logging_1 = __webpack_require__(/*! ../logging */ "./src/client/logging/index.ts"); const convertedKinds = new Map(Object.entries({ [info_1.PythonEnvKind.OtherGlobal]: info_2.EnvironmentType.Global, [info_1.PythonEnvKind.System]: info_2.EnvironmentType.System, [info_1.PythonEnvKind.MicrosoftStore]: info_2.EnvironmentType.MicrosoftStore, [info_1.PythonEnvKind.Pyenv]: info_2.EnvironmentType.Pyenv, [info_1.PythonEnvKind.Conda]: info_2.EnvironmentType.Conda, [info_1.PythonEnvKind.VirtualEnv]: info_2.EnvironmentType.VirtualEnv, [info_1.PythonEnvKind.Pipenv]: info_2.EnvironmentType.Pipenv, [info_1.PythonEnvKind.Poetry]: info_2.EnvironmentType.Poetry, [info_1.PythonEnvKind.Venv]: info_2.EnvironmentType.Venv, [info_1.PythonEnvKind.VirtualEnvWrapper]: info_2.EnvironmentType.VirtualEnvWrapper, [info_1.PythonEnvKind.ActiveState]: info_2.EnvironmentType.ActiveState, })); function convertEnvInfo(info) { const { name, location, executable, arch, kind, version, distro, id } = info; const { filename, sysPrefix } = executable; const env = { id, sysPrefix, envType: info_2.EnvironmentType.Unknown, envName: name, envPath: location, path: filename, architecture: arch, }; const envType = convertedKinds.get(kind); if (envType !== undefined) { env.envType = envType; } if (version !== undefined) { const { release, sysVersion } = version; if (release === undefined) { env.sysVersion = ''; } else { env.sysVersion = sysVersion; } const semverLikeVersion = (0, pythonVersion_1.toSemverLikeVersion)(version); env.version = semverLikeVersion; } if (distro !== undefined && distro.org !== '') { env.companyDisplayName = distro.org; } env.displayName = info.display; env.detailedDisplayName = info.detailedDisplayName; env.type = info.type; return env; } let ComponentAdapter = class ComponentAdapter { constructor(api) { this.api = api; this.changed = new vscode.EventEmitter(); this.api.onChanged((event) => { this.changed.fire({ type: event.type, new: event.new ? convertEnvInfo(event.new) : undefined, old: event.old ? convertEnvInfo(event.old) : undefined, resource: event.searchLocation, }); }); } triggerRefresh(query, options) { return this.api.triggerRefresh(query, options); } getRefreshPromise() { return this.api.getRefreshPromise(); } get onProgress() { return this.api.onProgress; } get onChanged() { return this.changed.event; } onDidCreate(resource, callback) { const workspaceFolder = resource ? vscode.workspace.getWorkspaceFolder(resource) : undefined; return this.api.onChanged((e) => { if (!workspaceFolder || !e.searchLocation) { return; } (0, logging_1.traceVerbose)(`Received event ${JSON.stringify(e)} file change event`); if (e.type === fileSystemWatcher_1.FileChangeType.Created && (0, externalDependencies_1.isParentPath)(e.searchLocation.fsPath, workspaceFolder.uri.fsPath)) { callback(); } }); } async getInterpreterInformation(pythonPath) { const env = await this.api.resolveEnv(pythonPath); return env ? convertEnvInfo(env) : undefined; } async isMacDefaultPythonPath(pythonPath) { return (0, macDefault_1.isMacDefaultPythonPath)(pythonPath); } async getInterpreterDetails(pythonPath) { const env = await this.api.resolveEnv(pythonPath); if (!env) { return undefined; } return convertEnvInfo(env); } async isCondaEnvironment(interpreterPath) { return (0, conda_1.isCondaEnvironment)(interpreterPath); } async getCondaEnvironment(interpreterPath) { if (!(await (0, conda_1.isCondaEnvironment)(interpreterPath))) { return undefined; } const env = await this.api.resolveEnv(interpreterPath); if (!env) { return undefined; } return { name: env.name, path: env.location }; } async isMicrosoftStoreInterpreter(pythonPath) { return (0, microsoftStoreEnv_1.isMicrosoftStoreEnvironment)(pythonPath); } async hasInterpreters(filter = async () => true) { const onAddedToCollection = (0, async_1.createDeferred)(); this.api.onChanged(async (e) => { if (e.new) { if (await filter(convertEnvInfo(e.new))) { onAddedToCollection.resolve(); } } }); const initialEnvs = await (0, arrayUtils_1.asyncFilter)(this.api.getEnvs(), (e) => filter(convertEnvInfo(e))); if (initialEnvs.length > 0) { return true; } await Promise.race([onAddedToCollection.promise, this.api.getRefreshPromise()]); const envs = await (0, arrayUtils_1.asyncFilter)(this.api.getEnvs(), (e) => filter(convertEnvInfo(e))); return envs.length > 0; } getInterpreters(resource, source) { const query = {}; let roots = []; let wsFolder; if (resource !== undefined) { wsFolder = vscode.workspace.getWorkspaceFolder(resource); if (wsFolder) { roots = [wsFolder.uri]; } } if (!wsFolder && vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0 && (!resource || resource.scheme === 'untitled')) { roots = vscode.workspace.workspaceFolders.map((w) => w.uri); } query.searchLocations = { roots, }; let envs = this.api.getEnvs(query); if (source) { envs = envs.filter((env) => (0, lodash_1.intersection)(source, env.source).length > 0); } return envs.map(convertEnvInfo); } async getWorkspaceVirtualEnvInterpreters(resource, options) { const workspaceFolder = vscode.workspace.getWorkspaceFolder(resource); if (!workspaceFolder) { return []; } const query = { searchLocations: { roots: [workspaceFolder.uri], doNotIncludeNonRooted: true, }, }; if (options === null || options === void 0 ? void 0 : options.ignoreCache) { await this.api.triggerRefresh(query); } await this.api.getRefreshPromise(); const envs = this.api.getEnvs(query); return envs.map(convertEnvInfo); } }; ComponentAdapter = __decorate([ (0, inversify_1.injectable)() ], ComponentAdapter); function registerNewDiscoveryForIOC(serviceManager, api) { serviceManager.addSingleton(contracts_1.ICondaService, condaService_1.CondaService); serviceManager.addSingletonInstance(contracts_1.IComponentAdapter, new ComponentAdapter(api)); } exports.registerNewDiscoveryForIOC = registerNewDiscoveryForIOC; /***/ }), /***/ "./src/client/telemetry/constants.ts": /*!*******************************************!*\ !*** ./src/client/telemetry/constants.ts ***! \*******************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PlatformErrors = exports.EventName = void 0; var EventName; (function (EventName) { EventName["EDITOR_LOAD"] = "EDITOR.LOAD"; EventName["REPL"] = "REPL"; EventName["CREATE_NEW_FILE_COMMAND"] = "CREATE_NEW_FILE_COMMAND"; EventName["SELECT_INTERPRETER"] = "SELECT_INTERPRETER"; EventName["PYTHON_INTERPRETER"] = "PYTHON_INTERPRETER"; EventName["PYTHON_INSTALL_PACKAGE"] = "PYTHON_INSTALL_PACKAGE"; EventName["ENVIRONMENT_WITHOUT_PYTHON_SELECTED"] = "ENVIRONMENT_WITHOUT_PYTHON_SELECTED"; EventName["PYTHON_ENVIRONMENTS_API"] = "PYTHON_ENVIRONMENTS_API"; EventName["PYTHON_INTERPRETER_DISCOVERY"] = "PYTHON_INTERPRETER_DISCOVERY"; EventName["PYTHON_INTERPRETER_AUTO_SELECTION"] = "PYTHON_INTERPRETER_AUTO_SELECTION"; EventName["PYTHON_INTERPRETER_ACTIVATION_ENVIRONMENT_VARIABLES"] = "PYTHON_INTERPRETER.ACTIVATION_ENVIRONMENT_VARIABLES"; EventName["PYTHON_INTERPRETER_ACTIVATION_FOR_RUNNING_CODE"] = "PYTHON_INTERPRETER_ACTIVATION_FOR_RUNNING_CODE"; EventName["PYTHON_INTERPRETER_ACTIVATION_FOR_TERMINAL"] = "PYTHON_INTERPRETER_ACTIVATION_FOR_TERMINAL"; EventName["TERMINAL_SHELL_IDENTIFICATION"] = "TERMINAL_SHELL_IDENTIFICATION"; EventName["PYTHON_INTERPRETER_ACTIVATE_ENVIRONMENT_PROMPT"] = "PYTHON_INTERPRETER_ACTIVATE_ENVIRONMENT_PROMPT"; EventName["PYTHON_NOT_INSTALLED_PROMPT"] = "PYTHON_NOT_INSTALLED_PROMPT"; EventName["CONDA_INHERIT_ENV_PROMPT"] = "CONDA_INHERIT_ENV_PROMPT"; EventName["REQUIRE_JUPYTER_PROMPT"] = "REQUIRE_JUPYTER_PROMPT"; EventName["ACTIVATED_CONDA_ENV_LAUNCH"] = "ACTIVATED_CONDA_ENV_LAUNCH"; EventName["ENVFILE_VARIABLE_SUBSTITUTION"] = "ENVFILE_VARIABLE_SUBSTITUTION"; EventName["ENVFILE_WORKSPACE"] = "ENVFILE_WORKSPACE"; EventName["EXECUTION_CODE"] = "EXECUTION_CODE"; EventName["EXECUTION_DJANGO"] = "EXECUTION_DJANGO"; EventName["DEBUG_IN_TERMINAL_BUTTON"] = "DEBUG.IN_TERMINAL"; EventName["DEBUG_ADAPTER_USING_WHEELS_PATH"] = "DEBUG_ADAPTER.USING_WHEELS_PATH"; EventName["DEBUG_SESSION_ERROR"] = "DEBUG_SESSION.ERROR"; EventName["DEBUG_SESSION_START"] = "DEBUG_SESSION.START"; EventName["DEBUG_SESSION_STOP"] = "DEBUG_SESSION.STOP"; EventName["DEBUG_SESSION_USER_CODE_RUNNING"] = "DEBUG_SESSION.USER_CODE_RUNNING"; EventName["DEBUGGER"] = "DEBUGGER"; EventName["DEBUGGER_ATTACH_TO_CHILD_PROCESS"] = "DEBUGGER.ATTACH_TO_CHILD_PROCESS"; EventName["DEBUGGER_ATTACH_TO_LOCAL_PROCESS"] = "DEBUGGER.ATTACH_TO_LOCAL_PROCESS"; EventName["DEBUGGER_CONFIGURATION_PROMPTS"] = "DEBUGGER.CONFIGURATION.PROMPTS"; EventName["DEBUGGER_CONFIGURATION_PROMPTS_IN_LAUNCH_JSON"] = "DEBUGGER.CONFIGURATION.PROMPTS.IN.LAUNCH.JSON"; EventName["UNITTEST_CONFIGURING"] = "UNITTEST.CONFIGURING"; EventName["UNITTEST_CONFIGURE"] = "UNITTEST.CONFIGURE"; EventName["UNITTEST_DISCOVERY_TRIGGER"] = "UNITTEST.DISCOVERY.TRIGGER"; EventName["UNITTEST_DISCOVERING"] = "UNITTEST.DISCOVERING"; EventName["UNITTEST_DISCOVERING_STOP"] = "UNITTEST.DISCOVERY.STOP"; EventName["UNITTEST_DISCOVERY_DONE"] = "UNITTEST.DISCOVERY.DONE"; EventName["UNITTEST_RUN_STOP"] = "UNITTEST.RUN.STOP"; EventName["UNITTEST_RUN"] = "UNITTEST.RUN"; EventName["UNITTEST_RUN_ALL_FAILED"] = "UNITTEST.RUN_ALL_FAILED"; EventName["UNITTEST_DISABLED"] = "UNITTEST.DISABLED"; EventName["PYTHON_EXPERIMENTS_INIT_PERFORMANCE"] = "PYTHON_EXPERIMENTS_INIT_PERFORMANCE"; EventName["PYTHON_EXPERIMENTS_LSP_NOTEBOOKS"] = "PYTHON_EXPERIMENTS_LSP_NOTEBOOKS"; EventName["PYTHON_EXPERIMENTS_OPT_IN_OPT_OUT_SETTINGS"] = "PYTHON_EXPERIMENTS_OPT_IN_OPT_OUT_SETTINGS"; EventName["EXTENSION_SURVEY_PROMPT"] = "EXTENSION_SURVEY_PROMPT"; EventName["LANGUAGE_SERVER_ENABLED"] = "LANGUAGE_SERVER.ENABLED"; EventName["LANGUAGE_SERVER_STARTUP"] = "LANGUAGE_SERVER.STARTUP"; EventName["LANGUAGE_SERVER_READY"] = "LANGUAGE_SERVER.READY"; EventName["LANGUAGE_SERVER_TELEMETRY"] = "LANGUAGE_SERVER.EVENT"; EventName["LANGUAGE_SERVER_REQUEST"] = "LANGUAGE_SERVER.REQUEST"; EventName["LANGUAGE_SERVER_RESTART"] = "LANGUAGE_SERVER.RESTART"; EventName["TERMINAL_CREATE"] = "TERMINAL.CREATE"; EventName["ACTIVATE_ENV_IN_CURRENT_TERMINAL"] = "ACTIVATE_ENV_IN_CURRENT_TERMINAL"; EventName["ACTIVATE_ENV_TO_GET_ENV_VARS_FAILED"] = "ACTIVATE_ENV_TO_GET_ENV_VARS_FAILED"; EventName["DIAGNOSTICS_ACTION"] = "DIAGNOSTICS.ACTION"; EventName["PLATFORM_INFO"] = "PLATFORM.INFO"; EventName["DIAGNOSTICS_MESSAGE"] = "DIAGNOSTICS.MESSAGE"; EventName["SELECT_LINTER"] = "LINTING.SELECT"; EventName["USE_REPORT_ISSUE_COMMAND"] = "USE_REPORT_ISSUE_COMMAND"; EventName["LINTER_NOT_INSTALLED_PROMPT"] = "LINTER_NOT_INSTALLED_PROMPT"; EventName["HASHED_PACKAGE_NAME"] = "HASHED_PACKAGE_NAME"; EventName["JEDI_LANGUAGE_SERVER_ENABLED"] = "JEDI_LANGUAGE_SERVER.ENABLED"; EventName["JEDI_LANGUAGE_SERVER_STARTUP"] = "JEDI_LANGUAGE_SERVER.STARTUP"; EventName["JEDI_LANGUAGE_SERVER_READY"] = "JEDI_LANGUAGE_SERVER.READY"; EventName["JEDI_LANGUAGE_SERVER_REQUEST"] = "JEDI_LANGUAGE_SERVER.REQUEST"; EventName["TENSORBOARD_SESSION_LAUNCH"] = "TENSORBOARD.SESSION_LAUNCH"; EventName["TENSORBOARD_SESSION_DURATION"] = "TENSORBOARD.SESSION_DURATION"; EventName["TENSORBOARD_SESSION_DAEMON_STARTUP_DURATION"] = "TENSORBOARD.SESSION_DAEMON_STARTUP_DURATION"; EventName["TENSORBOARD_LAUNCH_PROMPT_SELECTION"] = "TENSORBOARD.LAUNCH_PROMPT_SELECTION"; EventName["TENSORBOARD_SESSION_E2E_STARTUP_DURATION"] = "TENSORBOARD.SESSION_E2E_STARTUP_DURATION"; EventName["TENSORBOARD_ENTRYPOINT_SHOWN"] = "TENSORBOARD.ENTRYPOINT_SHOWN"; EventName["TENSORBOARD_INSTALL_PROMPT_SHOWN"] = "TENSORBOARD.INSTALL_PROMPT_SHOWN"; EventName["TENSORBOARD_INSTALL_PROMPT_SELECTION"] = "TENSORBOARD.INSTALL_PROMPT_SELECTION"; EventName["TENSORBOARD_DETECTED_IN_INTEGRATED_TERMINAL"] = "TENSORBOARD_DETECTED_IN_INTEGRATED_TERMINAL"; EventName["TENSORBOARD_PACKAGE_INSTALL_RESULT"] = "TENSORBOARD.PACKAGE_INSTALL_RESULT"; EventName["TENSORBOARD_TORCH_PROFILER_IMPORT"] = "TENSORBOARD.TORCH_PROFILER_IMPORT"; EventName["TENSORBOARD_JUMP_TO_SOURCE_REQUEST"] = "TENSORBOARD_JUMP_TO_SOURCE_REQUEST"; EventName["TENSORBOARD_JUMP_TO_SOURCE_FILE_NOT_FOUND"] = "TENSORBOARD_JUMP_TO_SOURCE_FILE_NOT_FOUND"; EventName["ENVIRONMENT_CREATING"] = "ENVIRONMENT.CREATING"; EventName["ENVIRONMENT_CREATED"] = "ENVIRONMENT.CREATED"; EventName["ENVIRONMENT_FAILED"] = "ENVIRONMENT.FAILED"; EventName["ENVIRONMENT_INSTALLING_PACKAGES"] = "ENVIRONMENT.INSTALLING_PACKAGES"; EventName["ENVIRONMENT_INSTALLED_PACKAGES"] = "ENVIRONMENT.INSTALLED_PACKAGES"; EventName["ENVIRONMENT_INSTALLING_PACKAGES_FAILED"] = "ENVIRONMENT.INSTALLING_PACKAGES_FAILED"; EventName["ENVIRONMENT_BUTTON"] = "ENVIRONMENT.BUTTON"; EventName["ENVIRONMENT_DELETE"] = "ENVIRONMENT.DELETE"; EventName["ENVIRONMENT_REUSE"] = "ENVIRONMENT.REUSE"; EventName["TOOLS_EXTENSIONS_ALREADY_INSTALLED"] = "TOOLS_EXTENSIONS.ALREADY_INSTALLED"; EventName["TOOLS_EXTENSIONS_PROMPT_SHOWN"] = "TOOLS_EXTENSIONS.PROMPT_SHOWN"; EventName["TOOLS_EXTENSIONS_INSTALL_SELECTED"] = "TOOLS_EXTENSIONS.INSTALL_SELECTED"; EventName["TOOLS_EXTENSIONS_PROMPT_DISMISSED"] = "TOOLS_EXTENSIONS.PROMPT_DISMISSED"; EventName["SELECT_INTERPRETER_ENTERED_EXISTS"] = "SELECT_INTERPRETER_ENTERED_EXISTS"; EventName["SELECT_INTERPRETER_ENTER_CHOICE"] = "SELECT_INTERPRETER_ENTER_CHOICE"; EventName["SELECT_INTERPRETER_SELECTED"] = "SELECT_INTERPRETER_SELECTED"; EventName["SELECT_INTERPRETER_ENTER_OR_FIND"] = "SELECT_INTERPRETER_ENTER_OR_FIND"; })(EventName = exports.EventName || (exports.EventName = {})); var PlatformErrors; (function (PlatformErrors) { PlatformErrors["FailedToParseVersion"] = "FailedToParseVersion"; PlatformErrors["FailedToDetermineOS"] = "FailedToDetermineOS"; })(PlatformErrors = exports.PlatformErrors || (exports.PlatformErrors = {})); /***/ }), /***/ "./src/client/telemetry/index.ts": /*!***************************************!*\ !*** ./src/client/telemetry/index.ts ***! \***************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.sendTelemetryEvent = exports._resetSharedProperties = exports.setSharedProperty = exports.isTelemetryDisabled = void 0; function isTelemetryDisabled() { return true; } exports.isTelemetryDisabled = isTelemetryDisabled; const sharedProperties = {}; function setSharedProperty(_name, _value) { } exports.setSharedProperty = setSharedProperty; function _resetSharedProperties() { for (const key of Object.keys(sharedProperties)) { delete sharedProperties[key]; } } exports._resetSharedProperties = _resetSharedProperties; function sendTelemetryEvent(_eventName, _measuresOrDurationMs, _properties, _ex) { } exports.sendTelemetryEvent = sendTelemetryEvent; /***/ }), /***/ "./src/environments/activeInterpreter.ts": /*!***********************************************!*\ !*** ./src/environments/activeInterpreter.ts ***! \***********************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.activate = void 0; const python_extension_1 = __webpack_require__(/*! @vscode/python-extension */ "./node_modules/@vscode/python-extension/out/main.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const misc_1 = __webpack_require__(/*! ../client/common/utils/misc */ "./src/client/common/utils/misc.ts"); function activate(context) { context.subscriptions.push(vscode_1.commands.registerCommand('python.envManager.setAsActiveInterpreter', async (item) => { const api = await python_extension_1.PythonExtension.api(); const env = 'env' in item ? item.env : api.environments.known.find((e) => e.id === item.id); if (!env) { return; } let folder; if ('owningFolder' in item && item.owningFolder) { folder = item.owningFolder; } else if (Array.isArray(vscode_1.workspace.workspaceFolders) && vscode_1.workspace.workspaceFolders.length > 0) { folder = vscode_1.workspace.workspaceFolders.length === 1 ? vscode_1.workspace.workspaceFolders[0] : await vscode_1.window.showWorkspaceFolderPick({ placeHolder: 'Select folder to change active Python Environment', }); } if (folder) { api.environments.updateActiveEnvironmentPath(env, folder.uri).catch(misc_1.noop); } else { vscode_1.commands.executeCommand('python.setInterpreter').then(misc_1.noop, misc_1.noop); } })); } exports.activate = activate; /***/ }), /***/ "./src/environments/cache.ts": /*!***********************************!*\ !*** ./src/environments/cache.ts ***! \***********************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.clearCacheIfNewVersionInstalled = exports.EnvironmentsCacheMementoKey = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const LastExtensionVersionKey = 'LAST_EXTENSION_VERSION'; exports.EnvironmentsCacheMementoKey = 'PYTHON:PACKAGE_MANAGER:ENVS_CACHE'; let cacheClearedOnce = false; async function clearCacheIfNewVersionInstalled(context, clearEnvCache = false) { var _a, _b; const shouldRefresh = context.extensionMode === vscode_1.ExtensionMode.Development; if (!shouldRefresh && (cacheClearedOnce || context.globalState.get(LastExtensionVersionKey, '') === ((_b = (_a = context.extension) === null || _a === void 0 ? void 0 : _a.packageJSON) === null || _b === void 0 ? void 0 : _b.version))) { return; } cacheClearedOnce = true; let venvEnvs = []; if (!clearEnvCache) { venvEnvs = context.globalState.get(exports.EnvironmentsCacheMementoKey, []); } await Promise.all([ vscode_1.commands.executeCommand('python.envManager.clearPersistentStorage'), context.globalState.keys().filter(key => key !== LastExtensionVersionKey).map(key => context.globalState.update(key, undefined)), context.workspaceState.keys().map(key => context.workspaceState.update(key, undefined)) ]); await context.globalState.update(LastExtensionVersionKey, context.extension.packageJSON.version); if (!clearEnvCache && Array.isArray(venvEnvs)) { await context.globalState.update(exports.EnvironmentsCacheMementoKey, venvEnvs); } } exports.clearCacheIfNewVersionInstalled = clearCacheIfNewVersionInstalled; /***/ }), /***/ "./src/environments/constants.ts": /*!***************************************!*\ !*** ./src/environments/constants.ts ***! \***************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.loggingOutputChannel = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); exports.loggingOutputChannel = vscode_1.window.createOutputChannel('Python Environments (logging)'); /***/ }), /***/ "./src/environments/envCreation.ts": /*!*****************************************!*\ !*** ./src/environments/envCreation.ts ***! \*****************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.activate = exports.canEnvBeCreated = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const logging_1 = __webpack_require__(/*! ../client/logging */ "./src/client/logging/index.ts"); const info_1 = __webpack_require__(/*! ../client/pythonEnvironments/info */ "./src/client/pythonEnvironments/info/index.ts"); const createEnvApi_1 = __webpack_require__(/*! ../client/pythonEnvironments/creation/createEnvApi */ "./src/client/pythonEnvironments/creation/createEnvApi.ts"); const createEnvironment_1 = __webpack_require__(/*! ../client/pythonEnvironments/creation/createEnvironment */ "./src/client/pythonEnvironments/creation/createEnvironment.ts"); function canEnvBeCreated(envType) { switch (envType) { case info_1.EnvironmentType.Conda: case info_1.EnvironmentType.Venv: case info_1.EnvironmentType.Pyenv: return true; case info_1.EnvironmentType.VirtualEnv: case info_1.EnvironmentType.VirtualEnvWrapper: case info_1.EnvironmentType.Pipenv: case info_1.EnvironmentType.Poetry: case info_1.EnvironmentType.System: case info_1.EnvironmentType.Unknown: return false; default: return false; } } exports.canEnvBeCreated = canEnvBeCreated; function activate(context) { context.subscriptions.push(vscode_1.commands.registerCommand('python.envManager.create', async (type) => { if (!type) { await vscode_1.commands.executeCommand('python.createEnvironment'); return vscode_1.commands.executeCommand('python.envManager.refresh'); } if (!canEnvBeCreated(type)) { (0, logging_1.traceError)(`Environment '${type}' cannot be created`); return; } const provider = createEnvApi_1._createEnvironmentProviders.getAll().find((e) => e.tools.includes(type)); if (!provider) { return; } try { await (0, createEnvironment_1.handleCreateEnvironmentCommand)([provider], {}); } catch (err) { console.error('Failed to create the environment', err); } })); } exports.activate = activate; /***/ }), /***/ "./src/environments/envDeletion.ts": /*!*****************************************!*\ !*** ./src/environments/envDeletion.ts ***! \*****************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.activate = exports.canEnvBeDeleted = void 0; const python_extension_1 = __webpack_require__(/*! @vscode/python-extension */ "./node_modules/@vscode/python-extension/out/main.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const logging_1 = __webpack_require__(/*! ../client/logging */ "./src/client/logging/index.ts"); const info_1 = __webpack_require__(/*! ../client/pythonEnvironments/info */ "./src/client/pythonEnvironments/info/index.ts"); const helpers_1 = __webpack_require__(/*! ./helpers */ "./src/environments/helpers.ts"); const conda_1 = __webpack_require__(/*! ./tools/conda */ "./src/environments/tools/conda.ts"); const venv_1 = __webpack_require__(/*! ./tools/venv */ "./src/environments/tools/venv.ts"); const poetry_1 = __webpack_require__(/*! ./tools/poetry */ "./src/environments/tools/poetry.ts"); const utils_1 = __webpack_require__(/*! ./utils */ "./src/environments/utils.ts"); const foldersTreeDataProvider_1 = __webpack_require__(/*! ./view/foldersTreeDataProvider */ "./src/environments/view/foldersTreeDataProvider.ts"); function canEnvBeDeleted(envType) { switch (envType) { case info_1.EnvironmentType.Conda: case info_1.EnvironmentType.Venv: case info_1.EnvironmentType.VirtualEnv: case info_1.EnvironmentType.VirtualEnvWrapper: return true; case info_1.EnvironmentType.Poetry: return true; case info_1.EnvironmentType.Pipenv: case info_1.EnvironmentType.Pyenv: case info_1.EnvironmentType.System: case info_1.EnvironmentType.Unknown: return false; default: return false; } } exports.canEnvBeDeleted = canEnvBeDeleted; function activate(context) { context.subscriptions.push(vscode_1.commands.registerCommand('python.envManager.delete', async (options) => { var _a; let id = ''; if (options instanceof foldersTreeDataProvider_1.ActiveWorkspaceEnvironment) { id = ((_a = options.asNode()) === null || _a === void 0 ? void 0 : _a.env.id) || ''; } else { id = options.id; } const api = await python_extension_1.PythonExtension.api(); const env = api.environments.known.find((e) => e.id === id); if (!env) { return; } if (!canEnvBeDeleted((0, utils_1.getEnvironmentType)(env))) { (0, logging_1.traceError)(`Environment '${(0, helpers_1.getEnvLoggingInfo)(env)}' cannot be deleted`); return; } const message = `Are you sure you want to delete the environment '${(0, helpers_1.getEnvDisplayInfo)(env)}'?`; const detail = `This will result in deleting the folder '${(0, helpers_1.getDisplayPath)(env.path)}'.`; if ((await vscode_1.window.showInformationMessage(message, { modal: true, detail }, 'Yes')) !== 'Yes') { return; } try { await vscode_1.window.withProgress({ location: vscode_1.ProgressLocation.Notification, title: `Deleting environment ${(0, helpers_1.getEnvDisplayInfo)(env)}`, }, async (progress, _token) => { switch ((0, utils_1.getEnvironmentType)(env)) { case info_1.EnvironmentType.Conda: return (0, conda_1.deleteEnv)(env, progress); case info_1.EnvironmentType.Poetry: return (0, poetry_1.deleteEnv)(env, progress); default: return (0, venv_1.deleteEnv)(env); } }); return vscode_1.commands.executeCommand('python.envManager.refresh', true); } catch (ex) { (0, logging_1.traceError)(`Failed to delete environment ${(0, helpers_1.getEnvLoggingInfo)(env)}`, ex); return vscode_1.window.showErrorMessage(`Failed to delete environment ${(0, helpers_1.getEnvDisplayInfo)(env)}, ${ex}`); } })); } exports.activate = activate; /***/ }), /***/ "./src/environments/helpers.ts": /*!*************************************!*\ !*** ./src/environments/helpers.ts ***! \*************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reportStdOutProgress = exports.getEnvDisplayInfo = exports.getEnvLoggingInfo = exports.createTempFile = exports.getDisplayPath = exports.home = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const path = __webpack_require__(/*! path */ "path"); const tmp = __webpack_require__(/*! tmp */ "./node_modules/tmp/lib/tmp.js"); const utils_1 = __webpack_require__(/*! ./utils */ "./src/environments/utils.ts"); const resourceLifecycle_1 = __webpack_require__(/*! ../client/common/utils/resourceLifecycle */ "./src/client/common/utils/resourceLifecycle.ts"); const constants_1 = __webpack_require__(/*! ./constants */ "./src/environments/constants.ts"); const logging_1 = __webpack_require__(/*! ../client/logging */ "./src/client/logging/index.ts"); const rawProcessApis_1 = __webpack_require__(/*! ../client/common/process/rawProcessApis */ "./src/client/common/process/rawProcessApis.ts"); const untildify = __webpack_require__(/*! untildify */ "./node_modules/untildify/index.js"); exports.home = untildify('~'); function getDisplayPath(value) { if (!value) { return ''; } value = vscode_1.workspace.asRelativePath(value, (vscode_1.workspace.workspaceFolders || []).length > 1); return value.startsWith(exports.home) ? `~${path.sep}${path.relative(exports.home, value)}` : value; } exports.getDisplayPath = getDisplayPath; function createTempFile(extension = '.txt') { return new Promise((resolve, reject) => { tmp.file({ postfix: extension }, (err, filename, _fd, cleanUp) => { if (err) { return reject(err); } resolve({ filePath: filename, dispose: cleanUp, }); }); }); } exports.createTempFile = createTempFile; function getEnvLoggingInfo(env) { var _a; return `${(0, utils_1.getEnvironmentType)(env)}:(${((_a = env.environment) === null || _a === void 0 ? void 0 : _a.name) || env.path},${getDisplayPath(env.path)})`; } exports.getEnvLoggingInfo = getEnvLoggingInfo; function getEnvDisplayInfo(env) { var _a, _b; return ((_a = env.environment) === null || _a === void 0 ? void 0 : _a.name) || ((_b = env.environment) === null || _b === void 0 ? void 0 : _b.folderUri) ? getDisplayPath(env.environment.folderUri.fsPath) : getDisplayPath(env.path); } exports.getEnvDisplayInfo = getEnvDisplayInfo; async function reportStdOutProgress(title, argsForExecution, progress, token) { (0, logging_1.traceVerbose)(title); constants_1.loggingOutputChannel.appendLine('>>>>>>>>>>>>>>>>>>>>>>>'); constants_1.loggingOutputChannel.appendLine(title); constants_1.loggingOutputChannel.appendLine(''); const result = await (0, rawProcessApis_1.execObservable)(...argsForExecution); const disposables = []; token.onCancellationRequested(() => { var _a; return (_a = result.proc) === null || _a === void 0 ? void 0 : _a.kill(); }, undefined, disposables); const ticker = ['.', '..', '...']; let counter = 0; await new Promise((resolve) => { const subscription = result.out.subscribe({ next: (output) => { const suffix = ticker[counter % 3]; const trimmedOutput = output.out.trim(); counter += 1; const message = trimmedOutput.length > 28 ? `${trimmedOutput.substring(0, 28)}${suffix}` : trimmedOutput; progress.report({ message }); }, complete: () => resolve(), }); disposables.push({ dispose: () => { try { subscription.unsubscribe(); constants_1.loggingOutputChannel.appendLine('<<<<<<<<<<<<<<<<<<<<<<<'); constants_1.loggingOutputChannel.appendLine(''); } catch (_a) { } }, }); }).finally(() => (0, resourceLifecycle_1.disposeAll)(disposables)); } exports.reportStdOutProgress = reportStdOutProgress; /***/ }), /***/ "./src/environments/installPython.ts": /*!*******************************************!*\ !*** ./src/environments/installPython.ts ***! \*******************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.activate = void 0; const fs = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const misc_1 = __webpack_require__(/*! ../client/common/utils/misc */ "./src/client/common/utils/misc.ts"); const conda_1 = __webpack_require__(/*! ./tools/conda */ "./src/environments/tools/conda.ts"); const helpers_1 = __webpack_require__(/*! ./helpers */ "./src/environments/helpers.ts"); const constants_1 = __webpack_require__(/*! ./micromamba/constants */ "./src/environments/micromamba/constants.ts"); const install_1 = __webpack_require__(/*! ./micromamba/install */ "./src/environments/micromamba/install.ts"); const environmentsTreeDataProvider_1 = __webpack_require__(/*! ./view/environmentsTreeDataProvider */ "./src/environments/view/environmentsTreeDataProvider.ts"); function activate(context) { context.subscriptions.push(vscode_1.commands.registerCommand('python.envManager.installPython', async () => { if (await fs.pathExists(constants_1.MICROMAMBA_EXE)) { const message = [ `Python is already setup via Micromamba. Please use Micromamba found here ${(0, helpers_1.getDisplayPath)(constants_1.MICROMAMBA_EXE)}.`, `If it does not worker, then initialize your shell using the command '${(0, helpers_1.getDisplayPath)(constants_1.MICROMAMBA_EXE)} shell init -s bash|zsh|cmd.exe|powershell|fish|xonsh -p ~/micromamba'.`, ]; void vscode_1.window.showInformationMessage(message.join(' \n')); return; } const moreInfo = 'More info'; const detail = `Micromamba will downloaded into ${(0, helpers_1.getDisplayPath)(constants_1.MICROMAMBA_DIR)} \n& Shell scripts will be updated to put Micromamba into the current path.`; const selection = await vscode_1.window.showInformationMessage('Do you want to download and setup Python via Micromamba?', { modal: true, detail }, 'Yes', moreInfo); switch (selection) { case moreInfo: void vscode_1.env.openExternal(vscode_1.Uri.parse('https://mamba.readthedocs.io/en/latest/user_guide/micromamba.html')); break; case 'Yes': await (0, install_1.installMicromamba)(environmentsTreeDataProvider_1.refreshUntilNewEnvIsAvailable); await createInstallContext(); break; default: break; } })); void createInstallContext(); } exports.activate = activate; async function createInstallContext() { const [condaVersion, installed] = await Promise.all([(0, conda_1.getCondaVersion)().catch(misc_1.noop), fs.pathExists(constants_1.MICROMAMBA_EXE)]); void vscode_1.commands.executeCommand('setContext', 'python.envManager.pythonIsNotInstalled', !installed && !condaVersion); } /***/ }), /***/ "./src/environments/micromamba/base.ts": /*!*********************************************!*\ !*** ./src/environments/micromamba/base.ts ***! \*********************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createBaseEnv = void 0; const fs = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const rawProcessApis_1 = __webpack_require__(/*! ../../client/common/process/rawProcessApis */ "./src/client/common/process/rawProcessApis.ts"); const logging_1 = __webpack_require__(/*! ../../client/logging */ "./src/client/logging/index.ts"); const info_1 = __webpack_require__(/*! ../../client/pythonEnvironments/info */ "./src/client/pythonEnvironments/info/index.ts"); const conda_1 = __webpack_require__(/*! ../tools/conda */ "./src/environments/tools/conda.ts"); const constants_1 = __webpack_require__(/*! ./constants */ "./src/environments/micromamba/constants.ts"); async function createBaseEnv(progress, token, refreshUntilAvailable, pythonVersion = '3.9') { var _a; try { progress.report({ message: `Creating Python ${pythonVersion} environment` }); (0, logging_1.traceInfo)(`Creating environment with Python ${pythonVersion}`); const args = [ 'install', `python=${pythonVersion || '3.9'}`, 'conda', '-c', 'conda-forge', '-y', '-p', constants_1.MICROMAMBA_ROOTPREFIX, ]; (0, logging_1.traceInfo)([constants_1.MICROMAMBA_EXE].concat(args).join(' ')); const result = await (0, rawProcessApis_1.execObservable)(constants_1.MICROMAMBA_EXE, args, { timeout: 120000, token, shell: true, env: { ...process.env, TARGET_PREFIX: constants_1.MICROMAMBA_ROOTPREFIX, ROOT_PREFIX: constants_1.MICROMAMBA_ROOTPREFIX, MAMBA_ROOT_PREFIX: constants_1.MICROMAMBA_ROOTPREFIX, MAMBA_EXE: constants_1.MICROMAMBA_EXE, }, }); (_a = result.proc) === null || _a === void 0 ? void 0 : _a.on('error', (ex) => console.error(`Conda create exited with an error`, ex)); await new Promise((resolve, reject) => { result.out.subscribe({ next: (output) => { if (output.out.trim().length) { progress.report({ message: output.out }); } (0, logging_1.traceInfo)(output.out); }, complete: () => resolve(), error: (ex) => reject(ex), }); }); if (!(await fs.pathExists(constants_1.BASE_MICROMAMBA_PYTHON_EXE))) { throw new Error(`Please try running the following command in the terminal "${[constants_1.MICROMAMBA_EXE].concat(args).join(' ')}"`); } await (0, conda_1.updateEnvironmentsTxt)(constants_1.MICROMAMBA_ROOTPREFIX).catch((ex) => (0, logging_1.traceError)('Failed to update environments.txt', ex)); progress.report({ message: 'Waiting for environment to be detected' }); await refreshUntilAvailable({ path: constants_1.BASE_MICROMAMBA_PYTHON_EXE, type: info_1.EnvironmentType.Conda }); } catch (ex) { (0, logging_1.traceError)(`Failed to create environment`, ex); vscode_1.window.showErrorMessage(`Failed to create environment ${constants_1.MICROMAMBA_ROOTPREFIX}, ${ex}`); } } exports.createBaseEnv = createBaseEnv; /***/ }), /***/ "./src/environments/micromamba/constants.ts": /*!**************************************************!*\ !*** ./src/environments/micromamba/constants.ts ***! \**************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BASE_MICROMAMBA_PYTHON_EXE = exports.MICROMAMBA_EXE = exports.CONDA_EXE = exports.MICROMAMBA_BASE_ENV_NAME = exports.MICROMAMBA_DIR = exports.MICROMAMBA_ROOTPREFIX = void 0; const path = __webpack_require__(/*! path */ "path"); const platform_1 = __webpack_require__(/*! ../../client/common/utils/platform */ "./src/client/common/utils/platform.ts"); const helpers_1 = __webpack_require__(/*! ../helpers */ "./src/environments/helpers.ts"); exports.MICROMAMBA_ROOTPREFIX = path.join((0, platform_1.getUserHomeDir)() || helpers_1.home, 'micromamba'); exports.MICROMAMBA_DIR = path.join((0, platform_1.getUserHomeDir)() || helpers_1.home, '.micromamba'); exports.MICROMAMBA_BASE_ENV_NAME = 'micromambaBase'; exports.CONDA_EXE = path.join(exports.MICROMAMBA_ROOTPREFIX, 'condabin', (0, platform_1.getOSType)() === platform_1.OSType.Windows ? 'conda.exe' : 'conda'); exports.MICROMAMBA_EXE = path.join(exports.MICROMAMBA_DIR, 'bin', (0, platform_1.getOSType)() === platform_1.OSType.Windows ? 'micromamba.exe' : 'micromamba'); exports.BASE_MICROMAMBA_PYTHON_EXE = path.join(exports.MICROMAMBA_ROOTPREFIX, (0, platform_1.getOSType)() === platform_1.OSType.Windows ? 'Scripts' : 'bin', (0, platform_1.getOSType)() === platform_1.OSType.Windows ? 'python.exe' : 'python'); /***/ }), /***/ "./src/environments/micromamba/downloader.ts": /*!***************************************************!*\ !*** ./src/environments/micromamba/downloader.ts ***! \***************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isMicroMambaInstalled = exports.downloadMamba = exports.activate = void 0; const fs = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const tar = __webpack_require__(/*! tar */ "./node_modules/tar/index.js"); const request = __webpack_require__(/*! request */ "./node_modules/request/index.js"); const platform_1 = __webpack_require__(/*! ../../client/common/utils/platform */ "./src/client/common/utils/platform.ts"); const constants_1 = __webpack_require__(/*! ./constants */ "./src/environments/micromamba/constants.ts"); const bz2 = __webpack_require__(/*! unbzip2-stream */ "./node_modules/unbzip2-stream/index.js"); const progress = __webpack_require__(/*! request-progress */ "./node_modules/request-progress/index.js"); function activate(_context) { } exports.activate = activate; function getUrl() { switch ((0, platform_1.getOSType)()) { case platform_1.OSType.Windows: return 'https://micro.mamba.pm/api/micromamba/win-64/latest'; case platform_1.OSType.OSX: return process.arch === 'arm64' ? 'https://micro.mamba.pm/api/micromamba/osx-arm64/latest' : 'https://micro.mamba.pm/api/micromamba/osx-64/latest'; case platform_1.OSType.Linux: default: return 'https://micro.mamba.pm/api/micromamba/linux-64/latest'; } } async function getDestinationDirectory() { await fs.ensureDir(constants_1.MICROMAMBA_DIR); return constants_1.MICROMAMBA_DIR; } const MB = 1024 * 1024; async function downloadMamba(uiProgress, token) { const [url, downloadDir] = await Promise.all([getUrl(), getDestinationDirectory()]); await new Promise((resolve, reject) => { const result = request(url); token.onCancellationRequested(() => { result.abort(); }); progress(result, {}) .on('progress', (state) => { var _a; const message = `Downloading Micromamba ${(state.percent * 100).toFixed(0)}% (${(state.size.transferred / MB).toFixed(2)} of ${(state.size.total / MB).toFixed(2)}MB).`; const suffix = ((_a = state.time) === null || _a === void 0 ? void 0 : _a.remaining) ? ` \nRemaining ${(state.time.remaining).toFixed(0)}s` : ''; uiProgress.report({ message: `${message}${suffix}` }); console.log('progress', state); }) .on('error', (err) => reject(err)) .pipe(bz2()) .pipe(tar.extract({ cwd: downloadDir })) .on('error', (err) => reject(err)) .on('end', () => resolve()); }); return downloadDir; } exports.downloadMamba = downloadMamba; async function isMicroMambaInstalled() { return fs.pathExists(constants_1.MICROMAMBA_EXE); } exports.isMicroMambaInstalled = isMicroMambaInstalled; /***/ }), /***/ "./src/environments/micromamba/install.ts": /*!************************************************!*\ !*** ./src/environments/micromamba/install.ts ***! \************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.installMicromamba = void 0; const fs = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const logging_1 = __webpack_require__(/*! ../../client/logging */ "./src/client/logging/index.ts"); const constants_1 = __webpack_require__(/*! ./constants */ "./src/environments/micromamba/constants.ts"); const base_1 = __webpack_require__(/*! ./base */ "./src/environments/micromamba/base.ts"); const shells_1 = __webpack_require__(/*! ./shells */ "./src/environments/micromamba/shells.ts"); const downloader_1 = __webpack_require__(/*! ./downloader */ "./src/environments/micromamba/downloader.ts"); async function installMicromamba(refreshUntilAvailable) { if (!await fs.pathExists(constants_1.MICROMAMBA_EXE)) { await vscode_1.window.withProgress({ location: vscode_1.ProgressLocation.Notification, cancellable: true, title: 'Setting up Python' }, async (uiProgress, token) => { try { await (0, downloader_1.downloadMamba)(uiProgress, token); uiProgress.report({ message: 'Configuring Micromamba Shells' }); await (0, shells_1.initializeMicromambaShells)(); await (0, base_1.createBaseEnv)(uiProgress, token, refreshUntilAvailable); uiProgress.report({ message: 'Configuring Conda Shells' }); await (0, shells_1.initializeCondaShells)(); uiProgress.report({ message: 'Updating user .vscode settings' }); await updatePythonSettings(); } catch (ex) { (0, logging_1.traceError)(`Failed to create Python environment`); vscode_1.window.showErrorMessage(`Failed to setup Python, see logs for more information. \n ${ex.toString()}`); } }); } (0, logging_1.traceInfo)(`Mamba file loaded at ${constants_1.MICROMAMBA_EXE}`); } exports.installMicromamba = installMicromamba; async function updatePythonSettings() { var _a, _b; const settings = vscode_1.workspace.getConfiguration('python', undefined); if (!((_a = settings.inspect('condaPath')) === null || _a === void 0 ? void 0 : _a.globalValue)) { if (!((_b = settings.inspect('condaPath')) === null || _b === void 0 ? void 0 : _b.globalValue)) { void settings.update('condaPath', constants_1.CONDA_EXE, vscode_1.ConfigurationTarget.Global); } } } /***/ }), /***/ "./src/environments/micromamba/shells.ts": /*!***********************************************!*\ !*** ./src/environments/micromamba/shells.ts ***! \***********************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.initializeCondaShells = exports.initializeMicromambaShells = void 0; const platform_1 = __webpack_require__(/*! ../../client/common/utils/platform */ "./src/client/common/utils/platform.ts"); const externalDependencies_1 = __webpack_require__(/*! ../../client/pythonEnvironments/common/externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); __webpack_require__(/*! ../../client/common/extensions */ "./src/client/common/extensions.ts"); const constants_1 = __webpack_require__(/*! ./constants */ "./src/environments/micromamba/constants.ts"); async function initializeMicromambaShells() { if ((0, platform_1.getOSType)() === platform_1.OSType.Windows) { await Promise.all([ (0, externalDependencies_1.exec)(constants_1.MICROMAMBA_EXE, ['shell', 'init', '-s', 'cmd.exe', '-p', constants_1.MICROMAMBA_ROOTPREFIX.fileToCommandArgumentForPythonMgrExt()]), (0, externalDependencies_1.exec)(constants_1.MICROMAMBA_EXE, ['shell', 'init', '-s', 'powershell', '-p', constants_1.MICROMAMBA_ROOTPREFIX.fileToCommandArgumentForPythonMgrExt()]) ]); } else { const results = await Promise.all([ (0, externalDependencies_1.exec)(constants_1.MICROMAMBA_EXE, ['shell', 'init', '-s', 'bash', '-p', constants_1.MICROMAMBA_ROOTPREFIX.fileToCommandArgumentForPythonMgrExt()]), (0, externalDependencies_1.exec)(constants_1.MICROMAMBA_EXE, ['shell', 'init', '-s', 'fish', '-p', constants_1.MICROMAMBA_ROOTPREFIX.fileToCommandArgumentForPythonMgrExt()]), (0, externalDependencies_1.exec)(constants_1.MICROMAMBA_EXE, ['shell', 'init', '-s', 'xonsh', '-p', constants_1.MICROMAMBA_ROOTPREFIX.fileToCommandArgumentForPythonMgrExt()]), (0, externalDependencies_1.exec)(constants_1.MICROMAMBA_EXE, ['shell', 'init', '-s', 'zsh', '-p', constants_1.MICROMAMBA_ROOTPREFIX.fileToCommandArgumentForPythonMgrExt()]) ]); console.log(results); } } exports.initializeMicromambaShells = initializeMicromambaShells; async function initializeCondaShells() { const result = await (0, externalDependencies_1.exec)(constants_1.CONDA_EXE, ['init', '--all'], { shell: true }); console.log(result); } exports.initializeCondaShells = initializeCondaShells; /***/ }), /***/ "./src/environments/packageSearch.ts": /*!*******************************************!*\ !*** ./src/environments/packageSearch.ts ***! \*******************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.searchPackageWithProvider = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); async function searchPackageWithProvider(searchProvider, env) { const quickPick = vscode_1.window.createQuickPick(); quickPick.placeholder = 'Enter package name to search'; quickPick.canSelectMany = false; quickPick.show(); let progressCounter = 0; const searchAndUpdate = async (value, token) => { if (!value.trim()) { quickPick.items = []; return; } quickPick.busy = true; progressCounter += 1; const packages = await searchProvider(value, env, token); progressCounter -= 1; if (!progressCounter) { quickPick.busy = false; } if (token.isCancellationRequested) { return; } quickPick.items = packages; }; let token; quickPick.onDidChangeValue(async (value) => { if (token) { token.cancel(); token.dispose(); } token = new vscode_1.CancellationTokenSource(); searchAndUpdate(value, token.token); }); return new Promise((resolve) => { quickPick.onDidHide(() => { if (token) { token.cancel(); token.dispose(); } resolve(undefined); quickPick.dispose(); }); quickPick.onDidAccept(async () => { if (!quickPick.selectedItems.length) { return; } resolve('item' in quickPick.selectedItems[0] ? quickPick.selectedItems[0].item : undefined); quickPick.hide(); }); }); } exports.searchPackageWithProvider = searchPackageWithProvider; /***/ }), /***/ "./src/environments/packages.ts": /*!**************************************!*\ !*** ./src/environments/packages.ts ***! \**************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.installPackage = exports.searchPackage = exports.exportPackages = exports.uninstallPackage = exports.updatePackages = exports.updatePackage = exports.getOutdatedPackages = exports.getPackages = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const logging_1 = __webpack_require__(/*! ../client/logging */ "./src/client/logging/index.ts"); const pip_1 = __webpack_require__(/*! ./tools/pip */ "./src/environments/tools/pip.ts"); const conda_1 = __webpack_require__(/*! ./tools/conda */ "./src/environments/tools/conda.ts"); const utils_1 = __webpack_require__(/*! ./utils */ "./src/environments/utils.ts"); const info_1 = __webpack_require__(/*! ../client/pythonEnvironments/info */ "./src/client/pythonEnvironments/info/index.ts"); const poetry_1 = __webpack_require__(/*! ./tools/poetry */ "./src/environments/tools/poetry.ts"); const helpers_1 = __webpack_require__(/*! ./helpers */ "./src/environments/helpers.ts"); const packageSearch_1 = __webpack_require__(/*! ./packageSearch */ "./src/environments/packageSearch.ts"); async function getPackages(env) { try { const [pipPackages, condaPackages] = await Promise.all([(0, pip_1.getPipPackages)(env), (0, conda_1.getCondaPackages)(env)]); const packages = new Map(); (pipPackages || []).forEach((pkg) => packages.set(pkg.name, pkg)); (condaPackages || []).forEach((pkg) => packages.set(pkg.name, pkg)); return Array.from(packages.values()).sort((a, b) => a.name.toLocaleLowerCase().localeCompare(b.name.toLocaleLowerCase())); } catch (ex) { (0, logging_1.traceError)(`Failed to get package information for ${env.id})`, ex); return []; } } exports.getPackages = getPackages; async function getOutdatedPackages(env) { try { const [pipPackages, condaPackages] = await Promise.all([ (0, pip_1.getOutdatedPipPackages)(env), (0, conda_1.getOutdatedCondaPackages)(env), ]); return condaPackages || pipPackages || new Map(); } catch (ex) { (0, logging_1.traceError)(`Failed to get latest package information for ${env.id})`, ex); return new Map(); } } exports.getOutdatedPackages = getOutdatedPackages; async function updatePackage(env, pkg) { try { if ((0, utils_1.isCondaEnvironment)(env)) { await (0, conda_1.updateCondaPackage)(env, pkg); } else { await (0, pip_1.updatePipPackage)(env, pkg); } } catch (ex) { (0, logging_1.traceError)(`Failed to update package ${pkg.name} in ${env.id})`, ex); return []; } } exports.updatePackage = updatePackage; async function updatePackages(env) { try { if ((0, utils_1.isCondaEnvironment)(env)) { await (0, conda_1.updateCondaPackages)(env); } else if ((0, utils_1.getEnvironmentType)(env) === info_1.EnvironmentType.Poetry) { await (0, poetry_1.updatePoetryPackages)(env); } else { await (0, pip_1.updatePipPackages)(env); } } catch (ex) { (0, logging_1.traceError)(`Failed to update packages in ${env.id})`, ex); return []; } } exports.updatePackages = updatePackages; async function uninstallPackage(env, pkg) { await vscode_1.window.withProgress({ location: vscode_1.ProgressLocation.Notification, cancellable: true, title: `Uninstalling ${pkg.name}` }, async (progress, token) => { let result; try { if ((0, utils_1.isCondaEnvironment)(env)) { result = await (0, conda_1.getUninstallCondaPackageSpawnOptions)(env, pkg, token); } else if ((0, utils_1.getEnvironmentType)(env) === info_1.EnvironmentType.Poetry) { result = await (0, poetry_1.getUninstallPoetryPackageSpawnOptions)(env, pkg.name, token); } else { result = await (0, pip_1.getUninstallPipPackageSpawnOptions)(env, pkg, token); } const message = `Uninstalling package ${pkg.name} from ${(0, helpers_1.getEnvLoggingInfo)(env)} with command ${[ result.command, ...result.args, ]}]}`; await (0, helpers_1.reportStdOutProgress)(message, [result.command, result.args, { timeout: 60000, ...(result.options || {}) }], progress, token); } catch (ex) { (0, logging_1.traceError)(`Failed to uninstall package ${pkg.name} in ${env.id})`, ex); return []; } }); } exports.uninstallPackage = uninstallPackage; async function exportPackages(env) { try { if ((0, utils_1.isCondaEnvironment)(env)) { return (0, conda_1.exportCondaPackages)(env); } if ((0, utils_1.getEnvironmentType)(env) === info_1.EnvironmentType.Poetry) { return (0, poetry_1.exportPoetryPackages)(env); } return (0, pip_1.exportPipPackages)(env); } catch (ex) { (0, logging_1.traceError)(`Failed to export environment ${env.id}`, ex); } } exports.exportPackages = exportPackages; async function searchPackage(env) { try { if ((0, utils_1.isCondaEnvironment)(env)) { const result = await (0, packageSearch_1.searchPackageWithProvider)(conda_1.searchCondaPackage, env); if (!result) { throw new vscode_1.CancellationError(); } return { conda: result }; } if ((0, utils_1.getEnvironmentType)(env) === info_1.EnvironmentType.Poetry) { const result = await (0, packageSearch_1.searchPackageWithProvider)(poetry_1.searchPoetryPackage, env); if (!result) { throw new vscode_1.CancellationError(); } return { poetry: result }; } const result = await (0, packageSearch_1.searchPackageWithProvider)(pip_1.searchPipPackage, env); if (!result) { throw new vscode_1.CancellationError(); } return { pip: result }; } catch (ex) { (0, logging_1.traceError)(`Failed to install a package in ${env.id})`, ex); throw ex; } } exports.searchPackage = searchPackage; async function installPackage(env, packageInfo) { let packageName = ''; if ('conda' in packageInfo && packageInfo.conda) { packageName = packageInfo.conda.name; } else if ('poetry' in packageInfo && packageInfo.poetry) { packageName = packageInfo.poetry; } else if ('pip' in packageInfo && packageInfo.pip) { packageName = packageInfo.pip.name; } else { throw new Error('Not supported'); } await vscode_1.window.withProgress({ location: vscode_1.ProgressLocation.Notification, cancellable: true, title: `Installing ${packageName}` }, async (progress, token) => { let result; try { if ('conda' in packageInfo && packageInfo.conda) { result = await (0, conda_1.getCondaPackageInstallSpawnOptions)(env, packageInfo.conda, token); } else if ('poetry' in packageInfo && packageInfo.poetry) { result = await (0, poetry_1.getPoetryPackageInstallSpawnOptions)(env, packageInfo.poetry, token); } else if ('pip' in packageInfo && packageInfo.pip) { result = await (0, pip_1.getInstallPipPackageSpawnOptions)(env, packageInfo.pip, token); } else { throw new Error('Not supported'); } const message = `Installing package ${packageName} into ${(0, helpers_1.getEnvLoggingInfo)(env)} with command ${[ result.command, ...result.args, ]}]}`; await (0, helpers_1.reportStdOutProgress)(message, [result.command, result.args, { timeout: 60000, ...(result.options || {}) }], progress, token); } catch (ex) { (0, logging_1.traceError)(`Failed to install package ${packageName} into ${(0, helpers_1.getEnvLoggingInfo)(env)})`, ex); } }); } exports.installPackage = installPackage; /***/ }), /***/ "./src/environments/serviceRegistry.ts": /*!*********************************************!*\ !*** ./src/environments/serviceRegistry.ts ***! \*********************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.registerTypes = void 0; const python_extension_1 = __webpack_require__(/*! @vscode/python-extension */ "./node_modules/@vscode/python-extension/out/main.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const terminal_1 = __webpack_require__(/*! ./terminal */ "./src/environments/terminal.ts"); const downloader_1 = __webpack_require__(/*! ./micromamba/downloader */ "./src/environments/micromamba/downloader.ts"); const installPython_1 = __webpack_require__(/*! ./installPython */ "./src/environments/installPython.ts"); const envDeletion_1 = __webpack_require__(/*! ./envDeletion */ "./src/environments/envDeletion.ts"); const envCreation_1 = __webpack_require__(/*! ./envCreation */ "./src/environments/envCreation.ts"); const activeInterpreter_1 = __webpack_require__(/*! ./activeInterpreter */ "./src/environments/activeInterpreter.ts"); const environmentsTreeDataProvider_1 = __webpack_require__(/*! ./view/environmentsTreeDataProvider */ "./src/environments/view/environmentsTreeDataProvider.ts"); const foldersTreeDataProvider_1 = __webpack_require__(/*! ./view/foldersTreeDataProvider */ "./src/environments/view/foldersTreeDataProvider.ts"); const commands_1 = __webpack_require__(/*! ./view/commands */ "./src/environments/view/commands.ts"); function registerTypes(serviceManager, context) { python_extension_1.PythonExtension.api().then((api) => { const treeDataProvider = new environmentsTreeDataProvider_1.PythonEnvironmentsTreeDataProvider(context, api, serviceManager); context.subscriptions.push(treeDataProvider); vscode_1.window.createTreeView('pythonEnvironments', { treeDataProvider }); const workspaceFoldersTreeDataProvider = new foldersTreeDataProvider_1.WorkspaceFoldersTreeDataProvider(context, api, envDeletion_1.canEnvBeDeleted); context.subscriptions.push(workspaceFoldersTreeDataProvider); vscode_1.window.createTreeView('workspaceEnvironments', { treeDataProvider: workspaceFoldersTreeDataProvider }); context.subscriptions.push(vscode_1.commands.registerCommand('python.envManager.refresh', (forceRefresh = true) => { treeDataProvider.refresh(forceRefresh); workspaceFoldersTreeDataProvider.refresh(forceRefresh); })); context.subscriptions.push(vscode_1.commands.registerCommand('python.envManager.refreshing', (forceRefresh = true) => { treeDataProvider.refresh(forceRefresh); workspaceFoldersTreeDataProvider.refresh(forceRefresh); })); }); (0, terminal_1.activate)(context, serviceManager); (0, downloader_1.activate)(context); (0, commands_1.registerCommands)(context); (0, installPython_1.activate)(context); (0, envCreation_1.activate)(context); (0, envDeletion_1.activate)(context); (0, activeInterpreter_1.activate)(context); } exports.registerTypes = registerTypes; /***/ }), /***/ "./src/environments/sillyDI.ts": /*!*************************************!*\ !*** ./src/environments/sillyDI.ts ***! \*************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Dummy = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); let Dummy = class Dummy { constructor() { this.supportedWorkspaceTypes = { untrustedWorkspace: false, virtualWorkspace: false }; } async activate(_resource) { } }; Dummy = __decorate([ (0, inversify_1.injectable)() ], Dummy); exports.Dummy = Dummy; /***/ }), /***/ "./src/environments/terminal.ts": /*!**************************************!*\ !*** ./src/environments/terminal.ts ***! \**************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getActivatedEnvVariables = exports.getTerminalEnvVariables = exports.activate = void 0; const python_extension_1 = __webpack_require__(/*! @vscode/python-extension */ "./node_modules/@vscode/python-extension/out/main.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const path = __webpack_require__(/*! path */ "path"); const fs = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const isWsl = __webpack_require__(/*! is-wsl */ "./node_modules/is-wsl/index.js"); const types_1 = __webpack_require__(/*! ../client/common/terminal/types */ "./src/client/common/terminal/types.ts"); const async_1 = __webpack_require__(/*! ../client/common/utils/async */ "./src/client/common/utils/async.ts"); const constants_1 = __webpack_require__(/*! ../client/common/process/internal/scripts/constants */ "./src/client/common/process/internal/scripts/constants.ts"); const stopWatch_1 = __webpack_require__(/*! ../client/common/utils/stopWatch */ "./src/client/common/utils/stopWatch.ts"); const fileSystem_1 = __webpack_require__(/*! ../client/common/platform/fileSystem */ "./src/client/common/platform/fileSystem.ts"); const helpers_1 = __webpack_require__(/*! ./helpers */ "./src/environments/helpers.ts"); const logging_1 = __webpack_require__(/*! ../client/logging */ "./src/client/logging/index.ts"); const contracts_1 = __webpack_require__(/*! ../client/interpreter/contracts */ "./src/client/interpreter/contracts.ts"); const utils_1 = __webpack_require__(/*! ./utils */ "./src/environments/utils.ts"); const foldersTreeDataProvider_1 = __webpack_require__(/*! ./view/foldersTreeDataProvider */ "./src/environments/view/foldersTreeDataProvider.ts"); const defaultEnvVars = new Map(); function activate(context, iocContainer) { vscode_1.workspace.onDidChangeConfiguration(() => { defaultEnvVars.clear(); }, undefined, context.subscriptions); let api; context.subscriptions.push(vscode_1.commands.registerCommand('python.envManager.openInTerminal', async (options) => { var _a, _b, _c, _d; let id = ''; if (options instanceof foldersTreeDataProvider_1.ActiveWorkspaceEnvironment) { id = ((_a = options.asNode()) === null || _a === void 0 ? void 0 : _a.env.id) || ''; } else { id = options.id; } const helper = iocContainer.get(types_1.ITerminalHelper); const pyenvs = iocContainer.get(contracts_1.IComponentAdapter); api = api || (await python_extension_1.PythonExtension.api()); const env = api.environments.known.find((e) => e.id === id); if (!env) { return; } const interpreter = await pyenvs.getInterpreterDetails(env.path); if (!interpreter || (!(interpreter === null || interpreter === void 0 ? void 0 : interpreter.sysPrefix) && (0, utils_1.isNonPythonCondaEnvironment)(env))) { return; } const cwd = await pickFolder(); const name = ((_b = env.environment) === null || _b === void 0 ? void 0 : _b.name) ? `Python ${env.environment.name}` : (0, helpers_1.getDisplayPath)(path.dirname(((_d = (_c = env.environment) === null || _c === void 0 ? void 0 : _c.folderUri) === null || _d === void 0 ? void 0 : _d.fsPath) || env.path)); let terminal = vscode_1.window.createTerminal({ hideFromUser: true, name, cwd }); const shell = helper.identifyTerminalShell(terminal); const activationCommands = await helper.getEnvironmentActivationCommands(shell, cwd, interpreter); if (Array.isArray(activationCommands) && activationCommands.length > 0) { terminal.show(false); for (const command of activationCommands || []) { terminal.sendText(command); if (activationCommands.length > 1) { await (0, async_1.sleep)(1000); } } return; } if (isWsl) { const exportScript = await getPathScript(shell, env.path, context); terminal.dispose(); terminal = vscode_1.window.createTerminal({ hideFromUser: true, name, cwd, }); if (exportScript) { terminal.sendText(exportScript); await (0, async_1.sleep)(1000); } terminal.show(false); return; } try { const [baseEnvVars, symlinkDir] = await Promise.all([ getEmptyTerminalVariables(terminal, shell, cwd === null || cwd === void 0 ? void 0 : cwd.fsPath), createSymlink(shell, env.path, context), ]); terminal.dispose(); const envVars = { ...baseEnvVars }; ['Path', 'PATH'].forEach((pathVarName) => { if (typeof envVars[pathVarName] === 'string') { envVars[pathVarName] = `${symlinkDir}${path.delimiter}${envVars[pathVarName]}`; } }); const terminalCustomEnvVars = vscode_1.window.createTerminal({ hideFromUser: false, name, cwd, env: envVars, strictEnv: true, }); terminalCustomEnvVars.show(false); } catch (ex) { console.error(`Failed to create terminal for ${(0, utils_1.getEnvironmentType)(env)}:${env.path}`, ex); } })); } exports.activate = activate; let cachedEnvVariables; async function getTerminalEnvVariables(iocContainer) { if (cachedEnvVariables) { return cachedEnvVariables; } cachedEnvVariables = (async () => { const helper = iocContainer.get(types_1.ITerminalHelper); const terminal = vscode_1.window.createTerminal({ hideFromUser: true, name: 'hidden' }); const shell = helper.identifyTerminalShell(terminal); try { return await getEmptyTerminalVariables(terminal, shell); } catch (ex) { return undefined; } finally { terminal.dispose(); } })(); return cachedEnvVariables; } exports.getTerminalEnvVariables = getTerminalEnvVariables; async function getEmptyTerminalVariables(terminal, shell, workspaceFolderUri = '') { if (defaultEnvVars.has(workspaceFolderUri)) { return defaultEnvVars.get(workspaceFolderUri); } const envFile = await (0, helpers_1.createTempFile)(); const cmd = getEnvDumpCommand(shell, envFile.filePath); try { terminal.sendText(cmd.command); const stopWatch = new stopWatch_1.StopWatch(); while (stopWatch.elapsedTime < 5000) { if (await fs.pathExists(envFile.filePath)) { const contents = await fs.readFile(envFile.filePath, 'utf8'); if (contents.length > 0) { const envVars = cmd.parser(contents); defaultEnvVars.set(workspaceFolderUri, envVars); defaultEnvVars.set(workspaceFolderUri, envVars); return envVars; } } await (0, async_1.sleep)(100); } (0, logging_1.traceError)(`Env vars file not created command ${cmd.command}`); return; } catch (ex) { (0, logging_1.traceError)(`Env vars file not created command ${cmd.command}`, ex); return; } finally { envFile.dispose(); } } function getEnvDumpCommand(shell, envFile) { switch (shell) { case types_1.TerminalShellType.commandPrompt: { const parser = (output) => { const dict = {}; output.split(/\r?\n/).forEach((line) => { if (line.indexOf('=') === -1) { return; } const key = line.substring(0, line.indexOf('=')).trim(); const value = line.substring(line.indexOf('=') + 1).trim(); dict[key] = value; }); return dict; }; return { command: `set > "${envFile}"`, parser }; } case types_1.TerminalShellType.powershell: case types_1.TerminalShellType.powershellCore: { const parser = (output) => { const dict = {}; let startProcessing = false; output.split(/\r?\n/).forEach((line) => { if (line.startsWith('----')) { startProcessing = true; return; } if (!startProcessing) { return; } const key = line.substring(0, line.indexOf(' ')).trim(); const value = line.substring(line.indexOf(' ') + 1).trim(); dict[key] = value; }); return dict; }; return { command: `Get-ChildItem env: | Out-File "${envFile}"`, parser }; } default: { const parser = (output) => { const dict = {}; output.split(/\r?\n/).forEach((line) => { if (line.indexOf('=') === -1) { return; } const key = line.substring(0, line.indexOf('=')).trim(); const value = line.substring(line.indexOf('=') + 1).trim(); dict[key] = value; }); return dict; }; return { command: `printenv > "${envFile.replace(/\\/g, '/')}"`, parser }; } } } async function createSymlink(shell, pythonPath, context) { const hash = (0, fileSystem_1.getHashString)(pythonPath); const script = createShellScript(shell, pythonPath); const symlinkDir = path.join(context.globalStorageUri.fsPath, 'symlinksV1', `python_${hash}`); const symlinkPythonFile = path.join(symlinkDir, `python${script.extension}`); const symlinkPipFile = path.join(symlinkDir, `pip${script.extension}`); if (await fs.pathExists(symlinkPythonFile)) { return symlinkDir; } await fs.ensureDir(symlinkDir); await Promise.all([fs.writeFile(symlinkPythonFile, script.python), fs.writeFile(symlinkPipFile, script.pip)]); await Promise.all([fs.chmod(symlinkPythonFile, 0o777), fs.chmod(symlinkPipFile, 0o777)]); return symlinkDir; } async function pickFolder() { if (!vscode_1.workspace.workspaceFolders || vscode_1.workspace.workspaceFolders.length === 0) { return; } if (vscode_1.workspace.workspaceFolders.length === 1) { return vscode_1.workspace.workspaceFolders[0].uri; } return vscode_1.window.showWorkspaceFolderPick({ placeHolder: 'Select cwd for terminal' }).then((folder) => folder === null || folder === void 0 ? void 0 : folder.uri); } const envVariables = new Map(); async function getActivatedEnvVariables(helper, shell, terminal, pythonPath) { if (envVariables.has(pythonPath)) { return envVariables.get(pythonPath); } const promise = (async () => { const tmpFile = await (0, helpers_1.createTempFile)(); tmpFile.dispose(); const args = helper.buildCommandForTerminal(shell, pythonPath, [ path.join(constants_1._SCRIPTS_DIR, 'printEnvVariablesToFile.py'), tmpFile.filePath, ]); terminal.sendText(args); const stopWatch = new stopWatch_1.StopWatch(); while (stopWatch.elapsedTime < 5000) { if (await fs.pathExists(tmpFile.filePath)) { break; } await (0, async_1.sleep)(100); } if (await fs.pathExists(tmpFile.filePath)) { try { return JSON.parse(await fs.readFile(tmpFile.filePath, 'utf8')); } catch (ex) { console.error(`Failed to parse activated env vars for ${pythonPath}, with command ${args}`, ex); throw new Error(`Failed to parse activated env vars for ${pythonPath}, with command ${args}`); } } else { throw new Error(`Failed to generate env vars for ${pythonPath}, with command ${args}`); } })(); envVariables.set(pythonPath, promise); promise.finally(() => envVariables.delete(pythonPath)); return promise; } exports.getActivatedEnvVariables = getActivatedEnvVariables; function createShellScript(shellType, realPath) { switch (shellType) { case types_1.TerminalShellType.commandPrompt: case types_1.TerminalShellType.powershell: case types_1.TerminalShellType.powershellCore: return { python: ` @ECHO off "${realPath}" %* `, pip: ` @ECHO off "${realPath}" -m pip %* `, extension: '.cmd', }; default: return { python: `#!/usr/bin/env bash "${realPath}" "$@" ret=$? exit $ret `, pip: `#!/usr/bin/env bash "${realPath}" -m pip "$@" ret=$? exit $ret `, extension: '', }; } } async function getPathScript(shell, pythonPath, context) { const symlinkFolder = await createSymlink(shell, pythonPath, context); switch (shell) { case types_1.TerminalShellType.commandPrompt: case types_1.TerminalShellType.powershell: case types_1.TerminalShellType.powershellCore: return; default: { return `export "PATH=${symlinkFolder}${path.delimiter}$PATH" && clear`; } } } /***/ }), /***/ "./src/environments/tools/conda.ts": /*!*****************************************!*\ !*** ./src/environments/tools/conda.ts ***! \*****************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.searchCondaPackage = exports.getCondaPackageInstallSpawnOptions = exports.exportCondaPackages = exports.updateEnvironmentsTxt = exports.createEnv = exports.getCondaVersion = exports.deleteEnv = exports.updateCondaPackage = exports.getUninstallCondaPackageSpawnOptions = exports.updateCondaPackages = exports.getOutdatedCondaPackages = exports.getCondaPackages = void 0; const python_extension_1 = __webpack_require__(/*! @vscode/python-extension */ "./node_modules/@vscode/python-extension/out/main.js"); const fs = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const path = __webpack_require__(/*! path */ "path"); const os_1 = __webpack_require__(/*! os */ "os"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const applicationShell_1 = __webpack_require__(/*! ../../client/common/application/applicationShell */ "./src/client/common/application/applicationShell.ts"); const rawProcessApis_1 = __webpack_require__(/*! ../../client/common/process/rawProcessApis */ "./src/client/common/process/rawProcessApis.ts"); const multiStepInput_1 = __webpack_require__(/*! ../../client/common/utils/multiStepInput */ "./src/client/common/utils/multiStepInput.ts"); const platform_1 = __webpack_require__(/*! ../../client/common/utils/platform */ "./src/client/common/utils/platform.ts"); const logging_1 = __webpack_require__(/*! ../../client/logging */ "./src/client/logging/index.ts"); const conda_1 = __webpack_require__(/*! ../../client/pythonEnvironments/common/environmentManagers/conda */ "./src/client/pythonEnvironments/common/environmentManagers/conda.ts"); const externalDependencies_1 = __webpack_require__(/*! ../../client/pythonEnvironments/common/externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const helpers_1 = __webpack_require__(/*! ../helpers */ "./src/environments/helpers.ts"); const constants_1 = __webpack_require__(/*! ../micromamba/constants */ "./src/environments/micromamba/constants.ts"); const utils_1 = __webpack_require__(/*! ../utils */ "./src/environments/utils.ts"); async function getCondaPackages(env) { var _a, _b, _c; if (!(0, utils_1.isCondaEnvironment)(env) || !env.executable.uri) { return; } const conda = await conda_1.Conda.getConda(); if (!conda) { return; } const args = ['list'].concat(((_a = env.environment) === null || _a === void 0 ? void 0 : _a.name) ? ['-n', env.environment.name] : ['-p', ((_c = (_b = env.environment) === null || _b === void 0 ? void 0 : _b.folderUri) === null || _c === void 0 ? void 0 : _c.fsPath) || path.dirname(env.path)]); const result = await (0, externalDependencies_1.exec)(conda.command, args.concat(['--json']), { timeout: 60000 }); const stdout = result.stdout.trim(); (0, logging_1.traceVerbose)(`conda info --json: ${result.stdout}`); const packages = stdout ? JSON.parse(result.stdout) : []; return packages; } exports.getCondaPackages = getCondaPackages; async function getOutdatedCondaPackages(env) { var _a, _b, _c; if (!(0, utils_1.isCondaEnvironment)(env) || !env.executable.uri) { return; } const conda = await conda_1.Conda.getConda(); if (!conda) { return; } const args = ['update', '--all', '-d'].concat(((_a = env.environment) === null || _a === void 0 ? void 0 : _a.name) ? ['-n', env.environment.name] : ['-p', ((_c = (_b = env.environment) === null || _b === void 0 ? void 0 : _b.folderUri) === null || _c === void 0 ? void 0 : _c.fsPath) || path.dirname(env.path)]); const result = await (0, externalDependencies_1.exec)(conda.command, args.concat(['--json']), { timeout: 60000 }); const stdout = result.stdout.trim(); (0, logging_1.traceVerbose)(`conda ${args.join(' ')} --json: ${result.stdout}`); if (!stdout) { return; } const map = new Map(); const unlink = new Set(); const { actions } = JSON.parse(result.stdout); actions.UNLINK.forEach((pkg) => unlink.add(pkg.name)); actions.LINK.forEach((pkg) => { if (unlink.has(pkg.name)) { map.set(pkg.name, pkg.version); } }); return map; } exports.getOutdatedCondaPackages = getOutdatedCondaPackages; async function updateCondaPackages(env) { var _a, _b, _c; if (!(0, utils_1.isCondaEnvironment)(env) || !env.executable.uri) { return; } const conda = await conda_1.Conda.getConda(); if (!conda) { return; } const args = ['update', '--all'].concat(((_a = env.environment) === null || _a === void 0 ? void 0 : _a.name) ? ['-n', env.environment.name] : ['-p', ((_c = (_b = env.environment) === null || _b === void 0 ? void 0 : _b.folderUri) === null || _c === void 0 ? void 0 : _c.fsPath) || path.dirname(env.path)]); await (0, externalDependencies_1.exec)(conda.command, args, { timeout: 60000 }); } exports.updateCondaPackages = updateCondaPackages; async function getUninstallCondaPackageSpawnOptions(env, pkg, _token) { var _a, _b, _c; if (!(0, utils_1.isCondaEnvironment)(env) || !env.executable.uri) { throw new Error('Not Supported'); } const conda = await conda_1.Conda.getConda(); if (!conda) { throw new Error('Not Supported'); } const args = ['remove', pkg.name, '-y'].concat(((_a = env.environment) === null || _a === void 0 ? void 0 : _a.name) ? ['-n', env.environment.name] : ['-p', ((_c = (_b = env.environment) === null || _b === void 0 ? void 0 : _b.folderUri) === null || _c === void 0 ? void 0 : _c.fsPath) || path.dirname(env.path)]); return { command: conda.command, args }; } exports.getUninstallCondaPackageSpawnOptions = getUninstallCondaPackageSpawnOptions; async function updateCondaPackage(env, pkg) { var _a, _b, _c; if (!(0, utils_1.isCondaEnvironment)(env) || !env.executable.uri) { return; } const conda = await conda_1.Conda.getConda(); if (!conda) { return; } const args = ['update', pkg.name, '-y'].concat(((_a = env.environment) === null || _a === void 0 ? void 0 : _a.name) ? ['-n', env.environment.name] : ['-p', ((_c = (_b = env.environment) === null || _b === void 0 ? void 0 : _b.folderUri) === null || _c === void 0 ? void 0 : _c.fsPath) || path.dirname(env.path)]); await (0, externalDependencies_1.exec)(conda.command, args, { timeout: 60000 }); } exports.updateCondaPackage = updateCondaPackage; async function deleteEnv(env, progress) { var _a, _b, _c; if (!(0, utils_1.isCondaEnvironment)(env)) { (0, logging_1.traceError)(`Cannot delete as its not a conda environment or no name/path for ${(0, helpers_1.getEnvLoggingInfo)(env)}`); return; } const conda = await conda_1.Conda.getConda(); if (!conda) { return; } const args = ((_a = env.environment) === null || _a === void 0 ? void 0 : _a.name) ? ['-n', env.environment.name] : ['-p', ((_c = (_b = env.environment) === null || _b === void 0 ? void 0 : _b.folderUri) === null || _c === void 0 ? void 0 : _c.fsPath) || env.path]; const message = `Deleting conda environment ${(0, helpers_1.getEnvLoggingInfo)(env)} with command ${[ conda.command, 'env', 'remove', ] .concat(args) .join(' ')}`; (0, logging_1.traceVerbose)(message); progress.report({ message }); const result = await (0, rawProcessApis_1.execObservable)(conda.command, ['env', 'remove'].concat(args), { timeout: 60000 }); await new Promise((resolve) => { result.out.subscribe({ next: (output) => progress.report({ message: output.out }), complete: () => resolve(), }); }); if (await fs.pathExists(env.path)) { throw new Error(`Failed to delete conda environment ${(0, helpers_1.getEnvDisplayInfo)(env)}, folder still exists ${(0, helpers_1.getDisplayPath)(env.path)} `); } } exports.deleteEnv = deleteEnv; async function getCondaVersion() { const conda = await conda_1.Conda.getConda(); if (!conda) { return; } return conda.getInfo().catch((ex) => (0, logging_1.traceError)('Failed to get conda info', ex)); } exports.getCondaVersion = getCondaVersion; function getLatestCondaPythonVersion(environments) { let maxMajorVersion = 3; let maxMinorVersion = 9; environments .filter((env) => (0, utils_1.isCondaEnvironment)(env)) .forEach((env) => { var _a, _b, _c, _d, _e, _f, _g; if (!((_a = env.version) === null || _a === void 0 ? void 0 : _a.major) || ((_b = env.version) === null || _b === void 0 ? void 0 : _b.major) < maxMajorVersion) { } else if (((_c = env.version) === null || _c === void 0 ? void 0 : _c.major) > maxMajorVersion) { maxMajorVersion = (_d = env.version) === null || _d === void 0 ? void 0 : _d.major; maxMinorVersion = ((_e = env.version) === null || _e === void 0 ? void 0 : _e.minor) || 0; } else if ((((_f = env.version) === null || _f === void 0 ? void 0 : _f.minor) || 0) > maxMinorVersion) { maxMinorVersion = ((_g = env.version) === null || _g === void 0 ? void 0 : _g.minor) || 0; } }); return `${maxMajorVersion}.${maxMinorVersion}`; } async function createEnv() { const api = await python_extension_1.PythonExtension.api(); const conda = await conda_1.Conda.getConda(); if (!conda) { (0, logging_1.traceError)(`Conda not found`); return; } const initialState = { name: '' }; const availableMaxPythonVersion = getLatestCondaPythonVersion(api.environments.known); const selectVersion = async (input, state) => { const version = await input.showInputBox({ title: 'Select Python Version', validate: async (value) => { if (!value.trim().length) { return 'Enter a Python version such as 3.9'; } }, placeholder: '3.7, 3.8, 3.9, 3.10, etc', prompt: 'Python Version', value: availableMaxPythonVersion, }); state.pythonVersion = version === null || version === void 0 ? void 0 : version.trim(); }; const specifyName = async (input, state) => { const name = await input.showInputBox({ title: 'Enter the name of the virtual environment', value: '.venv', step: 1, totalSteps: 3, prompt: 'Name', validate: async (value) => { if (!value) { return 'Enter a name'; } }, }); if (name) { state.name = name.trim(); return selectVersion(input, state); } }; const multistepInput = new multiStepInput_1.MultiStepInput(new applicationShell_1.ApplicationShell()); await multistepInput.run(specifyName, initialState); if (!initialState.name.trim() || !initialState.pythonVersion) { return; } await vscode_1.window.withProgress({ location: vscode_1.ProgressLocation.Notification, cancellable: true, title: `Creating environment '${initialState.name.trim()}'`, }, async (uiProgress, token) => { await createEnvWithInfo(uiProgress, token, initialState.name.trim(), conda.command, initialState.pythonVersion); }); } exports.createEnv = createEnv; async function createEnvWithInfo(progress, token, name, condaFile, pythonVersion = '3.9') { var _a; try { const isMicroMamba = condaFile.includes('.micromamba'); progress.report({ message: `Creating environment ${name}` }); (0, logging_1.traceInfo)(`Creating conda environment ${name} with python version ${pythonVersion}`); const extraCreationArgs = isMicroMamba ? ['-c', 'conda-forge'] : []; const args = ['create', `-n`, `${name.trim()}`, `python=${pythonVersion || '3.9'}`] .concat(extraCreationArgs) .concat(['-y']); (0, logging_1.traceInfo)([condaFile].concat(args).join(' ')); const result = await (0, rawProcessApis_1.execObservable)(condaFile, args, { timeout: 120000, token, }); (_a = result.proc) === null || _a === void 0 ? void 0 : _a.on('error', (ex) => console.error(`Conda create exited with an error`, ex)); await new Promise((resolve, reject) => { result.out.subscribe({ next: (output) => { if (output.out.trim().length) { progress.report({ message: output.out }); } (0, logging_1.traceInfo)(output.out); }, complete: () => resolve(), error: (ex) => reject(ex), }); }); if (isMicroMamba) { await updateEnvironmentsTxt(path.join(constants_1.MICROMAMBA_ROOTPREFIX, name.trim())).catch((ex) => (0, logging_1.traceError)('Failed to update environments.txt', ex)); } progress.report({ message: 'Waiting for environment to be detected' }); const api = await python_extension_1.PythonExtension.api(); await api.environments.refreshEnvironments(); } catch (ex) { (0, logging_1.traceError)(`Failed to create environment`, ex); vscode_1.window.showErrorMessage(`Failed to create environment ${name}, ${ex}`); } } async function updateEnvironmentsTxt(envFolder) { const txtFile = path.join((0, platform_1.getUserHomeDir)() || helpers_1.home, '.conda', 'environments.txt'); const contents = await fs.readFile(txtFile, 'utf-8'); if (contents.includes(envFolder)) { return; } await fs.writeFile(txtFile, `${contents.trim()}${os_1.EOL}${envFolder}${os_1.EOL}`); } exports.updateEnvironmentsTxt = updateEnvironmentsTxt; async function exportCondaPackages(env) { const conda = await conda_1.Conda.getConda(); if (!conda) { (0, logging_1.traceError)(`Conda not found`); return; } if (!env.executable.sysPrefix) { return; } const result = await (0, externalDependencies_1.exec)(conda.command, ['env', 'export', '-p', env.executable.sysPrefix.fileToCommandArgumentForPythonMgrExt()], { timeout: 60000 }); return { contents: result.stdout, language: 'yaml', file: 'environment.yml' }; } exports.exportCondaPackages = exportCondaPackages; async function getCondaPackageInstallSpawnOptions(env, packageInfo, _token) { const conda = await conda_1.Conda.getConda(); if (!conda) { throw new Error(`Conda not found`); } if (!env.executable.sysPrefix) { throw new Error(`Invalid Conda Env`); } const args = ['install']; if (packageInfo.channel) { args.push('-c', packageInfo.channel); } args.push(`${packageInfo.name}==${packageInfo.version}`); args.push('-p', env.executable.sysPrefix.fileToCommandArgumentForPythonMgrExt(), '-y'); return { command: conda.command, args }; } exports.getCondaPackageInstallSpawnOptions = getCondaPackageInstallSpawnOptions; async function searchCondaPackage(value, _env, token) { try { const conda = await conda_1.Conda.getConda(); if (!conda) { (0, logging_1.traceError)(`Conda not found`); return []; } const message = `Searching for Conda packages with command ${[ conda.command, 'search', '-f', value, ]}]}`; (0, logging_1.traceVerbose)(message); const result = await (0, externalDependencies_1.exec)(conda.command, ['search', '-f', value], { timeout: 60000, token }); const lines = result.stdout .split(/\r?\n/g) .filter((line) => line.trim().length) .filter((line) => !line.startsWith('Loading channels: done')) .filter((line) => !line.startsWith('# Name')); if (lines.length === 0) { return []; } const items = []; const addedItems = new Set(); lines.forEach((line) => { const parts = line .split(' ') .map((p) => p.trim()) .filter((p) => p.length); if (parts.length !== 4) { return; } const key = `${parts[0]}-${parts[1]}-${parts[3]}`; if (addedItems.has(key)) { return; } addedItems.add(key); const item = { name: parts[0], version: parts[1], channel: parts[3] }; items.push({ label: item.name, description: `${item.version} (${item.channel})`, item }); }); return items.reverse(); } catch (ex) { (0, logging_1.traceError)(`Failed to search for package`, ex); return []; } } exports.searchCondaPackage = searchCondaPackage; /***/ }), /***/ "./src/environments/tools/pip.ts": /*!***************************************!*\ !*** ./src/environments/tools/pip.ts ***! \***************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.searchPipPackage = exports.exportPipPackages = exports.getInstallPipPackageSpawnOptions = exports.getUninstallPipPackageSpawnOptions = exports.updatePipPackages = exports.updatePipPackage = exports.getOutdatedPipPackages = exports.getPipPackages = void 0; const logging_1 = __webpack_require__(/*! ../../client/logging */ "./src/client/logging/index.ts"); const externalDependencies_1 = __webpack_require__(/*! ../../client/pythonEnvironments/common/externalDependencies */ "./src/client/pythonEnvironments/common/externalDependencies.ts"); const info_1 = __webpack_require__(/*! ../../client/pythonEnvironments/info */ "./src/client/pythonEnvironments/info/index.ts"); const utils_1 = __webpack_require__(/*! ../utils */ "./src/environments/utils.ts"); async function getPipPackages(env) { if ((0, utils_1.getEnvironmentType)(env) === info_1.EnvironmentType.Conda) { return; } const result = await (0, externalDependencies_1.exec)(env.path, ['-m', 'pip', 'list', '--format', 'json'], { timeout: 60000 }); (0, logging_1.traceVerbose)(`python -m pip list --format --json: ${result.stdout}`); const stdout = result.stdout.trim(); const packages = stdout ? JSON.parse(result.stdout) : []; return packages; } exports.getPipPackages = getPipPackages; async function getOutdatedPipPackages(env) { if ((0, utils_1.getEnvironmentType)(env) === info_1.EnvironmentType.Conda) { return; } const result = await (0, externalDependencies_1.exec)(env.path, ['-m', 'pip', 'list', '--outdated', '--format', 'json'], { timeout: 60000 }); (0, logging_1.traceVerbose)(`python -m pip list --format --json: ${result.stdout}`); const stdout = result.stdout.trim(); if (!stdout) { return; } const map = new Map(); JSON.parse(result.stdout).forEach((pkg) => map.set(pkg.name, pkg.latest_version)); return map; } exports.getOutdatedPipPackages = getOutdatedPipPackages; async function updatePipPackage(env, pkg) { if ((0, utils_1.getEnvironmentType)(env) === info_1.EnvironmentType.Conda) { return []; } await (0, externalDependencies_1.exec)(env.path, ['-m', 'pip', 'install', '-U', pkg.name], { timeout: 60000 }); } exports.updatePipPackage = updatePipPackage; async function updatePipPackages(env) { if ((0, utils_1.getEnvironmentType)(env) === info_1.EnvironmentType.Conda) { return []; } const outdatedPackages = await getOutdatedPipPackages(env); const packages = outdatedPackages ? Array.from(outdatedPackages === null || outdatedPackages === void 0 ? void 0 : outdatedPackages.values()) : []; if (packages.length === 0) { (0, logging_1.traceError)(`No outdated packages found for ${env.id}`); } await (0, externalDependencies_1.exec)(env.path, ['-m', 'pip', 'install', '-U', ...packages], { timeout: 60000 }); } exports.updatePipPackages = updatePipPackages; async function getUninstallPipPackageSpawnOptions(env, pkg, _token) { return { command: env.path, args: ['-m', 'pip', 'uninstall', '-y', pkg.name] }; } exports.getUninstallPipPackageSpawnOptions = getUninstallPipPackageSpawnOptions; async function getInstallPipPackageSpawnOptions(env, pkg, _token) { return { command: env.path, args: ['-m', 'pip', 'install', pkg.name, '-q'] }; } exports.getInstallPipPackageSpawnOptions = getInstallPipPackageSpawnOptions; async function exportPipPackages(env) { const result = await (0, externalDependencies_1.exec)(env.path, ['-m', 'pip', 'freeze'], { timeout: 60000 }); return { contents: result === null || result === void 0 ? void 0 : result.stdout, language: 'pip-requirements', file: 'requirements.txt' }; } exports.exportPipPackages = exportPipPackages; async function searchPipPackage(value, _env, token) { const [page1Results, page2Results, page3Results] = await Promise.all([ searchPackageByPage(value, 1, token), searchPackageByPage(value, 2, token), searchPackageByPage(value, 3, token), ]); const items = [...page1Results, ...page2Results, ...page3Results]; return items.map(p => { const description = p.version ? `${p.version} ${p.updated ? `(${p.updated})` : ''}` : ''; return { label: p.name, description, detail: p.description, item: p, alwaysShow: true }; }); } exports.searchPipPackage = searchPipPackage; async function searchPackageByPage(value, page, token) { const pageQuery = page === 1 ? '' : `&page=${page}`; const response = await fetch(`https://pypi.org/search/?q=${encodeURIComponent(value)}${pageQuery}`); if (token.isCancellationRequested) { return []; } if (response.status !== 200) { return []; } const html = await response.text(); const results = html.substring(html.indexOf('
    ')); const packages = []; results .substring(0, results.indexOf('
')) .split('
  • ') .forEach((item) => { let name = ''; if (item.indexOf('')) { name = item.substring(item.indexOf('') + ''.length); name = name.substring(0, name.indexOf('')).trim(); } let version = ''; if (item.indexOf('')) { version = item.substring(item.indexOf('') + ''.length); version = version.substring(0, version.indexOf('')).trim(); } let desc = ''; if (item.indexOf('

    ')) { desc = item.substring(item.indexOf('

    ') + '

    '.length); desc = desc.substring(0, desc.indexOf('

    ')).trim(); } let updated = ''; if (item.indexOf('')) { updated = item.substring(item.indexOf('') + ''.length); updated = updated.substring(0, updated.indexOf('')); updated = updated.substring(updated.indexOf('>') + 1).trim(); } if (name && version) { packages.push({ name, version, description: desc, updated }); } }); return packages; } /***/ }), /***/ "./src/environments/tools/poetry.ts": /*!******************************************!*\ !*** ./src/environments/tools/poetry.ts ***! \******************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.searchPoetryPackage = exports.exportPoetryPackages = exports.getPoetryPackageInstallSpawnOptions = exports.getUninstallPoetryPackageSpawnOptions = exports.updatePoetryPackages = exports.deleteEnv = exports.hasPoetryEnvs = exports.getPoetryEnvironments = exports.getPoetryVersion = void 0; const fs = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const utils_1 = __webpack_require__(/*! ../utils */ "./src/environments/utils.ts"); const info_1 = __webpack_require__(/*! ../../client/pythonEnvironments/info */ "./src/client/pythonEnvironments/info/index.ts"); const poetry_1 = __webpack_require__(/*! ../../client/pythonEnvironments/common/environmentManagers/poetry */ "./src/client/pythonEnvironments/common/environmentManagers/poetry.ts"); const logging_1 = __webpack_require__(/*! ../../client/logging */ "./src/client/logging/index.ts"); const helpers_1 = __webpack_require__(/*! ../helpers */ "./src/environments/helpers.ts"); const rawProcessApis_1 = __webpack_require__(/*! ../../client/common/process/rawProcessApis */ "./src/client/common/process/rawProcessApis.ts"); const misc_1 = __webpack_require__(/*! ../../client/common/utils/misc */ "./src/client/common/utils/misc.ts"); const folderMappings = new Map(); async function getPoetryVersion() { const cwd = !vscode_1.workspace.workspaceFolders || vscode_1.workspace.workspaceFolders.length <= 1 ? __dirname : vscode_1.workspace.workspaceFolders[0].uri.fsPath; return poetry_1.Poetry.getVersion(cwd).catch(misc_1.noop); } exports.getPoetryVersion = getPoetryVersion; async function getPoetryEnvironments(workspaceFolder, envs) { if (!vscode_1.workspace.workspaceFolders || vscode_1.workspace.workspaceFolders.length <= 1) { const poetryEnvs = envs.filter((e) => (0, utils_1.getEnvironmentType)(e) === info_1.EnvironmentType.Poetry); folderMappings.set(workspaceFolder.uri.fsPath, poetryEnvs.map((e) => e.path)); return poetryEnvs; } const poetry = await poetry_1.Poetry.getPoetry(workspaceFolder.uri.fsPath); if (!poetry) { return []; } const envPaths = await poetry.getEnvList(); if (!envPaths || !Array.isArray(envPaths)) { return []; } folderMappings.set(workspaceFolder.uri.fsPath, envPaths); return envs .filter((e) => envPaths.includes(e.path)) .filter((e) => (0, utils_1.getEnvironmentType)(e) === info_1.EnvironmentType.Poetry); } exports.getPoetryEnvironments = getPoetryEnvironments; function hasPoetryEnvs(envs) { return envs.some((e) => (0, utils_1.getEnvironmentType)(e) === info_1.EnvironmentType.Poetry); } exports.hasPoetryEnvs = hasPoetryEnvs; function getMatchingWorkspaceFolder(env) { var _a; if ((0, utils_1.getEnvironmentType)(env) !== info_1.EnvironmentType.Poetry) { (0, logging_1.traceError)(`Cannot delete as its not a Poetry environment ${(0, helpers_1.getEnvLoggingInfo)(env)}`); return; } let workspaceFolderPath; folderMappings.forEach((envPaths, folder) => { if (envPaths.some((e) => env.path.includes(e))) { workspaceFolderPath = folder; } }); if (!workspaceFolderPath) { (0, logging_1.traceError)(`Cannot delete as its not a belong to any workspace folder we know of ${(0, helpers_1.getEnvLoggingInfo)(env)}`); } return (_a = vscode_1.workspace.workspaceFolders) === null || _a === void 0 ? void 0 : _a.find((w) => w.uri.fsPath === workspaceFolderPath); } async function getPoetry(env) { const workspaceFolder = getMatchingWorkspaceFolder(env); if (!workspaceFolder) { return { workspaceFolder: undefined, poetry: undefined }; } const poetry = await poetry_1.Poetry.getPoetry(workspaceFolder.uri.fsPath); return { workspaceFolder, poetry }; } async function deleteEnv(env, progress) { const { poetry, workspaceFolder } = await getPoetry(env); if (!poetry) { return []; } const args = [env.path.fileToCommandArgumentForPythonMgrExt()]; const message = `Deleting Poetry environment ${(0, helpers_1.getEnvLoggingInfo)(env)} with command ${[ poetry.command, 'env', env.path, ] .concat(args) .join(' ')}`; (0, logging_1.traceVerbose)(message); progress.report({ message }); const result = await (0, rawProcessApis_1.execObservable)(poetry.command, ['env', 'remove'].concat(args), { timeout: 60000, cwd: workspaceFolder.uri.fsPath, }); await new Promise((resolve) => { result.out.subscribe({ next: (output) => progress.report({ message: output.out }), complete: () => resolve(), }); }); if (await fs.pathExists(env.path)) { throw new Error(`Failed to delete Poetry environment ${(0, helpers_1.getEnvDisplayInfo)(env)}, folder still exists ${(0, helpers_1.getDisplayPath)(env.path)} `); } } exports.deleteEnv = deleteEnv; async function updatePoetryPackages(env) { const { poetry, workspaceFolder } = await getPoetry(env); if (!poetry) { return []; } const message = `Updating Poetry environment ${(0, helpers_1.getEnvLoggingInfo)(env)} with command ${[poetry.command, 'update']}`; (0, logging_1.traceVerbose)(message); const result = await (0, rawProcessApis_1.execObservable)(poetry.command, ['update'], { timeout: 60000, cwd: workspaceFolder.uri.fsPath, }); await new Promise((resolve) => { result.out.subscribe({ complete: () => resolve(), }); }); } exports.updatePoetryPackages = updatePoetryPackages; async function getUninstallPoetryPackageSpawnOptions(env, packageName, _token) { const { poetry, workspaceFolder } = await getPoetry(env); if (!poetry) { throw new Error('Not Supported'); } return { command: poetry.command, args: ['remove', packageName], options: { cwd: workspaceFolder.uri.fsPath } }; } exports.getUninstallPoetryPackageSpawnOptions = getUninstallPoetryPackageSpawnOptions; async function getPoetryPackageInstallSpawnOptions(env, packageName, _token) { const { poetry, workspaceFolder } = await getPoetry(env); if (!poetry) { throw new Error('Not Supported'); } return { command: poetry.command, args: ['add', packageName], options: { cwd: workspaceFolder.uri.fsPath } }; } exports.getPoetryPackageInstallSpawnOptions = getPoetryPackageInstallSpawnOptions; async function exportPoetryPackages(env) { const { poetry, workspaceFolder } = await getPoetry(env); if (!poetry) { return; } const message = `Exporting Poetry package from ${(0, helpers_1.getEnvLoggingInfo)(env)} with command ${[ poetry.command, 'export', '-f', 'requirements.txt', ]}]}`; (0, logging_1.traceVerbose)(message); const result = await (0, rawProcessApis_1.shellExec)(`${poetry.command.fileToCommandArgumentForPythonMgrExt()} export -f requirements.txt`, { timeout: 60000, cwd: workspaceFolder.uri.fsPath, throwOnStdErr: true, }).catch((ex) => (0, logging_1.traceError)(`Failed to export packages from ${(0, helpers_1.getEnvLoggingInfo)(env)}`, ex)); return { contents: result === null || result === void 0 ? void 0 : result.stdout, language: 'pip-requirements', file: 'requirements.txt' }; } exports.exportPoetryPackages = exportPoetryPackages; async function searchPoetryPackage(value, env, token) { const { poetry, workspaceFolder } = await getPoetry(env); if (!poetry) { return []; } const message = `Searching for Poetry packages from ${(0, helpers_1.getEnvLoggingInfo)(env)} with command ${[ poetry.command, 'search', value, '-n', '--no-ansi', ]}]}`; (0, logging_1.traceVerbose)(message); const result = await (0, rawProcessApis_1.shellExec)(`${poetry.command.fileToCommandArgumentForPythonMgrExt()} search ${value}`, { timeout: 60000, cwd: workspaceFolder.uri.fsPath, throwOnStdErr: true, }).catch(misc_1.noop); if (!result) { return []; } const items = []; let label = ''; let description = ''; let detail = ''; result.stdout.split(/\r?\n/g).forEach((line) => { if (!label && !line.trim().length) { return; } if (!label && line.trim().startsWith(line.charAt(0))) { label = line.trim(); if (label.includes('(') && label.endsWith(')')) { description = label.substring(label.lastIndexOf('(') + 1, label.lastIndexOf(')')); label = label.substring(0, label.lastIndexOf('(')).trim(); } detail = ''; return; } if (label) { detail = line.trim(); items.push({ label, detail, description, item: label }); label = ''; detail = ''; } }); if (token.isCancellationRequested) { return []; } return items; } exports.searchPoetryPackage = searchPoetryPackage; /***/ }), /***/ "./src/environments/tools/pyenv.ts": /*!*****************************************!*\ !*** ./src/environments/tools/pyenv.ts ***! \*****************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getPyEnvVersion = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const child_process_1 = __webpack_require__(/*! child_process */ "child_process"); const fs = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const path = __webpack_require__(/*! path */ "path"); const logging_1 = __webpack_require__(/*! ../../client/logging */ "./src/client/logging/index.ts"); const pyenv_1 = __webpack_require__(/*! ../../client/pythonEnvironments/common/environmentManagers/pyenv */ "./src/client/pythonEnvironments/common/environmentManagers/pyenv.ts"); const terminal_1 = __webpack_require__(/*! ../terminal */ "./src/environments/terminal.ts"); const async_1 = __webpack_require__(/*! ../../client/common/utils/async */ "./src/client/common/utils/async.ts"); const createEnvApi_1 = __webpack_require__(/*! ../../client/pythonEnvironments/creation/createEnvApi */ "./src/client/pythonEnvironments/creation/createEnvApi.ts"); const info_1 = __webpack_require__(/*! ../../client/pythonEnvironments/info */ "./src/client/pythonEnvironments/info/index.ts"); const stringUtils_1 = __webpack_require__(/*! ../../client/common/stringUtils */ "./src/client/common/stringUtils.ts"); const pyEnvEnvVars = (0, async_1.createDeferred)(); pyEnvEnvVars.promise.then(() => { (0, createEnvApi_1.registerCreateEnvironmentProvider)({ createEnvironment: async () => new Promise(async (resolve) => { const input = vscode_1.window.createQuickPick(); input.title = 'Select Python Version to Install'; input.busy = true; input.ignoreFocusOut = false; input.matchOnDescription = true; ; input.matchOnDetail = true; ; input.onDidHide(() => { resolve({ action: 'Cancel', error: undefined, path: undefined, workspaceFolder: undefined }); input.hide(); }); input.show(); input.onDidAccept(async () => { const version = input.selectedItems[0].label; input.enabled = false; input.busy = true; installPython(version).finally(() => { input.hide(); resolve({ action: 'Cancel', error: undefined, path: undefined, workspaceFolder: undefined }); }); }); const [installedVersions, allVersions] = await Promise.all([getInstalledPythonVersions(), getPythonVersions()]); input.busy = false; input.items = allVersions.filter(v => !installedVersions.includes(v)).map(v => ({ label: v })); }), description: "PyEnv", id: 'pyenv', name: 'PyEnv', tools: [info_1.EnvironmentType.Pyenv] }); }); async function getPyEnvVersion(iocContainer) { const dir = (0, pyenv_1.getPyenvDir)(); const changelogFile = path.join(dir, 'CHANGELOG.md'); try { if (await fs.pathExists(changelogFile)) { const textFile = await fs.readFile(changelogFile, 'utf-8'); const versionStart = textFile.indexOf('## Release '); if (versionStart === -1) { (0, logging_1.traceError)(`Failed to identify pyenv version from ${changelogFile}, with text ${textFile.substring(0, 100)} `); return; } const start = versionStart + '## Release '.length; const verionLines = (0, stringUtils_1.splitLines)(textFile .substring(start, start + 20)) .map((line) => line.trim()) .filter((line) => line.length); return verionLines.length === 0 ? '' : verionLines[0]; } return Promise.race([ getPyEnvVersionFromSpawn(process.env), new Promise((resolve) => (0, terminal_1.getTerminalEnvVariables)(iocContainer).then(env => env ? getPyEnvVersionFromSpawn(env).then(resolve) : undefined)) ]).catch(() => ''); } catch (ex) { (0, logging_1.traceError)('Failed to get pyenv version', ex); } } exports.getPyEnvVersion = getPyEnvVersion; async function getPythonVersions() { return pyEnvEnvVars.promise.then(env => new Promise(resolve => { const proc = (0, child_process_1.spawn)('pyenv', ['install', '-l'], { env }); let output = ''; proc.stdout.on('data', data => { output += data.toString(); }); proc.on('close', () => { const versions = output.trim().split(/\r?\n/g); resolve(versions.map(v => v.trim()).filter(v => v.length && v.trim() !== 'Available versions:')); }); })); } async function getInstalledPythonVersions() { return pyEnvEnvVars.promise.then(env => new Promise(resolve => { const proc = (0, child_process_1.spawn)('pyenv', ['version', '--bare'], { env }); let output = ''; proc.stdout.on('data', data => { output += data.toString(); }); proc.on('close', () => { const versions = output.trim().split(/\r?\n/g); resolve(versions.map(v => v.trim()).filter(v => v.length)); }); })); } async function installPython(version) { return vscode_1.window.withProgress({ location: vscode_1.ProgressLocation.Notification, cancellable: true, title: `Installing Python ${version}` }, (progress, token) => pyEnvEnvVars.promise.then(env => new Promise((resolve, reject) => { const proc = (0, child_process_1.spawn)('pyenv', ['install', version], { env }); let stdErr = ''; let failureError; const ticker = ['.', '..', '...']; let counter = 0; const reportProgress = (data) => { if (token.isCancellationRequested) { return; } const suffix = ticker[counter % 3]; const trimmedOutput = data.toString().trim(); counter += 1; const message = trimmedOutput.length > 28 ? `${trimmedOutput.substring(0, 28)}${suffix}` : trimmedOutput; progress.report({ message }); }; proc.stdout.on('data', data => { stdErr += data.toString(); reportProgress(data.toString()); }); proc.stderr.on('data', data => { stdErr += data.toString(); reportProgress(data.toString()); }); proc.on('error', err => { console.error(`Failed to install Python ${version} via PyEnv`, err); failureError = err; stdErr += err.toString(); }); proc.on('close', (code) => { if (code) { vscode_1.window.showErrorMessage(`Failed to install Python ${version}, via PyEnv`); reject(failureError || new Error(stdErr)); } else { resolve(); } }); token.onCancellationRequested(() => proc.kill()); }))); } async function getPyEnvVersionFromSpawn(env) { return new Promise(resolve => { const proc = (0, child_process_1.spawn)('pyenv', ['--version'], { env }); let output = ''; proc.stdout.on('data', data => { output += data.toString(); }); proc.on('close', () => { const version = output.toString().trim().replace('pyenv', '').trim(); if (version) { pyEnvEnvVars.resolve(env); resolve(version); } }); }); } /***/ }), /***/ "./src/environments/tools/venv.ts": /*!****************************************!*\ !*** ./src/environments/tools/venv.ts ***! \****************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createEnvOld = exports.canCreateVirtualEnv = exports.deleteEnv = void 0; const python_extension_1 = __webpack_require__(/*! @vscode/python-extension */ "./node_modules/@vscode/python-extension/out/main.js"); const fs = __webpack_require__(/*! fs-extra */ "./node_modules/fs-extra/lib/index.js"); const path = __webpack_require__(/*! path */ "path"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const applicationShell_1 = __webpack_require__(/*! ../../client/common/application/applicationShell */ "./src/client/common/application/applicationShell.ts"); const rawProcessApis_1 = __webpack_require__(/*! ../../client/common/process/rawProcessApis */ "./src/client/common/process/rawProcessApis.ts"); const multiStepInput_1 = __webpack_require__(/*! ../../client/common/utils/multiStepInput */ "./src/client/common/utils/multiStepInput.ts"); const logging_1 = __webpack_require__(/*! ../../client/logging */ "./src/client/logging/index.ts"); const info_1 = __webpack_require__(/*! ../../client/pythonEnvironments/info */ "./src/client/pythonEnvironments/info/index.ts"); const helpers_1 = __webpack_require__(/*! ../helpers */ "./src/environments/helpers.ts"); const utils_1 = __webpack_require__(/*! ../utils */ "./src/environments/utils.ts"); async function deleteEnv(env) { var _a, _b; const envType = (0, utils_1.getEnvironmentType)(env); if (envType !== info_1.EnvironmentType.Venv && envType !== info_1.EnvironmentType.VirtualEnv && envType !== info_1.EnvironmentType.VirtualEnvWrapper) { (0, logging_1.traceError)(`Cannot delete as its not a virtual environment ${(0, helpers_1.getEnvLoggingInfo)(env)}`); return; } const baseDir = path.dirname(env.path); if (!baseDir.toLowerCase().endsWith('scripts') && !baseDir.toLowerCase().endsWith('bin')) { (0, logging_1.traceError)(`Cannot delete as its not a virtual environment with script/bin directory ${(0, helpers_1.getEnvLoggingInfo)(env)}`); return; } const dirToDelete = ((_b = (_a = env.environment) === null || _a === void 0 ? void 0 : _a.folderUri) === null || _b === void 0 ? void 0 : _b.fsPath) || path.dirname(path.dirname(env.path)); (0, logging_1.traceVerbose)(`Deleting virtual environment ${(0, helpers_1.getEnvLoggingInfo)(env)}`); await fs.remove(dirToDelete); } exports.deleteEnv = deleteEnv; function getSortedEnvsFromWhichWeCanCreateVenvEnv(environments) { return environments .filter((env) => { switch ((0, utils_1.getEnvironmentType)(env)) { case info_1.EnvironmentType.Global: case info_1.EnvironmentType.System: case info_1.EnvironmentType.Venv: case info_1.EnvironmentType.VirtualEnv: case info_1.EnvironmentType.VirtualEnvWrapper: return true; default: return false; } }) .sort((a, b) => { const v1 = a.version; const v2 = b.version; if (v1 && v2) { if (v1.major === v2.major) { if (v1.minor === v2.minor) { if (v1.micro === v2.micro) { return 0; } return (v1.micro || 0) > (v2.minor || 0) ? -1 : 1; } return (v1.minor || 0) > (v2.minor || 0) ? -1 : 1; } return (v1.major || 0) > (v2.major || 0) ? -1 : 1; } if (v1 && !v2) { return 1; } if (!v1 && v2) { return -1; } return 0; }); } function canCreateVirtualEnv(environments) { return getSortedEnvsFromWhichWeCanCreateVenvEnv(environments).length; } exports.canCreateVirtualEnv = canCreateVirtualEnv; async function createEnvOld() { var _a; const api = await python_extension_1.PythonExtension.api(); const templateEnvs = getSortedEnvsFromWhichWeCanCreateVenvEnv(api.environments.known); if (templateEnvs.length === 0) { (0, logging_1.traceError)(`Cannot create a venv without an existing Python environment`); return; } const latestGlobal = templateEnvs.filter((env) => (0, utils_1.getEnvironmentType)(env) === info_1.EnvironmentType.Global); const currentWorkspaceUri = ((_a = vscode_1.workspace.workspaceFolders) === null || _a === void 0 ? void 0 : _a.length) ? vscode_1.workspace.workspaceFolders[0].uri : undefined; const templateEnvironment = latestGlobal.length ? latestGlobal[0] : templateEnvs[0]; const initialState = { dir: '', name: '', templateEnvironment: undefined }; const selectTemplateEnv = async (input, state) => { const quickPickItems = templateEnvs.map((env) => ({ label: (0, helpers_1.getEnvDisplayInfo)(env), pythonEnvironment: env, picked: env === templateEnvironment, description: (0, helpers_1.getDisplayPath)(env.path), })); const templateEnv = (await input.showQuickPick({ title: 'Select Python Environment to be used as a template for Virtual Environment', placeholder: 'Select Python Environment', acceptFilterBoxTextAsSelection: false, canGoBack: false, matchOnDescription: true, matchOnDetail: true, sortByLabel: false, step: 3, totalSteps: 3, items: quickPickItems, })); state.templateEnvironment = templateEnv === null || templateEnv === void 0 ? void 0 : templateEnv.pythonEnvironment; }; const specifyDirectory = async (input, state) => { const browseButton = { iconPath: new vscode_1.ThemeIcon('folder'), tooltip: 'Select a folder', }; let selectDirectory = true; while (selectDirectory) { const enterDirectoryPrompt = () => input.showInputBox({ title: 'Enter fully qualified path to where the venv would be created', value: (currentWorkspaceUri === null || currentWorkspaceUri === void 0 ? void 0 : currentWorkspaceUri.fsPath) || '', step: 2, totalSteps: 3, prompt: 'Directory', validate: async (value) => { if (!value && !currentWorkspaceUri) { return 'Please specify a directory or click the browse button'; } if (!value) { return 'Enter a name'; } if (!(await fs.pathExists(value))) { return 'Invalid directory'; } const targetVenvDir = path.join(value, state.name); if (await fs.pathExists(targetVenvDir)) { return `Virtual folder '${(0, helpers_1.getDisplayPath)(targetVenvDir)}' already exists`; } }, buttons: [browseButton], }); const directory = await enterDirectoryPrompt(); if (directory === browseButton) { const dir = await vscode_1.window.showOpenDialog({ canSelectFiles: false, canSelectFolders: true, canSelectMany: false, defaultUri: currentWorkspaceUri, openLabel: 'Select Folder', title: 'Select destination for Virtual Environment', }); if (Array.isArray(dir) && dir.length) { const targetVenvDir = path.join(dir[0].fsPath, state.name); if (await fs.pathExists(targetVenvDir)) { void vscode_1.window.showErrorMessage('A folder with the same name already exists', { modal: true, detail: targetVenvDir, }); } else { state.dir = dir[0].fsPath; selectDirectory = false; return selectTemplateEnv(input, state); } } } else if (typeof directory === 'string') { selectDirectory = false; const targetVenvDir = path.join(directory.trim(), state.name); if (!(await fs.pathExists(directory.trim()))) { void vscode_1.window.showErrorMessage('Invalid target directory for a Virtual Environment', { modal: true, detail: directory, }); } else if (await fs.pathExists(targetVenvDir)) { void vscode_1.window.showErrorMessage('A folder with the same name already exists', { modal: true, detail: targetVenvDir, }); } else { state.dir = directory.trim(); selectDirectory = false; return selectTemplateEnv(input, state); } } else { selectDirectory = false; } } }; const specifyName = async (input, state) => { const name = await input.showInputBox({ title: 'Enter the name of the virtual environment', value: '.venv', step: 1, totalSteps: 3, prompt: 'Name', validate: async (value) => { if (!value) { return 'Enter a name'; } }, }); if (name) { state.name = name.trim(); return specifyDirectory(input, state); } }; const multistepInput = new multiStepInput_1.MultiStepInput(new applicationShell_1.ApplicationShell()); await multistepInput.run(specifyName, initialState); if (!initialState.dir.trim() || !initialState.name.trim() || !initialState.templateEnvironment) { return; } if (!(await fs.pathExists(initialState.dir))) { return; } if (await fs.pathExists(path.join(initialState.dir, initialState.name))) { return; } try { await vscode_1.window.withProgress({ location: vscode_1.ProgressLocation.Notification, title: `Creating environment ${initialState.name}`, cancellable: true, }, async (progress, token) => { (0, logging_1.traceInfo)(`Creating environment ${initialState.name}`); (0, logging_1.traceInfo)([initialState.templateEnvironment.path, '-m', 'venv', initialState.name].join(' ')); const result = await (0, rawProcessApis_1.execObservable)(initialState.templateEnvironment.path, ['-m', 'venv', initialState.name], { timeout: 60000, cwd: initialState.dir, token, }); await new Promise((resolve) => { result.out.subscribe({ next: (output) => { (0, logging_1.traceInfo)(output.out); progress.report({ message: output.out }); }, complete: () => resolve(), }); }); }); void vscode_1.commands.executeCommand('python.envManager.refresh', false); } catch (ex) { (0, logging_1.traceError)(`Failed to create environment`, ex); vscode_1.window.showErrorMessage(`Failed to create environment ${initialState.name}, ${ex}`); } } exports.createEnvOld = createEnvOld; /***/ }), /***/ "./src/environments/utils.ts": /*!***********************************!*\ !*** ./src/environments/utils.ts ***! \***********************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEnvironmentType = exports.isNonPythonCondaEnvironment = exports.isCondaEnvironment = exports.getInterpreterDetailsFromExecPath = exports.getResolvedActiveInterpreter = void 0; const python_extension_1 = __webpack_require__(/*! @vscode/python-extension */ "./node_modules/@vscode/python-extension/out/main.js"); const info_1 = __webpack_require__(/*! ../client/pythonEnvironments/info */ "./src/client/pythonEnvironments/info/index.ts"); async function getResolvedActiveInterpreter(resource) { const api = await python_extension_1.PythonExtension.api(); const activeEnv = api.environments.getActiveEnvironmentPath(resource); return activeEnv ? api.environments.resolveEnvironment(activeEnv) : undefined; } exports.getResolvedActiveInterpreter = getResolvedActiveInterpreter; async function getInterpreterDetailsFromExecPath(execPath) { const api = await python_extension_1.PythonExtension.api(); return api.environments.resolveEnvironment(execPath); } exports.getInterpreterDetailsFromExecPath = getInterpreterDetailsFromExecPath; const KnownEnvironmentToolsToEnvironmentTypeMapping = new Map([ ['Conda', info_1.EnvironmentType.Conda], ['Pipenv', info_1.EnvironmentType.Pipenv], ['Poetry', info_1.EnvironmentType.Poetry], ['Pyenv', info_1.EnvironmentType.Pyenv], ['Unknown', info_1.EnvironmentType.Unknown], ['Venv', info_1.EnvironmentType.Venv], ['VirtualEnv', info_1.EnvironmentType.VirtualEnv], ['VirtualEnvWrapper', info_1.EnvironmentType.VirtualEnvWrapper], ]); function isCondaEnvironment(env) { return getEnvironmentType(env) === info_1.EnvironmentType.Conda; } exports.isCondaEnvironment = isCondaEnvironment; function isNonPythonCondaEnvironment(env) { return getEnvironmentType(env) === info_1.EnvironmentType.Conda && !env.executable.uri; } exports.isNonPythonCondaEnvironment = isNonPythonCondaEnvironment; function getEnvironmentType({ tools }) { tools = tools.map((tool) => tool.toLowerCase()); for (const tool of tools) { if (tool === info_1.EnvironmentType.Conda.toLowerCase()) { return info_1.EnvironmentType.Conda; } if (tool === info_1.EnvironmentType.Venv.toLowerCase()) { return info_1.EnvironmentType.Venv; } if (tool === info_1.EnvironmentType.VirtualEnv.toLowerCase()) { return info_1.EnvironmentType.VirtualEnv; } if (tool === info_1.EnvironmentType.VirtualEnvWrapper.toLowerCase()) { return info_1.EnvironmentType.VirtualEnvWrapper; } if (tool === info_1.EnvironmentType.Poetry.toLowerCase()) { return info_1.EnvironmentType.Poetry; } if (tool === info_1.EnvironmentType.Pipenv.toLowerCase()) { return info_1.EnvironmentType.Pipenv; } if (tool === info_1.EnvironmentType.Pyenv.toLowerCase()) { return info_1.EnvironmentType.Pyenv; } if (KnownEnvironmentToolsToEnvironmentTypeMapping.has(tool)) { return KnownEnvironmentToolsToEnvironmentTypeMapping.get(tool); } } return info_1.EnvironmentType.Unknown; } exports.getEnvironmentType = getEnvironmentType; /***/ }), /***/ "./src/environments/view/commands.ts": /*!*******************************************!*\ !*** ./src/environments/view/commands.ts ***! \*******************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.registerCommands = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const packages_1 = __webpack_require__(/*! ../packages */ "./src/environments/packages.ts"); const logging_1 = __webpack_require__(/*! ../../client/logging */ "./src/client/logging/index.ts"); const types_1 = __webpack_require__(/*! ./types */ "./src/environments/view/types.ts"); const foldersTreeDataProvider_1 = __webpack_require__(/*! ./foldersTreeDataProvider */ "./src/environments/view/foldersTreeDataProvider.ts"); const environmentsTreeDataProvider_1 = __webpack_require__(/*! ./environmentsTreeDataProvider */ "./src/environments/view/environmentsTreeDataProvider.ts"); const resourceLifecycle_1 = __webpack_require__(/*! ../../client/common/utils/resourceLifecycle */ "./src/client/common/utils/resourceLifecycle.ts"); const async_1 = __webpack_require__(/*! ../../client/common/utils/async */ "./src/client/common/utils/async.ts"); function triggerChanges(item) { foldersTreeDataProvider_1.WorkspaceFoldersTreeDataProvider.instance.triggerChanges(item); environmentsTreeDataProvider_1.PythonEnvironmentsTreeDataProvider.instance.triggerChanges(item); } function registerCommands(context) { const disposables = []; disposables.push(vscode_1.commands.registerCommand('python.envManager.updatePackage', async (pkg) => { const yes = await vscode_1.window.showWarningMessage(`Are you sure you want to update the package '${pkg.pkg.name} to the latest version ${pkg.latestVersion}?`, { modal: true }, 'Yes', 'No'); if (!yes || yes === 'No') { return; } pkg.status = 'DetectingLatestVersion'; triggerChanges(pkg); await (0, packages_1.updatePackage)(pkg.env, pkg.pkg).catch((ex) => (0, logging_1.traceError)(`Failed to update package ${pkg.pkg.name} in ${pkg.env.id}`, ex)); pkg.status = undefined; triggerChanges(pkg.parent); })); disposables.push(vscode_1.commands.registerCommand('python.envManager.uninstallPackage', async (pkg) => { const yes = await vscode_1.window.showWarningMessage(`Are you sure you want to uninstall the package '${pkg.pkg.name}'?`, { modal: true }, 'Yes', 'No'); if (yes === 'No') { return; } pkg.status = 'UnInstalling'; triggerChanges(pkg); (0, packages_1.uninstallPackage)(pkg.env, pkg.pkg); pkg.status = undefined; triggerChanges(pkg.parent); await (0, async_1.sleep)(1000); triggerChanges(pkg.parent); })); disposables.push(vscode_1.commands.registerCommand('python.envManager.searchAndInstallPackage', async (pkg) => { const result = await (0, packages_1.searchPackage)(pkg.env).catch((ex) => (0, logging_1.traceError)(`Failed to install a package in ${pkg.env.id}`, ex)); if (!result) { return; } await (0, packages_1.installPackage)(pkg.env, result); triggerChanges(pkg); })); disposables.push(vscode_1.commands.registerCommand('python.envManager.exportEnvironment', async (options) => { var _a; const env = options instanceof types_1.EnvironmentWrapper ? options.env : (_a = options.asNode()) === null || _a === void 0 ? void 0 : _a.env; if (!env) { return; } const exportedData = await (0, packages_1.exportPackages)(env).catch((ex) => (0, logging_1.traceError)(`Failed to export env ${env.id}`, ex)); if (!exportedData) { return; } const doc = await vscode_1.workspace.openTextDocument({ content: `# ${exportedData.file}\n\n${exportedData.contents}`, language: exportedData.language, }); vscode_1.window.showTextDocument(doc); })); disposables.push(vscode_1.commands.registerCommand('python.envManager.updateAllPackages', async (pkg) => { const yes = await vscode_1.window.showWarningMessage(`Are you sure you want to update all the packages?`, { modal: true }, 'Yes', 'No'); if (yes === 'No') { return; } pkg.packages.forEach((e) => { e.status = 'UpdatingToLatest'; triggerChanges(e); }); await (0, packages_1.updatePackages)(pkg.env); triggerChanges(pkg); })); disposables.push(vscode_1.commands.registerCommand('python.envManager.refreshPackages', async (pkg) => triggerChanges(pkg))); context.subscriptions.push(new vscode_1.Disposable(() => (0, resourceLifecycle_1.disposeAll)(disposables))); } exports.registerCommands = registerCommands; /***/ }), /***/ "./src/environments/view/envTreeDataProvider.ts": /*!******************************************************!*\ !*** ./src/environments/view/envTreeDataProvider.ts ***! \******************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PythonEnvironmentTreeDataProvider = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const info_1 = __webpack_require__(/*! ../../client/pythonEnvironments/info */ "./src/client/pythonEnvironments/info/index.ts"); const async_1 = __webpack_require__(/*! ../../client/common/utils/async */ "./src/client/common/utils/async.ts"); const packages_1 = __webpack_require__(/*! ../packages */ "./src/environments/packages.ts"); const envCreation_1 = __webpack_require__(/*! ../envCreation */ "./src/environments/envCreation.ts"); const logging_1 = __webpack_require__(/*! ../../client/logging */ "./src/client/logging/index.ts"); const types_1 = __webpack_require__(/*! ./types */ "./src/environments/view/types.ts"); const resourceLifecycle_1 = __webpack_require__(/*! ../../client/common/utils/resourceLifecycle */ "./src/client/common/utils/resourceLifecycle.ts"); const utils_1 = __webpack_require__(/*! ../utils */ "./src/environments/utils.ts"); let PythonEnvironmentTreeDataProvider = class PythonEnvironmentTreeDataProvider { constructor(api) { this.api = api; this.disposables = []; this.outdatedPackages = new Map(); this._changeTreeData = new vscode_1.EventEmitter(); this.onDidChangeTreeData = this._changeTreeData.event; } dispose() { this._changeTreeData.dispose(); (0, resourceLifecycle_1.disposeAll)(this.disposables); } async getTreeItem(element, defaultState = vscode_1.TreeItemCollapsibleState.Collapsed) { if (element instanceof types_1.EnvironmentWrapper) { return element.asTreeItem(this.api, defaultState); } if (element instanceof types_1.EnvironmentInformationWrapper) { const tree = new vscode_1.TreeItem('Info', defaultState); tree.contextValue = 'envInfo'; tree.iconPath = new vscode_1.ThemeIcon('info'); return tree; } if (element instanceof types_1.Package) { return element.asTreeItem(); } if (element instanceof types_1.PackageWrapper) { return element.asTreeItem(defaultState); } if (element instanceof types_1.EnvironmentInfo) { const tree = new vscode_1.TreeItem(element.label); tree.description = element.value; tree.contextValue = 'info'; tree.tooltip = element.value; return tree; } const tree = new vscode_1.TreeItem(element, defaultState); const createContext = (0, envCreation_1.canEnvBeCreated)(element) ? 'canCreate' : 'cannotCreate'; tree.contextValue = `envType:${createContext}:${element} `; if (element === info_1.EnvironmentType.Conda && this.condaInfo) { tree.description = this.condaInfo.conda_version; } else if (element === info_1.EnvironmentType.Pyenv && this.pyEnvVersion) { tree.description = this.pyEnvVersion; } tree.iconPath = new vscode_1.ThemeIcon('folder-library'); return tree; } async getChildren(element) { if (!element) { return []; } if (element instanceof types_1.Package) { return []; } if (element instanceof types_1.EnvironmentInformationWrapper) { return (0, types_1.getEnvironmentInfo)({ api: this.api, id: element.env.id }); } if (element instanceof types_1.EnvironmentInfo) { return []; } if (element instanceof types_1.EnvironmentWrapper) { if ((0, utils_1.isNonPythonCondaEnvironment)(element.env)) { return [new types_1.EnvironmentInformationWrapper(element.env)]; } return [ new types_1.EnvironmentInformationWrapper(element.env), new types_1.PackageWrapper(element.env, element.owningFolder), ]; } if (element instanceof types_1.PackageWrapper) { const env = this.api.environments.known.find((e) => e.id === element.env.id); if (!env) { return []; } const packagesByEnv = new Map(); const completedPackages = (0, async_1.createDeferred)(); (0, packages_1.getOutdatedPackages)(env) .then((outdatedPackages) => completedPackages.promise.then((installedPackages) => { this.outdatedPackages.set(env.id, outdatedPackages); for (const [pkgId, installedPackage] of installedPackages) { installedPackage.latestVersion = outdatedPackages.get(pkgId); installedPackage.status = undefined; this._changeTreeData.fire(installedPackage); } })) .catch((ex) => (0, logging_1.traceError)(`Failed to get outdated packages for ${env.id}`, ex)); return (0, packages_1.getPackages)(env).then((pkgs) => { const packages = pkgs.map((pkg) => { const item = new types_1.Package(element, env, pkg, element.owningFolder); const packagesMap = packagesByEnv.get(env.id) || new Map(); packagesByEnv.set(env.id, packagesMap); packagesMap.set(pkg.name, item); return item; }); completedPackages.resolve(packagesByEnv.get(env.id) || new Map()); return packages; }); } return []; } }; PythonEnvironmentTreeDataProvider = __decorate([ (0, inversify_1.injectable)() ], PythonEnvironmentTreeDataProvider); exports.PythonEnvironmentTreeDataProvider = PythonEnvironmentTreeDataProvider; /***/ }), /***/ "./src/environments/view/environmentsTreeDataProvider.ts": /*!***************************************************************!*\ !*** ./src/environments/view/environmentsTreeDataProvider.ts ***! \***************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var PythonEnvironmentsTreeDataProvider_1; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.refreshUntilNewEnvIsAvailable = exports.PythonEnvironmentsTreeDataProvider = void 0; const inversify_1 = __webpack_require__(/*! inversify */ "./node_modules/inversify/lib/inversify.js"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const info_1 = __webpack_require__(/*! ../../client/pythonEnvironments/info */ "./src/client/pythonEnvironments/info/index.ts"); const conda_1 = __webpack_require__(/*! ../tools/conda */ "./src/environments/tools/conda.ts"); const misc_1 = __webpack_require__(/*! ../../client/common/utils/misc */ "./src/client/common/utils/misc.ts"); const cache_1 = __webpack_require__(/*! ../cache */ "./src/environments/cache.ts"); const async_1 = __webpack_require__(/*! ../../client/common/utils/async */ "./src/client/common/utils/async.ts"); const utils_1 = __webpack_require__(/*! ../utils */ "./src/environments/utils.ts"); const pyenv_1 = __webpack_require__(/*! ../tools/pyenv */ "./src/environments/tools/pyenv.ts"); const envCreation_1 = __webpack_require__(/*! ../envCreation */ "./src/environments/envCreation.ts"); const types_1 = __webpack_require__(/*! ./types */ "./src/environments/view/types.ts"); const envTreeDataProvider_1 = __webpack_require__(/*! ./envTreeDataProvider */ "./src/environments/view/envTreeDataProvider.ts"); const venvCreationProvider_1 = __webpack_require__(/*! ../../client/pythonEnvironments/creation/provider/venvCreationProvider */ "./src/client/pythonEnvironments/creation/provider/venvCreationProvider.ts"); const envDeletion_1 = __webpack_require__(/*! ../envDeletion */ "./src/environments/envDeletion.ts"); const poetry_1 = __webpack_require__(/*! ../tools/poetry */ "./src/environments/tools/poetry.ts"); let PythonEnvironmentsTreeDataProvider = PythonEnvironmentsTreeDataProvider_1 = class PythonEnvironmentsTreeDataProvider { constructor(context, api, iocContainer) { this.context = context; this.api = api; this.iocContainer = iocContainer; this.interpreterInfo = new Map(); this.disposables = []; this.environmentTypes = new Map(); this._changeTreeData = new vscode_1.EventEmitter(); this.onDidChangeTreeData = this._changeTreeData.event; this.refreshing = false; this.envTreeDataProvider = new envTreeDataProvider_1.PythonEnvironmentTreeDataProvider(api); this.envTreeDataProvider.onDidChangeTreeData((e) => this._changeTreeData.fire(e), this, this.disposables); PythonEnvironmentsTreeDataProvider_1.instance = this; this.refresh(false); api.environments.onDidChangeEnvironments(this.rebuildEnvironmentTypesIfRequired, this, this.disposables); api.environments.onDidChangeEnvironments((e) => { if (e.type === 'add' || e.type === 'remove') { const envType = (0, utils_1.getEnvironmentType)(e.env); if (this.environmentTypes.has(envType)) { this._changeTreeData.fire(envType); } else { this._changeTreeData.fire(); } } else if (e.type === 'update' && this.interpreterInfo.get(e.env.id)) { this._changeTreeData.fire(this.interpreterInfo.get(e.env.id)); const envType = (0, utils_1.getEnvironmentType)(e.env); if (!this.environmentTypes.has(envType)) { this._changeTreeData.fire(); } } }, this, this.disposables); this.rebuildEnvironmentTypesIfRequired(); } triggerChanges(node) { this._changeTreeData.fire(node); } dispose() { this._changeTreeData.dispose(); this.envTreeDataProvider.dispose(); } rebuildEnvironmentTypesIfRequired() { const envs = new Set(this.api.environments.known.map((item) => (0, utils_1.getEnvironmentType)(item))); if (envs.size !== this.environmentTypes.size) { if (!envs.has(info_1.EnvironmentType.Venv) && !this.environmentTypes.has(info_1.EnvironmentType.Venv) && (0, venvCreationProvider_1.canCreateVenv)(this.api.environments.known)) { envs.add(info_1.EnvironmentType.Venv); } Array.from(envs) .filter((type) => !this.environmentTypes.has(type)) .forEach((type) => this.environmentTypes.set(type, new types_1.EnvironmentTypeWrapper(type))); this._changeTreeData.fire(); } } changeTreeData(item) { this._changeTreeData.fire(item); } async getTreeItem(element) { if (typeof element === 'string') { const tree = new vscode_1.TreeItem(element === info_1.EnvironmentType.Unknown ? 'Global' : element, vscode_1.TreeItemCollapsibleState.Collapsed); const createContext = (0, envCreation_1.canEnvBeCreated)(element) ? 'canCreate' : 'cannotCreate'; tree.contextValue = `envType:${createContext}:${element} `; if (element === info_1.EnvironmentType.Conda && this.condaInfo) { tree.description = this.condaInfo.conda_version; } else if (element === info_1.EnvironmentType.Pyenv && this.pyEnvVersion) { tree.description = this.pyEnvVersion; } else if (element === info_1.EnvironmentType.Poetry && this.poetryVersion) { tree.description = this.poetryVersion; } tree.iconPath = new vscode_1.ThemeIcon('folder-library'); return tree; } return this.envTreeDataProvider.getTreeItem(element); } async getChildren(element) { if (!element) { return Array.from(this.environmentTypes.keys()).sort(); } if (typeof element !== 'string') { return this.envTreeDataProvider.getChildren(element); } return this.api.environments.known .filter((env) => (0, utils_1.getEnvironmentType)(env) === element) .sort((a, b) => (0, types_1.getEnvLabel)(a).localeCompare((0, types_1.getEnvLabel)(b))) .map((env) => { if (!this.interpreterInfo.has(env.id)) { this.interpreterInfo.set(env.id, new types_1.EnvironmentWrapper(env, envDeletion_1.canEnvBeDeleted)); } return this.interpreterInfo.get(env.id); }) .sort((a, b) => { if ((0, utils_1.isNonPythonCondaEnvironment)(a.env) && !(0, utils_1.isNonPythonCondaEnvironment)(b.env)) { return 1; } if (!(0, utils_1.isNonPythonCondaEnvironment)(a.env) && (0, utils_1.isNonPythonCondaEnvironment)(b.env)) { return -1; } return (a.asTreeItem(this.api).label || '') .toString() .localeCompare((b.asTreeItem(this.api).label || '').toString()); }); } async refresh(clearCache = false) { if (this.refreshing) { return; } this.refreshing = true; vscode_1.commands.executeCommand('setContext', 'isRefreshingPythonEnvironments', true); try { this.refreshToolVersions(); const refreshPromise = this.api.environments.refreshEnvironments({ forceRefresh: clearCache }); await (0, cache_1.clearCacheIfNewVersionInstalled)(this.context, clearCache).then(misc_1.noop, misc_1.noop); await refreshPromise.catch(misc_1.noop); this._changeTreeData.fire(); this.refreshToolVersions(); } finally { this.refreshing = false; vscode_1.commands.executeCommand('setContext', 'isRefreshingPythonEnvironments', false).then(misc_1.noop, misc_1.noop); } } refreshToolVersions() { (0, conda_1.getCondaVersion)() .then((info) => { if (info) { this.condaInfo = info; if (this.environmentTypes.has(info_1.EnvironmentType.Conda)) { this._changeTreeData.fire(info_1.EnvironmentType.Conda); } } }) .catch(misc_1.noop); (0, pyenv_1.getPyEnvVersion)(this.iocContainer) .then((version) => { if (version) { this.pyEnvVersion = version; if (this.environmentTypes.has(info_1.EnvironmentType.Pyenv)) { this._changeTreeData.fire(info_1.EnvironmentType.Pyenv); } } }) .catch(misc_1.noop); (0, poetry_1.getPoetryVersion)() .then((version) => { if (version) { this.poetryVersion = version; if (this.environmentTypes.has(info_1.EnvironmentType.Poetry)) { this._changeTreeData.fire(info_1.EnvironmentType.Poetry); } } }) .catch(misc_1.noop); } }; PythonEnvironmentsTreeDataProvider = PythonEnvironmentsTreeDataProvider_1 = __decorate([ (0, inversify_1.injectable)() ], PythonEnvironmentsTreeDataProvider); exports.PythonEnvironmentsTreeDataProvider = PythonEnvironmentsTreeDataProvider; async function refreshUntilNewEnvIsAvailable(expectedEnvInfo) { const initialEnvCount = PythonEnvironmentsTreeDataProvider.environments.length; const isEnvAvailable = () => { if (!expectedEnvInfo.path && !expectedEnvInfo.name) { return true; } if (PythonEnvironmentsTreeDataProvider.environments.length > initialEnvCount) { return true; } return PythonEnvironmentsTreeDataProvider.environments.some((env) => { var _a; if (expectedEnvInfo.type !== (0, utils_1.getEnvironmentType)(env)) { return; } if (expectedEnvInfo.name && ((_a = env.environment) === null || _a === void 0 ? void 0 : _a.name) && env.environment.name.includes(expectedEnvInfo.name)) { return true; } if (expectedEnvInfo.path && env.path.includes(expectedEnvInfo.path)) { return true; } return false; }); }; for (let index = 0; index < 5; index += 1) { await PythonEnvironmentsTreeDataProvider.instance.refresh(); if (isEnvAvailable()) { return; } (0, async_1.sleep)(2000); } } exports.refreshUntilNewEnvIsAvailable = refreshUntilNewEnvIsAvailable; /***/ }), /***/ "./src/environments/view/foldersTreeDataProvider.ts": /*!**********************************************************!*\ !*** ./src/environments/view/foldersTreeDataProvider.ts ***! \**********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WorkspaceFoldersTreeDataProvider = exports.WorkspaceFolderEnvironments = exports.WorkspaceFolderWrapper = exports.ActiveWorkspaceEnvironment = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const types_1 = __webpack_require__(/*! ./types */ "./src/environments/view/types.ts"); const envTreeDataProvider_1 = __webpack_require__(/*! ./envTreeDataProvider */ "./src/environments/view/envTreeDataProvider.ts"); const resourceLifecycle_1 = __webpack_require__(/*! ../../client/common/utils/resourceLifecycle */ "./src/client/common/utils/resourceLifecycle.ts"); const cache_1 = __webpack_require__(/*! ../cache */ "./src/environments/cache.ts"); const misc_1 = __webpack_require__(/*! ../../client/common/utils/misc */ "./src/client/common/utils/misc.ts"); const poetry_1 = __webpack_require__(/*! ../tools/poetry */ "./src/environments/tools/poetry.ts"); const utils_1 = __webpack_require__(/*! ../utils */ "./src/environments/utils.ts"); class ActiveWorkspaceEnvironment { constructor(folder, api, canEnvBeDeleted) { this.folder = folder; this.api = api; this.canEnvBeDeleted = canEnvBeDeleted; } asNode(api = this.api) { const envPath = api.environments.getActiveEnvironmentPath(this.folder.uri); const env = envPath ? api.environments.known.find((e) => e.id === envPath.id) : undefined; if (env) { return new types_1.EnvironmentWrapper(env, this.canEnvBeDeleted, true, this.folder); } } asTreeItem(api, envTreeProvider) { var _a; const env = this.asNode(api); if (env) { return envTreeProvider.getTreeItem(env, vscode_1.TreeItemCollapsibleState.Expanded); } const label = (((_a = vscode_1.workspace.workspaceFolders) === null || _a === void 0 ? void 0 : _a.length) || 0) > 1 ? `No Active Environment for ${this.folder.name}` : `No Active Environment`; const tree = new vscode_1.TreeItem(label, vscode_1.TreeItemCollapsibleState.Collapsed); tree.iconPath = new vscode_1.ThemeIcon('folder'); return tree; } } exports.ActiveWorkspaceEnvironment = ActiveWorkspaceEnvironment; class WorkspaceFolderWrapper { constructor(folder, canEnvBeDeleted) { this.folder = folder; this.canEnvBeDeleted = canEnvBeDeleted; } asTreeItem(api) { var _a; if (((_a = vscode_1.workspace.workspaceFolders) === null || _a === void 0 ? void 0 : _a.length) === 1) { const envPath = api.environments.getActiveEnvironmentPath(this.folder.uri); const env = envPath ? api.environments.known.find((e) => e.id === envPath.id) : undefined; if (env) { return new types_1.EnvironmentWrapper(env, this.canEnvBeDeleted).asTreeItem(api); } } const tree = new vscode_1.TreeItem(this.folder.name, vscode_1.TreeItemCollapsibleState.Expanded); tree.iconPath = new vscode_1.ThemeIcon('folder'); return tree; } } exports.WorkspaceFolderWrapper = WorkspaceFolderWrapper; class WorkspaceFolderEnvironments { constructor(folder) { this.folder = folder; } asTreeItem() { const tree = new vscode_1.TreeItem('Workspace Envs', vscode_1.TreeItemCollapsibleState.Expanded); tree.iconPath = new vscode_1.ThemeIcon('folder'); return tree; } } exports.WorkspaceFolderEnvironments = WorkspaceFolderEnvironments; class WorkspaceFoldersTreeDataProvider { constructor(context, api, canEnvBeDeleted) { this.context = context; this.api = api; this.canEnvBeDeleted = canEnvBeDeleted; this._changeTreeData = new vscode_1.EventEmitter(); this.onDidChangeTreeData = this._changeTreeData.event; this.disposables = []; this.activeWorkspaceEnvs = new Map(); this.refreshing = false; WorkspaceFoldersTreeDataProvider.instance = this; this.envTreeDataProvider = new envTreeDataProvider_1.PythonEnvironmentTreeDataProvider(api); this.envTreeDataProvider.onDidChangeTreeData((e) => this._changeTreeData.fire(e), this, this.disposables); api.environments.onDidChangeActiveEnvironmentPath((e) => { if (!Array.isArray(vscode_1.workspace.workspaceFolders) || vscode_1.workspace.workspaceFolders.length <= 1) { this._changeTreeData.fire(); } else { const node = e.resource && this.activeWorkspaceEnvs.get(e.resource.uri.toString()); if (node) { this._changeTreeData.fire(node); } } }); api.environments.onDidChangeEnvironments((e) => { var _a; if ((e.type === 'add' || e.type !== 'update') && !((_a = e.env.environment) === null || _a === void 0 ? void 0 : _a.workspaceFolder)) { this._changeTreeData.fire(); } }); } triggerChanges(node) { this._changeTreeData.fire(node); } async refresh(clearCache = false) { if (this.refreshing) { return; } this.refreshing = true; vscode_1.commands.executeCommand('setContext', 'isRefreshingPythonEnvironments', true); try { const refreshPromise = this.api.environments.refreshEnvironments({ forceRefresh: clearCache }); await (0, cache_1.clearCacheIfNewVersionInstalled)(this.context, clearCache).then(misc_1.noop, misc_1.noop); await refreshPromise.catch(misc_1.noop); this._changeTreeData.fire(); this.refreshToolVersions(); } finally { this.refreshing = false; vscode_1.commands.executeCommand('setContext', 'isRefreshingPythonEnvironments', false).then(misc_1.noop, misc_1.noop); } } refreshToolVersions() { throw new Error('Method not implemented.'); } dispose() { (0, resourceLifecycle_1.disposeAll)(this.disposables); } async getTreeItem(element) { if (element instanceof WorkspaceFolderWrapper || element instanceof WorkspaceFolderEnvironments || element instanceof ActiveWorkspaceEnvironment) { return element.asTreeItem(this.api, this.envTreeDataProvider); } return this.envTreeDataProvider.getTreeItem(element); } getWorkspaceActiveEnv(folder) { const item = this.activeWorkspaceEnvs.get(folder.uri.toString()) || new ActiveWorkspaceEnvironment(folder, this.api, this.canEnvBeDeleted); this.activeWorkspaceEnvs.set(folder.uri.toString(), item); return item; } async getChildren(element) { if (!element) { if (!Array.isArray(vscode_1.workspace.workspaceFolders) || !vscode_1.workspace.workspaceFolders.length) { return []; } if (Array.isArray(vscode_1.workspace.workspaceFolders) && vscode_1.workspace.workspaceFolders.length > 1) { return vscode_1.workspace.workspaceFolders.map((e) => new WorkspaceFolderWrapper(e, this.canEnvBeDeleted)); } const folderUri = vscode_1.workspace.workspaceFolders[0]; const workspaceEnvs = await getAllEnvsBelongingToWorkspaceFolder(folderUri, this.api, this.canEnvBeDeleted); const items = [this.getWorkspaceActiveEnv(folderUri)]; if (workspaceEnvs.length > 1) { items.push(new WorkspaceFolderEnvironments(folderUri)); } else if (workspaceEnvs.length === 1) { const activeEnv = this.api.environments.getActiveEnvironmentPath(folderUri.uri); if (activeEnv.id !== workspaceEnvs[0].id) { items.push(new WorkspaceFolderEnvironments(folderUri)); } } return items; } if (element instanceof WorkspaceFolderEnvironments) { return getAllEnvsBelongingToWorkspaceFolder(element.folder, this.api, this.canEnvBeDeleted); } if (element instanceof ActiveWorkspaceEnvironment) { const env = element.asNode(this.api); return env ? this.envTreeDataProvider.getChildren(env) : []; } if (element instanceof WorkspaceFolderWrapper) { const items = [this.getWorkspaceActiveEnv(element.folder)]; const workspaceEnvs = await getAllEnvsBelongingToWorkspaceFolder(element.folder, this.api, this.canEnvBeDeleted); if (workspaceEnvs.length) { items.push(new WorkspaceFolderEnvironments(element.folder)); } return items; } return this.envTreeDataProvider.getChildren(element); } } exports.WorkspaceFoldersTreeDataProvider = WorkspaceFoldersTreeDataProvider; async function getAllEnvsBelongingToWorkspaceFolder(folder, api, canEnvBeDeleted) { const envs = api.environments.known .filter((e) => { var _a; if (!((_a = e.environment) === null || _a === void 0 ? void 0 : _a.folderUri)) { return false; } return e.environment.folderUri.fsPath.toLowerCase().startsWith(folder.uri.fsPath.toLowerCase()); }) .map((e) => new types_1.EnvironmentWrapper(e, canEnvBeDeleted, undefined, folder)); if (!(0, poetry_1.hasPoetryEnvs)(envs.map((e) => e.env)) && (0, poetry_1.hasPoetryEnvs)(api.environments.known)) { const poetryEnvsInWorkspaceFolder = await (0, poetry_1.getPoetryEnvironments)(folder, api.environments.known); envs.push(...poetryEnvsInWorkspaceFolder.map((e) => new types_1.EnvironmentWrapper(e, canEnvBeDeleted, undefined, folder))); } return envs.sort((a, b) => { if ((0, utils_1.isNonPythonCondaEnvironment)(a.env) && !(0, utils_1.isNonPythonCondaEnvironment)(b.env)) { return 1; } if (!(0, utils_1.isNonPythonCondaEnvironment)(a.env) && (0, utils_1.isNonPythonCondaEnvironment)(b.env)) { return -1; } return (a.asTreeItem(api).label || '').toString().localeCompare((b.asTreeItem(api).label || '').toString()); }); } /***/ }), /***/ "./src/environments/view/types.ts": /*!****************************************!*\ !*** ./src/environments/view/types.ts ***! \****************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEnvironmentInfo = exports.getEnvLabel = exports.PackageWrapper = exports.EnvironmentInformationWrapper = exports.EnvironmentInfo = exports.EnvironmentWrapper = exports.EnvironmentTypeWrapper = exports.Package = void 0; const path = __webpack_require__(/*! path */ "path"); const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); const constants_1 = __webpack_require__(/*! ../../client/constants */ "./src/client/constants.ts"); const info_1 = __webpack_require__(/*! ../../client/pythonEnvironments/info */ "./src/client/pythonEnvironments/info/index.ts"); const helpers_1 = __webpack_require__(/*! ../helpers */ "./src/environments/helpers.ts"); const utils_1 = __webpack_require__(/*! ../utils */ "./src/environments/utils.ts"); class Package { constructor(parent, env, pkg, owningFolder) { this.parent = parent; this.env = env; this.pkg = pkg; this.owningFolder = owningFolder; this.status = 'DetectingLatestVersion'; parent.packages.push(this); } asTreeItem() { const tree = new vscode_1.TreeItem(this.pkg.name); tree.contextValue = 'package:'; tree.description = this.pkg.version; let tooltip = ''; if ('channel' in this.pkg) { tooltip = [this.pkg.channel || '', this.pkg.base_url || ''].filter((item) => item.trim().length).join(': '); } if (this.latestVersion) { tree.contextValue = 'package:outdated'; tree.tooltip = new vscode_1.MarkdownString(`$(warning): Latest Version: ${this.latestVersion}\n${tooltip}`, true); tree.iconPath = this.status ? new vscode_1.ThemeIcon('loading~spin') : new vscode_1.ThemeIcon('warning'); } else { tree.tooltip = tooltip; tree.iconPath = this.status ? new vscode_1.ThemeIcon('loading~spin') : new vscode_1.ThemeIcon('library'); } if ((0, utils_1.isNonPythonCondaEnvironment)(this.env)) { } else if ((0, utils_1.getEnvironmentType)(this.env) === info_1.EnvironmentType.Poetry && !this.owningFolder) { } else { tree.contextValue = `${tree.contextValue.trim()}:canManagePackages`; } return tree; } } exports.Package = Package; class EnvironmentTypeWrapper { constructor(type) { this.type = type; } } exports.EnvironmentTypeWrapper = EnvironmentTypeWrapper; class EnvironmentWrapper { constructor(env, canEnvBeDeleted, isActiveEnvironment, owningFolder) { this.env = env; this.canEnvBeDeleted = canEnvBeDeleted; this.isActiveEnvironment = isActiveEnvironment; this.owningFolder = owningFolder; } get id() { return this.env.id; } asTreeItem(api, defaultState = vscode_1.TreeItemCollapsibleState.Collapsed) { var _a, _b; const env = api.environments.known.find((e) => e.id === this.env.id); if (!env) { const tree = new vscode_1.TreeItem('Not found', defaultState); tree.description = 'Environment no longer found, please try refreshing'; tree.iconPath = new vscode_1.ThemeIcon('error'); return tree; } const version = env.version ? `${env.version.major}.${env.version.minor}.${env.version.micro} ` : ''; const label = getEnvLabel(env); const activePrefix = ''; const tree = new vscode_1.TreeItem(activePrefix + label + (version.trim() ? ` (${version.trim()})` : ''), defaultState); const isEmptyCondaEnv = (0, utils_1.getEnvironmentType)(env) === info_1.EnvironmentType.Conda && !env.executable.uri; const executable = (0, helpers_1.getDisplayPath)(((_b = (_a = env.environment) === null || _a === void 0 ? void 0 : _a.folderUri) === null || _b === void 0 ? void 0 : _b.fsPath) || env.path); tree.tooltip = [version, executable].filter((item) => !!item).join('\n'); tree.tooltip = new vscode_1.MarkdownString(getEnvironmentInfo({ env }) .map((item) => `**${item.label}**: ${item.value} `) .join('\n')); tree.description = executable; const deleteContext = this.canEnvBeDeleted((0, utils_1.getEnvironmentType)(env)) ? 'canBeDeleted' : 'cannotBeDeleted'; tree.contextValue = `env:${deleteContext}:${(0, utils_1.getEnvironmentType)(env)} `; if (this.isActiveEnvironment) { tree.contextValue = `${tree.contextValue.trim()}:isActiveEnvironment`; } if (env.executable.sysPrefix) { tree.contextValue = `${tree.contextValue.trim()}:hasSysPrefix`; } if ((0, utils_1.isNonPythonCondaEnvironment)(this.env)) { tree.contextValue = `${tree.contextValue.trim()}:isNonPythonCondaEnvironment`; } const defaultIcon = this.isActiveEnvironment === true ? new vscode_1.ThemeIcon('star') : vscode_1.Uri.file(path.join(constants_1.EXTENSION_ROOT_DIR, 'resources/logo.svg')); tree.iconPath = isEmptyCondaEnv ? new vscode_1.ThemeIcon('warning') : defaultIcon; return tree; } } exports.EnvironmentWrapper = EnvironmentWrapper; class EnvironmentInfo { constructor(label, value) { this.label = label; this.value = value; } } exports.EnvironmentInfo = EnvironmentInfo; class EnvironmentInformationWrapper { constructor(env) { this.env = env; } } exports.EnvironmentInformationWrapper = EnvironmentInformationWrapper; class PackageWrapper { constructor(env, owningFolder) { this.env = env; this.owningFolder = owningFolder; this.packages = []; } asTreeItem(defaultState = vscode_1.TreeItemCollapsibleState.Collapsed) { const tree = new vscode_1.TreeItem('Packages', defaultState); tree.contextValue = 'packageContainer'; if ((0, utils_1.isNonPythonCondaEnvironment)(this.env)) { tree.contextValue = `${tree.contextValue.trim()}:isNonPythonCondaEnvironment`; } else if ((0, utils_1.getEnvironmentType)(this.env) === info_1.EnvironmentType.Poetry && !this.owningFolder) { } else { tree.contextValue = `${tree.contextValue.trim()}:canManagePackages`; } tree.iconPath = new vscode_1.ThemeIcon('package'); return tree; } } exports.PackageWrapper = PackageWrapper; function getEnvLabel(env) { var _a, _b; if ((_a = env.environment) === null || _a === void 0 ? void 0 : _a.name) { return env.environment.name; } if ((_b = env.environment) === null || _b === void 0 ? void 0 : _b.folderUri) { return path.basename(env.environment.folderUri.fsPath); } if (env.executable.uri) { return path.basename(path.dirname(path.dirname(env.executable.uri.fsPath))); } return path.basename(env.path); } exports.getEnvLabel = getEnvLabel; function getEnvironmentInfo(options) { var _a, _b, _c, _d, _e, _f; const info = []; let env; if ('api' in options) { env = options.api.environments.known.find((e) => e.id === options.id); if (!env) { return []; } } else { env = options.env; } const isEmptyCondaEnv = (0, utils_1.isCondaEnvironment)(env) && !env.executable.uri; if ((_a = env.environment) === null || _a === void 0 ? void 0 : _a.name) { info.push(new EnvironmentInfo('Name', (_b = env.environment) === null || _b === void 0 ? void 0 : _b.name)); } if (!((_c = env.environment) === null || _c === void 0 ? void 0 : _c.name) && ((_d = env.environment) === null || _d === void 0 ? void 0 : _d.folderUri) && (0, utils_1.isCondaEnvironment)(env)) { info.push(new EnvironmentInfo('Name', path.basename(env.environment.folderUri.fsPath))); } if ((_e = env.version) === null || _e === void 0 ? void 0 : _e.sysVersion) { info.push(new EnvironmentInfo('Version', env.version.sysVersion)); } if (!isEmptyCondaEnv && env.executable.bitness && env.executable.bitness !== 'Unknown') { info.push(new EnvironmentInfo('Architecture', env.executable.bitness)); } if (!isEmptyCondaEnv && env.path) { info.push(new EnvironmentInfo('Executable', (0, helpers_1.getDisplayPath)(env.path))); } if (!isEmptyCondaEnv && env.executable.sysPrefix) { info.push(new EnvironmentInfo('SysPrefix', (0, helpers_1.getDisplayPath)(env.executable.sysPrefix))); } if ((_f = env.environment) === null || _f === void 0 ? void 0 : _f.workspaceFolder) { info.push(new EnvironmentInfo('Folder', (0, helpers_1.getDisplayPath)(env.environment.workspaceFolder.uri.fsPath))); } info.push(new EnvironmentInfo('Environment Type', (0, utils_1.getEnvironmentType)(env))); return info; } exports.getEnvironmentInfo = getEnvironmentInfo; /***/ }), /***/ "./node_modules/@iarna/toml/lib/create-date.js": /*!*****************************************************!*\ !*** ./node_modules/@iarna/toml/lib/create-date.js ***! \*****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const f = __webpack_require__(/*! ./format-num.js */ "./node_modules/@iarna/toml/lib/format-num.js") const DateTime = global.Date class Date extends DateTime { constructor (value) { super(value) this.isDate = true } toISOString () { return `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}` } } module.exports = value => { const date = new Date(value) /* istanbul ignore if */ if (isNaN(date)) { throw new TypeError('Invalid Datetime') } else { return date } } /***/ }), /***/ "./node_modules/@iarna/toml/lib/create-datetime-float.js": /*!***************************************************************!*\ !*** ./node_modules/@iarna/toml/lib/create-datetime-float.js ***! \***************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const f = __webpack_require__(/*! ./format-num.js */ "./node_modules/@iarna/toml/lib/format-num.js") class FloatingDateTime extends Date { constructor (value) { super(value + 'Z') this.isFloating = true } toISOString () { const date = `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}` const time = `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}` return `${date}T${time}` } } module.exports = value => { const date = new FloatingDateTime(value) /* istanbul ignore if */ if (isNaN(date)) { throw new TypeError('Invalid Datetime') } else { return date } } /***/ }), /***/ "./node_modules/@iarna/toml/lib/create-datetime.js": /*!*********************************************************!*\ !*** ./node_modules/@iarna/toml/lib/create-datetime.js ***! \*********************************************************/ /***/ ((module) => { "use strict"; module.exports = value => { const date = new Date(value) /* istanbul ignore if */ if (isNaN(date)) { throw new TypeError('Invalid Datetime') } else { return date } } /***/ }), /***/ "./node_modules/@iarna/toml/lib/create-time.js": /*!*****************************************************!*\ !*** ./node_modules/@iarna/toml/lib/create-time.js ***! \*****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const f = __webpack_require__(/*! ./format-num.js */ "./node_modules/@iarna/toml/lib/format-num.js") class Time extends Date { constructor (value) { super(`0000-01-01T${value}Z`) this.isTime = true } toISOString () { return `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}` } } module.exports = value => { const date = new Time(value) /* istanbul ignore if */ if (isNaN(date)) { throw new TypeError('Invalid Datetime') } else { return date } } /***/ }), /***/ "./node_modules/@iarna/toml/lib/format-num.js": /*!****************************************************!*\ !*** ./node_modules/@iarna/toml/lib/format-num.js ***! \****************************************************/ /***/ ((module) => { "use strict"; module.exports = (d, num) => { num = String(num) while (num.length < d) num = '0' + num return num } /***/ }), /***/ "./node_modules/@iarna/toml/lib/parser.js": /*!************************************************!*\ !*** ./node_modules/@iarna/toml/lib/parser.js ***! \************************************************/ /***/ ((module) => { "use strict"; const ParserEND = 0x110000 class ParserError extends Error { /* istanbul ignore next */ constructor (msg, filename, linenumber) { super('[ParserError] ' + msg, filename, linenumber) this.name = 'ParserError' this.code = 'ParserError' if (Error.captureStackTrace) Error.captureStackTrace(this, ParserError) } } class State { constructor (parser) { this.parser = parser this.buf = '' this.returned = null this.result = null this.resultTable = null this.resultArr = null } } class Parser { constructor () { this.pos = 0 this.col = 0 this.line = 0 this.obj = {} this.ctx = this.obj this.stack = [] this._buf = '' this.char = null this.ii = 0 this.state = new State(this.parseStart) } parse (str) { /* istanbul ignore next */ if (str.length === 0 || str.length == null) return this._buf = String(str) this.ii = -1 this.char = -1 let getNext while (getNext === false || this.nextChar()) { getNext = this.runOne() } this._buf = null } nextChar () { if (this.char === 0x0A) { ++this.line this.col = -1 } ++this.ii this.char = this._buf.codePointAt(this.ii) ++this.pos ++this.col return this.haveBuffer() } haveBuffer () { return this.ii < this._buf.length } runOne () { return this.state.parser.call(this, this.state.returned) } finish () { this.char = ParserEND let last do { last = this.state.parser this.runOne() } while (this.state.parser !== last) this.ctx = null this.state = null this._buf = null return this.obj } next (fn) { /* istanbul ignore next */ if (typeof fn !== 'function') throw new ParserError('Tried to set state to non-existent state: ' + JSON.stringify(fn)) this.state.parser = fn } goto (fn) { this.next(fn) return this.runOne() } call (fn, returnWith) { if (returnWith) this.next(returnWith) this.stack.push(this.state) this.state = new State(fn) } callNow (fn, returnWith) { this.call(fn, returnWith) return this.runOne() } return (value) { /* istanbul ignore next */ if (this.stack.length === 0) throw this.error(new ParserError('Stack underflow')) if (value === undefined) value = this.state.buf this.state = this.stack.pop() this.state.returned = value } returnNow (value) { this.return(value) return this.runOne() } consume () { /* istanbul ignore next */ if (this.char === ParserEND) throw this.error(new ParserError('Unexpected end-of-buffer')) this.state.buf += this._buf[this.ii] } error (err) { err.line = this.line err.col = this.col err.pos = this.pos return err } /* istanbul ignore next */ parseStart () { throw new ParserError('Must declare a parseStart method') } } Parser.END = ParserEND Parser.Error = ParserError module.exports = Parser /***/ }), /***/ "./node_modules/@iarna/toml/lib/toml-parser.js": /*!*****************************************************!*\ !*** ./node_modules/@iarna/toml/lib/toml-parser.js ***! \*****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* eslint-disable no-new-wrappers, no-eval, camelcase, operator-linebreak */ module.exports = makeParserClass(__webpack_require__(/*! ./parser.js */ "./node_modules/@iarna/toml/lib/parser.js")) module.exports.makeParserClass = makeParserClass class TomlError extends Error { constructor (msg) { super(msg) this.name = 'TomlError' /* istanbul ignore next */ if (Error.captureStackTrace) Error.captureStackTrace(this, TomlError) this.fromTOML = true this.wrapped = null } } TomlError.wrap = err => { const terr = new TomlError(err.message) terr.code = err.code terr.wrapped = err return terr } module.exports.TomlError = TomlError const createDateTime = __webpack_require__(/*! ./create-datetime.js */ "./node_modules/@iarna/toml/lib/create-datetime.js") const createDateTimeFloat = __webpack_require__(/*! ./create-datetime-float.js */ "./node_modules/@iarna/toml/lib/create-datetime-float.js") const createDate = __webpack_require__(/*! ./create-date.js */ "./node_modules/@iarna/toml/lib/create-date.js") const createTime = __webpack_require__(/*! ./create-time.js */ "./node_modules/@iarna/toml/lib/create-time.js") const CTRL_I = 0x09 const CTRL_J = 0x0A const CTRL_M = 0x0D const CTRL_CHAR_BOUNDARY = 0x1F // the last non-character in the latin1 region of unicode, except DEL const CHAR_SP = 0x20 const CHAR_QUOT = 0x22 const CHAR_NUM = 0x23 const CHAR_APOS = 0x27 const CHAR_PLUS = 0x2B const CHAR_COMMA = 0x2C const CHAR_HYPHEN = 0x2D const CHAR_PERIOD = 0x2E const CHAR_0 = 0x30 const CHAR_1 = 0x31 const CHAR_7 = 0x37 const CHAR_9 = 0x39 const CHAR_COLON = 0x3A const CHAR_EQUALS = 0x3D const CHAR_A = 0x41 const CHAR_E = 0x45 const CHAR_F = 0x46 const CHAR_T = 0x54 const CHAR_U = 0x55 const CHAR_Z = 0x5A const CHAR_LOWBAR = 0x5F const CHAR_a = 0x61 const CHAR_b = 0x62 const CHAR_e = 0x65 const CHAR_f = 0x66 const CHAR_i = 0x69 const CHAR_l = 0x6C const CHAR_n = 0x6E const CHAR_o = 0x6F const CHAR_r = 0x72 const CHAR_s = 0x73 const CHAR_t = 0x74 const CHAR_u = 0x75 const CHAR_x = 0x78 const CHAR_z = 0x7A const CHAR_LCUB = 0x7B const CHAR_RCUB = 0x7D const CHAR_LSQB = 0x5B const CHAR_BSOL = 0x5C const CHAR_RSQB = 0x5D const CHAR_DEL = 0x7F const SURROGATE_FIRST = 0xD800 const SURROGATE_LAST = 0xDFFF const escapes = { [CHAR_b]: '\u0008', [CHAR_t]: '\u0009', [CHAR_n]: '\u000A', [CHAR_f]: '\u000C', [CHAR_r]: '\u000D', [CHAR_QUOT]: '\u0022', [CHAR_BSOL]: '\u005C' } function isDigit (cp) { return cp >= CHAR_0 && cp <= CHAR_9 } function isHexit (cp) { return (cp >= CHAR_A && cp <= CHAR_F) || (cp >= CHAR_a && cp <= CHAR_f) || (cp >= CHAR_0 && cp <= CHAR_9) } function isBit (cp) { return cp === CHAR_1 || cp === CHAR_0 } function isOctit (cp) { return (cp >= CHAR_0 && cp <= CHAR_7) } function isAlphaNumQuoteHyphen (cp) { return (cp >= CHAR_A && cp <= CHAR_Z) || (cp >= CHAR_a && cp <= CHAR_z) || (cp >= CHAR_0 && cp <= CHAR_9) || cp === CHAR_APOS || cp === CHAR_QUOT || cp === CHAR_LOWBAR || cp === CHAR_HYPHEN } function isAlphaNumHyphen (cp) { return (cp >= CHAR_A && cp <= CHAR_Z) || (cp >= CHAR_a && cp <= CHAR_z) || (cp >= CHAR_0 && cp <= CHAR_9) || cp === CHAR_LOWBAR || cp === CHAR_HYPHEN } const _type = Symbol('type') const _declared = Symbol('declared') const hasOwnProperty = Object.prototype.hasOwnProperty const defineProperty = Object.defineProperty const descriptor = {configurable: true, enumerable: true, writable: true, value: undefined} function hasKey (obj, key) { if (hasOwnProperty.call(obj, key)) return true if (key === '__proto__') defineProperty(obj, '__proto__', descriptor) return false } const INLINE_TABLE = Symbol('inline-table') function InlineTable () { return Object.defineProperties({}, { [_type]: {value: INLINE_TABLE} }) } function isInlineTable (obj) { if (obj === null || typeof (obj) !== 'object') return false return obj[_type] === INLINE_TABLE } const TABLE = Symbol('table') function Table () { return Object.defineProperties({}, { [_type]: {value: TABLE}, [_declared]: {value: false, writable: true} }) } function isTable (obj) { if (obj === null || typeof (obj) !== 'object') return false return obj[_type] === TABLE } const _contentType = Symbol('content-type') const INLINE_LIST = Symbol('inline-list') function InlineList (type) { return Object.defineProperties([], { [_type]: {value: INLINE_LIST}, [_contentType]: {value: type} }) } function isInlineList (obj) { if (obj === null || typeof (obj) !== 'object') return false return obj[_type] === INLINE_LIST } const LIST = Symbol('list') function List () { return Object.defineProperties([], { [_type]: {value: LIST} }) } function isList (obj) { if (obj === null || typeof (obj) !== 'object') return false return obj[_type] === LIST } // in an eval, to let bundlers not slurp in a util proxy let _custom try { const utilInspect = eval("require('util').inspect") _custom = utilInspect.custom } catch (_) { /* eval require not available in transpiled bundle */ } /* istanbul ignore next */ const _inspect = _custom || 'inspect' class BoxedBigInt { constructor (value) { try { this.value = global.BigInt.asIntN(64, value) } catch (_) { /* istanbul ignore next */ this.value = null } Object.defineProperty(this, _type, {value: INTEGER}) } isNaN () { return this.value === null } /* istanbul ignore next */ toString () { return String(this.value) } /* istanbul ignore next */ [_inspect] () { return `[BigInt: ${this.toString()}]}` } valueOf () { return this.value } } const INTEGER = Symbol('integer') function Integer (value) { let num = Number(value) // -0 is a float thing, not an int thing if (Object.is(num, -0)) num = 0 /* istanbul ignore else */ if (global.BigInt && !Number.isSafeInteger(num)) { return new BoxedBigInt(value) } else { /* istanbul ignore next */ return Object.defineProperties(new Number(num), { isNaN: {value: function () { return isNaN(this) }}, [_type]: {value: INTEGER}, [_inspect]: {value: () => `[Integer: ${value}]`} }) } } function isInteger (obj) { if (obj === null || typeof (obj) !== 'object') return false return obj[_type] === INTEGER } const FLOAT = Symbol('float') function Float (value) { /* istanbul ignore next */ return Object.defineProperties(new Number(value), { [_type]: {value: FLOAT}, [_inspect]: {value: () => `[Float: ${value}]`} }) } function isFloat (obj) { if (obj === null || typeof (obj) !== 'object') return false return obj[_type] === FLOAT } function tomlType (value) { const type = typeof value if (type === 'object') { /* istanbul ignore if */ if (value === null) return 'null' if (value instanceof Date) return 'datetime' /* istanbul ignore else */ if (_type in value) { switch (value[_type]) { case INLINE_TABLE: return 'inline-table' case INLINE_LIST: return 'inline-list' /* istanbul ignore next */ case TABLE: return 'table' /* istanbul ignore next */ case LIST: return 'list' case FLOAT: return 'float' case INTEGER: return 'integer' } } } return type } function makeParserClass (Parser) { class TOMLParser extends Parser { constructor () { super() this.ctx = this.obj = Table() } /* MATCH HELPER */ atEndOfWord () { return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine() } atEndOfLine () { return this.char === Parser.END || this.char === CTRL_J || this.char === CTRL_M } parseStart () { if (this.char === Parser.END) { return null } else if (this.char === CHAR_LSQB) { return this.call(this.parseTableOrList) } else if (this.char === CHAR_NUM) { return this.call(this.parseComment) } else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) { return null } else if (isAlphaNumQuoteHyphen(this.char)) { return this.callNow(this.parseAssignStatement) } else { throw this.error(new TomlError(`Unknown character "${this.char}"`)) } } // HELPER, this strips any whitespace and comments to the end of the line // then RETURNS. Last state in a production. parseWhitespaceToEOL () { if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) { return null } else if (this.char === CHAR_NUM) { return this.goto(this.parseComment) } else if (this.char === Parser.END || this.char === CTRL_J) { return this.return() } else { throw this.error(new TomlError('Unexpected character, expected only whitespace or comments till end of line')) } } /* ASSIGNMENT: key = value */ parseAssignStatement () { return this.callNow(this.parseAssign, this.recordAssignStatement) } recordAssignStatement (kv) { let target = this.ctx let finalKey = kv.key.pop() for (let kw of kv.key) { if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) { throw this.error(new TomlError("Can't redefine existing key")) } target = target[kw] = target[kw] || Table() } if (hasKey(target, finalKey)) { throw this.error(new TomlError("Can't redefine existing key")) } // unbox our numbers if (isInteger(kv.value) || isFloat(kv.value)) { target[finalKey] = kv.value.valueOf() } else { target[finalKey] = kv.value } return this.goto(this.parseWhitespaceToEOL) } /* ASSSIGNMENT expression, key = value possibly inside an inline table */ parseAssign () { return this.callNow(this.parseKeyword, this.recordAssignKeyword) } recordAssignKeyword (key) { if (this.state.resultTable) { this.state.resultTable.push(key) } else { this.state.resultTable = [key] } return this.goto(this.parseAssignKeywordPreDot) } parseAssignKeywordPreDot () { if (this.char === CHAR_PERIOD) { return this.next(this.parseAssignKeywordPostDot) } else if (this.char !== CHAR_SP && this.char !== CTRL_I) { return this.goto(this.parseAssignEqual) } } parseAssignKeywordPostDot () { if (this.char !== CHAR_SP && this.char !== CTRL_I) { return this.callNow(this.parseKeyword, this.recordAssignKeyword) } } parseAssignEqual () { if (this.char === CHAR_EQUALS) { return this.next(this.parseAssignPreValue) } else { throw this.error(new TomlError('Invalid character, expected "="')) } } parseAssignPreValue () { if (this.char === CHAR_SP || this.char === CTRL_I) { return null } else { return this.callNow(this.parseValue, this.recordAssignValue) } } recordAssignValue (value) { return this.returnNow({key: this.state.resultTable, value: value}) } /* COMMENTS: #...eol */ parseComment () { do { if (this.char === Parser.END || this.char === CTRL_J) { return this.return() } } while (this.nextChar()) } /* TABLES AND LISTS, [foo] and [[foo]] */ parseTableOrList () { if (this.char === CHAR_LSQB) { this.next(this.parseList) } else { return this.goto(this.parseTable) } } /* TABLE [foo.bar.baz] */ parseTable () { this.ctx = this.obj return this.goto(this.parseTableNext) } parseTableNext () { if (this.char === CHAR_SP || this.char === CTRL_I) { return null } else { return this.callNow(this.parseKeyword, this.parseTableMore) } } parseTableMore (keyword) { if (this.char === CHAR_SP || this.char === CTRL_I) { return null } else if (this.char === CHAR_RSQB) { if (hasKey(this.ctx, keyword) && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) { throw this.error(new TomlError("Can't redefine existing key")) } else { this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table() this.ctx[_declared] = true } return this.next(this.parseWhitespaceToEOL) } else if (this.char === CHAR_PERIOD) { if (!hasKey(this.ctx, keyword)) { this.ctx = this.ctx[keyword] = Table() } else if (isTable(this.ctx[keyword])) { this.ctx = this.ctx[keyword] } else if (isList(this.ctx[keyword])) { this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1] } else { throw this.error(new TomlError("Can't redefine existing key")) } return this.next(this.parseTableNext) } else { throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]')) } } /* LIST [[a.b.c]] */ parseList () { this.ctx = this.obj return this.goto(this.parseListNext) } parseListNext () { if (this.char === CHAR_SP || this.char === CTRL_I) { return null } else { return this.callNow(this.parseKeyword, this.parseListMore) } } parseListMore (keyword) { if (this.char === CHAR_SP || this.char === CTRL_I) { return null } else if (this.char === CHAR_RSQB) { if (!hasKey(this.ctx, keyword)) { this.ctx[keyword] = List() } if (isInlineList(this.ctx[keyword])) { throw this.error(new TomlError("Can't extend an inline array")) } else if (isList(this.ctx[keyword])) { const next = Table() this.ctx[keyword].push(next) this.ctx = next } else { throw this.error(new TomlError("Can't redefine an existing key")) } return this.next(this.parseListEnd) } else if (this.char === CHAR_PERIOD) { if (!hasKey(this.ctx, keyword)) { this.ctx = this.ctx[keyword] = Table() } else if (isInlineList(this.ctx[keyword])) { throw this.error(new TomlError("Can't extend an inline array")) } else if (isInlineTable(this.ctx[keyword])) { throw this.error(new TomlError("Can't extend an inline table")) } else if (isList(this.ctx[keyword])) { this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1] } else if (isTable(this.ctx[keyword])) { this.ctx = this.ctx[keyword] } else { throw this.error(new TomlError("Can't redefine an existing key")) } return this.next(this.parseListNext) } else { throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]')) } } parseListEnd (keyword) { if (this.char === CHAR_RSQB) { return this.next(this.parseWhitespaceToEOL) } else { throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]')) } } /* VALUE string, number, boolean, inline list, inline object */ parseValue () { if (this.char === Parser.END) { throw this.error(new TomlError('Key without value')) } else if (this.char === CHAR_QUOT) { return this.next(this.parseDoubleString) } if (this.char === CHAR_APOS) { return this.next(this.parseSingleString) } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) { return this.goto(this.parseNumberSign) } else if (this.char === CHAR_i) { return this.next(this.parseInf) } else if (this.char === CHAR_n) { return this.next(this.parseNan) } else if (isDigit(this.char)) { return this.goto(this.parseNumberOrDateTime) } else if (this.char === CHAR_t || this.char === CHAR_f) { return this.goto(this.parseBoolean) } else if (this.char === CHAR_LSQB) { return this.call(this.parseInlineList, this.recordValue) } else if (this.char === CHAR_LCUB) { return this.call(this.parseInlineTable, this.recordValue) } else { throw this.error(new TomlError('Unexpected character, expecting string, number, datetime, boolean, inline array or inline table')) } } recordValue (value) { return this.returnNow(value) } parseInf () { if (this.char === CHAR_n) { return this.next(this.parseInf2) } else { throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"')) } } parseInf2 () { if (this.char === CHAR_f) { if (this.state.buf === '-') { return this.return(-Infinity) } else { return this.return(Infinity) } } else { throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"')) } } parseNan () { if (this.char === CHAR_a) { return this.next(this.parseNan2) } else { throw this.error(new TomlError('Unexpected character, expected "nan"')) } } parseNan2 () { if (this.char === CHAR_n) { return this.return(NaN) } else { throw this.error(new TomlError('Unexpected character, expected "nan"')) } } /* KEYS, barewords or basic, literal, or dotted */ parseKeyword () { if (this.char === CHAR_QUOT) { return this.next(this.parseBasicString) } else if (this.char === CHAR_APOS) { return this.next(this.parseLiteralString) } else { return this.goto(this.parseBareKey) } } /* KEYS: barewords */ parseBareKey () { do { if (this.char === Parser.END) { throw this.error(new TomlError('Key ended without value')) } else if (isAlphaNumHyphen(this.char)) { this.consume() } else if (this.state.buf.length === 0) { throw this.error(new TomlError('Empty bare keys are not allowed')) } else { return this.returnNow() } } while (this.nextChar()) } /* STRINGS, single quoted (literal) */ parseSingleString () { if (this.char === CHAR_APOS) { return this.next(this.parseLiteralMultiStringMaybe) } else { return this.goto(this.parseLiteralString) } } parseLiteralString () { do { if (this.char === CHAR_APOS) { return this.return() } else if (this.atEndOfLine()) { throw this.error(new TomlError('Unterminated string')) } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I)) { throw this.errorControlCharInString() } else { this.consume() } } while (this.nextChar()) } parseLiteralMultiStringMaybe () { if (this.char === CHAR_APOS) { return this.next(this.parseLiteralMultiString) } else { return this.returnNow() } } parseLiteralMultiString () { if (this.char === CTRL_M) { return null } else if (this.char === CTRL_J) { return this.next(this.parseLiteralMultiStringContent) } else { return this.goto(this.parseLiteralMultiStringContent) } } parseLiteralMultiStringContent () { do { if (this.char === CHAR_APOS) { return this.next(this.parseLiteralMultiEnd) } else if (this.char === Parser.END) { throw this.error(new TomlError('Unterminated multi-line string')) } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M)) { throw this.errorControlCharInString() } else { this.consume() } } while (this.nextChar()) } parseLiteralMultiEnd () { if (this.char === CHAR_APOS) { return this.next(this.parseLiteralMultiEnd2) } else { this.state.buf += "'" return this.goto(this.parseLiteralMultiStringContent) } } parseLiteralMultiEnd2 () { if (this.char === CHAR_APOS) { return this.return() } else { this.state.buf += "''" return this.goto(this.parseLiteralMultiStringContent) } } /* STRINGS double quoted */ parseDoubleString () { if (this.char === CHAR_QUOT) { return this.next(this.parseMultiStringMaybe) } else { return this.goto(this.parseBasicString) } } parseBasicString () { do { if (this.char === CHAR_BSOL) { return this.call(this.parseEscape, this.recordEscapeReplacement) } else if (this.char === CHAR_QUOT) { return this.return() } else if (this.atEndOfLine()) { throw this.error(new TomlError('Unterminated string')) } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I)) { throw this.errorControlCharInString() } else { this.consume() } } while (this.nextChar()) } recordEscapeReplacement (replacement) { this.state.buf += replacement return this.goto(this.parseBasicString) } parseMultiStringMaybe () { if (this.char === CHAR_QUOT) { return this.next(this.parseMultiString) } else { return this.returnNow() } } parseMultiString () { if (this.char === CTRL_M) { return null } else if (this.char === CTRL_J) { return this.next(this.parseMultiStringContent) } else { return this.goto(this.parseMultiStringContent) } } parseMultiStringContent () { do { if (this.char === CHAR_BSOL) { return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement) } else if (this.char === CHAR_QUOT) { return this.next(this.parseMultiEnd) } else if (this.char === Parser.END) { throw this.error(new TomlError('Unterminated multi-line string')) } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M)) { throw this.errorControlCharInString() } else { this.consume() } } while (this.nextChar()) } errorControlCharInString () { let displayCode = '\\u00' if (this.char < 16) { displayCode += '0' } displayCode += this.char.toString(16) return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`)) } recordMultiEscapeReplacement (replacement) { this.state.buf += replacement return this.goto(this.parseMultiStringContent) } parseMultiEnd () { if (this.char === CHAR_QUOT) { return this.next(this.parseMultiEnd2) } else { this.state.buf += '"' return this.goto(this.parseMultiStringContent) } } parseMultiEnd2 () { if (this.char === CHAR_QUOT) { return this.return() } else { this.state.buf += '""' return this.goto(this.parseMultiStringContent) } } parseMultiEscape () { if (this.char === CTRL_M || this.char === CTRL_J) { return this.next(this.parseMultiTrim) } else if (this.char === CHAR_SP || this.char === CTRL_I) { return this.next(this.parsePreMultiTrim) } else { return this.goto(this.parseEscape) } } parsePreMultiTrim () { if (this.char === CHAR_SP || this.char === CTRL_I) { return null } else if (this.char === CTRL_M || this.char === CTRL_J) { return this.next(this.parseMultiTrim) } else { throw this.error(new TomlError("Can't escape whitespace")) } } parseMultiTrim () { // explicitly whitespace here, END should follow the same path as chars if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) { return null } else { return this.returnNow() } } parseEscape () { if (this.char in escapes) { return this.return(escapes[this.char]) } else if (this.char === CHAR_u) { return this.call(this.parseSmallUnicode, this.parseUnicodeReturn) } else if (this.char === CHAR_U) { return this.call(this.parseLargeUnicode, this.parseUnicodeReturn) } else { throw this.error(new TomlError('Unknown escape character: ' + this.char)) } } parseUnicodeReturn (char) { try { const codePoint = parseInt(char, 16) if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) { throw this.error(new TomlError('Invalid unicode, character in range 0xD800 - 0xDFFF is reserved')) } return this.returnNow(String.fromCodePoint(codePoint)) } catch (err) { throw this.error(TomlError.wrap(err)) } } parseSmallUnicode () { if (!isHexit(this.char)) { throw this.error(new TomlError('Invalid character in unicode sequence, expected hex')) } else { this.consume() if (this.state.buf.length >= 4) return this.return() } } parseLargeUnicode () { if (!isHexit(this.char)) { throw this.error(new TomlError('Invalid character in unicode sequence, expected hex')) } else { this.consume() if (this.state.buf.length >= 8) return this.return() } } /* NUMBERS */ parseNumberSign () { this.consume() return this.next(this.parseMaybeSignedInfOrNan) } parseMaybeSignedInfOrNan () { if (this.char === CHAR_i) { return this.next(this.parseInf) } else if (this.char === CHAR_n) { return this.next(this.parseNan) } else { return this.callNow(this.parseNoUnder, this.parseNumberIntegerStart) } } parseNumberIntegerStart () { if (this.char === CHAR_0) { this.consume() return this.next(this.parseNumberIntegerExponentOrDecimal) } else { return this.goto(this.parseNumberInteger) } } parseNumberIntegerExponentOrDecimal () { if (this.char === CHAR_PERIOD) { this.consume() return this.call(this.parseNoUnder, this.parseNumberFloat) } else if (this.char === CHAR_E || this.char === CHAR_e) { this.consume() return this.next(this.parseNumberExponentSign) } else { return this.returnNow(Integer(this.state.buf)) } } parseNumberInteger () { if (isDigit(this.char)) { this.consume() } else if (this.char === CHAR_LOWBAR) { return this.call(this.parseNoUnder) } else if (this.char === CHAR_E || this.char === CHAR_e) { this.consume() return this.next(this.parseNumberExponentSign) } else if (this.char === CHAR_PERIOD) { this.consume() return this.call(this.parseNoUnder, this.parseNumberFloat) } else { const result = Integer(this.state.buf) /* istanbul ignore if */ if (result.isNaN()) { throw this.error(new TomlError('Invalid number')) } else { return this.returnNow(result) } } } parseNoUnder () { if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD || this.char === CHAR_E || this.char === CHAR_e) { throw this.error(new TomlError('Unexpected character, expected digit')) } else if (this.atEndOfWord()) { throw this.error(new TomlError('Incomplete number')) } return this.returnNow() } parseNoUnderHexOctBinLiteral () { if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD) { throw this.error(new TomlError('Unexpected character, expected digit')) } else if (this.atEndOfWord()) { throw this.error(new TomlError('Incomplete number')) } return this.returnNow() } parseNumberFloat () { if (this.char === CHAR_LOWBAR) { return this.call(this.parseNoUnder, this.parseNumberFloat) } else if (isDigit(this.char)) { this.consume() } else if (this.char === CHAR_E || this.char === CHAR_e) { this.consume() return this.next(this.parseNumberExponentSign) } else { return this.returnNow(Float(this.state.buf)) } } parseNumberExponentSign () { if (isDigit(this.char)) { return this.goto(this.parseNumberExponent) } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) { this.consume() this.call(this.parseNoUnder, this.parseNumberExponent) } else { throw this.error(new TomlError('Unexpected character, expected -, + or digit')) } } parseNumberExponent () { if (isDigit(this.char)) { this.consume() } else if (this.char === CHAR_LOWBAR) { return this.call(this.parseNoUnder) } else { return this.returnNow(Float(this.state.buf)) } } /* NUMBERS or DATETIMES */ parseNumberOrDateTime () { if (this.char === CHAR_0) { this.consume() return this.next(this.parseNumberBaseOrDateTime) } else { return this.goto(this.parseNumberOrDateTimeOnly) } } parseNumberOrDateTimeOnly () { // note, if two zeros are in a row then it MUST be a date if (this.char === CHAR_LOWBAR) { return this.call(this.parseNoUnder, this.parseNumberInteger) } else if (isDigit(this.char)) { this.consume() if (this.state.buf.length > 4) this.next(this.parseNumberInteger) } else if (this.char === CHAR_E || this.char === CHAR_e) { this.consume() return this.next(this.parseNumberExponentSign) } else if (this.char === CHAR_PERIOD) { this.consume() return this.call(this.parseNoUnder, this.parseNumberFloat) } else if (this.char === CHAR_HYPHEN) { return this.goto(this.parseDateTime) } else if (this.char === CHAR_COLON) { return this.goto(this.parseOnlyTimeHour) } else { return this.returnNow(Integer(this.state.buf)) } } parseDateTimeOnly () { if (this.state.buf.length < 4) { if (isDigit(this.char)) { return this.consume() } else if (this.char === CHAR_COLON) { return this.goto(this.parseOnlyTimeHour) } else { throw this.error(new TomlError('Expected digit while parsing year part of a date')) } } else { if (this.char === CHAR_HYPHEN) { return this.goto(this.parseDateTime) } else { throw this.error(new TomlError('Expected hyphen (-) while parsing year part of date')) } } } parseNumberBaseOrDateTime () { if (this.char === CHAR_b) { this.consume() return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerBin) } else if (this.char === CHAR_o) { this.consume() return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerOct) } else if (this.char === CHAR_x) { this.consume() return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerHex) } else if (this.char === CHAR_PERIOD) { return this.goto(this.parseNumberInteger) } else if (isDigit(this.char)) { return this.goto(this.parseDateTimeOnly) } else { return this.returnNow(Integer(this.state.buf)) } } parseIntegerHex () { if (isHexit(this.char)) { this.consume() } else if (this.char === CHAR_LOWBAR) { return this.call(this.parseNoUnderHexOctBinLiteral) } else { const result = Integer(this.state.buf) /* istanbul ignore if */ if (result.isNaN()) { throw this.error(new TomlError('Invalid number')) } else { return this.returnNow(result) } } } parseIntegerOct () { if (isOctit(this.char)) { this.consume() } else if (this.char === CHAR_LOWBAR) { return this.call(this.parseNoUnderHexOctBinLiteral) } else { const result = Integer(this.state.buf) /* istanbul ignore if */ if (result.isNaN()) { throw this.error(new TomlError('Invalid number')) } else { return this.returnNow(result) } } } parseIntegerBin () { if (isBit(this.char)) { this.consume() } else if (this.char === CHAR_LOWBAR) { return this.call(this.parseNoUnderHexOctBinLiteral) } else { const result = Integer(this.state.buf) /* istanbul ignore if */ if (result.isNaN()) { throw this.error(new TomlError('Invalid number')) } else { return this.returnNow(result) } } } /* DATETIME */ parseDateTime () { // we enter here having just consumed the year and about to consume the hyphen if (this.state.buf.length < 4) { throw this.error(new TomlError('Years less than 1000 must be zero padded to four characters')) } this.state.result = this.state.buf this.state.buf = '' return this.next(this.parseDateMonth) } parseDateMonth () { if (this.char === CHAR_HYPHEN) { if (this.state.buf.length < 2) { throw this.error(new TomlError('Months less than 10 must be zero padded to two characters')) } this.state.result += '-' + this.state.buf this.state.buf = '' return this.next(this.parseDateDay) } else if (isDigit(this.char)) { this.consume() } else { throw this.error(new TomlError('Incomplete datetime')) } } parseDateDay () { if (this.char === CHAR_T || this.char === CHAR_SP) { if (this.state.buf.length < 2) { throw this.error(new TomlError('Days less than 10 must be zero padded to two characters')) } this.state.result += '-' + this.state.buf this.state.buf = '' return this.next(this.parseStartTimeHour) } else if (this.atEndOfWord()) { return this.returnNow(createDate(this.state.result + '-' + this.state.buf)) } else if (isDigit(this.char)) { this.consume() } else { throw this.error(new TomlError('Incomplete datetime')) } } parseStartTimeHour () { if (this.atEndOfWord()) { return this.returnNow(createDate(this.state.result)) } else { return this.goto(this.parseTimeHour) } } parseTimeHour () { if (this.char === CHAR_COLON) { if (this.state.buf.length < 2) { throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters')) } this.state.result += 'T' + this.state.buf this.state.buf = '' return this.next(this.parseTimeMin) } else if (isDigit(this.char)) { this.consume() } else { throw this.error(new TomlError('Incomplete datetime')) } } parseTimeMin () { if (this.state.buf.length < 2 && isDigit(this.char)) { this.consume() } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) { this.state.result += ':' + this.state.buf this.state.buf = '' return this.next(this.parseTimeSec) } else { throw this.error(new TomlError('Incomplete datetime')) } } parseTimeSec () { if (isDigit(this.char)) { this.consume() if (this.state.buf.length === 2) { this.state.result += ':' + this.state.buf this.state.buf = '' return this.next(this.parseTimeZoneOrFraction) } } else { throw this.error(new TomlError('Incomplete datetime')) } } parseOnlyTimeHour () { /* istanbul ignore else */ if (this.char === CHAR_COLON) { if (this.state.buf.length < 2) { throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters')) } this.state.result = this.state.buf this.state.buf = '' return this.next(this.parseOnlyTimeMin) } else { throw this.error(new TomlError('Incomplete time')) } } parseOnlyTimeMin () { if (this.state.buf.length < 2 && isDigit(this.char)) { this.consume() } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) { this.state.result += ':' + this.state.buf this.state.buf = '' return this.next(this.parseOnlyTimeSec) } else { throw this.error(new TomlError('Incomplete time')) } } parseOnlyTimeSec () { if (isDigit(this.char)) { this.consume() if (this.state.buf.length === 2) { return this.next(this.parseOnlyTimeFractionMaybe) } } else { throw this.error(new TomlError('Incomplete time')) } } parseOnlyTimeFractionMaybe () { this.state.result += ':' + this.state.buf if (this.char === CHAR_PERIOD) { this.state.buf = '' this.next(this.parseOnlyTimeFraction) } else { return this.return(createTime(this.state.result)) } } parseOnlyTimeFraction () { if (isDigit(this.char)) { this.consume() } else if (this.atEndOfWord()) { if (this.state.buf.length === 0) throw this.error(new TomlError('Expected digit in milliseconds')) return this.returnNow(createTime(this.state.result + '.' + this.state.buf)) } else { throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z')) } } parseTimeZoneOrFraction () { if (this.char === CHAR_PERIOD) { this.consume() this.next(this.parseDateTimeFraction) } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) { this.consume() this.next(this.parseTimeZoneHour) } else if (this.char === CHAR_Z) { this.consume() return this.return(createDateTime(this.state.result + this.state.buf)) } else if (this.atEndOfWord()) { return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf)) } else { throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z')) } } parseDateTimeFraction () { if (isDigit(this.char)) { this.consume() } else if (this.state.buf.length === 1) { throw this.error(new TomlError('Expected digit in milliseconds')) } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) { this.consume() this.next(this.parseTimeZoneHour) } else if (this.char === CHAR_Z) { this.consume() return this.return(createDateTime(this.state.result + this.state.buf)) } else if (this.atEndOfWord()) { return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf)) } else { throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z')) } } parseTimeZoneHour () { if (isDigit(this.char)) { this.consume() // FIXME: No more regexps if (/\d\d$/.test(this.state.buf)) return this.next(this.parseTimeZoneSep) } else { throw this.error(new TomlError('Unexpected character in datetime, expected digit')) } } parseTimeZoneSep () { if (this.char === CHAR_COLON) { this.consume() this.next(this.parseTimeZoneMin) } else { throw this.error(new TomlError('Unexpected character in datetime, expected colon')) } } parseTimeZoneMin () { if (isDigit(this.char)) { this.consume() if (/\d\d$/.test(this.state.buf)) return this.return(createDateTime(this.state.result + this.state.buf)) } else { throw this.error(new TomlError('Unexpected character in datetime, expected digit')) } } /* BOOLEAN */ parseBoolean () { /* istanbul ignore else */ if (this.char === CHAR_t) { this.consume() return this.next(this.parseTrue_r) } else if (this.char === CHAR_f) { this.consume() return this.next(this.parseFalse_a) } } parseTrue_r () { if (this.char === CHAR_r) { this.consume() return this.next(this.parseTrue_u) } else { throw this.error(new TomlError('Invalid boolean, expected true or false')) } } parseTrue_u () { if (this.char === CHAR_u) { this.consume() return this.next(this.parseTrue_e) } else { throw this.error(new TomlError('Invalid boolean, expected true or false')) } } parseTrue_e () { if (this.char === CHAR_e) { return this.return(true) } else { throw this.error(new TomlError('Invalid boolean, expected true or false')) } } parseFalse_a () { if (this.char === CHAR_a) { this.consume() return this.next(this.parseFalse_l) } else { throw this.error(new TomlError('Invalid boolean, expected true or false')) } } parseFalse_l () { if (this.char === CHAR_l) { this.consume() return this.next(this.parseFalse_s) } else { throw this.error(new TomlError('Invalid boolean, expected true or false')) } } parseFalse_s () { if (this.char === CHAR_s) { this.consume() return this.next(this.parseFalse_e) } else { throw this.error(new TomlError('Invalid boolean, expected true or false')) } } parseFalse_e () { if (this.char === CHAR_e) { return this.return(false) } else { throw this.error(new TomlError('Invalid boolean, expected true or false')) } } /* INLINE LISTS */ parseInlineList () { if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) { return null } else if (this.char === Parser.END) { throw this.error(new TomlError('Unterminated inline array')) } else if (this.char === CHAR_NUM) { return this.call(this.parseComment) } else if (this.char === CHAR_RSQB) { return this.return(this.state.resultArr || InlineList()) } else { return this.callNow(this.parseValue, this.recordInlineListValue) } } recordInlineListValue (value) { if (this.state.resultArr) { const listType = this.state.resultArr[_contentType] const valueType = tomlType(value) if (listType !== valueType) { throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`)) } } else { this.state.resultArr = InlineList(tomlType(value)) } if (isFloat(value) || isInteger(value)) { // unbox now that we've verified they're ok this.state.resultArr.push(value.valueOf()) } else { this.state.resultArr.push(value) } return this.goto(this.parseInlineListNext) } parseInlineListNext () { if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) { return null } else if (this.char === CHAR_NUM) { return this.call(this.parseComment) } else if (this.char === CHAR_COMMA) { return this.next(this.parseInlineList) } else if (this.char === CHAR_RSQB) { return this.goto(this.parseInlineList) } else { throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])')) } } /* INLINE TABLE */ parseInlineTable () { if (this.char === CHAR_SP || this.char === CTRL_I) { return null } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) { throw this.error(new TomlError('Unterminated inline array')) } else if (this.char === CHAR_RCUB) { return this.return(this.state.resultTable || InlineTable()) } else { if (!this.state.resultTable) this.state.resultTable = InlineTable() return this.callNow(this.parseAssign, this.recordInlineTableValue) } } recordInlineTableValue (kv) { let target = this.state.resultTable let finalKey = kv.key.pop() for (let kw of kv.key) { if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) { throw this.error(new TomlError("Can't redefine existing key")) } target = target[kw] = target[kw] || Table() } if (hasKey(target, finalKey)) { throw this.error(new TomlError("Can't redefine existing key")) } if (isInteger(kv.value) || isFloat(kv.value)) { target[finalKey] = kv.value.valueOf() } else { target[finalKey] = kv.value } return this.goto(this.parseInlineTableNext) } parseInlineTableNext () { if (this.char === CHAR_SP || this.char === CTRL_I) { return null } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) { throw this.error(new TomlError('Unterminated inline array')) } else if (this.char === CHAR_COMMA) { return this.next(this.parseInlineTable) } else if (this.char === CHAR_RCUB) { return this.goto(this.parseInlineTable) } else { throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])')) } } } return TOMLParser } /***/ }), /***/ "./node_modules/@iarna/toml/parse-async.js": /*!*************************************************!*\ !*** ./node_modules/@iarna/toml/parse-async.js ***! \*************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = parseAsync const TOMLParser = __webpack_require__(/*! ./lib/toml-parser.js */ "./node_modules/@iarna/toml/lib/toml-parser.js") const prettyError = __webpack_require__(/*! ./parse-pretty-error.js */ "./node_modules/@iarna/toml/parse-pretty-error.js") function parseAsync (str, opts) { if (!opts) opts = {} const index = 0 const blocksize = opts.blocksize || 40960 const parser = new TOMLParser() return new Promise((resolve, reject) => { setImmediate(parseAsyncNext, index, blocksize, resolve, reject) }) function parseAsyncNext (index, blocksize, resolve, reject) { if (index >= str.length) { try { return resolve(parser.finish()) } catch (err) { return reject(prettyError(err, str)) } } try { parser.parse(str.slice(index, index + blocksize)) setImmediate(parseAsyncNext, index + blocksize, blocksize, resolve, reject) } catch (err) { reject(prettyError(err, str)) } } } /***/ }), /***/ "./node_modules/@iarna/toml/parse-pretty-error.js": /*!********************************************************!*\ !*** ./node_modules/@iarna/toml/parse-pretty-error.js ***! \********************************************************/ /***/ ((module) => { "use strict"; module.exports = prettyError function prettyError (err, buf) { /* istanbul ignore if */ if (err.pos == null || err.line == null) return err let msg = err.message msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:\n` /* istanbul ignore else */ if (buf && buf.split) { const lines = buf.split(/\n/) const lineNumWidth = String(Math.min(lines.length, err.line + 3)).length let linePadding = ' ' while (linePadding.length < lineNumWidth) linePadding += ' ' for (let ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) { let lineNum = String(ii + 1) if (lineNum.length < lineNumWidth) lineNum = ' ' + lineNum if (err.line === ii) { msg += lineNum + '> ' + lines[ii] + '\n' msg += linePadding + ' ' for (let hh = 0; hh < err.col; ++hh) { msg += ' ' } msg += '^\n' } else { msg += lineNum + ': ' + lines[ii] + '\n' } } } err.message = msg + '\n' return err } /***/ }), /***/ "./node_modules/@iarna/toml/parse-stream.js": /*!**************************************************!*\ !*** ./node_modules/@iarna/toml/parse-stream.js ***! \**************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = parseStream const stream = __webpack_require__(/*! stream */ "stream") const TOMLParser = __webpack_require__(/*! ./lib/toml-parser.js */ "./node_modules/@iarna/toml/lib/toml-parser.js") function parseStream (stm) { if (stm) { return parseReadable(stm) } else { return parseTransform(stm) } } function parseReadable (stm) { const parser = new TOMLParser() stm.setEncoding('utf8') return new Promise((resolve, reject) => { let readable let ended = false let errored = false function finish () { ended = true if (readable) return try { resolve(parser.finish()) } catch (err) { reject(err) } } function error (err) { errored = true reject(err) } stm.once('end', finish) stm.once('error', error) readNext() function readNext () { readable = true let data while ((data = stm.read()) !== null) { try { parser.parse(data) } catch (err) { return error(err) } } readable = false /* istanbul ignore if */ if (ended) return finish() /* istanbul ignore if */ if (errored) return stm.once('readable', readNext) } }) } function parseTransform () { const parser = new TOMLParser() return new stream.Transform({ objectMode: true, transform (chunk, encoding, cb) { try { parser.parse(chunk.toString(encoding)) } catch (err) { this.emit('error', err) } cb() }, flush (cb) { try { this.push(parser.finish()) } catch (err) { this.emit('error', err) } cb() } }) } /***/ }), /***/ "./node_modules/@iarna/toml/parse-string.js": /*!**************************************************!*\ !*** ./node_modules/@iarna/toml/parse-string.js ***! \**************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = parseString const TOMLParser = __webpack_require__(/*! ./lib/toml-parser.js */ "./node_modules/@iarna/toml/lib/toml-parser.js") const prettyError = __webpack_require__(/*! ./parse-pretty-error.js */ "./node_modules/@iarna/toml/parse-pretty-error.js") function parseString (str) { if (global.Buffer && global.Buffer.isBuffer(str)) { str = str.toString('utf8') } const parser = new TOMLParser() try { parser.parse(str) return parser.finish() } catch (err) { throw prettyError(err, str) } } /***/ }), /***/ "./node_modules/@iarna/toml/parse.js": /*!*******************************************!*\ !*** ./node_modules/@iarna/toml/parse.js ***! \*******************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = __webpack_require__(/*! ./parse-string.js */ "./node_modules/@iarna/toml/parse-string.js") module.exports.async = __webpack_require__(/*! ./parse-async.js */ "./node_modules/@iarna/toml/parse-async.js") module.exports.stream = __webpack_require__(/*! ./parse-stream.js */ "./node_modules/@iarna/toml/parse-stream.js") module.exports.prettyError = __webpack_require__(/*! ./parse-pretty-error.js */ "./node_modules/@iarna/toml/parse-pretty-error.js") /***/ }), /***/ "./node_modules/@iarna/toml/stringify.js": /*!***********************************************!*\ !*** ./node_modules/@iarna/toml/stringify.js ***! \***********************************************/ /***/ ((module) => { "use strict"; module.exports = stringify module.exports.value = stringifyInline function stringify (obj) { if (obj === null) throw typeError('null') if (obj === void (0)) throw typeError('undefined') if (typeof obj !== 'object') throw typeError(typeof obj) if (typeof obj.toJSON === 'function') obj = obj.toJSON() if (obj == null) return null const type = tomlType(obj) if (type !== 'table') throw typeError(type) return stringifyObject('', '', obj) } function typeError (type) { return new Error('Can only stringify objects, not ' + type) } function arrayOneTypeError () { return new Error("Array values can't have mixed types") } function getInlineKeys (obj) { return Object.keys(obj).filter(key => isInline(obj[key])) } function getComplexKeys (obj) { return Object.keys(obj).filter(key => !isInline(obj[key])) } function toJSON (obj) { let nobj = Array.isArray(obj) ? [] : Object.prototype.hasOwnProperty.call(obj, '__proto__') ? {['__proto__']: undefined} : {} for (let prop of Object.keys(obj)) { if (obj[prop] && typeof obj[prop].toJSON === 'function' && !('toISOString' in obj[prop])) { nobj[prop] = obj[prop].toJSON() } else { nobj[prop] = obj[prop] } } return nobj } function stringifyObject (prefix, indent, obj) { obj = toJSON(obj) var inlineKeys var complexKeys inlineKeys = getInlineKeys(obj) complexKeys = getComplexKeys(obj) var result = [] var inlineIndent = indent || '' inlineKeys.forEach(key => { var type = tomlType(obj[key]) if (type !== 'undefined' && type !== 'null') { result.push(inlineIndent + stringifyKey(key) + ' = ' + stringifyAnyInline(obj[key], true)) } }) if (result.length > 0) result.push('') var complexIndent = prefix && inlineKeys.length > 0 ? indent + ' ' : '' complexKeys.forEach(key => { result.push(stringifyComplex(prefix, complexIndent, key, obj[key])) }) return result.join('\n') } function isInline (value) { switch (tomlType(value)) { case 'undefined': case 'null': case 'integer': case 'nan': case 'float': case 'boolean': case 'string': case 'datetime': return true case 'array': return value.length === 0 || tomlType(value[0]) !== 'table' case 'table': return Object.keys(value).length === 0 /* istanbul ignore next */ default: return false } } function tomlType (value) { if (value === undefined) { return 'undefined' } else if (value === null) { return 'null' /* eslint-disable valid-typeof */ } else if (typeof value === 'bigint' || (Number.isInteger(value) && !Object.is(value, -0))) { return 'integer' } else if (typeof value === 'number') { return 'float' } else if (typeof value === 'boolean') { return 'boolean' } else if (typeof value === 'string') { return 'string' } else if ('toISOString' in value) { return isNaN(value) ? 'undefined' : 'datetime' } else if (Array.isArray(value)) { return 'array' } else { return 'table' } } function stringifyKey (key) { var keyStr = String(key) if (/^[-A-Za-z0-9_]+$/.test(keyStr)) { return keyStr } else { return stringifyBasicString(keyStr) } } function stringifyBasicString (str) { return '"' + escapeString(str).replace(/"/g, '\\"') + '"' } function stringifyLiteralString (str) { return "'" + str + "'" } function numpad (num, str) { while (str.length < num) str = '0' + str return str } function escapeString (str) { return str.replace(/\\/g, '\\\\') .replace(/[\b]/g, '\\b') .replace(/\t/g, '\\t') .replace(/\n/g, '\\n') .replace(/\f/g, '\\f') .replace(/\r/g, '\\r') /* eslint-disable no-control-regex */ .replace(/([\u0000-\u001f\u007f])/, c => '\\u' + numpad(4, c.codePointAt(0).toString(16))) /* eslint-enable no-control-regex */ } function stringifyMultilineString (str) { let escaped = str.split(/\n/).map(str => { return escapeString(str).replace(/"(?="")/g, '\\"') }).join('\n') if (escaped.slice(-1) === '"') escaped += '\\\n' return '"""\n' + escaped + '"""' } function stringifyAnyInline (value, multilineOk) { let type = tomlType(value) if (type === 'string') { if (multilineOk && /\n/.test(value)) { type = 'string-multiline' } else if (!/[\b\t\n\f\r']/.test(value) && /"/.test(value)) { type = 'string-literal' } } return stringifyInline(value, type) } function stringifyInline (value, type) { /* istanbul ignore if */ if (!type) type = tomlType(value) switch (type) { case 'string-multiline': return stringifyMultilineString(value) case 'string': return stringifyBasicString(value) case 'string-literal': return stringifyLiteralString(value) case 'integer': return stringifyInteger(value) case 'float': return stringifyFloat(value) case 'boolean': return stringifyBoolean(value) case 'datetime': return stringifyDatetime(value) case 'array': return stringifyInlineArray(value.filter(_ => tomlType(_) !== 'null' && tomlType(_) !== 'undefined' && tomlType(_) !== 'nan')) case 'table': return stringifyInlineTable(value) /* istanbul ignore next */ default: throw typeError(type) } } function stringifyInteger (value) { /* eslint-disable security/detect-unsafe-regex */ return String(value).replace(/\B(?=(\d{3})+(?!\d))/g, '_') } function stringifyFloat (value) { if (value === Infinity) { return 'inf' } else if (value === -Infinity) { return '-inf' } else if (Object.is(value, NaN)) { return 'nan' } else if (Object.is(value, -0)) { return '-0.0' } var chunks = String(value).split('.') var int = chunks[0] var dec = chunks[1] || 0 return stringifyInteger(int) + '.' + dec } function stringifyBoolean (value) { return String(value) } function stringifyDatetime (value) { return value.toISOString() } function isNumber (type) { return type === 'float' || type === 'integer' } function arrayType (values) { var contentType = tomlType(values[0]) if (values.every(_ => tomlType(_) === contentType)) return contentType // mixed integer/float, emit as floats if (values.every(_ => isNumber(tomlType(_)))) return 'float' return 'mixed' } function validateArray (values) { const type = arrayType(values) if (type === 'mixed') { throw arrayOneTypeError() } return type } function stringifyInlineArray (values) { values = toJSON(values) const type = validateArray(values) var result = '[' var stringified = values.map(_ => stringifyInline(_, type)) if (stringified.join(', ').length > 60 || /\n/.test(stringified)) { result += '\n ' + stringified.join(',\n ') + '\n' } else { result += ' ' + stringified.join(', ') + (stringified.length > 0 ? ' ' : '') } return result + ']' } function stringifyInlineTable (value) { value = toJSON(value) var result = [] Object.keys(value).forEach(key => { result.push(stringifyKey(key) + ' = ' + stringifyAnyInline(value[key], false)) }) return '{ ' + result.join(', ') + (result.length > 0 ? ' ' : '') + '}' } function stringifyComplex (prefix, indent, key, value) { var valueType = tomlType(value) /* istanbul ignore else */ if (valueType === 'array') { return stringifyArrayOfTables(prefix, indent, key, value) } else if (valueType === 'table') { return stringifyComplexTable(prefix, indent, key, value) } else { throw typeError(valueType) } } function stringifyArrayOfTables (prefix, indent, key, values) { values = toJSON(values) validateArray(values) var firstValueType = tomlType(values[0]) /* istanbul ignore if */ if (firstValueType !== 'table') throw typeError(firstValueType) var fullKey = prefix + stringifyKey(key) var result = '' values.forEach(table => { if (result.length > 0) result += '\n' result += indent + '[[' + fullKey + ']]\n' result += stringifyObject(fullKey + '.', indent, table) }) return result } function stringifyComplexTable (prefix, indent, key, value) { var fullKey = prefix + stringifyKey(key) var result = '' if (getInlineKeys(value).length > 0) { result += indent + '[' + fullKey + ']\n' } return result + stringifyObject(fullKey + '.', indent, value) } /***/ }), /***/ "./node_modules/@iarna/toml/toml.js": /*!******************************************!*\ !*** ./node_modules/@iarna/toml/toml.js ***! \******************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; exports.parse = __webpack_require__(/*! ./parse.js */ "./node_modules/@iarna/toml/parse.js") exports.stringify = __webpack_require__(/*! ./stringify.js */ "./node_modules/@iarna/toml/stringify.js") /***/ }), /***/ "./node_modules/@vscode/python-extension/out/main.js": /*!***********************************************************!*\ !*** ./node_modules/@vscode/python-extension/out/main.js ***! \***********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PythonExtension = exports.PVSC_EXTENSION_ID = void 0; const vscode_1 = __webpack_require__(/*! vscode */ "vscode"); exports.PVSC_EXTENSION_ID = 'ms-python.python'; // eslint-disable-next-line @typescript-eslint/no-namespace var PythonExtension; (function (PythonExtension) { /** * Returns the API exposed by the Python extension in VS Code. */ async function api() { const extension = vscode_1.extensions.getExtension(exports.PVSC_EXTENSION_ID); if (extension === undefined) { throw new Error(`Python extension is not installed or is disabled`); } if (!extension.isActive) { await extension.activate(); } const pythonApi = extension.exports; return pythonApi; } PythonExtension.api = api; })(PythonExtension = exports.PythonExtension || (exports.PythonExtension = {})); //# sourceMappingURL=main.js.map /***/ }), /***/ "./node_modules/ajv/lib/ajv.js": /*!*************************************!*\ !*** ./node_modules/ajv/lib/ajv.js ***! \*************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var compileSchema = __webpack_require__(/*! ./compile */ "./node_modules/ajv/lib/compile/index.js") , resolve = __webpack_require__(/*! ./compile/resolve */ "./node_modules/ajv/lib/compile/resolve.js") , Cache = __webpack_require__(/*! ./cache */ "./node_modules/ajv/lib/cache.js") , SchemaObject = __webpack_require__(/*! ./compile/schema_obj */ "./node_modules/ajv/lib/compile/schema_obj.js") , stableStringify = __webpack_require__(/*! fast-json-stable-stringify */ "./node_modules/fast-json-stable-stringify/index.js") , formats = __webpack_require__(/*! ./compile/formats */ "./node_modules/ajv/lib/compile/formats.js") , rules = __webpack_require__(/*! ./compile/rules */ "./node_modules/ajv/lib/compile/rules.js") , $dataMetaSchema = __webpack_require__(/*! ./data */ "./node_modules/ajv/lib/data.js") , util = __webpack_require__(/*! ./compile/util */ "./node_modules/ajv/lib/compile/util.js"); module.exports = Ajv; Ajv.prototype.validate = validate; Ajv.prototype.compile = compile; Ajv.prototype.addSchema = addSchema; Ajv.prototype.addMetaSchema = addMetaSchema; Ajv.prototype.validateSchema = validateSchema; Ajv.prototype.getSchema = getSchema; Ajv.prototype.removeSchema = removeSchema; Ajv.prototype.addFormat = addFormat; Ajv.prototype.errorsText = errorsText; Ajv.prototype._addSchema = _addSchema; Ajv.prototype._compile = _compile; Ajv.prototype.compileAsync = __webpack_require__(/*! ./compile/async */ "./node_modules/ajv/lib/compile/async.js"); var customKeyword = __webpack_require__(/*! ./keyword */ "./node_modules/ajv/lib/keyword.js"); Ajv.prototype.addKeyword = customKeyword.add; Ajv.prototype.getKeyword = customKeyword.get; Ajv.prototype.removeKeyword = customKeyword.remove; Ajv.prototype.validateKeyword = customKeyword.validate; var errorClasses = __webpack_require__(/*! ./compile/error_classes */ "./node_modules/ajv/lib/compile/error_classes.js"); Ajv.ValidationError = errorClasses.Validation; Ajv.MissingRefError = errorClasses.MissingRef; Ajv.$dataMetaSchema = $dataMetaSchema; var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ]; var META_SUPPORT_DATA = ['/properties']; /** * Creates validator instance. * Usage: `Ajv(opts)` * @param {Object} opts optional options * @return {Object} ajv instance */ function Ajv(opts) { if (!(this instanceof Ajv)) return new Ajv(opts); opts = this._opts = util.copy(opts) || {}; setLogger(this); this._schemas = {}; this._refs = {}; this._fragments = {}; this._formats = formats(opts.format); this._cache = opts.cache || new Cache; this._loadingSchemas = {}; this._compilations = []; this.RULES = rules(); this._getId = chooseGetId(opts); opts.loopRequired = opts.loopRequired || Infinity; if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; if (opts.serialize === undefined) opts.serialize = stableStringify; this._metaOpts = getMetaSchemaOptions(this); if (opts.formats) addInitialFormats(this); if (opts.keywords) addInitialKeywords(this); addDefaultMetaSchema(this); if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta); if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}}); addInitialSchemas(this); } /** * Validate data using schema * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize. * @this Ajv * @param {String|Object} schemaKeyRef key, ref or schema object * @param {Any} data to be validated * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). */ function validate(schemaKeyRef, data) { var v; if (typeof schemaKeyRef == 'string') { v = this.getSchema(schemaKeyRef); if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); } else { var schemaObj = this._addSchema(schemaKeyRef); v = schemaObj.validate || this._compile(schemaObj); } var valid = v(data); if (v.$async !== true) this.errors = v.errors; return valid; } /** * Create validating function for passed schema. * @this Ajv * @param {Object} schema schema object * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. * @return {Function} validating function */ function compile(schema, _meta) { var schemaObj = this._addSchema(schema, undefined, _meta); return schemaObj.validate || this._compile(schemaObj); } /** * Adds schema to the instance. * @this Ajv * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. * @return {Ajv} this for method chaining */ function addSchema(schema, key, _skipValidation, _meta) { if (Array.isArray(schema)){ for (var i=0; i} errors optional array of validation errors, if not passed errors from the instance are used. * @param {Object} options optional options with properties `separator` and `dataVar`. * @return {String} human readable string with all errors descriptions */ function errorsText(errors, options) { errors = errors || this.errors; if (!errors) return 'No errors'; options = options || {}; var separator = options.separator === undefined ? ', ' : options.separator; var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; var text = ''; for (var i=0; i { "use strict"; var Cache = module.exports = function Cache() { this._cache = {}; }; Cache.prototype.put = function Cache_put(key, value) { this._cache[key] = value; }; Cache.prototype.get = function Cache_get(key) { return this._cache[key]; }; Cache.prototype.del = function Cache_del(key) { delete this._cache[key]; }; Cache.prototype.clear = function Cache_clear() { this._cache = {}; }; /***/ }), /***/ "./node_modules/ajv/lib/compile/async.js": /*!***********************************************!*\ !*** ./node_modules/ajv/lib/compile/async.js ***! \***********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var MissingRefError = (__webpack_require__(/*! ./error_classes */ "./node_modules/ajv/lib/compile/error_classes.js").MissingRef); module.exports = compileAsync; /** * Creates validating function for passed schema with asynchronous loading of missing schemas. * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema. * @this Ajv * @param {Object} schema schema object * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function. * @return {Promise} promise that resolves with a validating function. */ function compileAsync(schema, meta, callback) { /* eslint no-shadow: 0 */ /* global Promise */ /* jshint validthis: true */ var self = this; if (typeof this._opts.loadSchema != 'function') throw new Error('options.loadSchema should be a function'); if (typeof meta == 'function') { callback = meta; meta = undefined; } var p = loadMetaSchemaOf(schema).then(function () { var schemaObj = self._addSchema(schema, undefined, meta); return schemaObj.validate || _compileAsync(schemaObj); }); if (callback) { p.then( function(v) { callback(null, v); }, callback ); } return p; function loadMetaSchemaOf(sch) { var $schema = sch.$schema; return $schema && !self.getSchema($schema) ? compileAsync.call(self, { $ref: $schema }, true) : Promise.resolve(); } function _compileAsync(schemaObj) { try { return self._compile(schemaObj); } catch(e) { if (e instanceof MissingRefError) return loadMissingSchema(e); throw e; } function loadMissingSchema(e) { var ref = e.missingSchema; if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved'); var schemaPromise = self._loadingSchemas[ref]; if (!schemaPromise) { schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref); schemaPromise.then(removePromise, removePromise); } return schemaPromise.then(function (sch) { if (!added(ref)) { return loadMetaSchemaOf(sch).then(function () { if (!added(ref)) self.addSchema(sch, ref, undefined, meta); }); } }).then(function() { return _compileAsync(schemaObj); }); function removePromise() { delete self._loadingSchemas[ref]; } function added(ref) { return self._refs[ref] || self._schemas[ref]; } } } } /***/ }), /***/ "./node_modules/ajv/lib/compile/error_classes.js": /*!*******************************************************!*\ !*** ./node_modules/ajv/lib/compile/error_classes.js ***! \*******************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var resolve = __webpack_require__(/*! ./resolve */ "./node_modules/ajv/lib/compile/resolve.js"); module.exports = { Validation: errorSubclass(ValidationError), MissingRef: errorSubclass(MissingRefError) }; function ValidationError(errors) { this.message = 'validation failed'; this.errors = errors; this.ajv = this.validation = true; } MissingRefError.message = function (baseId, ref) { return 'can\'t resolve reference ' + ref + ' from id ' + baseId; }; function MissingRefError(baseId, ref, message) { this.message = message || MissingRefError.message(baseId, ref); this.missingRef = resolve.url(baseId, ref); this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef)); } function errorSubclass(Subclass) { Subclass.prototype = Object.create(Error.prototype); Subclass.prototype.constructor = Subclass; return Subclass; } /***/ }), /***/ "./node_modules/ajv/lib/compile/formats.js": /*!*************************************************!*\ !*** ./node_modules/ajv/lib/compile/formats.js ***! \*************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var util = __webpack_require__(/*! ./util */ "./node_modules/ajv/lib/compile/util.js"); var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31]; var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; // uri-template: https://tools.ietf.org/html/rfc6570 var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; // For the source: https://gist.github.com/dperini/729294 // For test cases: https://mathiasbynens.be/demo/url-regex // @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983. // var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i; var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; module.exports = formats; function formats(mode) { mode = mode == 'full' ? 'full' : 'fast'; return util.copy(formats[mode]); } formats.fast = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, 'uri-reference': /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, 'uri-template': URITEMPLATE, url: URL, // email (sources from jsen validator): // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation') email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, hostname: HOSTNAME, // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, regex: regex, // uuid: http://tools.ietf.org/html/rfc4122 uuid: UUID, // JSON-pointer: https://tools.ietf.org/html/rfc6901 // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A 'json-pointer': JSON_POINTER, 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 'relative-json-pointer': RELATIVE_JSON_POINTER }; formats.full = { date: date, time: time, 'date-time': date_time, uri: uri, 'uri-reference': URIREF, 'uri-template': URITEMPLATE, url: URL, email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, hostname: HOSTNAME, ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, regex: regex, uuid: UUID, 'json-pointer': JSON_POINTER, 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, 'relative-json-pointer': RELATIVE_JSON_POINTER }; function isLeapYear(year) { // https://tools.ietf.org/html/rfc3339#appendix-C return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } function date(str) { // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 var matches = str.match(DATE); if (!matches) return false; var year = +matches[1]; var month = +matches[2]; var day = +matches[3]; return month >= 1 && month <= 12 && day >= 1 && day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); } function time(str, full) { var matches = str.match(TIME); if (!matches) return false; var hour = matches[1]; var minute = matches[2]; var second = matches[3]; var timeZone = matches[5]; return ((hour <= 23 && minute <= 59 && second <= 59) || (hour == 23 && minute == 59 && second == 60)) && (!full || timeZone); } var DATE_TIME_SEPARATOR = /t|\s/i; function date_time(str) { // http://tools.ietf.org/html/rfc3339#section-5.6 var dateTime = str.split(DATE_TIME_SEPARATOR); return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); } var NOT_URI_FRAGMENT = /\/|:/; function uri(str) { // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." return NOT_URI_FRAGMENT.test(str) && URI.test(str); } var Z_ANCHOR = /[^\\]\\Z/; function regex(str) { if (Z_ANCHOR.test(str)) return false; try { new RegExp(str); return true; } catch(e) { return false; } } /***/ }), /***/ "./node_modules/ajv/lib/compile/index.js": /*!***********************************************!*\ !*** ./node_modules/ajv/lib/compile/index.js ***! \***********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var resolve = __webpack_require__(/*! ./resolve */ "./node_modules/ajv/lib/compile/resolve.js") , util = __webpack_require__(/*! ./util */ "./node_modules/ajv/lib/compile/util.js") , errorClasses = __webpack_require__(/*! ./error_classes */ "./node_modules/ajv/lib/compile/error_classes.js") , stableStringify = __webpack_require__(/*! fast-json-stable-stringify */ "./node_modules/fast-json-stable-stringify/index.js"); var validateGenerator = __webpack_require__(/*! ../dotjs/validate */ "./node_modules/ajv/lib/dotjs/validate.js"); /** * Functions below are used inside compiled validations function */ var ucs2length = util.ucs2length; var equal = __webpack_require__(/*! fast-deep-equal */ "./node_modules/fast-deep-equal/index.js"); // this error is thrown by async schemas to return validation errors via exception var ValidationError = errorClasses.Validation; module.exports = compile; /** * Compiles schema to validation function * @this Ajv * @param {Object} schema schema object * @param {Object} root object with information about the root schema for this schema * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution * @param {String} baseId base ID for IDs in the schema * @return {Function} validation function */ function compile(schema, root, localRefs, baseId) { /* jshint validthis: true, evil: true */ /* eslint no-shadow: 0 */ var self = this , opts = this._opts , refVal = [ undefined ] , refs = {} , patterns = [] , patternsHash = {} , defaults = [] , defaultsHash = {} , customRules = []; root = root || { schema: schema, refVal: refVal, refs: refs }; var c = checkCompiling.call(this, schema, root, baseId); var compilation = this._compilations[c.index]; if (c.compiling) return (compilation.callValidate = callValidate); var formats = this._formats; var RULES = this.RULES; try { var v = localCompile(schema, root, localRefs, baseId); compilation.validate = v; var cv = compilation.callValidate; if (cv) { cv.schema = v.schema; cv.errors = null; cv.refs = v.refs; cv.refVal = v.refVal; cv.root = v.root; cv.$async = v.$async; if (opts.sourceCode) cv.source = v.source; } return v; } finally { endCompiling.call(this, schema, root, baseId); } /* @this {*} - custom context, see passContext option */ function callValidate() { /* jshint validthis: true */ var validate = compilation.validate; var result = validate.apply(this, arguments); callValidate.errors = validate.errors; return result; } function localCompile(_schema, _root, localRefs, baseId) { var isRoot = !_root || (_root && _root.schema == _schema); if (_root.schema != root.schema) return compile.call(self, _schema, _root, localRefs, baseId); var $async = _schema.$async === true; var sourceCode = validateGenerator({ isTop: true, schema: _schema, isRoot: isRoot, baseId: baseId, root: _root, schemaPath: '', errSchemaPath: '#', errorPath: '""', MissingRefError: errorClasses.MissingRef, RULES: RULES, validate: validateGenerator, util: util, resolve: resolve, resolveRef: resolveRef, usePattern: usePattern, useDefault: useDefault, useCustomRule: useCustomRule, opts: opts, formats: formats, logger: self.logger, self: self }); sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + sourceCode; if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema); // console.log('\n\n\n *** \n', JSON.stringify(sourceCode)); var validate; try { var makeValidate = new Function( 'self', 'RULES', 'formats', 'root', 'refVal', 'defaults', 'customRules', 'equal', 'ucs2length', 'ValidationError', sourceCode ); validate = makeValidate( self, RULES, formats, root, refVal, defaults, customRules, equal, ucs2length, ValidationError ); refVal[0] = validate; } catch(e) { self.logger.error('Error compiling schema, function code:', sourceCode); throw e; } validate.schema = _schema; validate.errors = null; validate.refs = refs; validate.refVal = refVal; validate.root = isRoot ? validate : _root; if ($async) validate.$async = true; if (opts.sourceCode === true) { validate.source = { code: sourceCode, patterns: patterns, defaults: defaults }; } return validate; } function resolveRef(baseId, ref, isRoot) { ref = resolve.url(baseId, ref); var refIndex = refs[ref]; var _refVal, refCode; if (refIndex !== undefined) { _refVal = refVal[refIndex]; refCode = 'refVal[' + refIndex + ']'; return resolvedRef(_refVal, refCode); } if (!isRoot && root.refs) { var rootRefId = root.refs[ref]; if (rootRefId !== undefined) { _refVal = root.refVal[rootRefId]; refCode = addLocalRef(ref, _refVal); return resolvedRef(_refVal, refCode); } } refCode = addLocalRef(ref); var v = resolve.call(self, localCompile, root, ref); if (v === undefined) { var localSchema = localRefs && localRefs[ref]; if (localSchema) { v = resolve.inlineRef(localSchema, opts.inlineRefs) ? localSchema : compile.call(self, localSchema, root, localRefs, baseId); } } if (v === undefined) { removeLocalRef(ref); } else { replaceLocalRef(ref, v); return resolvedRef(v, refCode); } } function addLocalRef(ref, v) { var refId = refVal.length; refVal[refId] = v; refs[ref] = refId; return 'refVal' + refId; } function removeLocalRef(ref) { delete refs[ref]; } function replaceLocalRef(ref, v) { var refId = refs[ref]; refVal[refId] = v; } function resolvedRef(refVal, code) { return typeof refVal == 'object' || typeof refVal == 'boolean' ? { code: code, schema: refVal, inline: true } : { code: code, $async: refVal && !!refVal.$async }; } function usePattern(regexStr) { var index = patternsHash[regexStr]; if (index === undefined) { index = patternsHash[regexStr] = patterns.length; patterns[index] = regexStr; } return 'pattern' + index; } function useDefault(value) { switch (typeof value) { case 'boolean': case 'number': return '' + value; case 'string': return util.toQuotedString(value); case 'object': if (value === null) return 'null'; var valueStr = stableStringify(value); var index = defaultsHash[valueStr]; if (index === undefined) { index = defaultsHash[valueStr] = defaults.length; defaults[index] = value; } return 'default' + index; } } function useCustomRule(rule, schema, parentSchema, it) { if (self._opts.validateSchema !== false) { var deps = rule.definition.dependencies; if (deps && !deps.every(function(keyword) { return Object.prototype.hasOwnProperty.call(parentSchema, keyword); })) throw new Error('parent schema must have all required keywords: ' + deps.join(',')); var validateSchema = rule.definition.validateSchema; if (validateSchema) { var valid = validateSchema(schema); if (!valid) { var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); if (self._opts.validateSchema == 'log') self.logger.error(message); else throw new Error(message); } } } var compile = rule.definition.compile , inline = rule.definition.inline , macro = rule.definition.macro; var validate; if (compile) { validate = compile.call(self, schema, parentSchema, it); } else if (macro) { validate = macro.call(self, schema, parentSchema, it); if (opts.validateSchema !== false) self.validateSchema(validate, true); } else if (inline) { validate = inline.call(self, it, rule.keyword, schema, parentSchema); } else { validate = rule.definition.validate; if (!validate) return; } if (validate === undefined) throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); var index = customRules.length; customRules[index] = validate; return { code: 'customRule' + index, validate: validate }; } } /** * Checks if the schema is currently compiled * @this Ajv * @param {Object} schema schema to compile * @param {Object} root root object * @param {String} baseId base schema ID * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) */ function checkCompiling(schema, root, baseId) { /* jshint validthis: true */ var index = compIndex.call(this, schema, root, baseId); if (index >= 0) return { index: index, compiling: true }; index = this._compilations.length; this._compilations[index] = { schema: schema, root: root, baseId: baseId }; return { index: index, compiling: false }; } /** * Removes the schema from the currently compiled list * @this Ajv * @param {Object} schema schema to compile * @param {Object} root root object * @param {String} baseId base schema ID */ function endCompiling(schema, root, baseId) { /* jshint validthis: true */ var i = compIndex.call(this, schema, root, baseId); if (i >= 0) this._compilations.splice(i, 1); } /** * Index of schema compilation in the currently compiled list * @this Ajv * @param {Object} schema schema to compile * @param {Object} root root object * @param {String} baseId base schema ID * @return {Integer} compilation index */ function compIndex(schema, root, baseId) { /* jshint validthis: true */ for (var i=0; i { "use strict"; var URI = __webpack_require__(/*! uri-js */ "./node_modules/uri-js/dist/es5/uri.all.js") , equal = __webpack_require__(/*! fast-deep-equal */ "./node_modules/fast-deep-equal/index.js") , util = __webpack_require__(/*! ./util */ "./node_modules/ajv/lib/compile/util.js") , SchemaObject = __webpack_require__(/*! ./schema_obj */ "./node_modules/ajv/lib/compile/schema_obj.js") , traverse = __webpack_require__(/*! json-schema-traverse */ "./node_modules/json-schema-traverse/index.js"); module.exports = resolve; resolve.normalizeId = normalizeId; resolve.fullPath = getFullPath; resolve.url = resolveUrl; resolve.ids = resolveIds; resolve.inlineRef = inlineRef; resolve.schema = resolveSchema; /** * [resolve and compile the references ($ref)] * @this Ajv * @param {Function} compile reference to schema compilation funciton (localCompile) * @param {Object} root object with information about the root schema for the current schema * @param {String} ref reference to resolve * @return {Object|Function} schema object (if the schema can be inlined) or validation function */ function resolve(compile, root, ref) { /* jshint validthis: true */ var refVal = this._refs[ref]; if (typeof refVal == 'string') { if (this._refs[refVal]) refVal = this._refs[refVal]; else return resolve.call(this, compile, root, refVal); } refVal = refVal || this._schemas[ref]; if (refVal instanceof SchemaObject) { return inlineRef(refVal.schema, this._opts.inlineRefs) ? refVal.schema : refVal.validate || this._compile(refVal); } var res = resolveSchema.call(this, root, ref); var schema, v, baseId; if (res) { schema = res.schema; root = res.root; baseId = res.baseId; } if (schema instanceof SchemaObject) { v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId); } else if (schema !== undefined) { v = inlineRef(schema, this._opts.inlineRefs) ? schema : compile.call(this, schema, root, undefined, baseId); } return v; } /** * Resolve schema, its root and baseId * @this Ajv * @param {Object} root root object with properties schema, refVal, refs * @param {String} ref reference to resolve * @return {Object} object with properties schema, root, baseId */ function resolveSchema(root, ref) { /* jshint validthis: true */ var p = URI.parse(ref) , refPath = _getFullPath(p) , baseId = getFullPath(this._getId(root.schema)); if (Object.keys(root.schema).length === 0 || refPath !== baseId) { var id = normalizeId(refPath); var refVal = this._refs[id]; if (typeof refVal == 'string') { return resolveRecursive.call(this, root, refVal, p); } else if (refVal instanceof SchemaObject) { if (!refVal.validate) this._compile(refVal); root = refVal; } else { refVal = this._schemas[id]; if (refVal instanceof SchemaObject) { if (!refVal.validate) this._compile(refVal); if (id == normalizeId(ref)) return { schema: refVal, root: root, baseId: baseId }; root = refVal; } else { return; } } if (!root.schema) return; baseId = getFullPath(this._getId(root.schema)); } return getJsonPointer.call(this, p, baseId, root.schema, root); } /* @this Ajv */ function resolveRecursive(root, ref, parsedRef) { /* jshint validthis: true */ var res = resolveSchema.call(this, root, ref); if (res) { var schema = res.schema; var baseId = res.baseId; root = res.root; var id = this._getId(schema); if (id) baseId = resolveUrl(baseId, id); return getJsonPointer.call(this, parsedRef, baseId, schema, root); } } var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']); /* @this Ajv */ function getJsonPointer(parsedRef, baseId, schema, root) { /* jshint validthis: true */ parsedRef.fragment = parsedRef.fragment || ''; if (parsedRef.fragment.slice(0,1) != '/') return; var parts = parsedRef.fragment.split('/'); for (var i = 1; i < parts.length; i++) { var part = parts[i]; if (part) { part = util.unescapeFragment(part); schema = schema[part]; if (schema === undefined) break; var id; if (!PREVENT_SCOPE_CHANGE[part]) { id = this._getId(schema); if (id) baseId = resolveUrl(baseId, id); if (schema.$ref) { var $ref = resolveUrl(baseId, schema.$ref); var res = resolveSchema.call(this, root, $ref); if (res) { schema = res.schema; root = res.root; baseId = res.baseId; } } } } } if (schema !== undefined && schema !== root.schema) return { schema: schema, root: root, baseId: baseId }; } var SIMPLE_INLINED = util.toHash([ 'type', 'format', 'pattern', 'maxLength', 'minLength', 'maxProperties', 'minProperties', 'maxItems', 'minItems', 'maximum', 'minimum', 'uniqueItems', 'multipleOf', 'required', 'enum' ]); function inlineRef(schema, limit) { if (limit === false) return false; if (limit === undefined || limit === true) return checkNoRef(schema); else if (limit) return countKeys(schema) <= limit; } function checkNoRef(schema) { var item; if (Array.isArray(schema)) { for (var i=0; i { "use strict"; var ruleModules = __webpack_require__(/*! ../dotjs */ "./node_modules/ajv/lib/dotjs/index.js") , toHash = (__webpack_require__(/*! ./util */ "./node_modules/ajv/lib/compile/util.js").toHash); module.exports = function rules() { var RULES = [ { type: 'number', rules: [ { 'maximum': ['exclusiveMaximum'] }, { 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] }, { type: 'string', rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] }, { type: 'array', rules: [ 'maxItems', 'minItems', 'items', 'contains', 'uniqueItems' ] }, { type: 'object', rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames', { 'properties': ['additionalProperties', 'patternProperties'] } ] }, { rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if' ] } ]; var ALL = [ 'type', '$comment' ]; var KEYWORDS = [ '$schema', '$id', 'id', '$data', '$async', 'title', 'description', 'default', 'definitions', 'examples', 'readOnly', 'writeOnly', 'contentMediaType', 'contentEncoding', 'additionalItems', 'then', 'else' ]; var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ]; RULES.all = toHash(ALL); RULES.types = toHash(TYPES); RULES.forEach(function (group) { group.rules = group.rules.map(function (keyword) { var implKeywords; if (typeof keyword == 'object') { var key = Object.keys(keyword)[0]; implKeywords = keyword[key]; keyword = key; implKeywords.forEach(function (k) { ALL.push(k); RULES.all[k] = true; }); } ALL.push(keyword); var rule = RULES.all[keyword] = { keyword: keyword, code: ruleModules[keyword], implements: implKeywords }; return rule; }); RULES.all.$comment = { keyword: '$comment', code: ruleModules.$comment }; if (group.type) RULES.types[group.type] = group; }); RULES.keywords = toHash(ALL.concat(KEYWORDS)); RULES.custom = {}; return RULES; }; /***/ }), /***/ "./node_modules/ajv/lib/compile/schema_obj.js": /*!****************************************************!*\ !*** ./node_modules/ajv/lib/compile/schema_obj.js ***! \****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var util = __webpack_require__(/*! ./util */ "./node_modules/ajv/lib/compile/util.js"); module.exports = SchemaObject; function SchemaObject(obj) { util.copy(obj, this); } /***/ }), /***/ "./node_modules/ajv/lib/compile/ucs2length.js": /*!****************************************************!*\ !*** ./node_modules/ajv/lib/compile/ucs2length.js ***! \****************************************************/ /***/ ((module) => { "use strict"; // https://mathiasbynens.be/notes/javascript-encoding // https://github.com/bestiejs/punycode.js - punycode.ucs2.decode module.exports = function ucs2length(str) { var length = 0 , len = str.length , pos = 0 , value; while (pos < len) { length++; value = str.charCodeAt(pos++); if (value >= 0xD800 && value <= 0xDBFF && pos < len) { // high surrogate, and there is a next character value = str.charCodeAt(pos); if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate } } return length; }; /***/ }), /***/ "./node_modules/ajv/lib/compile/util.js": /*!**********************************************!*\ !*** ./node_modules/ajv/lib/compile/util.js ***! \**********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = { copy: copy, checkDataType: checkDataType, checkDataTypes: checkDataTypes, coerceToTypes: coerceToTypes, toHash: toHash, getProperty: getProperty, escapeQuotes: escapeQuotes, equal: __webpack_require__(/*! fast-deep-equal */ "./node_modules/fast-deep-equal/index.js"), ucs2length: __webpack_require__(/*! ./ucs2length */ "./node_modules/ajv/lib/compile/ucs2length.js"), varOccurences: varOccurences, varReplace: varReplace, schemaHasRules: schemaHasRules, schemaHasRulesExcept: schemaHasRulesExcept, schemaUnknownRules: schemaUnknownRules, toQuotedString: toQuotedString, getPathExpr: getPathExpr, getPath: getPath, getData: getData, unescapeFragment: unescapeFragment, unescapeJsonPointer: unescapeJsonPointer, escapeFragment: escapeFragment, escapeJsonPointer: escapeJsonPointer }; function copy(o, to) { to = to || {}; for (var key in o) to[key] = o[key]; return to; } function checkDataType(dataType, data, strictNumbers, negate) { var EQUAL = negate ? ' !== ' : ' === ' , AND = negate ? ' || ' : ' && ' , OK = negate ? '!' : '' , NOT = negate ? '' : '!'; switch (dataType) { case 'null': return data + EQUAL + 'null'; case 'array': return OK + 'Array.isArray(' + data + ')'; case 'object': return '(' + OK + data + AND + 'typeof ' + data + EQUAL + '"object"' + AND + NOT + 'Array.isArray(' + data + '))'; case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND + NOT + '(' + data + ' % 1)' + AND + data + EQUAL + data + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; default: return 'typeof ' + data + EQUAL + '"' + dataType + '"'; } } function checkDataTypes(dataTypes, data, strictNumbers) { switch (dataTypes.length) { case 1: return checkDataType(dataTypes[0], data, strictNumbers, true); default: var code = ''; var types = toHash(dataTypes); if (types.array && types.object) { code = types.null ? '(': '(!' + data + ' || '; code += 'typeof ' + data + ' !== "object")'; delete types.null; delete types.array; delete types.object; } if (types.number) delete types.integer; for (var t in types) code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true); return code; } } var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); function coerceToTypes(optionCoerceTypes, dataTypes) { if (Array.isArray(dataTypes)) { var types = []; for (var i=0; i= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); return paths[lvl - up]; } if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); data = 'data' + ((lvl - up) || ''); if (!jsonPointer) return data; } var expr = data; var segments = jsonPointer.split('/'); for (var i=0; i { "use strict"; var KEYWORDS = [ 'multipleOf', 'maximum', 'exclusiveMaximum', 'minimum', 'exclusiveMinimum', 'maxLength', 'minLength', 'pattern', 'additionalItems', 'maxItems', 'minItems', 'uniqueItems', 'maxProperties', 'minProperties', 'required', 'additionalProperties', 'enum', 'format', 'const' ]; module.exports = function (metaSchema, keywordsJsonPointers) { for (var i=0; i { "use strict"; var metaSchema = __webpack_require__(/*! ./refs/json-schema-draft-07.json */ "./node_modules/ajv/lib/refs/json-schema-draft-07.json"); module.exports = { $id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js', definitions: { simpleTypes: metaSchema.definitions.simpleTypes }, type: 'object', dependencies: { schema: ['validate'], $data: ['validate'], statements: ['inline'], valid: {not: {required: ['macro']}} }, properties: { type: metaSchema.properties.type, schema: {type: 'boolean'}, statements: {type: 'boolean'}, dependencies: { type: 'array', items: {type: 'string'} }, metaSchema: {type: 'object'}, modifying: {type: 'boolean'}, valid: {type: 'boolean'}, $data: {type: 'boolean'}, async: {type: 'boolean'}, errors: { anyOf: [ {type: 'boolean'}, {const: 'full'} ] } } }; /***/ }), /***/ "./node_modules/ajv/lib/dotjs/_limit.js": /*!**********************************************!*\ !*** ./node_modules/ajv/lib/dotjs/_limit.js ***! \**********************************************/ /***/ ((module) => { "use strict"; module.exports = function generate__limit(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $errorKeyword; var $data = 'data' + ($dataLvl || ''); var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $isMax = $keyword == 'maximum', $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum', $schemaExcl = it.schema[$exclusiveKeyword], $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, $op = $isMax ? '<' : '>', $notOp = $isMax ? '>' : '<', $errorKeyword = undefined; if (!($isData || typeof $schema == 'number' || $schema === undefined)) { throw new Error($keyword + ' must be number'); } if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) { throw new Error($exclusiveKeyword + ' must be number or boolean'); } if ($isDataExcl) { var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), $exclusive = 'exclusive' + $lvl, $exclType = 'exclType' + $lvl, $exclIsNumber = 'exclIsNumber' + $lvl, $opExpr = 'op' + $lvl, $opStr = '\' + ' + $opExpr + ' + \''; out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; $schemaValueExcl = 'schemaExcl' + $lvl; out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { '; var $errorKeyword = $exclusiveKeyword; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; if (it.opts.messages !== false) { out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } else if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; '; if ($schema === undefined) { $errorKeyword = $exclusiveKeyword; $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; $schemaValue = $schemaValueExcl; $isData = $isDataExcl; } } else { var $exclIsNumber = typeof $schemaExcl == 'number', $opStr = $op; if ($exclIsNumber && $isData) { var $opExpr = '\'' + $opStr + '\''; out += ' if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { '; } else { if ($exclIsNumber && $schema === undefined) { $exclusive = true; $errorKeyword = $exclusiveKeyword; $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; $schemaValue = $schemaExcl; $notOp += '='; } else { if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { $exclusive = true; $errorKeyword = $exclusiveKeyword; $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; $notOp += '='; } else { $exclusive = false; $opStr += '='; } } var $opExpr = '\'' + $opStr + '\''; out += ' if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { '; } } $errorKeyword = $errorKeyword || $keyword; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should be ' + ($opStr) + ' '; if ($isData) { out += '\' + ' + ($schemaValue); } else { out += '' + ($schemaValue) + '\''; } } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + ($schema); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } '; if ($breakOnError) { out += ' else { '; } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/_limitItems.js": /*!***************************************************!*\ !*** ./node_modules/ajv/lib/dotjs/_limitItems.js ***! \***************************************************/ /***/ ((module) => { "use strict"; module.exports = function generate__limitItems(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $errorKeyword; var $data = 'data' + ($dataLvl || ''); var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } if (!($isData || typeof $schema == 'number')) { throw new Error($keyword + ' must be number'); } var $op = $keyword == 'maxItems' ? '>' : '<'; out += 'if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { '; var $errorKeyword = $keyword; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should NOT have '; if ($keyword == 'maxItems') { out += 'more'; } else { out += 'fewer'; } out += ' than '; if ($isData) { out += '\' + ' + ($schemaValue) + ' + \''; } else { out += '' + ($schema); } out += ' items\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + ($schema); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += '} '; if ($breakOnError) { out += ' else { '; } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/_limitLength.js": /*!****************************************************!*\ !*** ./node_modules/ajv/lib/dotjs/_limitLength.js ***! \****************************************************/ /***/ ((module) => { "use strict"; module.exports = function generate__limitLength(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $errorKeyword; var $data = 'data' + ($dataLvl || ''); var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } if (!($isData || typeof $schema == 'number')) { throw new Error($keyword + ' must be number'); } var $op = $keyword == 'maxLength' ? '>' : '<'; out += 'if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } if (it.opts.unicode === false) { out += ' ' + ($data) + '.length '; } else { out += ' ucs2length(' + ($data) + ') '; } out += ' ' + ($op) + ' ' + ($schemaValue) + ') { '; var $errorKeyword = $keyword; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should NOT be '; if ($keyword == 'maxLength') { out += 'longer'; } else { out += 'shorter'; } out += ' than '; if ($isData) { out += '\' + ' + ($schemaValue) + ' + \''; } else { out += '' + ($schema); } out += ' characters\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + ($schema); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += '} '; if ($breakOnError) { out += ' else { '; } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/_limitProperties.js": /*!********************************************************!*\ !*** ./node_modules/ajv/lib/dotjs/_limitProperties.js ***! \********************************************************/ /***/ ((module) => { "use strict"; module.exports = function generate__limitProperties(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $errorKeyword; var $data = 'data' + ($dataLvl || ''); var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } if (!($isData || typeof $schema == 'number')) { throw new Error($keyword + ' must be number'); } var $op = $keyword == 'maxProperties' ? '>' : '<'; out += 'if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { '; var $errorKeyword = $keyword; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should NOT have '; if ($keyword == 'maxProperties') { out += 'more'; } else { out += 'fewer'; } out += ' than '; if ($isData) { out += '\' + ' + ($schemaValue) + ' + \''; } else { out += '' + ($schema); } out += ' properties\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + ($schema); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += '} '; if ($breakOnError) { out += ' else { '; } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/allOf.js": /*!*********************************************!*\ !*** ./node_modules/ajv/lib/dotjs/allOf.js ***! \*********************************************/ /***/ ((module) => { "use strict"; module.exports = function generate_allOf(it, $keyword, $ruleType) { var out = ' '; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $currentBaseId = $it.baseId, $allSchemasEmpty = true; var arr1 = $schema; if (arr1) { var $sch, $i = -1, l1 = arr1.length - 1; while ($i < l1) { $sch = arr1[$i += 1]; if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { $allSchemasEmpty = false; $it.schema = $sch; $it.schemaPath = $schemaPath + '[' + $i + ']'; $it.errSchemaPath = $errSchemaPath + '/' + $i; out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } } } if ($breakOnError) { if ($allSchemasEmpty) { out += ' if (true) { '; } else { out += ' ' + ($closingBraces.slice(0, -1)) + ' '; } } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/anyOf.js": /*!*********************************************!*\ !*** ./node_modules/ajv/lib/dotjs/anyOf.js ***! \*********************************************/ /***/ ((module) => { "use strict"; module.exports = function generate_anyOf(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $noEmptySchema = $schema.every(function($sch) { return (it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)); }); if ($noEmptySchema) { var $currentBaseId = $it.baseId; out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; '; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; var arr1 = $schema; if (arr1) { var $sch, $i = -1, l1 = arr1.length - 1; while ($i < l1) { $sch = arr1[$i += 1]; $it.schema = $sch; $it.schemaPath = $schemaPath + '[' + $i + ']'; $it.errSchemaPath = $errSchemaPath + '/' + $i; out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { '; $closingBraces += '}'; } } it.compositeRule = $it.compositeRule = $wasComposite; out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; if (it.opts.messages !== false) { out += ' , message: \'should match some schema in anyOf\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError(vErrors); '; } else { out += ' validate.errors = vErrors; return false; '; } } out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; if (it.opts.allErrors) { out += ' } '; } } else { if ($breakOnError) { out += ' if (true) { '; } } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/comment.js": /*!***********************************************!*\ !*** ./node_modules/ajv/lib/dotjs/comment.js ***! \***********************************************/ /***/ ((module) => { "use strict"; module.exports = function generate_comment(it, $keyword, $ruleType) { var out = ' '; var $schema = it.schema[$keyword]; var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $comment = it.util.toQuotedString($schema); if (it.opts.$comment === true) { out += ' console.log(' + ($comment) + ');'; } else if (typeof it.opts.$comment == 'function') { out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);'; } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/const.js": /*!*********************************************!*\ !*** ./node_modules/ajv/lib/dotjs/const.js ***! \*********************************************/ /***/ ((module) => { "use strict"; module.exports = function generate_const(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } if (!$isData) { out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';'; } out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should be equal to constant\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' }'; if ($breakOnError) { out += ' else { '; } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/contains.js": /*!************************************************!*\ !*** ./node_modules/ajv/lib/dotjs/contains.js ***! \************************************************/ /***/ ((module) => { "use strict"; module.exports = function generate_contains(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $idx = 'i' + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $currentBaseId = it.baseId, $nonEmptySchema = (it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all)); out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; if ($nonEmptySchema) { var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; $it.schema = $schema; $it.schemaPath = $schemaPath; $it.errSchemaPath = $errSchemaPath; out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); var $passData = $data + '[' + $idx + ']'; $it.dataPathArr[$dataNxt] = $idx; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } out += ' if (' + ($nextValid) + ') break; } '; it.compositeRule = $it.compositeRule = $wasComposite; out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {'; } else { out += ' if (' + ($data) + '.length == 0) {'; } var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; if (it.opts.messages !== false) { out += ' , message: \'should contain a valid item\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } else { '; if ($nonEmptySchema) { out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; } if (it.opts.allErrors) { out += ' } '; } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/custom.js": /*!**********************************************!*\ !*** ./node_modules/ajv/lib/dotjs/custom.js ***! \**********************************************/ /***/ ((module) => { "use strict"; module.exports = function generate_custom(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $errorKeyword; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $errs = 'errs__' + $lvl; var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $rule = this, $definition = 'definition' + $lvl, $rDef = $rule.definition, $closingBraces = ''; var $compile, $inline, $macro, $ruleValidate, $validateCode; if ($isData && $rDef.$data) { $validateCode = 'keywordValidate' + $lvl; var $validateSchema = $rDef.validateSchema; out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;'; } else { $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); if (!$ruleValidate) return; $schemaValue = 'validate.schema' + $schemaPath; $validateCode = $ruleValidate.code; $compile = $rDef.compile; $inline = $rDef.inline; $macro = $rDef.macro; } var $ruleErrs = $validateCode + '.errors', $i = 'i' + $lvl, $ruleErr = 'ruleErr' + $lvl, $asyncKeyword = $rDef.async; if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); if (!($inline || $macro)) { out += '' + ($ruleErrs) + ' = null;'; } out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; if ($isData && $rDef.$data) { $closingBraces += '}'; out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { '; if ($validateSchema) { $closingBraces += '}'; out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { '; } } if ($inline) { if ($rDef.statements) { out += ' ' + ($ruleValidate.validate) + ' '; } else { out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; '; } } else if ($macro) { var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; $it.schema = $ruleValidate.validate; $it.schemaPath = ''; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); it.compositeRule = $it.compositeRule = $wasComposite; out += ' ' + ($code); } else { var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; out += ' ' + ($validateCode) + '.call( '; if (it.opts.passContext) { out += 'this'; } else { out += 'self'; } if ($compile || $rDef.schema === false) { out += ' , ' + ($data) + ' '; } else { out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' '; } out += ' , (dataPath || \'\')'; if (it.errorPath != '""') { out += ' + ' + (it.errorPath); } var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) '; var def_callRuleValidate = out; out = $$outStack.pop(); if ($rDef.errors === false) { out += ' ' + ($valid) + ' = '; if ($asyncKeyword) { out += 'await '; } out += '' + (def_callRuleValidate) + '; '; } else { if ($asyncKeyword) { $ruleErrs = 'customErrors' + $lvl; out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } '; } else { out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; '; } } } if ($rDef.modifying) { out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; } out += '' + ($closingBraces); if ($rDef.valid) { if ($breakOnError) { out += ' if (true) { '; } } else { out += ' if ( '; if ($rDef.valid === undefined) { out += ' !'; if ($macro) { out += '' + ($nextValid); } else { out += '' + ($valid); } } else { out += ' ' + (!$rDef.valid) + ' '; } out += ') { '; $errorKeyword = $rule.keyword; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } var def_customError = out; out = $$outStack.pop(); if ($inline) { if ($rDef.errors) { if ($rDef.errors != 'full') { out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + ' { "use strict"; module.exports = function generate_dependencies(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $schemaDeps = {}, $propertyDeps = {}, $ownProperties = it.opts.ownProperties; for ($property in $schema) { if ($property == '__proto__') continue; var $sch = $schema[$property]; var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps; $deps[$property] = $sch; } out += 'var ' + ($errs) + ' = errors;'; var $currentErrorPath = it.errorPath; out += 'var missing' + ($lvl) + ';'; for (var $property in $propertyDeps) { $deps = $propertyDeps[$property]; if ($deps.length) { out += ' if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; if ($ownProperties) { out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; } if ($breakOnError) { out += ' && ( '; var arr1 = $deps; if (arr1) { var $propertyKey, $i = -1, l1 = arr1.length - 1; while ($i < l1) { $propertyKey = arr1[$i += 1]; if ($i) { out += ' || '; } var $prop = it.util.getProperty($propertyKey), $useData = $data + $prop; out += ' ( ( ' + ($useData) + ' === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; } } out += ')) { '; var $propertyPath = 'missing' + $lvl, $missingProperty = '\' + ' + $propertyPath + ' + \''; if (it.opts._errorDataPathProperty) { it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; } var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \'should have '; if ($deps.length == 1) { out += 'property ' + (it.util.escapeQuotes($deps[0])); } else { out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); } out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } } else { out += ' ) { '; var arr2 = $deps; if (arr2) { var $propertyKey, i2 = -1, l2 = arr2.length - 1; while (i2 < l2) { $propertyKey = arr2[i2 += 1]; var $prop = it.util.getProperty($propertyKey), $missingProperty = it.util.escapeQuotes($propertyKey), $useData = $data + $prop; if (it.opts._errorDataPathProperty) { it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); } out += ' if ( ' + ($useData) + ' === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ') { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \'should have '; if ($deps.length == 1) { out += 'property ' + (it.util.escapeQuotes($deps[0])); } else { out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); } out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; } } } out += ' } '; if ($breakOnError) { $closingBraces += '}'; out += ' else { '; } } } it.errorPath = $currentErrorPath; var $currentBaseId = $it.baseId; for (var $property in $schemaDeps) { var $sch = $schemaDeps[$property]; if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; if ($ownProperties) { out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; } out += ') { '; $it.schema = $sch; $it.schemaPath = $schemaPath + it.util.getProperty($property); $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property); out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; out += ' } '; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } } if ($breakOnError) { out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/enum.js": /*!********************************************!*\ !*** ./node_modules/ajv/lib/dotjs/enum.js ***! \********************************************/ /***/ ((module) => { "use strict"; module.exports = function generate_enum(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $i = 'i' + $lvl, $vSchema = 'schema' + $lvl; if (!$isData) { out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';'; } out += 'var ' + ($valid) + ';'; if ($isData) { out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; } out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }'; if ($isData) { out += ' } '; } out += ' if (!' + ($valid) + ') { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should be equal to one of the allowed values\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' }'; if ($breakOnError) { out += ' else { '; } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/format.js": /*!**********************************************!*\ !*** ./node_modules/ajv/lib/dotjs/format.js ***! \**********************************************/ /***/ ((module) => { "use strict"; module.exports = function generate_format(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); if (it.opts.format === false) { if ($breakOnError) { out += ' if (true) { '; } return out; } var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $unknownFormats = it.opts.unknownFormats, $allowUnknown = Array.isArray($unknownFormats); if ($isData) { var $format = 'format' + $lvl, $isObject = 'isObject' + $lvl, $formatType = 'formatType' + $lvl; out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { '; if (it.async) { out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; '; } out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; } out += ' ('; if ($unknownFormats != 'ignore') { out += ' (' + ($schemaValue) + ' && !' + ($format) + ' '; if ($allowUnknown) { out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 '; } out += ') || '; } out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? '; if (it.async) { out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) '; } else { out += ' ' + ($format) + '(' + ($data) + ') '; } out += ' : ' + ($format) + '.test(' + ($data) + '))))) {'; } else { var $format = it.formats[$schema]; if (!$format) { if ($unknownFormats == 'ignore') { it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); if ($breakOnError) { out += ' if (true) { '; } return out; } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) { if ($breakOnError) { out += ' if (true) { '; } return out; } else { throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); } } var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate; var $formatType = $isObject && $format.type || 'string'; if ($isObject) { var $async = $format.async === true; $format = $format.validate; } if ($formatType != $ruleType) { if ($breakOnError) { out += ' if (true) { '; } return out; } if ($async) { if (!it.async) throw new Error('async format in sync schema'); var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { '; } else { out += ' if (! '; var $formatRef = 'formats' + it.util.getProperty($schema); if ($isObject) $formatRef += '.validate'; if (typeof $format == 'function') { out += ' ' + ($formatRef) + '(' + ($data) + ') '; } else { out += ' ' + ($formatRef) + '.test(' + ($data) + ') '; } out += ') { '; } } var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: '; if ($isData) { out += '' + ($schemaValue); } else { out += '' + (it.util.toQuotedString($schema)); } out += ' } '; if (it.opts.messages !== false) { out += ' , message: \'should match format "'; if ($isData) { out += '\' + ' + ($schemaValue) + ' + \''; } else { out += '' + (it.util.escapeQuotes($schema)); } out += '"\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + (it.util.toQuotedString($schema)); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } '; if ($breakOnError) { out += ' else { '; } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/if.js": /*!******************************************!*\ !*** ./node_modules/ajv/lib/dotjs/if.js ***! \******************************************/ /***/ ((module) => { "use strict"; module.exports = function generate_if(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); $it.level++; var $nextValid = 'valid' + $it.level; var $thenSch = it.schema['then'], $elseSch = it.schema['else'], $thenPresent = $thenSch !== undefined && (it.opts.strictKeywords ? (typeof $thenSch == 'object' && Object.keys($thenSch).length > 0) || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)), $elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? (typeof $elseSch == 'object' && Object.keys($elseSch).length > 0) || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)), $currentBaseId = $it.baseId; if ($thenPresent || $elsePresent) { var $ifClause; $it.createErrors = false; $it.schema = $schema; $it.schemaPath = $schemaPath; $it.errSchemaPath = $errSchemaPath; out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; '; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; $it.createErrors = true; out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; it.compositeRule = $it.compositeRule = $wasComposite; if ($thenPresent) { out += ' if (' + ($nextValid) + ') { '; $it.schema = it.schema['then']; $it.schemaPath = it.schemaPath + '.then'; $it.errSchemaPath = it.errSchemaPath + '/then'; out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; if ($thenPresent && $elsePresent) { $ifClause = 'ifClause' + $lvl; out += ' var ' + ($ifClause) + ' = \'then\'; '; } else { $ifClause = '\'then\''; } out += ' } '; if ($elsePresent) { out += ' else { '; } } else { out += ' if (!' + ($nextValid) + ') { '; } if ($elsePresent) { $it.schema = it.schema['else']; $it.schemaPath = it.schemaPath + '.else'; $it.errSchemaPath = it.errSchemaPath + '/else'; out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; if ($thenPresent && $elsePresent) { $ifClause = 'ifClause' + $lvl; out += ' var ' + ($ifClause) + ' = \'else\'; '; } else { $ifClause = '\'else\''; } out += ' } '; } out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError(vErrors); '; } else { out += ' validate.errors = vErrors; return false; '; } } out += ' } '; if ($breakOnError) { out += ' else { '; } } else { if ($breakOnError) { out += ' if (true) { '; } } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/index.js": /*!*********************************************!*\ !*** ./node_modules/ajv/lib/dotjs/index.js ***! \*********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; //all requires must be explicit because browserify won't work with dynamic requires module.exports = { '$ref': __webpack_require__(/*! ./ref */ "./node_modules/ajv/lib/dotjs/ref.js"), allOf: __webpack_require__(/*! ./allOf */ "./node_modules/ajv/lib/dotjs/allOf.js"), anyOf: __webpack_require__(/*! ./anyOf */ "./node_modules/ajv/lib/dotjs/anyOf.js"), '$comment': __webpack_require__(/*! ./comment */ "./node_modules/ajv/lib/dotjs/comment.js"), const: __webpack_require__(/*! ./const */ "./node_modules/ajv/lib/dotjs/const.js"), contains: __webpack_require__(/*! ./contains */ "./node_modules/ajv/lib/dotjs/contains.js"), dependencies: __webpack_require__(/*! ./dependencies */ "./node_modules/ajv/lib/dotjs/dependencies.js"), 'enum': __webpack_require__(/*! ./enum */ "./node_modules/ajv/lib/dotjs/enum.js"), format: __webpack_require__(/*! ./format */ "./node_modules/ajv/lib/dotjs/format.js"), 'if': __webpack_require__(/*! ./if */ "./node_modules/ajv/lib/dotjs/if.js"), items: __webpack_require__(/*! ./items */ "./node_modules/ajv/lib/dotjs/items.js"), maximum: __webpack_require__(/*! ./_limit */ "./node_modules/ajv/lib/dotjs/_limit.js"), minimum: __webpack_require__(/*! ./_limit */ "./node_modules/ajv/lib/dotjs/_limit.js"), maxItems: __webpack_require__(/*! ./_limitItems */ "./node_modules/ajv/lib/dotjs/_limitItems.js"), minItems: __webpack_require__(/*! ./_limitItems */ "./node_modules/ajv/lib/dotjs/_limitItems.js"), maxLength: __webpack_require__(/*! ./_limitLength */ "./node_modules/ajv/lib/dotjs/_limitLength.js"), minLength: __webpack_require__(/*! ./_limitLength */ "./node_modules/ajv/lib/dotjs/_limitLength.js"), maxProperties: __webpack_require__(/*! ./_limitProperties */ "./node_modules/ajv/lib/dotjs/_limitProperties.js"), minProperties: __webpack_require__(/*! ./_limitProperties */ "./node_modules/ajv/lib/dotjs/_limitProperties.js"), multipleOf: __webpack_require__(/*! ./multipleOf */ "./node_modules/ajv/lib/dotjs/multipleOf.js"), not: __webpack_require__(/*! ./not */ "./node_modules/ajv/lib/dotjs/not.js"), oneOf: __webpack_require__(/*! ./oneOf */ "./node_modules/ajv/lib/dotjs/oneOf.js"), pattern: __webpack_require__(/*! ./pattern */ "./node_modules/ajv/lib/dotjs/pattern.js"), properties: __webpack_require__(/*! ./properties */ "./node_modules/ajv/lib/dotjs/properties.js"), propertyNames: __webpack_require__(/*! ./propertyNames */ "./node_modules/ajv/lib/dotjs/propertyNames.js"), required: __webpack_require__(/*! ./required */ "./node_modules/ajv/lib/dotjs/required.js"), uniqueItems: __webpack_require__(/*! ./uniqueItems */ "./node_modules/ajv/lib/dotjs/uniqueItems.js"), validate: __webpack_require__(/*! ./validate */ "./node_modules/ajv/lib/dotjs/validate.js") }; /***/ }), /***/ "./node_modules/ajv/lib/dotjs/items.js": /*!*********************************************!*\ !*** ./node_modules/ajv/lib/dotjs/items.js ***! \*********************************************/ /***/ ((module) => { "use strict"; module.exports = function generate_items(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $idx = 'i' + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $currentBaseId = it.baseId; out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; if (Array.isArray($schema)) { var $additionalItems = it.schema.additionalItems; if ($additionalItems === false) { out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; '; var $currErrSchemaPath = $errSchemaPath; $errSchemaPath = it.errSchemaPath + '/additionalItems'; out += ' if (!' + ($valid) + ') { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' '; } if (it.opts.verbose) { out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } '; $errSchemaPath = $currErrSchemaPath; if ($breakOnError) { $closingBraces += '}'; out += ' else { '; } } var arr1 = $schema; if (arr1) { var $sch, $i = -1, l1 = arr1.length - 1; while ($i < l1) { $sch = arr1[$i += 1]; if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { '; var $passData = $data + '[' + $i + ']'; $it.schema = $sch; $it.schemaPath = $schemaPath + '[' + $i + ']'; $it.errSchemaPath = $errSchemaPath + '/' + $i; $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); $it.dataPathArr[$dataNxt] = $i; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } out += ' } '; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } } } if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? (typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0) || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) { $it.schema = $additionalItems; $it.schemaPath = it.schemaPath + '.additionalItems'; $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); var $passData = $data + '[' + $idx + ']'; $it.dataPathArr[$dataNxt] = $idx; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } if ($breakOnError) { out += ' if (!' + ($nextValid) + ') break; '; } out += ' } } '; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } } else if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { $it.schema = $schema; $it.schemaPath = $schemaPath; $it.errSchemaPath = $errSchemaPath; out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); var $passData = $data + '[' + $idx + ']'; $it.dataPathArr[$dataNxt] = $idx; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } if ($breakOnError) { out += ' if (!' + ($nextValid) + ') break; '; } out += ' }'; } if ($breakOnError) { out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/multipleOf.js": /*!**************************************************!*\ !*** ./node_modules/ajv/lib/dotjs/multipleOf.js ***! \**************************************************/ /***/ ((module) => { "use strict"; module.exports = function generate_multipleOf(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } if (!($isData || typeof $schema == 'number')) { throw new Error($keyword + ' must be number'); } out += 'var division' + ($lvl) + ';if ('; if ($isData) { out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || '; } out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', '; if (it.opts.multipleOfPrecision) { out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' '; } else { out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') '; } out += ' ) '; if ($isData) { out += ' ) '; } out += ' ) { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should be multiple of '; if ($isData) { out += '\' + ' + ($schemaValue); } else { out += '' + ($schemaValue) + '\''; } } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + ($schema); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += '} '; if ($breakOnError) { out += ' else { '; } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/not.js": /*!*******************************************!*\ !*** ./node_modules/ajv/lib/dotjs/not.js ***! \*******************************************/ /***/ ((module) => { "use strict"; module.exports = function generate_not(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); $it.level++; var $nextValid = 'valid' + $it.level; if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { $it.schema = $schema; $it.schemaPath = $schemaPath; $it.errSchemaPath = $errSchemaPath; out += ' var ' + ($errs) + ' = errors; '; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; $it.createErrors = false; var $allErrorsOption; if ($it.opts.allErrors) { $allErrorsOption = $it.opts.allErrors; $it.opts.allErrors = false; } out += ' ' + (it.validate($it)) + ' '; $it.createErrors = true; if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; it.compositeRule = $it.compositeRule = $wasComposite; out += ' if (' + ($nextValid) + ') { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; if (it.opts.messages !== false) { out += ' , message: \'should NOT be valid\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; if (it.opts.allErrors) { out += ' } '; } } else { out += ' var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; if (it.opts.messages !== false) { out += ' , message: \'should NOT be valid\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; if ($breakOnError) { out += ' if (false) { '; } } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/oneOf.js": /*!*********************************************!*\ !*** ./node_modules/ajv/lib/dotjs/oneOf.js ***! \*********************************************/ /***/ ((module) => { "use strict"; module.exports = function generate_oneOf(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $currentBaseId = $it.baseId, $prevValid = 'prevValid' + $lvl, $passingSchemas = 'passingSchemas' + $lvl; out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; '; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; var arr1 = $schema; if (arr1) { var $sch, $i = -1, l1 = arr1.length - 1; while ($i < l1) { $sch = arr1[$i += 1]; if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { $it.schema = $sch; $it.schemaPath = $schemaPath + '[' + $i + ']'; $it.errSchemaPath = $errSchemaPath + '/' + $i; out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; } else { out += ' var ' + ($nextValid) + ' = true; '; } if ($i) { out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { '; $closingBraces += '}'; } out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }'; } } it.compositeRule = $it.compositeRule = $wasComposite; out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should match exactly one schema in oneOf\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError(vErrors); '; } else { out += ' validate.errors = vErrors; return false; '; } } out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }'; if (it.opts.allErrors) { out += ' } '; } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/pattern.js": /*!***********************************************!*\ !*** ./node_modules/ajv/lib/dotjs/pattern.js ***! \***********************************************/ /***/ ((module) => { "use strict"; module.exports = function generate_pattern(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema); out += 'if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; } out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: '; if ($isData) { out += '' + ($schemaValue); } else { out += '' + (it.util.toQuotedString($schema)); } out += ' } '; if (it.opts.messages !== false) { out += ' , message: \'should match pattern "'; if ($isData) { out += '\' + ' + ($schemaValue) + ' + \''; } else { out += '' + (it.util.escapeQuotes($schema)); } out += '"\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + (it.util.toQuotedString($schema)); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += '} '; if ($breakOnError) { out += ' else { '; } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/properties.js": /*!**************************************************!*\ !*** ./node_modules/ajv/lib/dotjs/properties.js ***! \**************************************************/ /***/ ((module) => { "use strict"; module.exports = function generate_properties(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $key = 'key' + $lvl, $idx = 'idx' + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $dataProperties = 'dataProperties' + $lvl; var $schemaKeys = Object.keys($schema || {}).filter(notProto), $pProperties = it.schema.patternProperties || {}, $pPropertyKeys = Object.keys($pProperties).filter(notProto), $aProperties = it.schema.additionalProperties, $someProperties = $schemaKeys.length || $pPropertyKeys.length, $noAdditional = $aProperties === false, $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length, $removeAdditional = it.opts.removeAdditional, $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, $ownProperties = it.opts.ownProperties, $currentBaseId = it.baseId; var $required = it.schema.required; if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) { var $requiredHash = it.util.toHash($required); } function notProto(p) { return p !== '__proto__'; } out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; if ($ownProperties) { out += ' var ' + ($dataProperties) + ' = undefined;'; } if ($checkAdditional) { if ($ownProperties) { out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; } else { out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; } if ($someProperties) { out += ' var isAdditional' + ($lvl) + ' = !(false '; if ($schemaKeys.length) { if ($schemaKeys.length > 8) { out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') '; } else { var arr1 = $schemaKeys; if (arr1) { var $propertyKey, i1 = -1, l1 = arr1.length - 1; while (i1 < l1) { $propertyKey = arr1[i1 += 1]; out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' '; } } } } if ($pPropertyKeys.length) { var arr2 = $pPropertyKeys; if (arr2) { var $pProperty, $i = -1, l2 = arr2.length - 1; while ($i < l2) { $pProperty = arr2[$i += 1]; out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') '; } } } out += ' ); if (isAdditional' + ($lvl) + ') { '; } if ($removeAdditional == 'all') { out += ' delete ' + ($data) + '[' + ($key) + ']; '; } else { var $currentErrorPath = it.errorPath; var $additionalProperty = '\' + ' + $key + ' + \''; if (it.opts._errorDataPathProperty) { it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); } if ($noAdditional) { if ($removeAdditional) { out += ' delete ' + ($data) + '[' + ($key) + ']; '; } else { out += ' ' + ($nextValid) + ' = false; '; var $currErrSchemaPath = $errSchemaPath; $errSchemaPath = it.errSchemaPath + '/additionalProperties'; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is an invalid additional property'; } else { out += 'should NOT have additional properties'; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } $errSchemaPath = $currErrSchemaPath; if ($breakOnError) { out += ' break; '; } } } else if ($additionalIsSchema) { if ($removeAdditional == 'failing') { out += ' var ' + ($errs) + ' = errors; '; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; $it.schema = $aProperties; $it.schemaPath = it.schemaPath + '.additionalProperties'; $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); var $passData = $data + '[' + $key + ']'; $it.dataPathArr[$dataNxt] = $key; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } '; it.compositeRule = $it.compositeRule = $wasComposite; } else { $it.schema = $aProperties; $it.schemaPath = it.schemaPath + '.additionalProperties'; $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); var $passData = $data + '[' + $key + ']'; $it.dataPathArr[$dataNxt] = $key; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } if ($breakOnError) { out += ' if (!' + ($nextValid) + ') break; '; } } } it.errorPath = $currentErrorPath; } if ($someProperties) { out += ' } '; } out += ' } '; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } var $useDefaults = it.opts.useDefaults && !it.compositeRule; if ($schemaKeys.length) { var arr3 = $schemaKeys; if (arr3) { var $propertyKey, i3 = -1, l3 = arr3.length - 1; while (i3 < l3) { $propertyKey = arr3[i3 += 1]; var $sch = $schema[$propertyKey]; if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { var $prop = it.util.getProperty($propertyKey), $passData = $data + $prop, $hasDefault = $useDefaults && $sch.default !== undefined; $it.schema = $sch; $it.schemaPath = $schemaPath + $prop; $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { $code = it.util.varReplace($code, $nextData, $passData); var $useData = $passData; } else { var $useData = $nextData; out += ' var ' + ($nextData) + ' = ' + ($passData) + '; '; } if ($hasDefault) { out += ' ' + ($code) + ' '; } else { if ($requiredHash && $requiredHash[$propertyKey]) { out += ' if ( ' + ($useData) + ' === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ') { ' + ($nextValid) + ' = false; '; var $currentErrorPath = it.errorPath, $currErrSchemaPath = $errSchemaPath, $missingProperty = it.util.escapeQuotes($propertyKey); if (it.opts._errorDataPathProperty) { it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); } $errSchemaPath = it.errSchemaPath + '/required'; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is a required property'; } else { out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } $errSchemaPath = $currErrSchemaPath; it.errorPath = $currentErrorPath; out += ' } else { '; } else { if ($breakOnError) { out += ' if ( ' + ($useData) + ' === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ') { ' + ($nextValid) + ' = true; } else { '; } else { out += ' if (' + ($useData) + ' !== undefined '; if ($ownProperties) { out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ' ) { '; } } out += ' ' + ($code) + ' } '; } } if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } } } if ($pPropertyKeys.length) { var arr4 = $pPropertyKeys; if (arr4) { var $pProperty, i4 = -1, l4 = arr4.length - 1; while (i4 < l4) { $pProperty = arr4[i4 += 1]; var $sch = $pProperties[$pProperty]; if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { $it.schema = $sch; $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty); if ($ownProperties) { out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; } else { out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; } out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { '; $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); var $passData = $data + '[' + $key + ']'; $it.dataPathArr[$dataNxt] = $key; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } if ($breakOnError) { out += ' if (!' + ($nextValid) + ') break; '; } out += ' } '; if ($breakOnError) { out += ' else ' + ($nextValid) + ' = true; '; } out += ' } '; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } } } } if ($breakOnError) { out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/propertyNames.js": /*!*****************************************************!*\ !*** ./node_modules/ajv/lib/dotjs/propertyNames.js ***! \*****************************************************/ /***/ ((module) => { "use strict"; module.exports = function generate_propertyNames(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; out += 'var ' + ($errs) + ' = errors;'; if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { $it.schema = $schema; $it.schemaPath = $schemaPath; $it.errSchemaPath = $errSchemaPath; var $key = 'key' + $lvl, $idx = 'idx' + $lvl, $i = 'i' + $lvl, $invalidName = '\' + ' + $key + ' + \'', $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $dataProperties = 'dataProperties' + $lvl, $ownProperties = it.opts.ownProperties, $currentBaseId = it.baseId; if ($ownProperties) { out += ' var ' + ($dataProperties) + ' = undefined; '; } if ($ownProperties) { out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; } else { out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; } out += ' var startErrs' + ($lvl) + ' = errors; '; var $passData = $key; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } it.compositeRule = $it.compositeRule = $wasComposite; out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + ' { "use strict"; module.exports = function generate_ref(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $async, $refCode; if ($schema == '#' || $schema == '#/') { if (it.isRoot) { $async = it.async; $refCode = 'validate'; } else { $async = it.root.schema.$async === true; $refCode = 'root.refVal[0]'; } } else { var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot); if ($refVal === undefined) { var $message = it.MissingRefError.message(it.baseId, $schema); if (it.opts.missingRefs == 'fail') { it.logger.error($message); var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' '; } if (it.opts.verbose) { out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } if ($breakOnError) { out += ' if (false) { '; } } else if (it.opts.missingRefs == 'ignore') { it.logger.warn($message); if ($breakOnError) { out += ' if (true) { '; } } else { throw new it.MissingRefError(it.baseId, $schema, $message); } } else if ($refVal.inline) { var $it = it.util.copy(it); $it.level++; var $nextValid = 'valid' + $it.level; $it.schema = $refVal.schema; $it.schemaPath = ''; $it.errSchemaPath = $schema; var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code); out += ' ' + ($code) + ' '; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; } } else { $async = $refVal.$async === true || (it.async && $refVal.$async !== false); $refCode = $refVal.code; } } if ($refCode) { var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; if (it.opts.passContext) { out += ' ' + ($refCode) + '.call(this, '; } else { out += ' ' + ($refCode) + '( '; } out += ' ' + ($data) + ', (dataPath || \'\')'; if (it.errorPath != '""') { out += ' + ' + (it.errorPath); } var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData) '; var __callValidate = out; out = $$outStack.pop(); if ($async) { if (!it.async) throw new Error('async schema referenced by sync schema'); if ($breakOnError) { out += ' var ' + ($valid) + '; '; } out += ' try { await ' + (__callValidate) + '; '; if ($breakOnError) { out += ' ' + ($valid) + ' = true; '; } out += ' } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; '; if ($breakOnError) { out += ' ' + ($valid) + ' = false; '; } out += ' } '; if ($breakOnError) { out += ' if (' + ($valid) + ') { '; } } else { out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } '; if ($breakOnError) { out += ' else { '; } } } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/required.js": /*!************************************************!*\ !*** ./node_modules/ajv/lib/dotjs/required.js ***! \************************************************/ /***/ ((module) => { "use strict"; module.exports = function generate_required(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $vSchema = 'schema' + $lvl; if (!$isData) { if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) { var $required = []; var arr1 = $schema; if (arr1) { var $property, i1 = -1, l1 = arr1.length - 1; while (i1 < l1) { $property = arr1[i1 += 1]; var $propertySch = it.schema.properties[$property]; if (!($propertySch && (it.opts.strictKeywords ? (typeof $propertySch == 'object' && Object.keys($propertySch).length > 0) || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) { $required[$required.length] = $property; } } } } else { var $required = $schema; } } if ($isData || $required.length) { var $currentErrorPath = it.errorPath, $loopRequired = $isData || $required.length >= it.opts.loopRequired, $ownProperties = it.opts.ownProperties; if ($breakOnError) { out += ' var missing' + ($lvl) + '; '; if ($loopRequired) { if (!$isData) { out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; } var $i = 'i' + $lvl, $propertyPath = 'schema' + $lvl + '[' + $i + ']', $missingProperty = '\' + ' + $propertyPath + ' + \''; if (it.opts._errorDataPathProperty) { it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); } out += ' var ' + ($valid) + ' = true; '; if ($isData) { out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; } out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined '; if ($ownProperties) { out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; } out += '; if (!' + ($valid) + ') break; } '; if ($isData) { out += ' } '; } out += ' if (!' + ($valid) + ') { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is a required property'; } else { out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } else { '; } else { out += ' if ( '; var arr2 = $required; if (arr2) { var $propertyKey, $i = -1, l2 = arr2.length - 1; while ($i < l2) { $propertyKey = arr2[$i += 1]; if ($i) { out += ' || '; } var $prop = it.util.getProperty($propertyKey), $useData = $data + $prop; out += ' ( ( ' + ($useData) + ' === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; } } out += ') { '; var $propertyPath = 'missing' + $lvl, $missingProperty = '\' + ' + $propertyPath + ' + \''; if (it.opts._errorDataPathProperty) { it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; } var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is a required property'; } else { out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } else { '; } } else { if ($loopRequired) { if (!$isData) { out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; } var $i = 'i' + $lvl, $propertyPath = 'schema' + $lvl + '[' + $i + ']', $missingProperty = '\' + ' + $propertyPath + ' + \''; if (it.opts._errorDataPathProperty) { it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); } if ($isData) { out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is a required property'; } else { out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { '; } out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; } out += ') { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is a required property'; } else { out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; if ($isData) { out += ' } '; } } else { var arr3 = $required; if (arr3) { var $propertyKey, i3 = -1, l3 = arr3.length - 1; while (i3 < l3) { $propertyKey = arr3[i3 += 1]; var $prop = it.util.getProperty($propertyKey), $missingProperty = it.util.escapeQuotes($propertyKey), $useData = $data + $prop; if (it.opts._errorDataPathProperty) { it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); } out += ' if ( ' + ($useData) + ' === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ') { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is a required property'; } else { out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; } } } } it.errorPath = $currentErrorPath; } else if ($breakOnError) { out += ' if (true) {'; } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/uniqueItems.js": /*!***************************************************!*\ !*** ./node_modules/ajv/lib/dotjs/uniqueItems.js ***! \***************************************************/ /***/ ((module) => { "use strict"; module.exports = function generate_uniqueItems(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } if (($schema || $isData) && it.opts.uniqueItems !== false) { if ($isData) { out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { '; } out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { '; var $itemType = it.schema.items && it.schema.items.type, $typeIsArray = Array.isArray($itemType); if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) { out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } '; } else { out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; '; var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); out += ' if (' + (it.util[$method]($itemType, 'item', it.opts.strictNumbers, true)) + ') continue; '; if ($typeIsArray) { out += ' if (typeof item == \'string\') item = \'"\' + item; '; } out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } '; } out += ' } '; if ($isData) { out += ' } '; } out += ' if (!' + ($valid) + ') { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } '; if (it.opts.messages !== false) { out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + ($schema); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } '; if ($breakOnError) { out += ' else { '; } } else { if ($breakOnError) { out += ' if (true) { '; } } return out; } /***/ }), /***/ "./node_modules/ajv/lib/dotjs/validate.js": /*!************************************************!*\ !*** ./node_modules/ajv/lib/dotjs/validate.js ***! \************************************************/ /***/ ((module) => { "use strict"; module.exports = function generate_validate(it, $keyword, $ruleType) { var out = ''; var $async = it.schema.$async === true, $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'), $id = it.self._getId(it.schema); if (it.opts.strictKeywords) { var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords); if ($unknownKwd) { var $keywordsMsg = 'unknown keyword: ' + $unknownKwd; if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg); else throw new Error($keywordsMsg); } } if (it.isTop) { out += ' var validate = '; if ($async) { it.async = true; out += 'async '; } out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; '; if ($id && (it.opts.sourceCode || it.opts.processCode)) { out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' '; } } if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) { var $keyword = 'false schema'; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $errorKeyword; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; if (it.schema === false) { if (it.isTop) { $breakOnError = true; } else { out += ' var ' + ($valid) + ' = false; '; } var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; if (it.opts.messages !== false) { out += ' , message: \'boolean schema is false\' '; } if (it.opts.verbose) { out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } } else { if (it.isTop) { if ($async) { out += ' return data; '; } else { out += ' validate.errors = null; return true; '; } } else { out += ' var ' + ($valid) + ' = true; '; } } if (it.isTop) { out += ' }; return validate; '; } return out; } if (it.isTop) { var $top = it.isTop, $lvl = it.level = 0, $dataLvl = it.dataLevel = 0, $data = 'data'; it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); it.baseId = it.baseId || it.rootId; delete it.isTop; it.dataPathArr = [""]; if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) { var $defaultMsg = 'default is ignored in the schema root'; if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); else throw new Error($defaultMsg); } out += ' var vErrors = null; '; out += ' var errors = 0; '; out += ' if (rootData === undefined) rootData = data; '; } else { var $lvl = it.level, $dataLvl = it.dataLevel, $data = 'data' + ($dataLvl || ''); if ($id) it.baseId = it.resolve.url(it.baseId, $id); if ($async && !it.async) throw new Error('async schema in sync schema'); out += ' var errs_' + ($lvl) + ' = errors;'; } var $valid = 'valid' + $lvl, $breakOnError = !it.opts.allErrors, $closingBraces1 = '', $closingBraces2 = ''; var $errorKeyword; var $typeSchema = it.schema.type, $typeIsArray = Array.isArray($typeSchema); if ($typeSchema && it.opts.nullable && it.schema.nullable === true) { if ($typeIsArray) { if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null'); } else if ($typeSchema != 'null') { $typeSchema = [$typeSchema, 'null']; $typeIsArray = true; } } if ($typeIsArray && $typeSchema.length == 1) { $typeSchema = $typeSchema[0]; $typeIsArray = false; } if (it.schema.$ref && $refKeywords) { if (it.opts.extendRefs == 'fail') { throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); } else if (it.opts.extendRefs !== true) { $refKeywords = false; it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); } } if (it.schema.$comment && it.opts.$comment) { out += ' ' + (it.RULES.all.$comment.code(it, '$comment')); } if ($typeSchema) { if (it.opts.coerceTypes) { var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); } var $rulesGroup = it.RULES.types[$typeSchema]; if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) { var $schemaPath = it.schemaPath + '.type', $errSchemaPath = it.errSchemaPath + '/type'; var $schemaPath = it.schemaPath + '.type', $errSchemaPath = it.errSchemaPath + '/type', $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; out += ' if (' + (it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true)) + ') { '; if ($coerceToTypes) { var $dataType = 'dataType' + $lvl, $coerced = 'coerced' + $lvl; out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; var ' + ($coerced) + ' = undefined; '; if (it.opts.coerceTypes == 'array') { out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ') && ' + ($data) + '.length == 1) { ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; if (' + (it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)) + ') ' + ($coerced) + ' = ' + ($data) + '; } '; } out += ' if (' + ($coerced) + ' !== undefined) ; '; var arr1 = $coerceToTypes; if (arr1) { var $type, $i = -1, l1 = arr1.length - 1; while ($i < l1) { $type = arr1[$i += 1]; if ($type == 'string') { out += ' else if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; '; } else if ($type == 'number' || $type == 'integer') { out += ' else if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' '; if ($type == 'integer') { out += ' && !(' + ($data) + ' % 1)'; } out += ')) ' + ($coerced) + ' = +' + ($data) + '; '; } else if ($type == 'boolean') { out += ' else if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; '; } else if ($type == 'null') { out += ' else if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; '; } else if (it.opts.coerceTypes == 'array' && $type == 'array') { out += ' else if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; '; } } } out += ' else { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; if ($typeIsArray) { out += '' + ($typeSchema.join(",")); } else { out += '' + ($typeSchema); } out += '\' } '; if (it.opts.messages !== false) { out += ' , message: \'should be '; if ($typeIsArray) { out += '' + ($typeSchema.join(",")); } else { out += '' + ($typeSchema); } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } if (' + ($coerced) + ' !== undefined) { '; var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; out += ' ' + ($data) + ' = ' + ($coerced) + '; '; if (!$dataLvl) { out += 'if (' + ($parentData) + ' !== undefined)'; } out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } '; } else { var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; if ($typeIsArray) { out += '' + ($typeSchema.join(",")); } else { out += '' + ($typeSchema); } out += '\' } '; if (it.opts.messages !== false) { out += ' , message: \'should be '; if ($typeIsArray) { out += '' + ($typeSchema.join(",")); } else { out += '' + ($typeSchema); } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } } out += ' } '; } } if (it.schema.$ref && !$refKeywords) { out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' '; if ($breakOnError) { out += ' } if (errors === '; if ($top) { out += '0'; } else { out += 'errs_' + ($lvl); } out += ') { '; $closingBraces2 += '}'; } } else { var arr2 = it.RULES; if (arr2) { var $rulesGroup, i2 = -1, l2 = arr2.length - 1; while (i2 < l2) { $rulesGroup = arr2[i2 += 1]; if ($shouldUseGroup($rulesGroup)) { if ($rulesGroup.type) { out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers)) + ') { '; } if (it.opts.useDefaults) { if ($rulesGroup.type == 'object' && it.schema.properties) { var $schema = it.schema.properties, $schemaKeys = Object.keys($schema); var arr3 = $schemaKeys; if (arr3) { var $propertyKey, i3 = -1, l3 = arr3.length - 1; while (i3 < l3) { $propertyKey = arr3[i3 += 1]; var $sch = $schema[$propertyKey]; if ($sch.default !== undefined) { var $passData = $data + it.util.getProperty($propertyKey); if (it.compositeRule) { if (it.opts.strictDefaults) { var $defaultMsg = 'default is ignored for: ' + $passData; if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); else throw new Error($defaultMsg); } } else { out += ' if (' + ($passData) + ' === undefined '; if (it.opts.useDefaults == 'empty') { out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; } out += ' ) ' + ($passData) + ' = '; if (it.opts.useDefaults == 'shared') { out += ' ' + (it.useDefault($sch.default)) + ' '; } else { out += ' ' + (JSON.stringify($sch.default)) + ' '; } out += '; '; } } } } } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) { var arr4 = it.schema.items; if (arr4) { var $sch, $i = -1, l4 = arr4.length - 1; while ($i < l4) { $sch = arr4[$i += 1]; if ($sch.default !== undefined) { var $passData = $data + '[' + $i + ']'; if (it.compositeRule) { if (it.opts.strictDefaults) { var $defaultMsg = 'default is ignored for: ' + $passData; if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); else throw new Error($defaultMsg); } } else { out += ' if (' + ($passData) + ' === undefined '; if (it.opts.useDefaults == 'empty') { out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; } out += ' ) ' + ($passData) + ' = '; if (it.opts.useDefaults == 'shared') { out += ' ' + (it.useDefault($sch.default)) + ' '; } else { out += ' ' + (JSON.stringify($sch.default)) + ' '; } out += '; '; } } } } } } var arr5 = $rulesGroup.rules; if (arr5) { var $rule, i5 = -1, l5 = arr5.length - 1; while (i5 < l5) { $rule = arr5[i5 += 1]; if ($shouldUseRule($rule)) { var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); if ($code) { out += ' ' + ($code) + ' '; if ($breakOnError) { $closingBraces1 += '}'; } } } } } if ($breakOnError) { out += ' ' + ($closingBraces1) + ' '; $closingBraces1 = ''; } if ($rulesGroup.type) { out += ' } '; if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { out += ' else { '; var $schemaPath = it.schemaPath + '.type', $errSchemaPath = it.errSchemaPath + '/type'; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; if ($typeIsArray) { out += '' + ($typeSchema.join(",")); } else { out += '' + ($typeSchema); } out += '\' } '; if (it.opts.messages !== false) { out += ' , message: \'should be '; if ($typeIsArray) { out += '' + ($typeSchema.join(",")); } else { out += '' + ($typeSchema); } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } '; } } if ($breakOnError) { out += ' if (errors === '; if ($top) { out += '0'; } else { out += 'errs_' + ($lvl); } out += ') { '; $closingBraces2 += '}'; } } } } } if ($breakOnError) { out += ' ' + ($closingBraces2) + ' '; } if ($top) { if ($async) { out += ' if (errors === 0) return data; '; out += ' else throw new ValidationError(vErrors); '; } else { out += ' validate.errors = vErrors; '; out += ' return errors === 0; '; } out += ' }; return validate;'; } else { out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';'; } function $shouldUseGroup($rulesGroup) { var rules = $rulesGroup.rules; for (var i = 0; i < rules.length; i++) if ($shouldUseRule(rules[i])) return true; } function $shouldUseRule($rule) { return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule)); } function $ruleImplementsSomeKeyword($rule) { var impl = $rule.implements; for (var i = 0; i < impl.length; i++) if (it.schema[impl[i]] !== undefined) return true; } return out; } /***/ }), /***/ "./node_modules/ajv/lib/keyword.js": /*!*****************************************!*\ !*** ./node_modules/ajv/lib/keyword.js ***! \*****************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i; var customRuleCode = __webpack_require__(/*! ./dotjs/custom */ "./node_modules/ajv/lib/dotjs/custom.js"); var definitionSchema = __webpack_require__(/*! ./definition_schema */ "./node_modules/ajv/lib/definition_schema.js"); module.exports = { add: addKeyword, get: getKeyword, remove: removeKeyword, validate: validateKeyword }; /** * Define custom keyword * @this Ajv * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords). * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. * @return {Ajv} this for method chaining */ function addKeyword(keyword, definition) { /* jshint validthis: true */ /* eslint no-shadow: 0 */ var RULES = this.RULES; if (RULES.keywords[keyword]) throw new Error('Keyword ' + keyword + ' is already defined'); if (!IDENTIFIER.test(keyword)) throw new Error('Keyword ' + keyword + ' is not a valid identifier'); if (definition) { this.validateKeyword(definition, true); var dataType = definition.type; if (Array.isArray(dataType)) { for (var i=0; i { /*! arch. MIT License. Feross Aboukhadijeh */ var cp = __webpack_require__(/*! child_process */ "child_process") var fs = __webpack_require__(/*! fs */ "fs") var path = __webpack_require__(/*! path */ "path") /** * Returns the operating system's CPU architecture. This is different than * `process.arch` or `os.arch()` which returns the architecture the Node.js (or * Electron) binary was compiled for. */ module.exports = function arch () { /** * The running binary is 64-bit, so the OS is clearly 64-bit. */ if (process.arch === 'x64') { return 'x64' } /** * All recent versions of Mac OS are 64-bit. */ if (process.platform === 'darwin') { return 'x64' } /** * On Windows, the most reliable way to detect a 64-bit OS from within a 32-bit * app is based on the presence of a WOW64 file: %SystemRoot%\SysNative. * See: https://twitter.com/feross/status/776949077208510464 */ if (process.platform === 'win32') { var useEnv = false try { useEnv = !!(process.env.SYSTEMROOT && fs.statSync(process.env.SYSTEMROOT)) } catch (err) {} var sysRoot = useEnv ? process.env.SYSTEMROOT : 'C:\\Windows' // If %SystemRoot%\SysNative exists, we are in a WOW64 FS Redirected application. var isWOW64 = false try { isWOW64 = !!fs.statSync(path.join(sysRoot, 'sysnative')) } catch (err) {} return isWOW64 ? 'x64' : 'x86' } /** * On Linux, use the `getconf` command to get the architecture. */ if (process.platform === 'linux') { var output = cp.execSync('getconf LONG_BIT', { encoding: 'utf8' }) return output === '64\n' ? 'x64' : 'x86' } /** * If none of the above, assume the architecture is 32-bit. */ return 'x86' } /***/ }), /***/ "./node_modules/asn1/lib/ber/errors.js": /*!*********************************************!*\ !*** ./node_modules/asn1/lib/ber/errors.js ***! \*********************************************/ /***/ ((module) => { // Copyright 2011 Mark Cavage All rights reserved. module.exports = { newInvalidAsn1Error: function (msg) { var e = new Error(); e.name = 'InvalidAsn1Error'; e.message = msg || ''; return e; } }; /***/ }), /***/ "./node_modules/asn1/lib/ber/index.js": /*!********************************************!*\ !*** ./node_modules/asn1/lib/ber/index.js ***! \********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Copyright 2011 Mark Cavage All rights reserved. var errors = __webpack_require__(/*! ./errors */ "./node_modules/asn1/lib/ber/errors.js"); var types = __webpack_require__(/*! ./types */ "./node_modules/asn1/lib/ber/types.js"); var Reader = __webpack_require__(/*! ./reader */ "./node_modules/asn1/lib/ber/reader.js"); var Writer = __webpack_require__(/*! ./writer */ "./node_modules/asn1/lib/ber/writer.js"); // --- Exports module.exports = { Reader: Reader, Writer: Writer }; for (var t in types) { if (types.hasOwnProperty(t)) module.exports[t] = types[t]; } for (var e in errors) { if (errors.hasOwnProperty(e)) module.exports[e] = errors[e]; } /***/ }), /***/ "./node_modules/asn1/lib/ber/reader.js": /*!*********************************************!*\ !*** ./node_modules/asn1/lib/ber/reader.js ***! \*********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Copyright 2011 Mark Cavage All rights reserved. var assert = __webpack_require__(/*! assert */ "assert"); var Buffer = (__webpack_require__(/*! safer-buffer */ "./node_modules/safer-buffer/safer.js").Buffer); var ASN1 = __webpack_require__(/*! ./types */ "./node_modules/asn1/lib/ber/types.js"); var errors = __webpack_require__(/*! ./errors */ "./node_modules/asn1/lib/ber/errors.js"); // --- Globals var newInvalidAsn1Error = errors.newInvalidAsn1Error; // --- API function Reader(data) { if (!data || !Buffer.isBuffer(data)) throw new TypeError('data must be a node Buffer'); this._buf = data; this._size = data.length; // These hold the "current" state this._len = 0; this._offset = 0; } Object.defineProperty(Reader.prototype, 'length', { enumerable: true, get: function () { return (this._len); } }); Object.defineProperty(Reader.prototype, 'offset', { enumerable: true, get: function () { return (this._offset); } }); Object.defineProperty(Reader.prototype, 'remain', { get: function () { return (this._size - this._offset); } }); Object.defineProperty(Reader.prototype, 'buffer', { get: function () { return (this._buf.slice(this._offset)); } }); /** * Reads a single byte and advances offset; you can pass in `true` to make this * a "peek" operation (i.e., get the byte, but don't advance the offset). * * @param {Boolean} peek true means don't move offset. * @return {Number} the next byte, null if not enough data. */ Reader.prototype.readByte = function (peek) { if (this._size - this._offset < 1) return null; var b = this._buf[this._offset] & 0xff; if (!peek) this._offset += 1; return b; }; Reader.prototype.peek = function () { return this.readByte(true); }; /** * Reads a (potentially) variable length off the BER buffer. This call is * not really meant to be called directly, as callers have to manipulate * the internal buffer afterwards. * * As a result of this call, you can call `Reader.length`, until the * next thing called that does a readLength. * * @return {Number} the amount of offset to advance the buffer. * @throws {InvalidAsn1Error} on bad ASN.1 */ Reader.prototype.readLength = function (offset) { if (offset === undefined) offset = this._offset; if (offset >= this._size) return null; var lenB = this._buf[offset++] & 0xff; if (lenB === null) return null; if ((lenB & 0x80) === 0x80) { lenB &= 0x7f; if (lenB === 0) throw newInvalidAsn1Error('Indefinite length not supported'); if (lenB > 4) throw newInvalidAsn1Error('encoding too long'); if (this._size - offset < lenB) return null; this._len = 0; for (var i = 0; i < lenB; i++) this._len = (this._len << 8) + (this._buf[offset++] & 0xff); } else { // Wasn't a variable length this._len = lenB; } return offset; }; /** * Parses the next sequence in this BER buffer. * * To get the length of the sequence, call `Reader.length`. * * @return {Number} the sequence's tag. */ Reader.prototype.readSequence = function (tag) { var seq = this.peek(); if (seq === null) return null; if (tag !== undefined && tag !== seq) throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + ': got 0x' + seq.toString(16)); var o = this.readLength(this._offset + 1); // stored in `length` if (o === null) return null; this._offset = o; return seq; }; Reader.prototype.readInt = function () { return this._readTag(ASN1.Integer); }; Reader.prototype.readBoolean = function () { return (this._readTag(ASN1.Boolean) === 0 ? false : true); }; Reader.prototype.readEnumeration = function () { return this._readTag(ASN1.Enumeration); }; Reader.prototype.readString = function (tag, retbuf) { if (!tag) tag = ASN1.OctetString; var b = this.peek(); if (b === null) return null; if (b !== tag) throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + ': got 0x' + b.toString(16)); var o = this.readLength(this._offset + 1); // stored in `length` if (o === null) return null; if (this.length > this._size - o) return null; this._offset = o; if (this.length === 0) return retbuf ? Buffer.alloc(0) : ''; var str = this._buf.slice(this._offset, this._offset + this.length); this._offset += this.length; return retbuf ? str : str.toString('utf8'); }; Reader.prototype.readOID = function (tag) { if (!tag) tag = ASN1.OID; var b = this.readString(tag, true); if (b === null) return null; var values = []; var value = 0; for (var i = 0; i < b.length; i++) { var byte = b[i] & 0xff; value <<= 7; value += byte & 0x7f; if ((byte & 0x80) === 0) { values.push(value); value = 0; } } value = values.shift(); values.unshift(value % 40); values.unshift((value / 40) >> 0); return values.join('.'); }; Reader.prototype._readTag = function (tag) { assert.ok(tag !== undefined); var b = this.peek(); if (b === null) return null; if (b !== tag) throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + ': got 0x' + b.toString(16)); var o = this.readLength(this._offset + 1); // stored in `length` if (o === null) return null; if (this.length > 4) throw newInvalidAsn1Error('Integer too long: ' + this.length); if (this.length > this._size - o) return null; this._offset = o; var fb = this._buf[this._offset]; var value = 0; for (var i = 0; i < this.length; i++) { value <<= 8; value |= (this._buf[this._offset++] & 0xff); } if ((fb & 0x80) === 0x80 && i !== 4) value -= (1 << (i * 8)); return value >> 0; }; // --- Exported API module.exports = Reader; /***/ }), /***/ "./node_modules/asn1/lib/ber/types.js": /*!********************************************!*\ !*** ./node_modules/asn1/lib/ber/types.js ***! \********************************************/ /***/ ((module) => { // Copyright 2011 Mark Cavage All rights reserved. module.exports = { EOC: 0, Boolean: 1, Integer: 2, BitString: 3, OctetString: 4, Null: 5, OID: 6, ObjectDescriptor: 7, External: 8, Real: 9, // float Enumeration: 10, PDV: 11, Utf8String: 12, RelativeOID: 13, Sequence: 16, Set: 17, NumericString: 18, PrintableString: 19, T61String: 20, VideotexString: 21, IA5String: 22, UTCTime: 23, GeneralizedTime: 24, GraphicString: 25, VisibleString: 26, GeneralString: 28, UniversalString: 29, CharacterString: 30, BMPString: 31, Constructor: 32, Context: 128 }; /***/ }), /***/ "./node_modules/asn1/lib/ber/writer.js": /*!*********************************************!*\ !*** ./node_modules/asn1/lib/ber/writer.js ***! \*********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Copyright 2011 Mark Cavage All rights reserved. var assert = __webpack_require__(/*! assert */ "assert"); var Buffer = (__webpack_require__(/*! safer-buffer */ "./node_modules/safer-buffer/safer.js").Buffer); var ASN1 = __webpack_require__(/*! ./types */ "./node_modules/asn1/lib/ber/types.js"); var errors = __webpack_require__(/*! ./errors */ "./node_modules/asn1/lib/ber/errors.js"); // --- Globals var newInvalidAsn1Error = errors.newInvalidAsn1Error; var DEFAULT_OPTS = { size: 1024, growthFactor: 8 }; // --- Helpers function merge(from, to) { assert.ok(from); assert.equal(typeof (from), 'object'); assert.ok(to); assert.equal(typeof (to), 'object'); var keys = Object.getOwnPropertyNames(from); keys.forEach(function (key) { if (to[key]) return; var value = Object.getOwnPropertyDescriptor(from, key); Object.defineProperty(to, key, value); }); return to; } // --- API function Writer(options) { options = merge(DEFAULT_OPTS, options || {}); this._buf = Buffer.alloc(options.size || 1024); this._size = this._buf.length; this._offset = 0; this._options = options; // A list of offsets in the buffer where we need to insert // sequence tag/len pairs. this._seq = []; } Object.defineProperty(Writer.prototype, 'buffer', { get: function () { if (this._seq.length) throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)'); return (this._buf.slice(0, this._offset)); } }); Writer.prototype.writeByte = function (b) { if (typeof (b) !== 'number') throw new TypeError('argument must be a Number'); this._ensure(1); this._buf[this._offset++] = b; }; Writer.prototype.writeInt = function (i, tag) { if (typeof (i) !== 'number') throw new TypeError('argument must be a Number'); if (typeof (tag) !== 'number') tag = ASN1.Integer; var sz = 4; while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && (sz > 1)) { sz--; i <<= 8; } if (sz > 4) throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff'); this._ensure(2 + sz); this._buf[this._offset++] = tag; this._buf[this._offset++] = sz; while (sz-- > 0) { this._buf[this._offset++] = ((i & 0xff000000) >>> 24); i <<= 8; } }; Writer.prototype.writeNull = function () { this.writeByte(ASN1.Null); this.writeByte(0x00); }; Writer.prototype.writeEnumeration = function (i, tag) { if (typeof (i) !== 'number') throw new TypeError('argument must be a Number'); if (typeof (tag) !== 'number') tag = ASN1.Enumeration; return this.writeInt(i, tag); }; Writer.prototype.writeBoolean = function (b, tag) { if (typeof (b) !== 'boolean') throw new TypeError('argument must be a Boolean'); if (typeof (tag) !== 'number') tag = ASN1.Boolean; this._ensure(3); this._buf[this._offset++] = tag; this._buf[this._offset++] = 0x01; this._buf[this._offset++] = b ? 0xff : 0x00; }; Writer.prototype.writeString = function (s, tag) { if (typeof (s) !== 'string') throw new TypeError('argument must be a string (was: ' + typeof (s) + ')'); if (typeof (tag) !== 'number') tag = ASN1.OctetString; var len = Buffer.byteLength(s); this.writeByte(tag); this.writeLength(len); if (len) { this._ensure(len); this._buf.write(s, this._offset); this._offset += len; } }; Writer.prototype.writeBuffer = function (buf, tag) { if (typeof (tag) !== 'number') throw new TypeError('tag must be a number'); if (!Buffer.isBuffer(buf)) throw new TypeError('argument must be a buffer'); this.writeByte(tag); this.writeLength(buf.length); this._ensure(buf.length); buf.copy(this._buf, this._offset, 0, buf.length); this._offset += buf.length; }; Writer.prototype.writeStringArray = function (strings) { if ((!strings instanceof Array)) throw new TypeError('argument must be an Array[String]'); var self = this; strings.forEach(function (s) { self.writeString(s); }); }; // This is really to solve DER cases, but whatever for now Writer.prototype.writeOID = function (s, tag) { if (typeof (s) !== 'string') throw new TypeError('argument must be a string'); if (typeof (tag) !== 'number') tag = ASN1.OID; if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) throw new Error('argument is not a valid OID string'); function encodeOctet(bytes, octet) { if (octet < 128) { bytes.push(octet); } else if (octet < 16384) { bytes.push((octet >>> 7) | 0x80); bytes.push(octet & 0x7F); } else if (octet < 2097152) { bytes.push((octet >>> 14) | 0x80); bytes.push(((octet >>> 7) | 0x80) & 0xFF); bytes.push(octet & 0x7F); } else if (octet < 268435456) { bytes.push((octet >>> 21) | 0x80); bytes.push(((octet >>> 14) | 0x80) & 0xFF); bytes.push(((octet >>> 7) | 0x80) & 0xFF); bytes.push(octet & 0x7F); } else { bytes.push(((octet >>> 28) | 0x80) & 0xFF); bytes.push(((octet >>> 21) | 0x80) & 0xFF); bytes.push(((octet >>> 14) | 0x80) & 0xFF); bytes.push(((octet >>> 7) | 0x80) & 0xFF); bytes.push(octet & 0x7F); } } var tmp = s.split('.'); var bytes = []; bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); tmp.slice(2).forEach(function (b) { encodeOctet(bytes, parseInt(b, 10)); }); var self = this; this._ensure(2 + bytes.length); this.writeByte(tag); this.writeLength(bytes.length); bytes.forEach(function (b) { self.writeByte(b); }); }; Writer.prototype.writeLength = function (len) { if (typeof (len) !== 'number') throw new TypeError('argument must be a Number'); this._ensure(4); if (len <= 0x7f) { this._buf[this._offset++] = len; } else if (len <= 0xff) { this._buf[this._offset++] = 0x81; this._buf[this._offset++] = len; } else if (len <= 0xffff) { this._buf[this._offset++] = 0x82; this._buf[this._offset++] = len >> 8; this._buf[this._offset++] = len; } else if (len <= 0xffffff) { this._buf[this._offset++] = 0x83; this._buf[this._offset++] = len >> 16; this._buf[this._offset++] = len >> 8; this._buf[this._offset++] = len; } else { throw newInvalidAsn1Error('Length too long (> 4 bytes)'); } }; Writer.prototype.startSequence = function (tag) { if (typeof (tag) !== 'number') tag = ASN1.Sequence | ASN1.Constructor; this.writeByte(tag); this._seq.push(this._offset); this._ensure(3); this._offset += 3; }; Writer.prototype.endSequence = function () { var seq = this._seq.pop(); var start = seq + 3; var len = this._offset - start; if (len <= 0x7f) { this._shift(start, len, -2); this._buf[seq] = len; } else if (len <= 0xff) { this._shift(start, len, -1); this._buf[seq] = 0x81; this._buf[seq + 1] = len; } else if (len <= 0xffff) { this._buf[seq] = 0x82; this._buf[seq + 1] = len >> 8; this._buf[seq + 2] = len; } else if (len <= 0xffffff) { this._shift(start, len, 1); this._buf[seq] = 0x83; this._buf[seq + 1] = len >> 16; this._buf[seq + 2] = len >> 8; this._buf[seq + 3] = len; } else { throw newInvalidAsn1Error('Sequence too long'); } }; Writer.prototype._shift = function (start, len, shift) { assert.ok(start !== undefined); assert.ok(len !== undefined); assert.ok(shift); this._buf.copy(this._buf, start + shift, start, start + len); this._offset += shift; }; Writer.prototype._ensure = function (len) { assert.ok(len); if (this._size - this._offset < len) { var sz = this._size * this._options.growthFactor; if (sz - this._offset < len) sz += len; var buf = Buffer.alloc(sz); this._buf.copy(buf, 0, 0, this._offset); this._buf = buf; this._size = sz; } }; // --- Exported API module.exports = Writer; /***/ }), /***/ "./node_modules/asn1/lib/index.js": /*!****************************************!*\ !*** ./node_modules/asn1/lib/index.js ***! \****************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Copyright 2011 Mark Cavage All rights reserved. // If you have no idea what ASN.1 or BER is, see this: // ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc var Ber = __webpack_require__(/*! ./ber/index */ "./node_modules/asn1/lib/ber/index.js"); // --- Exported API module.exports = { Ber: Ber, BerReader: Ber.Reader, BerWriter: Ber.Writer }; /***/ }), /***/ "./node_modules/assert-plus/assert.js": /*!********************************************!*\ !*** ./node_modules/assert-plus/assert.js ***! \********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Copyright (c) 2012, Mark Cavage. All rights reserved. // Copyright 2015 Joyent, Inc. var assert = __webpack_require__(/*! assert */ "assert"); var Stream = (__webpack_require__(/*! stream */ "stream").Stream); var util = __webpack_require__(/*! util */ "util"); ///--- Globals /* JSSTYLED */ var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/; ///--- Internal function _capitalize(str) { return (str.charAt(0).toUpperCase() + str.slice(1)); } function _toss(name, expected, oper, arg, actual) { throw new assert.AssertionError({ message: util.format('%s (%s) is required', name, expected), actual: (actual === undefined) ? typeof (arg) : actual(arg), expected: expected, operator: oper || '===', stackStartFunction: _toss.caller }); } function _getClass(arg) { return (Object.prototype.toString.call(arg).slice(8, -1)); } function noop() { // Why even bother with asserts? } ///--- Exports var types = { bool: { check: function (arg) { return typeof (arg) === 'boolean'; } }, func: { check: function (arg) { return typeof (arg) === 'function'; } }, string: { check: function (arg) { return typeof (arg) === 'string'; } }, object: { check: function (arg) { return typeof (arg) === 'object' && arg !== null; } }, number: { check: function (arg) { return typeof (arg) === 'number' && !isNaN(arg); } }, finite: { check: function (arg) { return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg); } }, buffer: { check: function (arg) { return Buffer.isBuffer(arg); }, operator: 'Buffer.isBuffer' }, array: { check: function (arg) { return Array.isArray(arg); }, operator: 'Array.isArray' }, stream: { check: function (arg) { return arg instanceof Stream; }, operator: 'instanceof', actual: _getClass }, date: { check: function (arg) { return arg instanceof Date; }, operator: 'instanceof', actual: _getClass }, regexp: { check: function (arg) { return arg instanceof RegExp; }, operator: 'instanceof', actual: _getClass }, uuid: { check: function (arg) { return typeof (arg) === 'string' && UUID_REGEXP.test(arg); }, operator: 'isUUID' } }; function _setExports(ndebug) { var keys = Object.keys(types); var out; /* re-export standard assert */ if (process.env.NODE_NDEBUG) { out = noop; } else { out = function (arg, msg) { if (!arg) { _toss(msg, 'true', arg); } }; } /* standard checks */ keys.forEach(function (k) { if (ndebug) { out[k] = noop; return; } var type = types[k]; out[k] = function (arg, msg) { if (!type.check(arg)) { _toss(msg, k, type.operator, arg, type.actual); } }; }); /* optional checks */ keys.forEach(function (k) { var name = 'optional' + _capitalize(k); if (ndebug) { out[name] = noop; return; } var type = types[k]; out[name] = function (arg, msg) { if (arg === undefined || arg === null) { return; } if (!type.check(arg)) { _toss(msg, k, type.operator, arg, type.actual); } }; }); /* arrayOf checks */ keys.forEach(function (k) { var name = 'arrayOf' + _capitalize(k); if (ndebug) { out[name] = noop; return; } var type = types[k]; var expected = '[' + k + ']'; out[name] = function (arg, msg) { if (!Array.isArray(arg)) { _toss(msg, expected, type.operator, arg, type.actual); } var i; for (i = 0; i < arg.length; i++) { if (!type.check(arg[i])) { _toss(msg, expected, type.operator, arg, type.actual); } } }; }); /* optionalArrayOf checks */ keys.forEach(function (k) { var name = 'optionalArrayOf' + _capitalize(k); if (ndebug) { out[name] = noop; return; } var type = types[k]; var expected = '[' + k + ']'; out[name] = function (arg, msg) { if (arg === undefined || arg === null) { return; } if (!Array.isArray(arg)) { _toss(msg, expected, type.operator, arg, type.actual); } var i; for (i = 0; i < arg.length; i++) { if (!type.check(arg[i])) { _toss(msg, expected, type.operator, arg, type.actual); } } }; }); /* re-export built-in assertions */ Object.keys(assert).forEach(function (k) { if (k === 'AssertionError') { out[k] = assert[k]; return; } if (ndebug) { out[k] = noop; return; } out[k] = assert[k]; }); /* export ourselves (for unit tests _only_) */ out._setExports = _setExports; return out; } module.exports = _setExports(process.env.NODE_NDEBUG); /***/ }), /***/ "./node_modules/asynckit/index.js": /*!****************************************!*\ !*** ./node_modules/asynckit/index.js ***! \****************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = { parallel : __webpack_require__(/*! ./parallel.js */ "./node_modules/asynckit/parallel.js"), serial : __webpack_require__(/*! ./serial.js */ "./node_modules/asynckit/serial.js"), serialOrdered : __webpack_require__(/*! ./serialOrdered.js */ "./node_modules/asynckit/serialOrdered.js") }; /***/ }), /***/ "./node_modules/asynckit/lib/abort.js": /*!********************************************!*\ !*** ./node_modules/asynckit/lib/abort.js ***! \********************************************/ /***/ ((module) => { // API module.exports = abort; /** * Aborts leftover active jobs * * @param {object} state - current state object */ function abort(state) { Object.keys(state.jobs).forEach(clean.bind(state)); // reset leftover jobs state.jobs = {}; } /** * Cleans up leftover job by invoking abort function for the provided job id * * @this state * @param {string|number} key - job id to abort */ function clean(key) { if (typeof this.jobs[key] == 'function') { this.jobs[key](); } } /***/ }), /***/ "./node_modules/asynckit/lib/async.js": /*!********************************************!*\ !*** ./node_modules/asynckit/lib/async.js ***! \********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var defer = __webpack_require__(/*! ./defer.js */ "./node_modules/asynckit/lib/defer.js"); // API module.exports = async; /** * Runs provided callback asynchronously * even if callback itself is not * * @param {function} callback - callback to invoke * @returns {function} - augmented callback */ function async(callback) { var isAsync = false; // check if async happened defer(function() { isAsync = true; }); return function async_callback(err, result) { if (isAsync) { callback(err, result); } else { defer(function nextTick_callback() { callback(err, result); }); } }; } /***/ }), /***/ "./node_modules/asynckit/lib/defer.js": /*!********************************************!*\ !*** ./node_modules/asynckit/lib/defer.js ***! \********************************************/ /***/ ((module) => { module.exports = defer; /** * Runs provided function on next iteration of the event loop * * @param {function} fn - function to run */ function defer(fn) { var nextTick = typeof setImmediate == 'function' ? setImmediate : ( typeof process == 'object' && typeof process.nextTick == 'function' ? process.nextTick : null ); if (nextTick) { nextTick(fn); } else { setTimeout(fn, 0); } } /***/ }), /***/ "./node_modules/asynckit/lib/iterate.js": /*!**********************************************!*\ !*** ./node_modules/asynckit/lib/iterate.js ***! \**********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var async = __webpack_require__(/*! ./async.js */ "./node_modules/asynckit/lib/async.js") , abort = __webpack_require__(/*! ./abort.js */ "./node_modules/asynckit/lib/abort.js") ; // API module.exports = iterate; /** * Iterates over each job object * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {object} state - current job status * @param {function} callback - invoked when all elements processed */ function iterate(list, iterator, state, callback) { // store current index var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; state.jobs[key] = runJob(iterator, key, list[key], function(error, output) { // don't repeat yourself // skip secondary callbacks if (!(key in state.jobs)) { return; } // clean up jobs delete state.jobs[key]; if (error) { // don't process rest of the results // stop still active jobs // and reset the list abort(state); } else { state.results[key] = output; } // return salvaged results callback(error, state.results); }); } /** * Runs iterator over provided job element * * @param {function} iterator - iterator to invoke * @param {string|number} key - key/index of the element in the list of jobs * @param {mixed} item - job description * @param {function} callback - invoked after iterator is done with the job * @returns {function|mixed} - job abort function or something else */ function runJob(iterator, key, item, callback) { var aborter; // allow shortcut if iterator expects only two arguments if (iterator.length == 2) { aborter = iterator(item, async(callback)); } // otherwise go with full three arguments else { aborter = iterator(item, key, async(callback)); } return aborter; } /***/ }), /***/ "./node_modules/asynckit/lib/state.js": /*!********************************************!*\ !*** ./node_modules/asynckit/lib/state.js ***! \********************************************/ /***/ ((module) => { // API module.exports = state; /** * Creates initial state object * for iteration over list * * @param {array|object} list - list to iterate over * @param {function|null} sortMethod - function to use for keys sort, * or `null` to keep them as is * @returns {object} - initial state object */ function state(list, sortMethod) { var isNamedList = !Array.isArray(list) , initState = { index : 0, keyedList: isNamedList || sortMethod ? Object.keys(list) : null, jobs : {}, results : isNamedList ? {} : [], size : isNamedList ? Object.keys(list).length : list.length } ; if (sortMethod) { // sort array keys based on it's values // sort object's keys just on own merit initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) { return sortMethod(list[a], list[b]); }); } return initState; } /***/ }), /***/ "./node_modules/asynckit/lib/terminator.js": /*!*************************************************!*\ !*** ./node_modules/asynckit/lib/terminator.js ***! \*************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var abort = __webpack_require__(/*! ./abort.js */ "./node_modules/asynckit/lib/abort.js") , async = __webpack_require__(/*! ./async.js */ "./node_modules/asynckit/lib/async.js") ; // API module.exports = terminator; /** * Terminates jobs in the attached state context * * @this AsyncKitState# * @param {function} callback - final callback to invoke after termination */ function terminator(callback) { if (!Object.keys(this.jobs).length) { return; } // fast forward iteration index this.index = this.size; // abort jobs abort(this); // send back results we have so far async(callback)(null, this.results); } /***/ }), /***/ "./node_modules/asynckit/parallel.js": /*!*******************************************!*\ !*** ./node_modules/asynckit/parallel.js ***! \*******************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var iterate = __webpack_require__(/*! ./lib/iterate.js */ "./node_modules/asynckit/lib/iterate.js") , initState = __webpack_require__(/*! ./lib/state.js */ "./node_modules/asynckit/lib/state.js") , terminator = __webpack_require__(/*! ./lib/terminator.js */ "./node_modules/asynckit/lib/terminator.js") ; // Public API module.exports = parallel; /** * Runs iterator over provided array elements in parallel * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {function} callback - invoked when all elements processed * @returns {function} - jobs terminator */ function parallel(list, iterator, callback) { var state = initState(list); while (state.index < (state['keyedList'] || list).length) { iterate(list, iterator, state, function(error, result) { if (error) { callback(error, result); return; } // looks like it's the last one if (Object.keys(state.jobs).length === 0) { callback(null, state.results); return; } }); state.index++; } return terminator.bind(state, callback); } /***/ }), /***/ "./node_modules/asynckit/serial.js": /*!*****************************************!*\ !*** ./node_modules/asynckit/serial.js ***! \*****************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var serialOrdered = __webpack_require__(/*! ./serialOrdered.js */ "./node_modules/asynckit/serialOrdered.js"); // Public API module.exports = serial; /** * Runs iterator over provided array elements in series * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {function} callback - invoked when all elements processed * @returns {function} - jobs terminator */ function serial(list, iterator, callback) { return serialOrdered(list, iterator, null, callback); } /***/ }), /***/ "./node_modules/asynckit/serialOrdered.js": /*!************************************************!*\ !*** ./node_modules/asynckit/serialOrdered.js ***! \************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var iterate = __webpack_require__(/*! ./lib/iterate.js */ "./node_modules/asynckit/lib/iterate.js") , initState = __webpack_require__(/*! ./lib/state.js */ "./node_modules/asynckit/lib/state.js") , terminator = __webpack_require__(/*! ./lib/terminator.js */ "./node_modules/asynckit/lib/terminator.js") ; // Public API module.exports = serialOrdered; // sorting helpers module.exports.ascending = ascending; module.exports.descending = descending; /** * Runs iterator over provided sorted array elements in series * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {function} sortMethod - custom sort function * @param {function} callback - invoked when all elements processed * @returns {function} - jobs terminator */ function serialOrdered(list, iterator, sortMethod, callback) { var state = initState(list, sortMethod); iterate(list, iterator, state, function iteratorHandler(error, result) { if (error) { callback(error, result); return; } state.index++; // are we there yet? if (state.index < (state['keyedList'] || list).length) { iterate(list, iterator, state, iteratorHandler); return; } // done here callback(null, state.results); }); return terminator.bind(state, callback); } /* * -- Sort methods */ /** * sort helper to sort array elements in ascending order * * @param {mixed} a - an item to compare * @param {mixed} b - an item to compare * @returns {number} - comparison result */ function ascending(a, b) { return a < b ? -1 : a > b ? 1 : 0; } /** * sort helper to sort array elements in descending order * * @param {mixed} a - an item to compare * @param {mixed} b - an item to compare * @returns {number} - comparison result */ function descending(a, b) { return -1 * ascending(a, b); } /***/ }), /***/ "./node_modules/aws-sign2/index.js": /*!*****************************************!*\ !*** ./node_modules/aws-sign2/index.js ***! \*****************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /*! * Copyright 2010 LearnBoost * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Module dependencies. */ var crypto = __webpack_require__(/*! crypto */ "crypto") , parse = (__webpack_require__(/*! url */ "url").parse) ; /** * Valid keys. */ var keys = [ 'acl' , 'location' , 'logging' , 'notification' , 'partNumber' , 'policy' , 'requestPayment' , 'torrent' , 'uploadId' , 'uploads' , 'versionId' , 'versioning' , 'versions' , 'website' ] /** * Return an "Authorization" header value with the given `options` * in the form of "AWS :" * * @param {Object} options * @return {String} * @api private */ function authorization (options) { return 'AWS ' + options.key + ':' + sign(options) } module.exports = authorization module.exports.authorization = authorization /** * Simple HMAC-SHA1 Wrapper * * @param {Object} options * @return {String} * @api private */ function hmacSha1 (options) { return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64') } module.exports.hmacSha1 = hmacSha1 /** * Create a base64 sha1 HMAC for `options`. * * @param {Object} options * @return {String} * @api private */ function sign (options) { options.message = stringToSign(options) return hmacSha1(options) } module.exports.sign = sign /** * Create a base64 sha1 HMAC for `options`. * * Specifically to be used with S3 presigned URLs * * @param {Object} options * @return {String} * @api private */ function signQuery (options) { options.message = queryStringToSign(options) return hmacSha1(options) } module.exports.signQuery= signQuery /** * Return a string for sign() with the given `options`. * * Spec: * * \n * \n * \n * \n * [headers\n] * * * @param {Object} options * @return {String} * @api private */ function stringToSign (options) { var headers = options.amazonHeaders || '' if (headers) headers += '\n' var r = [ options.verb , options.md5 , options.contentType , options.date ? options.date.toUTCString() : '' , headers + options.resource ] return r.join('\n') } module.exports.stringToSign = stringToSign /** * Return a string for sign() with the given `options`, but is meant exclusively * for S3 presigned URLs * * Spec: * * \n * * * @param {Object} options * @return {String} * @api private */ function queryStringToSign (options){ return 'GET\n\n\n' + options.date + '\n' + options.resource } module.exports.queryStringToSign = queryStringToSign /** * Perform the following: * * - ignore non-amazon headers * - lowercase fields * - sort lexicographically * - trim whitespace between ":" * - join with newline * * @param {Object} headers * @return {String} * @api private */ function canonicalizeHeaders (headers) { var buf = [] , fields = Object.keys(headers) ; for (var i = 0, len = fields.length; i < len; ++i) { var field = fields[i] , val = headers[field] , field = field.toLowerCase() ; if (0 !== field.indexOf('x-amz')) continue buf.push(field + ':' + val) } return buf.sort().join('\n') } module.exports.canonicalizeHeaders = canonicalizeHeaders /** * Perform the following: * * - ignore non sub-resources * - sort lexicographically * * @param {String} resource * @return {String} * @api private */ function canonicalizeResource (resource) { var url = parse(resource, true) , path = url.pathname , buf = [] ; Object.keys(url.query).forEach(function(key){ if (!~keys.indexOf(key)) return var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key]) buf.push(key + val) }) return path + (buf.length ? '?' + buf.sort().join('&') : '') } module.exports.canonicalizeResource = canonicalizeResource /***/ }), /***/ "./node_modules/aws4/aws4.js": /*!***********************************!*\ !*** ./node_modules/aws4/aws4.js ***! \***********************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var aws4 = exports, url = __webpack_require__(/*! url */ "url"), querystring = __webpack_require__(/*! querystring */ "querystring"), crypto = __webpack_require__(/*! crypto */ "crypto"), lru = __webpack_require__(/*! ./lru */ "./node_modules/aws4/lru.js"), credentialsCache = lru(1000) // http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html function hmac(key, string, encoding) { return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding) } function hash(string, encoding) { return crypto.createHash('sha256').update(string, 'utf8').digest(encoding) } // This function assumes the string has already been percent encoded function encodeRfc3986(urlEncodedString) { return urlEncodedString.replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase() }) } function encodeRfc3986Full(str) { return encodeRfc3986(encodeURIComponent(str)) } // A bit of a combination of: // https://github.com/aws/aws-sdk-java-v2/blob/dc695de6ab49ad03934e1b02e7263abbd2354be0/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAws4Signer.java#L59 // https://github.com/aws/aws-sdk-js/blob/18cb7e5b463b46239f9fdd4a65e2ff8c81831e8f/lib/signers/v4.js#L191-L199 // https://github.com/mhart/aws4fetch/blob/b3aed16b6f17384cf36ea33bcba3c1e9f3bdfefd/src/main.js#L25-L34 var HEADERS_TO_IGNORE = { 'authorization': true, 'connection': true, 'x-amzn-trace-id': true, 'user-agent': true, 'expect': true, 'presigned-expires': true, 'range': true, } // request: { path | body, [host], [method], [headers], [service], [region] } // credentials: { accessKeyId, secretAccessKey, [sessionToken] } function RequestSigner(request, credentials) { if (typeof request === 'string') request = url.parse(request) var headers = request.headers = (request.headers || {}), hostParts = (!this.service || !this.region) && this.matchHost(request.hostname || request.host || headers.Host || headers.host) this.request = request this.credentials = credentials || this.defaultCredentials() this.service = request.service || hostParts[0] || '' this.region = request.region || hostParts[1] || 'us-east-1' // SES uses a different domain from the service name if (this.service === 'email') this.service = 'ses' if (!request.method && request.body) request.method = 'POST' if (!headers.Host && !headers.host) { headers.Host = request.hostname || request.host || this.createHost() // If a port is specified explicitly, use it as is if (request.port) headers.Host += ':' + request.port } if (!request.hostname && !request.host) request.hostname = headers.Host || headers.host this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT' this.extraHeadersToIgnore = request.extraHeadersToIgnore || Object.create(null) this.extraHeadersToInclude = request.extraHeadersToInclude || Object.create(null) } RequestSigner.prototype.matchHost = function(host) { var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/) var hostParts = (match || []).slice(1, 3) // ES's hostParts are sometimes the other way round, if the value that is expected // to be region equals ‘es’ switch them back // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com if (hostParts[1] === 'es' || hostParts[1] === 'aoss') hostParts = hostParts.reverse() if (hostParts[1] == 's3') { hostParts[0] = 's3' hostParts[1] = 'us-east-1' } else { for (var i = 0; i < 2; i++) { if (/^s3-/.test(hostParts[i])) { hostParts[1] = hostParts[i].slice(3) hostParts[0] = 's3' break } } } return hostParts } // http://docs.aws.amazon.com/general/latest/gr/rande.html RequestSigner.prototype.isSingleRegion = function() { // Special case for S3 and SimpleDB in us-east-1 if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts'] .indexOf(this.service) >= 0 } RequestSigner.prototype.createHost = function() { var region = this.isSingleRegion() ? '' : '.' + this.region, subdomain = this.service === 'ses' ? 'email' : this.service return subdomain + region + '.amazonaws.com' } RequestSigner.prototype.prepareRequest = function() { this.parsePath() var request = this.request, headers = request.headers, query if (request.signQuery) { this.parsedPath.query = query = this.parsedPath.query || {} if (this.credentials.sessionToken) query['X-Amz-Security-Token'] = this.credentials.sessionToken if (this.service === 's3' && !query['X-Amz-Expires']) query['X-Amz-Expires'] = 86400 if (query['X-Amz-Date']) this.datetime = query['X-Amz-Date'] else query['X-Amz-Date'] = this.getDateTime() query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256' query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString() query['X-Amz-SignedHeaders'] = this.signedHeaders() } else { if (!request.doNotModifyHeaders && !this.isCodeCommitGit) { if (request.body && !headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8' if (request.body && !headers['Content-Length'] && !headers['content-length']) headers['Content-Length'] = Buffer.byteLength(request.body) if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token']) headers['X-Amz-Security-Token'] = this.credentials.sessionToken if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256']) headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex') if (headers['X-Amz-Date'] || headers['x-amz-date']) this.datetime = headers['X-Amz-Date'] || headers['x-amz-date'] else headers['X-Amz-Date'] = this.getDateTime() } delete headers.Authorization delete headers.authorization } } RequestSigner.prototype.sign = function() { if (!this.parsedPath) this.prepareRequest() if (this.request.signQuery) { this.parsedPath.query['X-Amz-Signature'] = this.signature() } else { this.request.headers.Authorization = this.authHeader() } this.request.path = this.formatPath() return this.request } RequestSigner.prototype.getDateTime = function() { if (!this.datetime) { var headers = this.request.headers, date = new Date(headers.Date || headers.date || new Date) this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '') // Remove the trailing 'Z' on the timestamp string for CodeCommit git access if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1) } return this.datetime } RequestSigner.prototype.getDate = function() { return this.getDateTime().substr(0, 8) } RequestSigner.prototype.authHeader = function() { return [ 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(), 'SignedHeaders=' + this.signedHeaders(), 'Signature=' + this.signature(), ].join(', ') } RequestSigner.prototype.signature = function() { var date = this.getDate(), cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(), kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey) if (!kCredentials) { kDate = hmac('AWS4' + this.credentials.secretAccessKey, date) kRegion = hmac(kDate, this.region) kService = hmac(kRegion, this.service) kCredentials = hmac(kService, 'aws4_request') credentialsCache.set(cacheKey, kCredentials) } return hmac(kCredentials, this.stringToSign(), 'hex') } RequestSigner.prototype.stringToSign = function() { return [ 'AWS4-HMAC-SHA256', this.getDateTime(), this.credentialString(), hash(this.canonicalString(), 'hex'), ].join('\n') } RequestSigner.prototype.canonicalString = function() { if (!this.parsedPath) this.prepareRequest() var pathStr = this.parsedPath.path, query = this.parsedPath.query, headers = this.request.headers, queryStr = '', normalizePath = this.service !== 's3', decodePath = this.service === 's3' || this.request.doNotEncodePath, decodeSlashesInPath = this.service === 's3', firstValOnly = this.service === 's3', bodyHash if (this.service === 's3' && this.request.signQuery) { bodyHash = 'UNSIGNED-PAYLOAD' } else if (this.isCodeCommitGit) { bodyHash = '' } else { bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] || hash(this.request.body || '', 'hex') } if (query) { var reducedQuery = Object.keys(query).reduce(function(obj, key) { if (!key) return obj obj[encodeRfc3986Full(key)] = !Array.isArray(query[key]) ? query[key] : (firstValOnly ? query[key][0] : query[key]) return obj }, {}) var encodedQueryPieces = [] Object.keys(reducedQuery).sort().forEach(function(key) { if (!Array.isArray(reducedQuery[key])) { encodedQueryPieces.push(key + '=' + encodeRfc3986Full(reducedQuery[key])) } else { reducedQuery[key].map(encodeRfc3986Full).sort() .forEach(function(val) { encodedQueryPieces.push(key + '=' + val) }) } }) queryStr = encodedQueryPieces.join('&') } if (pathStr !== '/') { if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/') pathStr = pathStr.split('/').reduce(function(path, piece) { if (normalizePath && piece === '..') { path.pop() } else if (!normalizePath || piece !== '.') { if (decodePath) piece = decodeURIComponent(piece.replace(/\+/g, ' ')) path.push(encodeRfc3986Full(piece)) } return path }, []).join('/') if (pathStr[0] !== '/') pathStr = '/' + pathStr if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/') } return [ this.request.method || 'GET', pathStr, queryStr, this.canonicalHeaders() + '\n', this.signedHeaders(), bodyHash, ].join('\n') } RequestSigner.prototype.canonicalHeaders = function() { var headers = this.request.headers function trimAll(header) { return header.toString().trim().replace(/\s+/g, ' ') } return Object.keys(headers) .filter(function(key) { return HEADERS_TO_IGNORE[key.toLowerCase()] == null }) .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 }) .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) }) .join('\n') } RequestSigner.prototype.signedHeaders = function() { var extraHeadersToInclude = this.extraHeadersToInclude, extraHeadersToIgnore = this.extraHeadersToIgnore return Object.keys(this.request.headers) .map(function(key) { return key.toLowerCase() }) .filter(function(key) { return extraHeadersToInclude[key] || (HEADERS_TO_IGNORE[key] == null && !extraHeadersToIgnore[key]) }) .sort() .join(';') } RequestSigner.prototype.credentialString = function() { return [ this.getDate(), this.region, this.service, 'aws4_request', ].join('/') } RequestSigner.prototype.defaultCredentials = function() { var env = process.env return { accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY, secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY, sessionToken: env.AWS_SESSION_TOKEN, } } RequestSigner.prototype.parsePath = function() { var path = this.request.path || '/' // S3 doesn't always encode characters > 127 correctly and // all services don't encode characters > 255 correctly // So if there are non-reserved chars (and it's not already all % encoded), just encode them all if (/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(path)) { path = encodeURI(decodeURI(path)) } var queryIx = path.indexOf('?'), query = null if (queryIx >= 0) { query = querystring.parse(path.slice(queryIx + 1)) path = path.slice(0, queryIx) } this.parsedPath = { path: path, query: query, } } RequestSigner.prototype.formatPath = function() { var path = this.parsedPath.path, query = this.parsedPath.query if (!query) return path // Services don't support empty query string keys if (query[''] != null) delete query[''] return path + '?' + encodeRfc3986(querystring.stringify(query)) } aws4.RequestSigner = RequestSigner aws4.sign = function(request, credentials) { return new RequestSigner(request, credentials).sign() } /***/ }), /***/ "./node_modules/aws4/lru.js": /*!**********************************!*\ !*** ./node_modules/aws4/lru.js ***! \**********************************/ /***/ ((module) => { module.exports = function(size) { return new LruCache(size) } function LruCache(size) { this.capacity = size | 0 this.map = Object.create(null) this.list = new DoublyLinkedList() } LruCache.prototype.get = function(key) { var node = this.map[key] if (node == null) return undefined this.used(node) return node.val } LruCache.prototype.set = function(key, val) { var node = this.map[key] if (node != null) { node.val = val } else { if (!this.capacity) this.prune() if (!this.capacity) return false node = new DoublyLinkedNode(key, val) this.map[key] = node this.capacity-- } this.used(node) return true } LruCache.prototype.used = function(node) { this.list.moveToFront(node) } LruCache.prototype.prune = function() { var node = this.list.pop() if (node != null) { delete this.map[node.key] this.capacity++ } } function DoublyLinkedList() { this.firstNode = null this.lastNode = null } DoublyLinkedList.prototype.moveToFront = function(node) { if (this.firstNode == node) return this.remove(node) if (this.firstNode == null) { this.firstNode = node this.lastNode = node node.prev = null node.next = null } else { node.prev = null node.next = this.firstNode node.next.prev = node this.firstNode = node } } DoublyLinkedList.prototype.pop = function() { var lastNode = this.lastNode if (lastNode != null) { this.remove(lastNode) } return lastNode } DoublyLinkedList.prototype.remove = function(node) { if (this.firstNode == node) { this.firstNode = node.next } else if (node.prev != null) { node.prev.next = node.next } if (this.lastNode == node) { this.lastNode = node.prev } else if (node.next != null) { node.next.prev = node.prev } } function DoublyLinkedNode(key, val) { this.key = key this.val = val this.prev = null this.next = null } /***/ }), /***/ "./node_modules/balanced-match/index.js": /*!**********************************************!*\ !*** ./node_modules/balanced-match/index.js ***! \**********************************************/ /***/ ((module) => { "use strict"; module.exports = balanced; function balanced(a, b, str) { if (a instanceof RegExp) a = maybeMatch(a, str); if (b instanceof RegExp) b = maybeMatch(b, str); var r = range(a, b, str); return r && { start: r[0], end: r[1], pre: str.slice(0, r[0]), body: str.slice(r[0] + a.length, r[1]), post: str.slice(r[1] + b.length) }; } function maybeMatch(reg, str) { var m = str.match(reg); return m ? m[0] : null; } balanced.range = range; function range(a, b, str) { var begs, beg, left, right, result; var ai = str.indexOf(a); var bi = str.indexOf(b, ai + 1); var i = ai; if (ai >= 0 && bi > 0) { begs = []; left = str.length; while (i >= 0 && !result) { if (i == ai) { begs.push(i); ai = str.indexOf(a, i + 1); } else if (begs.length == 1) { result = [ begs.pop(), bi ]; } else { beg = begs.pop(); if (beg < left) { left = beg; right = bi; } bi = str.indexOf(b, i + 1); } i = ai < bi && ai >= 0 ? ai : bi; } if (begs.length) { result = [ left, right ]; } } return result; } /***/ }), /***/ "./node_modules/bcrypt-pbkdf/index.js": /*!********************************************!*\ !*** ./node_modules/bcrypt-pbkdf/index.js ***! \********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var crypto_hash_sha512 = (__webpack_require__(/*! tweetnacl */ "./node_modules/tweetnacl/nacl-fast.js").lowlevel.crypto_hash); /* * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a * result, it retains the original copyright and license. The two files are * under slightly different (but compatible) licenses, and are here combined in * one file. * * Credit for the actual porting work goes to: * Devi Mandiri */ /* * The Blowfish portions are under the following license: * * Blowfish block cipher for OpenBSD * Copyright 1997 Niels Provos * All rights reserved. * * Implementation advice by David Mazieres . * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * The bcrypt_pbkdf portions are under the following license: * * Copyright (c) 2013 Ted Unangst * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* * Performance improvements (Javascript-specific): * * Copyright 2016, Joyent Inc * Author: Alex Wilson * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // Ported from OpenBSD bcrypt_pbkdf.c v1.9 var BLF_J = 0; var Blowfish = function() { this.S = [ new Uint32Array([ 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]), new Uint32Array([ 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]), new Uint32Array([ 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]), new Uint32Array([ 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6]) ]; this.P = new Uint32Array([ 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b]); }; function F(S, x8, i) { return (((S[0][x8[i+3]] + S[1][x8[i+2]]) ^ S[2][x8[i+1]]) + S[3][x8[i]]); }; Blowfish.prototype.encipher = function(x, x8) { if (x8 === undefined) { x8 = new Uint8Array(x.buffer); if (x.byteOffset !== 0) x8 = x8.subarray(x.byteOffset); } x[0] ^= this.P[0]; for (var i = 1; i < 16; i += 2) { x[1] ^= F(this.S, x8, 0) ^ this.P[i]; x[0] ^= F(this.S, x8, 4) ^ this.P[i+1]; } var t = x[0]; x[0] = x[1] ^ this.P[17]; x[1] = t; }; Blowfish.prototype.decipher = function(x) { var x8 = new Uint8Array(x.buffer); if (x.byteOffset !== 0) x8 = x8.subarray(x.byteOffset); x[0] ^= this.P[17]; for (var i = 16; i > 0; i -= 2) { x[1] ^= F(this.S, x8, 0) ^ this.P[i]; x[0] ^= F(this.S, x8, 4) ^ this.P[i-1]; } var t = x[0]; x[0] = x[1] ^ this.P[0]; x[1] = t; }; function stream2word(data, databytes){ var i, temp = 0; for (i = 0; i < 4; i++, BLF_J++) { if (BLF_J >= databytes) BLF_J = 0; temp = (temp << 8) | data[BLF_J]; } return temp; }; Blowfish.prototype.expand0state = function(key, keybytes) { var d = new Uint32Array(2), i, k; var d8 = new Uint8Array(d.buffer); for (i = 0, BLF_J = 0; i < 18; i++) { this.P[i] ^= stream2word(key, keybytes); } BLF_J = 0; for (i = 0; i < 18; i += 2) { this.encipher(d, d8); this.P[i] = d[0]; this.P[i+1] = d[1]; } for (i = 0; i < 4; i++) { for (k = 0; k < 256; k += 2) { this.encipher(d, d8); this.S[i][k] = d[0]; this.S[i][k+1] = d[1]; } } }; Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { var d = new Uint32Array(2), i, k; for (i = 0, BLF_J = 0; i < 18; i++) { this.P[i] ^= stream2word(key, keybytes); } for (i = 0, BLF_J = 0; i < 18; i += 2) { d[0] ^= stream2word(data, databytes); d[1] ^= stream2word(data, databytes); this.encipher(d); this.P[i] = d[0]; this.P[i+1] = d[1]; } for (i = 0; i < 4; i++) { for (k = 0; k < 256; k += 2) { d[0] ^= stream2word(data, databytes); d[1] ^= stream2word(data, databytes); this.encipher(d); this.S[i][k] = d[0]; this.S[i][k+1] = d[1]; } } BLF_J = 0; }; Blowfish.prototype.enc = function(data, blocks) { for (var i = 0; i < blocks; i++) { this.encipher(data.subarray(i*2)); } }; Blowfish.prototype.dec = function(data, blocks) { for (var i = 0; i < blocks; i++) { this.decipher(data.subarray(i*2)); } }; var BCRYPT_BLOCKS = 8, BCRYPT_HASHSIZE = 32; function bcrypt_hash(sha2pass, sha2salt, out) { var state = new Blowfish(), cdata = new Uint32Array(BCRYPT_BLOCKS), i, ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105, 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109, 105,116,101]); //"OxychromaticBlowfishSwatDynamite" state.expandstate(sha2salt, 64, sha2pass, 64); for (i = 0; i < 64; i++) { state.expand0state(sha2salt, 64); state.expand0state(sha2pass, 64); } for (i = 0; i < BCRYPT_BLOCKS; i++) cdata[i] = stream2word(ciphertext, ciphertext.byteLength); for (i = 0; i < 64; i++) state.enc(cdata, cdata.byteLength / 8); for (i = 0; i < BCRYPT_BLOCKS; i++) { out[4*i+3] = cdata[i] >>> 24; out[4*i+2] = cdata[i] >>> 16; out[4*i+1] = cdata[i] >>> 8; out[4*i+0] = cdata[i]; } }; function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { var sha2pass = new Uint8Array(64), sha2salt = new Uint8Array(64), out = new Uint8Array(BCRYPT_HASHSIZE), tmpout = new Uint8Array(BCRYPT_HASHSIZE), countsalt = new Uint8Array(saltlen+4), i, j, amt, stride, dest, count, origkeylen = keylen; if (rounds < 1) return -1; if (passlen === 0 || saltlen === 0 || keylen === 0 || keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20)) return -1; stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); amt = Math.floor((keylen + stride - 1) / stride); for (i = 0; i < saltlen; i++) countsalt[i] = salt[i]; crypto_hash_sha512(sha2pass, pass, passlen); for (count = 1; keylen > 0; count++) { countsalt[saltlen+0] = count >>> 24; countsalt[saltlen+1] = count >>> 16; countsalt[saltlen+2] = count >>> 8; countsalt[saltlen+3] = count; crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); bcrypt_hash(sha2pass, sha2salt, tmpout); for (i = out.byteLength; i--;) out[i] = tmpout[i]; for (i = 1; i < rounds; i++) { crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); bcrypt_hash(sha2pass, sha2salt, tmpout); for (j = 0; j < out.byteLength; j++) out[j] ^= tmpout[j]; } amt = Math.min(amt, keylen); for (i = 0; i < amt; i++) { dest = i * stride + (count - 1); if (dest >= origkeylen) break; key[dest] = out[i]; } keylen -= i; } return 0; }; module.exports = { BLOCKS: BCRYPT_BLOCKS, HASHSIZE: BCRYPT_HASHSIZE, hash: bcrypt_hash, pbkdf: bcrypt_pbkdf }; /***/ }), /***/ "./node_modules/brace-expansion/index.js": /*!***********************************************!*\ !*** ./node_modules/brace-expansion/index.js ***! \***********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var concatMap = __webpack_require__(/*! concat-map */ "./node_modules/concat-map/index.js"); var balanced = __webpack_require__(/*! balanced-match */ "./node_modules/balanced-match/index.js"); module.exports = expandTop; var escSlash = '\0SLASH'+Math.random()+'\0'; var escOpen = '\0OPEN'+Math.random()+'\0'; var escClose = '\0CLOSE'+Math.random()+'\0'; var escComma = '\0COMMA'+Math.random()+'\0'; var escPeriod = '\0PERIOD'+Math.random()+'\0'; function numeric(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } function escapeBraces(str) { return str.split('\\\\').join(escSlash) .split('\\{').join(escOpen) .split('\\}').join(escClose) .split('\\,').join(escComma) .split('\\.').join(escPeriod); } function unescapeBraces(str) { return str.split(escSlash).join('\\') .split(escOpen).join('{') .split(escClose).join('}') .split(escComma).join(',') .split(escPeriod).join('.'); } // Basically just str.split(","), but handling cases // where we have nested braced sections, which should be // treated as individual members, like {a,{b,c},d} function parseCommaParts(str) { if (!str) return ['']; var parts = []; var m = balanced('{', '}', str); if (!m) return str.split(','); var pre = m.pre; var body = m.body; var post = m.post; var p = pre.split(','); p[p.length-1] += '{' + body + '}'; var postParts = parseCommaParts(post); if (post.length) { p[p.length-1] += postParts.shift(); p.push.apply(p, postParts); } parts.push.apply(parts, p); return parts; } function expandTop(str) { if (!str) return []; // I don't know why Bash 4.3 does this, but it does. // Anything starting with {} will have the first two bytes preserved // but *only* at the top level, so {},a}b will not expand to anything, // but a{},b}c will be expanded to [a}c,abc]. // One could argue that this is a bug in Bash, but since the goal of // this module is to match Bash's rules, we escape a leading {} if (str.substr(0, 2) === '{}') { str = '\\{\\}' + str.substr(2); } return expand(escapeBraces(str), true).map(unescapeBraces); } function identity(e) { return e; } function embrace(str) { return '{' + str + '}'; } function isPadded(el) { return /^-?0\d/.test(el); } function lte(i, y) { return i <= y; } function gte(i, y) { return i >= y; } function expand(str, isTop) { var expansions = []; var m = balanced('{', '}', str); if (!m || /\$$/.test(m.pre)) return [str]; var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(',') >= 0; if (!isSequence && !isOptions) { // {a},b} if (m.post.match(/,.*\}/)) { str = m.pre + '{' + m.body + escClose + m.post; return expand(str); } return [str]; } var n; if (isSequence) { n = m.body.split(/\.\./); } else { n = parseCommaParts(m.body); if (n.length === 1) { // x{{a,b}}y ==> x{a}y x{b}y n = expand(n[0], false).map(embrace); if (n.length === 1) { var post = m.post.length ? expand(m.post, false) : ['']; return post.map(function(p) { return m.pre + n[0] + p; }); } } } // at this point, n is the parts, and we know it's not a comma set // with a single entry. // no need to expand pre, since it is guaranteed to be free of brace-sets var pre = m.pre; var post = m.post.length ? expand(m.post, false) : ['']; var N; if (isSequence) { var x = numeric(n[0]); var y = numeric(n[1]); var width = Math.max(n[0].length, n[1].length) var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; var test = lte; var reverse = y < x; if (reverse) { incr *= -1; test = gte; } var pad = n.some(isPadded); N = []; for (var i = x; test(i, y); i += incr) { var c; if (isAlphaSequence) { c = String.fromCharCode(i); if (c === '\\') c = ''; } else { c = String(i); if (pad) { var need = width - c.length; if (need > 0) { var z = new Array(need + 1).join('0'); if (i < 0) c = '-' + z + c.slice(1); else c = z + c; } } } N.push(c); } } else { N = concatMap(n, function(el) { return expand(el, false) }); } for (var j = 0; j < N.length; j++) { for (var k = 0; k < post.length; k++) { var expansion = pre + N[j] + post[k]; if (!isTop || isSequence || expansion) expansions.push(expansion); } } return expansions; } /***/ }), /***/ "./node_modules/caseless/index.js": /*!****************************************!*\ !*** ./node_modules/caseless/index.js ***! \****************************************/ /***/ ((module) => { function Caseless (dict) { this.dict = dict || {} } Caseless.prototype.set = function (name, value, clobber) { if (typeof name === 'object') { for (var i in name) { this.set(i, name[i], value) } } else { if (typeof clobber === 'undefined') clobber = true var has = this.has(name) if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value else this.dict[has || name] = value return has } } Caseless.prototype.has = function (name) { var keys = Object.keys(this.dict) , name = name.toLowerCase() ; for (var i=0;i { var charenc = { // UTF-8 encoding utf8: { // Convert a string to a byte array stringToBytes: function(str) { return charenc.bin.stringToBytes(unescape(encodeURIComponent(str))); }, // Convert a byte array to a string bytesToString: function(bytes) { return decodeURIComponent(escape(charenc.bin.bytesToString(bytes))); } }, // Binary encoding bin: { // Convert a string to a byte array stringToBytes: function(str) { for (var bytes = [], i = 0; i < str.length; i++) bytes.push(str.charCodeAt(i) & 0xFF); return bytes; }, // Convert a byte array to a string bytesToString: function(bytes) { for (var str = [], i = 0; i < bytes.length; i++) str.push(String.fromCharCode(bytes[i])); return str.join(''); } } }; module.exports = charenc; /***/ }), /***/ "./node_modules/combined-stream/lib/combined_stream.js": /*!*************************************************************!*\ !*** ./node_modules/combined-stream/lib/combined_stream.js ***! \*************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var util = __webpack_require__(/*! util */ "util"); var Stream = (__webpack_require__(/*! stream */ "stream").Stream); var DelayedStream = __webpack_require__(/*! delayed-stream */ "./node_modules/delayed-stream/lib/delayed_stream.js"); module.exports = CombinedStream; function CombinedStream() { this.writable = false; this.readable = true; this.dataSize = 0; this.maxDataSize = 2 * 1024 * 1024; this.pauseStreams = true; this._released = false; this._streams = []; this._currentStream = null; this._insideLoop = false; this._pendingNext = false; } util.inherits(CombinedStream, Stream); CombinedStream.create = function(options) { var combinedStream = new this(); options = options || {}; for (var option in options) { combinedStream[option] = options[option]; } return combinedStream; }; CombinedStream.isStreamLike = function(stream) { return (typeof stream !== 'function') && (typeof stream !== 'string') && (typeof stream !== 'boolean') && (typeof stream !== 'number') && (!Buffer.isBuffer(stream)); }; CombinedStream.prototype.append = function(stream) { var isStreamLike = CombinedStream.isStreamLike(stream); if (isStreamLike) { if (!(stream instanceof DelayedStream)) { var newStream = DelayedStream.create(stream, { maxDataSize: Infinity, pauseStream: this.pauseStreams, }); stream.on('data', this._checkDataSize.bind(this)); stream = newStream; } this._handleErrors(stream); if (this.pauseStreams) { stream.pause(); } } this._streams.push(stream); return this; }; CombinedStream.prototype.pipe = function(dest, options) { Stream.prototype.pipe.call(this, dest, options); this.resume(); return dest; }; CombinedStream.prototype._getNext = function() { this._currentStream = null; if (this._insideLoop) { this._pendingNext = true; return; // defer call } this._insideLoop = true; try { do { this._pendingNext = false; this._realGetNext(); } while (this._pendingNext); } finally { this._insideLoop = false; } }; CombinedStream.prototype._realGetNext = function() { var stream = this._streams.shift(); if (typeof stream == 'undefined') { this.end(); return; } if (typeof stream !== 'function') { this._pipeNext(stream); return; } var getStream = stream; getStream(function(stream) { var isStreamLike = CombinedStream.isStreamLike(stream); if (isStreamLike) { stream.on('data', this._checkDataSize.bind(this)); this._handleErrors(stream); } this._pipeNext(stream); }.bind(this)); }; CombinedStream.prototype._pipeNext = function(stream) { this._currentStream = stream; var isStreamLike = CombinedStream.isStreamLike(stream); if (isStreamLike) { stream.on('end', this._getNext.bind(this)); stream.pipe(this, {end: false}); return; } var value = stream; this.write(value); this._getNext(); }; CombinedStream.prototype._handleErrors = function(stream) { var self = this; stream.on('error', function(err) { self._emitError(err); }); }; CombinedStream.prototype.write = function(data) { this.emit('data', data); }; CombinedStream.prototype.pause = function() { if (!this.pauseStreams) { return; } if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); this.emit('pause'); }; CombinedStream.prototype.resume = function() { if (!this._released) { this._released = true; this.writable = true; this._getNext(); } if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); this.emit('resume'); }; CombinedStream.prototype.end = function() { this._reset(); this.emit('end'); }; CombinedStream.prototype.destroy = function() { this._reset(); this.emit('close'); }; CombinedStream.prototype._reset = function() { this.writable = false; this._streams = []; this._currentStream = null; }; CombinedStream.prototype._checkDataSize = function() { this._updateDataSize(); if (this.dataSize <= this.maxDataSize) { return; } var message = 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; this._emitError(new Error(message)); }; CombinedStream.prototype._updateDataSize = function() { this.dataSize = 0; var self = this; this._streams.forEach(function(stream) { if (!stream.dataSize) { return; } self.dataSize += stream.dataSize; }); if (this._currentStream && this._currentStream.dataSize) { this.dataSize += this._currentStream.dataSize; } }; CombinedStream.prototype._emitError = function(err) { this._reset(); this.emit('error', err); }; /***/ }), /***/ "./node_modules/concat-map/index.js": /*!******************************************!*\ !*** ./node_modules/concat-map/index.js ***! \******************************************/ /***/ ((module) => { module.exports = function (xs, fn) { var res = []; for (var i = 0; i < xs.length; i++) { var x = fn(xs[i], i); if (isArray(x)) res.push.apply(res, x); else res.push(x); } return res; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; /***/ }), /***/ "./node_modules/core-util-is/lib/util.js": /*!***********************************************!*\ !*** ./node_modules/core-util-is/lib/util.js ***! \***********************************************/ /***/ ((__unused_webpack_module, exports) => { // Copyright Joyent, Inc. and other Node contributors. // // 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. // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(arg) { if (Array.isArray) { return Array.isArray(arg); } return objectToString(arg) === '[object Array]'; } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = Buffer.isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } /***/ }), /***/ "./node_modules/crypt/crypt.js": /*!*************************************!*\ !*** ./node_modules/crypt/crypt.js ***! \*************************************/ /***/ ((module) => { (function() { var base64map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', crypt = { // Bit-wise rotation left rotl: function(n, b) { return (n << b) | (n >>> (32 - b)); }, // Bit-wise rotation right rotr: function(n, b) { return (n << (32 - b)) | (n >>> b); }, // Swap big-endian to little-endian and vice versa endian: function(n) { // If number given, swap endian if (n.constructor == Number) { return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00; } // Else, assume array and swap all items for (var i = 0; i < n.length; i++) n[i] = crypt.endian(n[i]); return n; }, // Generate an array of any length of random bytes randomBytes: function(n) { for (var bytes = []; n > 0; n--) bytes.push(Math.floor(Math.random() * 256)); return bytes; }, // Convert a byte array to big-endian 32-bit words bytesToWords: function(bytes) { for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8) words[b >>> 5] |= bytes[i] << (24 - b % 32); return words; }, // Convert big-endian 32-bit words to a byte array wordsToBytes: function(words) { for (var bytes = [], b = 0; b < words.length * 32; b += 8) bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); return bytes; }, // Convert a byte array to a hex string bytesToHex: function(bytes) { for (var hex = [], i = 0; i < bytes.length; i++) { hex.push((bytes[i] >>> 4).toString(16)); hex.push((bytes[i] & 0xF).toString(16)); } return hex.join(''); }, // Convert a hex string to a byte array hexToBytes: function(hex) { for (var bytes = [], c = 0; c < hex.length; c += 2) bytes.push(parseInt(hex.substr(c, 2), 16)); return bytes; }, // Convert a byte array to a base-64 string bytesToBase64: function(bytes) { for (var base64 = [], i = 0; i < bytes.length; i += 3) { var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; for (var j = 0; j < 4; j++) if (i * 8 + j * 6 <= bytes.length * 8) base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F)); else base64.push('='); } return base64.join(''); }, // Convert a base-64 string to a byte array base64ToBytes: function(base64) { // Remove non-base-64 characters base64 = base64.replace(/[^A-Z0-9+\/]/ig, ''); for (var bytes = [], i = 0, imod4 = 0; i < base64.length; imod4 = ++i % 4) { if (imod4 == 0) continue; bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2)) | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2))); } return bytes; } }; module.exports = crypt; })(); /***/ }), /***/ "./node_modules/delayed-stream/lib/delayed_stream.js": /*!***********************************************************!*\ !*** ./node_modules/delayed-stream/lib/delayed_stream.js ***! \***********************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var Stream = (__webpack_require__(/*! stream */ "stream").Stream); var util = __webpack_require__(/*! util */ "util"); module.exports = DelayedStream; function DelayedStream() { this.source = null; this.dataSize = 0; this.maxDataSize = 1024 * 1024; this.pauseStream = true; this._maxDataSizeExceeded = false; this._released = false; this._bufferedEvents = []; } util.inherits(DelayedStream, Stream); DelayedStream.create = function(source, options) { var delayedStream = new this(); options = options || {}; for (var option in options) { delayedStream[option] = options[option]; } delayedStream.source = source; var realEmit = source.emit; source.emit = function() { delayedStream._handleEmit(arguments); return realEmit.apply(source, arguments); }; source.on('error', function() {}); if (delayedStream.pauseStream) { source.pause(); } return delayedStream; }; Object.defineProperty(DelayedStream.prototype, 'readable', { configurable: true, enumerable: true, get: function() { return this.source.readable; } }); DelayedStream.prototype.setEncoding = function() { return this.source.setEncoding.apply(this.source, arguments); }; DelayedStream.prototype.resume = function() { if (!this._released) { this.release(); } this.source.resume(); }; DelayedStream.prototype.pause = function() { this.source.pause(); }; DelayedStream.prototype.release = function() { this._released = true; this._bufferedEvents.forEach(function(args) { this.emit.apply(this, args); }.bind(this)); this._bufferedEvents = []; }; DelayedStream.prototype.pipe = function() { var r = Stream.prototype.pipe.apply(this, arguments); this.resume(); return r; }; DelayedStream.prototype._handleEmit = function(args) { if (this._released) { this.emit.apply(this, args); return; } if (args[0] === 'data') { this.dataSize += args[1].length; this._checkIfMaxDataSizeExceeded(); } this._bufferedEvents.push(args); }; DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { if (this._maxDataSizeExceeded) { return; } if (this.dataSize <= this.maxDataSize) { return; } this._maxDataSizeExceeded = true; var message = 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' this.emit('error', new Error(message)); }; /***/ }), /***/ "./node_modules/ecc-jsbn/index.js": /*!****************************************!*\ !*** ./node_modules/ecc-jsbn/index.js ***! \****************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var crypto = __webpack_require__(/*! crypto */ "crypto"); var BigInteger = (__webpack_require__(/*! jsbn */ "./node_modules/jsbn/index.js").BigInteger); var ECPointFp = (__webpack_require__(/*! ./lib/ec.js */ "./node_modules/ecc-jsbn/lib/ec.js").ECPointFp); var Buffer = (__webpack_require__(/*! safer-buffer */ "./node_modules/safer-buffer/safer.js").Buffer); exports.ECCurves = __webpack_require__(/*! ./lib/sec.js */ "./node_modules/ecc-jsbn/lib/sec.js"); // zero prepad function unstupid(hex,len) { return (hex.length >= len) ? hex : unstupid("0"+hex,len); } exports.ECKey = function(curve, key, isPublic) { var priv; var c = curve(); var n = c.getN(); var bytes = Math.floor(n.bitLength()/8); if(key) { if(isPublic) { var curve = c.getCurve(); // var x = key.slice(1,bytes+1); // skip the 04 for uncompressed format // var y = key.slice(bytes+1); // this.P = new ECPointFp(curve, // curve.fromBigInteger(new BigInteger(x.toString("hex"), 16)), // curve.fromBigInteger(new BigInteger(y.toString("hex"), 16))); this.P = curve.decodePointHex(key.toString("hex")); }else{ if(key.length != bytes) return false; priv = new BigInteger(key.toString("hex"), 16); } }else{ var n1 = n.subtract(BigInteger.ONE); var r = new BigInteger(crypto.randomBytes(n.bitLength())); priv = r.mod(n1).add(BigInteger.ONE); this.P = c.getG().multiply(priv); } if(this.P) { // var pubhex = unstupid(this.P.getX().toBigInteger().toString(16),bytes*2)+unstupid(this.P.getY().toBigInteger().toString(16),bytes*2); // this.PublicKey = Buffer.from("04"+pubhex,"hex"); this.PublicKey = Buffer.from(c.getCurve().encodeCompressedPointHex(this.P),"hex"); } if(priv) { this.PrivateKey = Buffer.from(unstupid(priv.toString(16),bytes*2),"hex"); this.deriveSharedSecret = function(key) { if(!key || !key.P) return false; var S = key.P.multiply(priv); return Buffer.from(unstupid(S.getX().toBigInteger().toString(16),bytes*2),"hex"); } } } /***/ }), /***/ "./node_modules/ecc-jsbn/lib/ec.js": /*!*****************************************!*\ !*** ./node_modules/ecc-jsbn/lib/ec.js ***! \*****************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Basic Javascript Elliptic Curve implementation // Ported loosely from BouncyCastle's Java EC code // Only Fp curves implemented for now // Requires jsbn.js and jsbn2.js var BigInteger = (__webpack_require__(/*! jsbn */ "./node_modules/jsbn/index.js").BigInteger) var Barrett = BigInteger.prototype.Barrett // ---------------- // ECFieldElementFp // constructor function ECFieldElementFp(q,x) { this.x = x; // TODO if(x.compareTo(q) >= 0) error this.q = q; } function feFpEquals(other) { if(other == this) return true; return (this.q.equals(other.q) && this.x.equals(other.x)); } function feFpToBigInteger() { return this.x; } function feFpNegate() { return new ECFieldElementFp(this.q, this.x.negate().mod(this.q)); } function feFpAdd(b) { return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q)); } function feFpSubtract(b) { return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q)); } function feFpMultiply(b) { return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q)); } function feFpSquare() { return new ECFieldElementFp(this.q, this.x.square().mod(this.q)); } function feFpDivide(b) { return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q)); } ECFieldElementFp.prototype.equals = feFpEquals; ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger; ECFieldElementFp.prototype.negate = feFpNegate; ECFieldElementFp.prototype.add = feFpAdd; ECFieldElementFp.prototype.subtract = feFpSubtract; ECFieldElementFp.prototype.multiply = feFpMultiply; ECFieldElementFp.prototype.square = feFpSquare; ECFieldElementFp.prototype.divide = feFpDivide; // ---------------- // ECPointFp // constructor function ECPointFp(curve,x,y,z) { this.curve = curve; this.x = x; this.y = y; // Projective coordinates: either zinv == null or z * zinv == 1 // z and zinv are just BigIntegers, not fieldElements if(z == null) { this.z = BigInteger.ONE; } else { this.z = z; } this.zinv = null; //TODO: compression flag } function pointFpGetX() { if(this.zinv == null) { this.zinv = this.z.modInverse(this.curve.q); } var r = this.x.toBigInteger().multiply(this.zinv); this.curve.reduce(r); return this.curve.fromBigInteger(r); } function pointFpGetY() { if(this.zinv == null) { this.zinv = this.z.modInverse(this.curve.q); } var r = this.y.toBigInteger().multiply(this.zinv); this.curve.reduce(r); return this.curve.fromBigInteger(r); } function pointFpEquals(other) { if(other == this) return true; if(this.isInfinity()) return other.isInfinity(); if(other.isInfinity()) return this.isInfinity(); var u, v; // u = Y2 * Z1 - Y1 * Z2 u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q); if(!u.equals(BigInteger.ZERO)) return false; // v = X2 * Z1 - X1 * Z2 v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q); return v.equals(BigInteger.ZERO); } function pointFpIsInfinity() { if((this.x == null) && (this.y == null)) return true; return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO); } function pointFpNegate() { return new ECPointFp(this.curve, this.x, this.y.negate(), this.z); } function pointFpAdd(b) { if(this.isInfinity()) return b; if(b.isInfinity()) return this; // u = Y2 * Z1 - Y1 * Z2 var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q); // v = X2 * Z1 - X1 * Z2 var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q); if(BigInteger.ZERO.equals(v)) { if(BigInteger.ZERO.equals(u)) { return this.twice(); // this == b, so double } return this.curve.getInfinity(); // this = -b, so infinity } var THREE = new BigInteger("3"); var x1 = this.x.toBigInteger(); var y1 = this.y.toBigInteger(); var x2 = b.x.toBigInteger(); var y2 = b.y.toBigInteger(); var v2 = v.square(); var v3 = v2.multiply(v); var x1v2 = x1.multiply(v2); var zu2 = u.square().multiply(this.z); // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q); // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q); // z3 = v^3 * z1 * z2 var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q); return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); } function pointFpTwice() { if(this.isInfinity()) return this; if(this.y.toBigInteger().signum() == 0) return this.curve.getInfinity(); // TODO: optimized handling of constants var THREE = new BigInteger("3"); var x1 = this.x.toBigInteger(); var y1 = this.y.toBigInteger(); var y1z1 = y1.multiply(this.z); var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q); var a = this.curve.a.toBigInteger(); // w = 3 * x1^2 + a * z1^2 var w = x1.square().multiply(THREE); if(!BigInteger.ZERO.equals(a)) { w = w.add(this.z.square().multiply(a)); } w = w.mod(this.curve.q); //this.curve.reduce(w); // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q); // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q); // z3 = 8 * (y1 * z1)^3 var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q); return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); } // Simple NAF (Non-Adjacent Form) multiplication algorithm // TODO: modularize the multiplication algorithm function pointFpMultiply(k) { if(this.isInfinity()) return this; if(k.signum() == 0) return this.curve.getInfinity(); var e = k; var h = e.multiply(new BigInteger("3")); var neg = this.negate(); var R = this; var i; for(i = h.bitLength() - 2; i > 0; --i) { R = R.twice(); var hBit = h.testBit(i); var eBit = e.testBit(i); if (hBit != eBit) { R = R.add(hBit ? this : neg); } } return R; } // Compute this*j + x*k (simultaneous multiplication) function pointFpMultiplyTwo(j,x,k) { var i; if(j.bitLength() > k.bitLength()) i = j.bitLength() - 1; else i = k.bitLength() - 1; var R = this.curve.getInfinity(); var both = this.add(x); while(i >= 0) { R = R.twice(); if(j.testBit(i)) { if(k.testBit(i)) { R = R.add(both); } else { R = R.add(this); } } else { if(k.testBit(i)) { R = R.add(x); } } --i; } return R; } ECPointFp.prototype.getX = pointFpGetX; ECPointFp.prototype.getY = pointFpGetY; ECPointFp.prototype.equals = pointFpEquals; ECPointFp.prototype.isInfinity = pointFpIsInfinity; ECPointFp.prototype.negate = pointFpNegate; ECPointFp.prototype.add = pointFpAdd; ECPointFp.prototype.twice = pointFpTwice; ECPointFp.prototype.multiply = pointFpMultiply; ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo; // ---------------- // ECCurveFp // constructor function ECCurveFp(q,a,b) { this.q = q; this.a = this.fromBigInteger(a); this.b = this.fromBigInteger(b); this.infinity = new ECPointFp(this, null, null); this.reducer = new Barrett(this.q); } function curveFpGetQ() { return this.q; } function curveFpGetA() { return this.a; } function curveFpGetB() { return this.b; } function curveFpEquals(other) { if(other == this) return true; return(this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); } function curveFpGetInfinity() { return this.infinity; } function curveFpFromBigInteger(x) { return new ECFieldElementFp(this.q, x); } function curveReduce(x) { this.reducer.reduce(x); } // for now, work with hex strings because they're easier in JS function curveFpDecodePointHex(s) { switch(parseInt(s.substr(0,2), 16)) { // first byte case 0: return this.infinity; case 2: case 3: // point compression not supported yet return null; case 4: case 6: case 7: var len = (s.length - 2) / 2; var xHex = s.substr(2, len); var yHex = s.substr(len+2, len); return new ECPointFp(this, this.fromBigInteger(new BigInteger(xHex, 16)), this.fromBigInteger(new BigInteger(yHex, 16))); default: // unsupported return null; } } function curveFpEncodePointHex(p) { if (p.isInfinity()) return "00"; var xHex = p.getX().toBigInteger().toString(16); var yHex = p.getY().toBigInteger().toString(16); var oLen = this.getQ().toString(16).length; if ((oLen % 2) != 0) oLen++; while (xHex.length < oLen) { xHex = "0" + xHex; } while (yHex.length < oLen) { yHex = "0" + yHex; } return "04" + xHex + yHex; } ECCurveFp.prototype.getQ = curveFpGetQ; ECCurveFp.prototype.getA = curveFpGetA; ECCurveFp.prototype.getB = curveFpGetB; ECCurveFp.prototype.equals = curveFpEquals; ECCurveFp.prototype.getInfinity = curveFpGetInfinity; ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger; ECCurveFp.prototype.reduce = curveReduce; //ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex; ECCurveFp.prototype.encodePointHex = curveFpEncodePointHex; // from: https://github.com/kaielvin/jsbn-ec-point-compression ECCurveFp.prototype.decodePointHex = function(s) { var yIsEven; switch(parseInt(s.substr(0,2), 16)) { // first byte case 0: return this.infinity; case 2: yIsEven = false; case 3: if(yIsEven == undefined) yIsEven = true; var len = s.length - 2; var xHex = s.substr(2, len); var x = this.fromBigInteger(new BigInteger(xHex,16)); var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); var beta = alpha.sqrt(); if (beta == null) throw "Invalid point compression"; var betaValue = beta.toBigInteger(); if (betaValue.testBit(0) != yIsEven) { // Use the other root beta = this.fromBigInteger(this.getQ().subtract(betaValue)); } return new ECPointFp(this,x,beta); case 4: case 6: case 7: var len = (s.length - 2) / 2; var xHex = s.substr(2, len); var yHex = s.substr(len+2, len); return new ECPointFp(this, this.fromBigInteger(new BigInteger(xHex, 16)), this.fromBigInteger(new BigInteger(yHex, 16))); default: // unsupported return null; } } ECCurveFp.prototype.encodeCompressedPointHex = function(p) { if (p.isInfinity()) return "00"; var xHex = p.getX().toBigInteger().toString(16); var oLen = this.getQ().toString(16).length; if ((oLen % 2) != 0) oLen++; while (xHex.length < oLen) xHex = "0" + xHex; var yPrefix; if(p.getY().toBigInteger().isEven()) yPrefix = "02"; else yPrefix = "03"; return yPrefix + xHex; } ECFieldElementFp.prototype.getR = function() { if(this.r != undefined) return this.r; this.r = null; var bitLength = this.q.bitLength(); if (bitLength > 128) { var firstWord = this.q.shiftRight(bitLength - 64); if (firstWord.intValue() == -1) { this.r = BigInteger.ONE.shiftLeft(bitLength).subtract(this.q); } } return this.r; } ECFieldElementFp.prototype.modMult = function(x1,x2) { return this.modReduce(x1.multiply(x2)); } ECFieldElementFp.prototype.modReduce = function(x) { if (this.getR() != null) { var qLen = q.bitLength(); while (x.bitLength() > (qLen + 1)) { var u = x.shiftRight(qLen); var v = x.subtract(u.shiftLeft(qLen)); if (!this.getR().equals(BigInteger.ONE)) { u = u.multiply(this.getR()); } x = u.add(v); } while (x.compareTo(q) >= 0) { x = x.subtract(q); } } else { x = x.mod(q); } return x; } ECFieldElementFp.prototype.sqrt = function() { if (!this.q.testBit(0)) throw "unsupported"; // p mod 4 == 3 if (this.q.testBit(1)) { var z = new ECFieldElementFp(this.q,this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE),this.q)); return z.square().equals(this) ? z : null; } // p mod 4 == 1 var qMinusOne = this.q.subtract(BigInteger.ONE); var legendreExponent = qMinusOne.shiftRight(1); if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE))) { return null; } var u = qMinusOne.shiftRight(2); var k = u.shiftLeft(1).add(BigInteger.ONE); var Q = this.x; var fourQ = modDouble(modDouble(Q)); var U, V; do { var P; do { P = new BigInteger(this.q.bitLength(), new SecureRandom()); } while (P.compareTo(this.q) >= 0 || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, this.q).equals(qMinusOne))); var result = this.lucasSequence(P, Q, k); U = result[0]; V = result[1]; if (this.modMult(V, V).equals(fourQ)) { // Integer division by 2, mod q if (V.testBit(0)) { V = V.add(q); } V = V.shiftRight(1); return new ECFieldElementFp(q,V); } } while (U.equals(BigInteger.ONE) || U.equals(qMinusOne)); return null; } ECFieldElementFp.prototype.lucasSequence = function(P,Q,k) { var n = k.bitLength(); var s = k.getLowestSetBit(); var Uh = BigInteger.ONE; var Vl = BigInteger.TWO; var Vh = P; var Ql = BigInteger.ONE; var Qh = BigInteger.ONE; for (var j = n - 1; j >= s + 1; --j) { Ql = this.modMult(Ql, Qh); if (k.testBit(j)) { Qh = this.modMult(Ql, Q); Uh = this.modMult(Uh, Vh); Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); Vh = this.modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1))); } else { Qh = Ql; Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); Vh = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); } } Ql = this.modMult(Ql, Qh); Qh = this.modMult(Ql, Q); Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); Ql = this.modMult(Ql, Qh); for (var j = 1; j <= s; ++j) { Uh = this.modMult(Uh, Vl); Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); Ql = this.modMult(Ql, Ql); } return [ Uh, Vl ]; } var exports = { ECCurveFp: ECCurveFp, ECPointFp: ECPointFp, ECFieldElementFp: ECFieldElementFp } module.exports = exports /***/ }), /***/ "./node_modules/ecc-jsbn/lib/sec.js": /*!******************************************!*\ !*** ./node_modules/ecc-jsbn/lib/sec.js ***! \******************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Named EC curves // Requires ec.js, jsbn.js, and jsbn2.js var BigInteger = (__webpack_require__(/*! jsbn */ "./node_modules/jsbn/index.js").BigInteger) var ECCurveFp = (__webpack_require__(/*! ./ec.js */ "./node_modules/ecc-jsbn/lib/ec.js").ECCurveFp) // ---------------- // X9ECParameters // constructor function X9ECParameters(curve,g,n,h) { this.curve = curve; this.g = g; this.n = n; this.h = h; } function x9getCurve() { return this.curve; } function x9getG() { return this.g; } function x9getN() { return this.n; } function x9getH() { return this.h; } X9ECParameters.prototype.getCurve = x9getCurve; X9ECParameters.prototype.getG = x9getG; X9ECParameters.prototype.getN = x9getN; X9ECParameters.prototype.getH = x9getH; // ---------------- // SECNamedCurves function fromHex(s) { return new BigInteger(s, 16); } function secp128r1() { // p = 2^128 - 2^97 - 1 var p = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF"); var a = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC"); var b = fromHex("E87579C11079F43DD824993C2CEE5ED3"); //byte[] S = Hex.decode("000E0D4D696E6768756151750CC03A4473D03679"); var n = fromHex("FFFFFFFE0000000075A30D1B9038A115"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "161FF7528B899B2D0C28607CA52C5B86" + "CF5AC8395BAFEB13C02DA292DDED7A83"); return new X9ECParameters(curve, G, n, h); } function secp160k1() { // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73"); var a = BigInteger.ZERO; var b = fromHex("7"); //byte[] S = null; var n = fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB" + "938CF935318FDCED6BC28286531733C3F03C4FEE"); return new X9ECParameters(curve, G, n, h); } function secp160r1() { // p = 2^160 - 2^31 - 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF"); var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC"); var b = fromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45"); //byte[] S = Hex.decode("1053CDE42C14D696E67687561517533BF3F83345"); var n = fromHex("0100000000000000000001F4C8F927AED3CA752257"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "4A96B5688EF573284664698968C38BB913CBFC82" + "23A628553168947D59DCC912042351377AC5FB32"); return new X9ECParameters(curve, G, n, h); } function secp192k1() { // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37"); var a = BigInteger.ZERO; var b = fromHex("3"); //byte[] S = null; var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D" + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D"); return new X9ECParameters(curve, G, n, h); } function secp192r1() { // p = 2^192 - 2^64 - 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"); var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC"); var b = fromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1"); //byte[] S = Hex.decode("3045AE6FC8422F64ED579528D38120EAE12196D5"); var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012" + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"); return new X9ECParameters(curve, G, n, h); } function secp224r1() { // p = 2^224 - 2^96 + 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001"); var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE"); var b = fromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4"); //byte[] S = Hex.decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5"); var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21" + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"); return new X9ECParameters(curve, G, n, h); } function secp256r1() { // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1 var p = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF"); var a = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC"); var b = fromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"); //byte[] S = Hex.decode("C49D360886E704936A6678E1139D26B7819F7E90"); var n = fromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296" + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"); return new X9ECParameters(curve, G, n, h); } // TODO: make this into a proper hashtable function getSECCurveByName(name) { if(name == "secp128r1") return secp128r1(); if(name == "secp160k1") return secp160k1(); if(name == "secp160r1") return secp160r1(); if(name == "secp192k1") return secp192k1(); if(name == "secp192r1") return secp192r1(); if(name == "secp224r1") return secp224r1(); if(name == "secp256r1") return secp256r1(); return null; } module.exports = { "secp128r1":secp128r1, "secp160k1":secp160k1, "secp160r1":secp160r1, "secp192k1":secp192k1, "secp192r1":secp192r1, "secp224r1":secp224r1, "secp256r1":secp256r1 } /***/ }), /***/ "./node_modules/extend/index.js": /*!**************************************!*\ !*** ./node_modules/extend/index.js ***! \**************************************/ /***/ ((module) => { "use strict"; var hasOwn = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var defineProperty = Object.defineProperty; var gOPD = Object.getOwnPropertyDescriptor; var isArray = function isArray(arr) { if (typeof Array.isArray === 'function') { return Array.isArray(arr); } return toStr.call(arr) === '[object Array]'; }; var isPlainObject = function isPlainObject(obj) { if (!obj || toStr.call(obj) !== '[object Object]') { return false; } var hasOwnConstructor = hasOwn.call(obj, 'constructor'); var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); // Not own constructor property must be Object if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for (key in obj) { /**/ } return typeof key === 'undefined' || hasOwn.call(obj, key); }; // If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target var setProperty = function setProperty(target, options) { if (defineProperty && options.name === '__proto__') { defineProperty(target, options.name, { enumerable: true, configurable: true, value: options.newValue, writable: true }); } else { target[options.name] = options.newValue; } }; // Return undefined instead of __proto__ if '__proto__' is not an own property var getProperty = function getProperty(obj, name) { if (name === '__proto__') { if (!hasOwn.call(obj, name)) { return void 0; } else if (gOPD) { // In early versions of node, obj['__proto__'] is buggy when obj has // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. return gOPD(obj, name).value; } } return obj[name]; }; module.exports = function extend() { var options, name, src, copy, copyIsArray, clone; var target = arguments[0]; var i = 1; var length = arguments.length; var deep = false; // Handle a deep copy situation if (typeof target === 'boolean') { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { target = {}; } for (; i < length; ++i) { options = arguments[i]; // Only deal with non-null/undefined values if (options != null) { // Extend the base object for (name in options) { src = getProperty(target, name); copy = getProperty(options, name); // Prevent never-ending loop if (target !== copy) { // Recurse if we're merging plain objects or arrays if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move original objects, clone them setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); // Don't bring in undefined values } else if (typeof copy !== 'undefined') { setProperty(target, { name: name, newValue: copy }); } } } } } // Return the modified object return target; }; /***/ }), /***/ "./node_modules/extsprintf/lib/extsprintf.js": /*!***************************************************!*\ !*** ./node_modules/extsprintf/lib/extsprintf.js ***! \***************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { /* * extsprintf.js: extended POSIX-style sprintf */ var mod_assert = __webpack_require__(/*! assert */ "assert"); var mod_util = __webpack_require__(/*! util */ "util"); /* * Public interface */ exports.sprintf = jsSprintf; exports.printf = jsPrintf; exports.fprintf = jsFprintf; /* * Stripped down version of s[n]printf(3c). We make a best effort to throw an * exception when given a format string we don't understand, rather than * ignoring it, so that we won't break existing programs if/when we go implement * the rest of this. * * This implementation currently supports specifying * - field alignment ('-' flag), * - zero-pad ('0' flag) * - always show numeric sign ('+' flag), * - field width * - conversions for strings, decimal integers, and floats (numbers). * - argument size specifiers. These are all accepted but ignored, since * Javascript has no notion of the physical size of an argument. * * Everything else is currently unsupported, most notably precision, unsigned * numbers, non-decimal numbers, and characters. */ function jsSprintf(fmt) { var regex = [ '([^%]*)', /* normal text */ '%', /* start of format */ '([\'\\-+ #0]*?)', /* flags (optional) */ '([1-9]\\d*)?', /* width (optional) */ '(\\.([1-9]\\d*))?', /* precision (optional) */ '[lhjztL]*?', /* length mods (ignored) */ '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */ ].join(''); var re = new RegExp(regex); var args = Array.prototype.slice.call(arguments, 1); var flags, width, precision, conversion; var left, pad, sign, arg, match; var ret = ''; var argn = 1; mod_assert.equal('string', typeof (fmt)); while ((match = re.exec(fmt)) !== null) { ret += match[1]; fmt = fmt.substring(match[0].length); flags = match[2] || ''; width = match[3] || 0; precision = match[4] || ''; conversion = match[6]; left = false; sign = false; pad = ' '; if (conversion == '%') { ret += '%'; continue; } if (args.length === 0) throw (new Error('too few args to sprintf')); arg = args.shift(); argn++; if (flags.match(/[\' #]/)) throw (new Error( 'unsupported flags: ' + flags)); if (precision.length > 0) throw (new Error( 'non-zero precision not supported')); if (flags.match(/-/)) left = true; if (flags.match(/0/)) pad = '0'; if (flags.match(/\+/)) sign = true; switch (conversion) { case 's': if (arg === undefined || arg === null) throw (new Error('argument ' + argn + ': attempted to print undefined or null ' + 'as a string')); ret += doPad(pad, width, left, arg.toString()); break; case 'd': arg = Math.floor(arg); /*jsl:fallthru*/ case 'f': sign = sign && arg > 0 ? '+' : ''; ret += sign + doPad(pad, width, left, arg.toString()); break; case 'x': ret += doPad(pad, width, left, arg.toString(16)); break; case 'j': /* non-standard */ if (width === 0) width = 10; ret += mod_util.inspect(arg, false, width); break; case 'r': /* non-standard */ ret += dumpException(arg); break; default: throw (new Error('unsupported conversion: ' + conversion)); } } ret += fmt; return (ret); } function jsPrintf() { var args = Array.prototype.slice.call(arguments); args.unshift(process.stdout); jsFprintf.apply(null, args); } function jsFprintf(stream) { var args = Array.prototype.slice.call(arguments, 1); return (stream.write(jsSprintf.apply(this, args))); } function doPad(chr, width, left, str) { var ret = str; while (ret.length < width) { if (left) ret += chr; else ret = chr + ret; } return (ret); } /* * This function dumps long stack traces for exceptions having a cause() method. * See node-verror for an example. */ function dumpException(ex) { var ret; if (!(ex instanceof Error)) throw (new Error(jsSprintf('invalid type for %%r: %j', ex))); /* Note that V8 prepends "ex.stack" with ex.toString(). */ ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack; if (ex.cause && typeof (ex.cause) === 'function') { var cex = ex.cause(); if (cex) { ret += '\nCaused by: ' + dumpException(cex); } } return (ret); } /***/ }), /***/ "./node_modules/fast-deep-equal/index.js": /*!***********************************************!*\ !*** ./node_modules/fast-deep-equal/index.js ***! \***********************************************/ /***/ ((module) => { "use strict"; // do not edit .js files directly - edit src/index.jst module.exports = function equal(a, b) { if (a === b) return true; if (a && b && typeof a == 'object' && typeof b == 'object') { if (a.constructor !== b.constructor) return false; var length, i, keys; if (Array.isArray(a)) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; return true; } if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); keys = Object.keys(a); length = keys.length; if (length !== Object.keys(b).length) return false; for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; for (i = length; i-- !== 0;) { var key = keys[i]; if (!equal(a[key], b[key])) return false; } return true; } // true if both NaN, false otherwise return a!==a && b!==b; }; /***/ }), /***/ "./node_modules/fast-json-stable-stringify/index.js": /*!**********************************************************!*\ !*** ./node_modules/fast-json-stable-stringify/index.js ***! \**********************************************************/ /***/ ((module) => { "use strict"; module.exports = function (data, opts) { if (!opts) opts = {}; if (typeof opts === 'function') opts = { cmp: opts }; var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; var cmp = opts.cmp && (function (f) { return function (node) { return function (a, b) { var aobj = { key: a, value: node[a] }; var bobj = { key: b, value: node[b] }; return f(aobj, bobj); }; }; })(opts.cmp); var seen = []; return (function stringify (node) { if (node && node.toJSON && typeof node.toJSON === 'function') { node = node.toJSON(); } if (node === undefined) return; if (typeof node == 'number') return isFinite(node) ? '' + node : 'null'; if (typeof node !== 'object') return JSON.stringify(node); var i, out; if (Array.isArray(node)) { out = '['; for (i = 0; i < node.length; i++) { if (i) out += ','; out += stringify(node[i]) || 'null'; } return out + ']'; } if (node === null) return 'null'; if (seen.indexOf(node) !== -1) { if (cycles) return JSON.stringify('__cycle__'); throw new TypeError('Converting circular structure to JSON'); } var seenIndex = seen.push(node) - 1; var keys = Object.keys(node).sort(cmp && cmp(node)); out = ''; for (i = 0; i < keys.length; i++) { var key = keys[i]; var value = stringify(node[key]); if (!value) continue; if (out) out += ','; out += JSON.stringify(key) + ':' + value; } seen.splice(seenIndex, 1); return '{' + out + '}'; })(data); }; /***/ }), /***/ "./node_modules/forever-agent/index.js": /*!*********************************************!*\ !*** ./node_modules/forever-agent/index.js ***! \*********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = ForeverAgent ForeverAgent.SSL = ForeverAgentSSL var util = __webpack_require__(/*! util */ "util") , Agent = (__webpack_require__(/*! http */ "http").Agent) , net = __webpack_require__(/*! net */ "net") , tls = __webpack_require__(/*! tls */ "tls") , AgentSSL = (__webpack_require__(/*! https */ "https").Agent) function getConnectionName(host, port) { var name = '' if (typeof host === 'string') { name = host + ':' + port } else { // For node.js v012.0 and iojs-v1.5.1, host is an object. And any existing localAddress is part of the connection name. name = host.host + ':' + host.port + ':' + (host.localAddress ? (host.localAddress + ':') : ':') } return name } function ForeverAgent(options) { var self = this self.options = options || {} self.requests = {} self.sockets = {} self.freeSockets = {} self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets self.on('free', function(socket, host, port) { var name = getConnectionName(host, port) if (self.requests[name] && self.requests[name].length) { self.requests[name].shift().onSocket(socket) } else if (self.sockets[name].length < self.minSockets) { if (!self.freeSockets[name]) self.freeSockets[name] = [] self.freeSockets[name].push(socket) // if an error happens while we don't use the socket anyway, meh, throw the socket away var onIdleError = function() { socket.destroy() } socket._onIdleError = onIdleError socket.on('error', onIdleError) } else { // If there are no pending requests just destroy the // socket and it will get removed from the pool. This // gets us out of timeout issues and allows us to // default to Connection:keep-alive. socket.destroy() } }) } util.inherits(ForeverAgent, Agent) ForeverAgent.defaultMinSockets = 5 ForeverAgent.prototype.createConnection = net.createConnection ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest ForeverAgent.prototype.addRequest = function(req, host, port) { var name = getConnectionName(host, port) if (typeof host !== 'string') { var options = host port = options.port host = options.host } if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) { var idleSocket = this.freeSockets[name].pop() idleSocket.removeListener('error', idleSocket._onIdleError) delete idleSocket._onIdleError req._reusedSocket = true req.onSocket(idleSocket) } else { this.addRequestNoreuse(req, host, port) } } ForeverAgent.prototype.removeSocket = function(s, name, host, port) { if (this.sockets[name]) { var index = this.sockets[name].indexOf(s) if (index !== -1) { this.sockets[name].splice(index, 1) } } else if (this.sockets[name] && this.sockets[name].length === 0) { // don't leak delete this.sockets[name] delete this.requests[name] } if (this.freeSockets[name]) { var index = this.freeSockets[name].indexOf(s) if (index !== -1) { this.freeSockets[name].splice(index, 1) if (this.freeSockets[name].length === 0) { delete this.freeSockets[name] } } } if (this.requests[name] && this.requests[name].length) { // If we have pending requests and a socket gets closed a new one // needs to be created to take over in the pool for the one that closed. this.createSocket(name, host, port).emit('free') } } function ForeverAgentSSL (options) { ForeverAgent.call(this, options) } util.inherits(ForeverAgentSSL, ForeverAgent) ForeverAgentSSL.prototype.createConnection = createConnectionSSL ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest function createConnectionSSL (port, host, options) { if (typeof port === 'object') { options = port; } else if (typeof host === 'object') { options = host; } else if (typeof options === 'object') { options = options; } else { options = {}; } if (typeof port === 'number') { options.port = port; } if (typeof host === 'string') { options.host = host; } return tls.connect(options); } /***/ }), /***/ "./node_modules/fs-extra/lib/copy/copy-sync.js": /*!*****************************************************!*\ !*** ./node_modules/fs-extra/lib/copy/copy-sync.js ***! \*****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const fs = __webpack_require__(/*! graceful-fs */ "./node_modules/graceful-fs/graceful-fs.js") const path = __webpack_require__(/*! path */ "path") const mkdirsSync = (__webpack_require__(/*! ../mkdirs */ "./node_modules/fs-extra/lib/mkdirs/index.js").mkdirsSync) const utimesMillisSync = (__webpack_require__(/*! ../util/utimes */ "./node_modules/fs-extra/lib/util/utimes.js").utimesMillisSync) const stat = __webpack_require__(/*! ../util/stat */ "./node_modules/fs-extra/lib/util/stat.js") function copySync (src, dest, opts) { if (typeof opts === 'function') { opts = { filter: opts } } opts = opts || {} opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber // Warn about using preserveTimestamps on 32-bit node if (opts.preserveTimestamps && process.arch === 'ia32') { console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n see https://github.com/jprichardson/node-fs-extra/issues/269`) } const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy', opts) stat.checkParentPathsSync(src, srcStat, dest, 'copy') return handleFilterAndCopy(destStat, src, dest, opts) } function handleFilterAndCopy (destStat, src, dest, opts) { if (opts.filter && !opts.filter(src, dest)) return const destParent = path.dirname(dest) if (!fs.existsSync(destParent)) mkdirsSync(destParent) return getStats(destStat, src, dest, opts) } function startCopy (destStat, src, dest, opts) { if (opts.filter && !opts.filter(src, dest)) return return getStats(destStat, src, dest, opts) } function getStats (destStat, src, dest, opts) { const statSync = opts.dereference ? fs.statSync : fs.lstatSync const srcStat = statSync(src) if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts) else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts) else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts) else if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`) else if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`) throw new Error(`Unknown file: ${src}`) } function onFile (srcStat, destStat, src, dest, opts) { if (!destStat) return copyFile(srcStat, src, dest, opts) return mayCopyFile(srcStat, src, dest, opts) } function mayCopyFile (srcStat, src, dest, opts) { if (opts.overwrite) { fs.unlinkSync(dest) return copyFile(srcStat, src, dest, opts) } else if (opts.errorOnExist) { throw new Error(`'${dest}' already exists`) } } function copyFile (srcStat, src, dest, opts) { fs.copyFileSync(src, dest) if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest) return setDestMode(dest, srcStat.mode) } function handleTimestamps (srcMode, src, dest) { // Make sure the file is writable before setting the timestamp // otherwise open fails with EPERM when invoked with 'r+' // (through utimes call) if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode) return setDestTimestamps(src, dest) } function fileIsNotWritable (srcMode) { return (srcMode & 0o200) === 0 } function makeFileWritable (dest, srcMode) { return setDestMode(dest, srcMode | 0o200) } function setDestMode (dest, srcMode) { return fs.chmodSync(dest, srcMode) } function setDestTimestamps (src, dest) { // The initial srcStat.atime cannot be trusted // because it is modified by the read(2) system call // (See https://nodejs.org/api/fs.html#fs_stat_time_values) const updatedSrcStat = fs.statSync(src) return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime) } function onDir (srcStat, destStat, src, dest, opts) { if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts) return copyDir(src, dest, opts) } function mkDirAndCopy (srcMode, src, dest, opts) { fs.mkdirSync(dest) copyDir(src, dest, opts) return setDestMode(dest, srcMode) } function copyDir (src, dest, opts) { fs.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts)) } function copyDirItem (item, src, dest, opts) { const srcItem = path.join(src, item) const destItem = path.join(dest, item) const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy', opts) return startCopy(destStat, srcItem, destItem, opts) } function onLink (destStat, src, dest, opts) { let resolvedSrc = fs.readlinkSync(src) if (opts.dereference) { resolvedSrc = path.resolve(process.cwd(), resolvedSrc) } if (!destStat) { return fs.symlinkSync(resolvedSrc, dest) } else { let resolvedDest try { resolvedDest = fs.readlinkSync(dest) } catch (err) { // dest exists and is a regular file or directory, // Windows may throw UNKNOWN error. If dest already exists, // fs throws error anyway, so no need to guard against it here. if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest) throw err } if (opts.dereference) { resolvedDest = path.resolve(process.cwd(), resolvedDest) } if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) } // prevent copy if src is a subdir of dest since unlinking // dest in this case would result in removing src contents // and therefore a broken symlink would be created. if (fs.statSync(dest).isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) } return copyLink(resolvedSrc, dest) } } function copyLink (resolvedSrc, dest) { fs.unlinkSync(dest) return fs.symlinkSync(resolvedSrc, dest) } module.exports = copySync /***/ }), /***/ "./node_modules/fs-extra/lib/copy/copy.js": /*!************************************************!*\ !*** ./node_modules/fs-extra/lib/copy/copy.js ***! \************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const fs = __webpack_require__(/*! graceful-fs */ "./node_modules/graceful-fs/graceful-fs.js") const path = __webpack_require__(/*! path */ "path") const mkdirs = (__webpack_require__(/*! ../mkdirs */ "./node_modules/fs-extra/lib/mkdirs/index.js").mkdirs) const pathExists = (__webpack_require__(/*! ../path-exists */ "./node_modules/fs-extra/lib/path-exists/index.js").pathExists) const utimesMillis = (__webpack_require__(/*! ../util/utimes */ "./node_modules/fs-extra/lib/util/utimes.js").utimesMillis) const stat = __webpack_require__(/*! ../util/stat */ "./node_modules/fs-extra/lib/util/stat.js") function copy (src, dest, opts, cb) { if (typeof opts === 'function' && !cb) { cb = opts opts = {} } else if (typeof opts === 'function') { opts = { filter: opts } } cb = cb || function () {} opts = opts || {} opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber // Warn about using preserveTimestamps on 32-bit node if (opts.preserveTimestamps && process.arch === 'ia32') { console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n see https://github.com/jprichardson/node-fs-extra/issues/269`) } stat.checkPaths(src, dest, 'copy', opts, (err, stats) => { if (err) return cb(err) const { srcStat, destStat } = stats stat.checkParentPaths(src, srcStat, dest, 'copy', err => { if (err) return cb(err) if (opts.filter) return handleFilter(checkParentDir, destStat, src, dest, opts, cb) return checkParentDir(destStat, src, dest, opts, cb) }) }) } function checkParentDir (destStat, src, dest, opts, cb) { const destParent = path.dirname(dest) pathExists(destParent, (err, dirExists) => { if (err) return cb(err) if (dirExists) return getStats(destStat, src, dest, opts, cb) mkdirs(destParent, err => { if (err) return cb(err) return getStats(destStat, src, dest, opts, cb) }) }) } function handleFilter (onInclude, destStat, src, dest, opts, cb) { Promise.resolve(opts.filter(src, dest)).then(include => { if (include) return onInclude(destStat, src, dest, opts, cb) return cb() }, error => cb(error)) } function startCopy (destStat, src, dest, opts, cb) { if (opts.filter) return handleFilter(getStats, destStat, src, dest, opts, cb) return getStats(destStat, src, dest, opts, cb) } function getStats (destStat, src, dest, opts, cb) { const stat = opts.dereference ? fs.stat : fs.lstat stat(src, (err, srcStat) => { if (err) return cb(err) if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts, cb) else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts, cb) else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts, cb) else if (srcStat.isSocket()) return cb(new Error(`Cannot copy a socket file: ${src}`)) else if (srcStat.isFIFO()) return cb(new Error(`Cannot copy a FIFO pipe: ${src}`)) return cb(new Error(`Unknown file: ${src}`)) }) } function onFile (srcStat, destStat, src, dest, opts, cb) { if (!destStat) return copyFile(srcStat, src, dest, opts, cb) return mayCopyFile(srcStat, src, dest, opts, cb) } function mayCopyFile (srcStat, src, dest, opts, cb) { if (opts.overwrite) { fs.unlink(dest, err => { if (err) return cb(err) return copyFile(srcStat, src, dest, opts, cb) }) } else if (opts.errorOnExist) { return cb(new Error(`'${dest}' already exists`)) } else return cb() } function copyFile (srcStat, src, dest, opts, cb) { fs.copyFile(src, dest, err => { if (err) return cb(err) if (opts.preserveTimestamps) return handleTimestampsAndMode(srcStat.mode, src, dest, cb) return setDestMode(dest, srcStat.mode, cb) }) } function handleTimestampsAndMode (srcMode, src, dest, cb) { // Make sure the file is writable before setting the timestamp // otherwise open fails with EPERM when invoked with 'r+' // (through utimes call) if (fileIsNotWritable(srcMode)) { return makeFileWritable(dest, srcMode, err => { if (err) return cb(err) return setDestTimestampsAndMode(srcMode, src, dest, cb) }) } return setDestTimestampsAndMode(srcMode, src, dest, cb) } function fileIsNotWritable (srcMode) { return (srcMode & 0o200) === 0 } function makeFileWritable (dest, srcMode, cb) { return setDestMode(dest, srcMode | 0o200, cb) } function setDestTimestampsAndMode (srcMode, src, dest, cb) { setDestTimestamps(src, dest, err => { if (err) return cb(err) return setDestMode(dest, srcMode, cb) }) } function setDestMode (dest, srcMode, cb) { return fs.chmod(dest, srcMode, cb) } function setDestTimestamps (src, dest, cb) { // The initial srcStat.atime cannot be trusted // because it is modified by the read(2) system call // (See https://nodejs.org/api/fs.html#fs_stat_time_values) fs.stat(src, (err, updatedSrcStat) => { if (err) return cb(err) return utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime, cb) }) } function onDir (srcStat, destStat, src, dest, opts, cb) { if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts, cb) return copyDir(src, dest, opts, cb) } function mkDirAndCopy (srcMode, src, dest, opts, cb) { fs.mkdir(dest, err => { if (err) return cb(err) copyDir(src, dest, opts, err => { if (err) return cb(err) return setDestMode(dest, srcMode, cb) }) }) } function copyDir (src, dest, opts, cb) { fs.readdir(src, (err, items) => { if (err) return cb(err) return copyDirItems(items, src, dest, opts, cb) }) } function copyDirItems (items, src, dest, opts, cb) { const item = items.pop() if (!item) return cb() return copyDirItem(items, item, src, dest, opts, cb) } function copyDirItem (items, item, src, dest, opts, cb) { const srcItem = path.join(src, item) const destItem = path.join(dest, item) stat.checkPaths(srcItem, destItem, 'copy', opts, (err, stats) => { if (err) return cb(err) const { destStat } = stats startCopy(destStat, srcItem, destItem, opts, err => { if (err) return cb(err) return copyDirItems(items, src, dest, opts, cb) }) }) } function onLink (destStat, src, dest, opts, cb) { fs.readlink(src, (err, resolvedSrc) => { if (err) return cb(err) if (opts.dereference) { resolvedSrc = path.resolve(process.cwd(), resolvedSrc) } if (!destStat) { return fs.symlink(resolvedSrc, dest, cb) } else { fs.readlink(dest, (err, resolvedDest) => { if (err) { // dest exists and is a regular file or directory, // Windows may throw UNKNOWN error. If dest already exists, // fs throws error anyway, so no need to guard against it here. if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest, cb) return cb(err) } if (opts.dereference) { resolvedDest = path.resolve(process.cwd(), resolvedDest) } if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)) } // do not copy if src is a subdir of dest since unlinking // dest in this case would result in removing src contents // and therefore a broken symlink would be created. if (destStat.isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)) } return copyLink(resolvedSrc, dest, cb) }) } }) } function copyLink (resolvedSrc, dest, cb) { fs.unlink(dest, err => { if (err) return cb(err) return fs.symlink(resolvedSrc, dest, cb) }) } module.exports = copy /***/ }), /***/ "./node_modules/fs-extra/lib/copy/index.js": /*!*************************************************!*\ !*** ./node_modules/fs-extra/lib/copy/index.js ***! \*************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const u = (__webpack_require__(/*! universalify */ "./node_modules/fs-extra/node_modules/universalify/index.js").fromCallback) module.exports = { copy: u(__webpack_require__(/*! ./copy */ "./node_modules/fs-extra/lib/copy/copy.js")), copySync: __webpack_require__(/*! ./copy-sync */ "./node_modules/fs-extra/lib/copy/copy-sync.js") } /***/ }), /***/ "./node_modules/fs-extra/lib/empty/index.js": /*!**************************************************!*\ !*** ./node_modules/fs-extra/lib/empty/index.js ***! \**************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const u = (__webpack_require__(/*! universalify */ "./node_modules/fs-extra/node_modules/universalify/index.js").fromPromise) const fs = __webpack_require__(/*! ../fs */ "./node_modules/fs-extra/lib/fs/index.js") const path = __webpack_require__(/*! path */ "path") const mkdir = __webpack_require__(/*! ../mkdirs */ "./node_modules/fs-extra/lib/mkdirs/index.js") const remove = __webpack_require__(/*! ../remove */ "./node_modules/fs-extra/lib/remove/index.js") const emptyDir = u(async function emptyDir (dir) { let items try { items = await fs.readdir(dir) } catch { return mkdir.mkdirs(dir) } return Promise.all(items.map(item => remove.remove(path.join(dir, item)))) }) function emptyDirSync (dir) { let items try { items = fs.readdirSync(dir) } catch { return mkdir.mkdirsSync(dir) } items.forEach(item => { item = path.join(dir, item) remove.removeSync(item) }) } module.exports = { emptyDirSync, emptydirSync: emptyDirSync, emptyDir, emptydir: emptyDir } /***/ }), /***/ "./node_modules/fs-extra/lib/ensure/file.js": /*!**************************************************!*\ !*** ./node_modules/fs-extra/lib/ensure/file.js ***! \**************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const u = (__webpack_require__(/*! universalify */ "./node_modules/fs-extra/node_modules/universalify/index.js").fromCallback) const path = __webpack_require__(/*! path */ "path") const fs = __webpack_require__(/*! graceful-fs */ "./node_modules/graceful-fs/graceful-fs.js") const mkdir = __webpack_require__(/*! ../mkdirs */ "./node_modules/fs-extra/lib/mkdirs/index.js") function createFile (file, callback) { function makeFile () { fs.writeFile(file, '', err => { if (err) return callback(err) callback() }) } fs.stat(file, (err, stats) => { // eslint-disable-line handle-callback-err if (!err && stats.isFile()) return callback() const dir = path.dirname(file) fs.stat(dir, (err, stats) => { if (err) { // if the directory doesn't exist, make it if (err.code === 'ENOENT') { return mkdir.mkdirs(dir, err => { if (err) return callback(err) makeFile() }) } return callback(err) } if (stats.isDirectory()) makeFile() else { // parent is not a directory // This is just to cause an internal ENOTDIR error to be thrown fs.readdir(dir, err => { if (err) return callback(err) }) } }) }) } function createFileSync (file) { let stats try { stats = fs.statSync(file) } catch {} if (stats && stats.isFile()) return const dir = path.dirname(file) try { if (!fs.statSync(dir).isDirectory()) { // parent is not a directory // This is just to cause an internal ENOTDIR error to be thrown fs.readdirSync(dir) } } catch (err) { // If the stat call above failed because the directory doesn't exist, create it if (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir) else throw err } fs.writeFileSync(file, '') } module.exports = { createFile: u(createFile), createFileSync } /***/ }), /***/ "./node_modules/fs-extra/lib/ensure/index.js": /*!***************************************************!*\ !*** ./node_modules/fs-extra/lib/ensure/index.js ***! \***************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const { createFile, createFileSync } = __webpack_require__(/*! ./file */ "./node_modules/fs-extra/lib/ensure/file.js") const { createLink, createLinkSync } = __webpack_require__(/*! ./link */ "./node_modules/fs-extra/lib/ensure/link.js") const { createSymlink, createSymlinkSync } = __webpack_require__(/*! ./symlink */ "./node_modules/fs-extra/lib/ensure/symlink.js") module.exports = { // file createFile, createFileSync, ensureFile: createFile, ensureFileSync: createFileSync, // link createLink, createLinkSync, ensureLink: createLink, ensureLinkSync: createLinkSync, // symlink createSymlink, createSymlinkSync, ensureSymlink: createSymlink, ensureSymlinkSync: createSymlinkSync } /***/ }), /***/ "./node_modules/fs-extra/lib/ensure/link.js": /*!**************************************************!*\ !*** ./node_modules/fs-extra/lib/ensure/link.js ***! \**************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const u = (__webpack_require__(/*! universalify */ "./node_modules/fs-extra/node_modules/universalify/index.js").fromCallback) const path = __webpack_require__(/*! path */ "path") const fs = __webpack_require__(/*! graceful-fs */ "./node_modules/graceful-fs/graceful-fs.js") const mkdir = __webpack_require__(/*! ../mkdirs */ "./node_modules/fs-extra/lib/mkdirs/index.js") const pathExists = (__webpack_require__(/*! ../path-exists */ "./node_modules/fs-extra/lib/path-exists/index.js").pathExists) const { areIdentical } = __webpack_require__(/*! ../util/stat */ "./node_modules/fs-extra/lib/util/stat.js") function createLink (srcpath, dstpath, callback) { function makeLink (srcpath, dstpath) { fs.link(srcpath, dstpath, err => { if (err) return callback(err) callback(null) }) } fs.lstat(dstpath, (_, dstStat) => { fs.lstat(srcpath, (err, srcStat) => { if (err) { err.message = err.message.replace('lstat', 'ensureLink') return callback(err) } if (dstStat && areIdentical(srcStat, dstStat)) return callback(null) const dir = path.dirname(dstpath) pathExists(dir, (err, dirExists) => { if (err) return callback(err) if (dirExists) return makeLink(srcpath, dstpath) mkdir.mkdirs(dir, err => { if (err) return callback(err) makeLink(srcpath, dstpath) }) }) }) }) } function createLinkSync (srcpath, dstpath) { let dstStat try { dstStat = fs.lstatSync(dstpath) } catch {} try { const srcStat = fs.lstatSync(srcpath) if (dstStat && areIdentical(srcStat, dstStat)) return } catch (err) { err.message = err.message.replace('lstat', 'ensureLink') throw err } const dir = path.dirname(dstpath) const dirExists = fs.existsSync(dir) if (dirExists) return fs.linkSync(srcpath, dstpath) mkdir.mkdirsSync(dir) return fs.linkSync(srcpath, dstpath) } module.exports = { createLink: u(createLink), createLinkSync } /***/ }), /***/ "./node_modules/fs-extra/lib/ensure/symlink-paths.js": /*!***********************************************************!*\ !*** ./node_modules/fs-extra/lib/ensure/symlink-paths.js ***! \***********************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const path = __webpack_require__(/*! path */ "path") const fs = __webpack_require__(/*! graceful-fs */ "./node_modules/graceful-fs/graceful-fs.js") const pathExists = (__webpack_require__(/*! ../path-exists */ "./node_modules/fs-extra/lib/path-exists/index.js").pathExists) /** * Function that returns two types of paths, one relative to symlink, and one * relative to the current working directory. Checks if path is absolute or * relative. If the path is relative, this function checks if the path is * relative to symlink or relative to current working directory. This is an * initiative to find a smarter `srcpath` to supply when building symlinks. * This allows you to determine which path to use out of one of three possible * types of source paths. The first is an absolute path. This is detected by * `path.isAbsolute()`. When an absolute path is provided, it is checked to * see if it exists. If it does it's used, if not an error is returned * (callback)/ thrown (sync). The other two options for `srcpath` are a * relative url. By default Node's `fs.symlink` works by creating a symlink * using `dstpath` and expects the `srcpath` to be relative to the newly * created symlink. If you provide a `srcpath` that does not exist on the file * system it results in a broken symlink. To minimize this, the function * checks to see if the 'relative to symlink' source file exists, and if it * does it will use it. If it does not, it checks if there's a file that * exists that is relative to the current working directory, if does its used. * This preserves the expectations of the original fs.symlink spec and adds * the ability to pass in `relative to current working direcotry` paths. */ function symlinkPaths (srcpath, dstpath, callback) { if (path.isAbsolute(srcpath)) { return fs.lstat(srcpath, (err) => { if (err) { err.message = err.message.replace('lstat', 'ensureSymlink') return callback(err) } return callback(null, { toCwd: srcpath, toDst: srcpath }) }) } else { const dstdir = path.dirname(dstpath) const relativeToDst = path.join(dstdir, srcpath) return pathExists(relativeToDst, (err, exists) => { if (err) return callback(err) if (exists) { return callback(null, { toCwd: relativeToDst, toDst: srcpath }) } else { return fs.lstat(srcpath, (err) => { if (err) { err.message = err.message.replace('lstat', 'ensureSymlink') return callback(err) } return callback(null, { toCwd: srcpath, toDst: path.relative(dstdir, srcpath) }) }) } }) } } function symlinkPathsSync (srcpath, dstpath) { let exists if (path.isAbsolute(srcpath)) { exists = fs.existsSync(srcpath) if (!exists) throw new Error('absolute srcpath does not exist') return { toCwd: srcpath, toDst: srcpath } } else { const dstdir = path.dirname(dstpath) const relativeToDst = path.join(dstdir, srcpath) exists = fs.existsSync(relativeToDst) if (exists) { return { toCwd: relativeToDst, toDst: srcpath } } else { exists = fs.existsSync(srcpath) if (!exists) throw new Error('relative srcpath does not exist') return { toCwd: srcpath, toDst: path.relative(dstdir, srcpath) } } } } module.exports = { symlinkPaths, symlinkPathsSync } /***/ }), /***/ "./node_modules/fs-extra/lib/ensure/symlink-type.js": /*!**********************************************************!*\ !*** ./node_modules/fs-extra/lib/ensure/symlink-type.js ***! \**********************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const fs = __webpack_require__(/*! graceful-fs */ "./node_modules/graceful-fs/graceful-fs.js") function symlinkType (srcpath, type, callback) { callback = (typeof type === 'function') ? type : callback type = (typeof type === 'function') ? false : type if (type) return callback(null, type) fs.lstat(srcpath, (err, stats) => { if (err) return callback(null, 'file') type = (stats && stats.isDirectory()) ? 'dir' : 'file' callback(null, type) }) } function symlinkTypeSync (srcpath, type) { let stats if (type) return type try { stats = fs.lstatSync(srcpath) } catch { return 'file' } return (stats && stats.isDirectory()) ? 'dir' : 'file' } module.exports = { symlinkType, symlinkTypeSync } /***/ }), /***/ "./node_modules/fs-extra/lib/ensure/symlink.js": /*!*****************************************************!*\ !*** ./node_modules/fs-extra/lib/ensure/symlink.js ***! \*****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const u = (__webpack_require__(/*! universalify */ "./node_modules/fs-extra/node_modules/universalify/index.js").fromCallback) const path = __webpack_require__(/*! path */ "path") const fs = __webpack_require__(/*! ../fs */ "./node_modules/fs-extra/lib/fs/index.js") const _mkdirs = __webpack_require__(/*! ../mkdirs */ "./node_modules/fs-extra/lib/mkdirs/index.js") const mkdirs = _mkdirs.mkdirs const mkdirsSync = _mkdirs.mkdirsSync const _symlinkPaths = __webpack_require__(/*! ./symlink-paths */ "./node_modules/fs-extra/lib/ensure/symlink-paths.js") const symlinkPaths = _symlinkPaths.symlinkPaths const symlinkPathsSync = _symlinkPaths.symlinkPathsSync const _symlinkType = __webpack_require__(/*! ./symlink-type */ "./node_modules/fs-extra/lib/ensure/symlink-type.js") const symlinkType = _symlinkType.symlinkType const symlinkTypeSync = _symlinkType.symlinkTypeSync const pathExists = (__webpack_require__(/*! ../path-exists */ "./node_modules/fs-extra/lib/path-exists/index.js").pathExists) const { areIdentical } = __webpack_require__(/*! ../util/stat */ "./node_modules/fs-extra/lib/util/stat.js") function createSymlink (srcpath, dstpath, type, callback) { callback = (typeof type === 'function') ? type : callback type = (typeof type === 'function') ? false : type fs.lstat(dstpath, (err, stats) => { if (!err && stats.isSymbolicLink()) { Promise.all([ fs.stat(srcpath), fs.stat(dstpath) ]).then(([srcStat, dstStat]) => { if (areIdentical(srcStat, dstStat)) return callback(null) _createSymlink(srcpath, dstpath, type, callback) }) } else _createSymlink(srcpath, dstpath, type, callback) }) } function _createSymlink (srcpath, dstpath, type, callback) { symlinkPaths(srcpath, dstpath, (err, relative) => { if (err) return callback(err) srcpath = relative.toDst symlinkType(relative.toCwd, type, (err, type) => { if (err) return callback(err) const dir = path.dirname(dstpath) pathExists(dir, (err, dirExists) => { if (err) return callback(err) if (dirExists) return fs.symlink(srcpath, dstpath, type, callback) mkdirs(dir, err => { if (err) return callback(err) fs.symlink(srcpath, dstpath, type, callback) }) }) }) }) } function createSymlinkSync (srcpath, dstpath, type) { let stats try { stats = fs.lstatSync(dstpath) } catch {} if (stats && stats.isSymbolicLink()) { const srcStat = fs.statSync(srcpath) const dstStat = fs.statSync(dstpath) if (areIdentical(srcStat, dstStat)) return } const relative = symlinkPathsSync(srcpath, dstpath) srcpath = relative.toDst type = symlinkTypeSync(relative.toCwd, type) const dir = path.dirname(dstpath) const exists = fs.existsSync(dir) if (exists) return fs.symlinkSync(srcpath, dstpath, type) mkdirsSync(dir) return fs.symlinkSync(srcpath, dstpath, type) } module.exports = { createSymlink: u(createSymlink), createSymlinkSync } /***/ }), /***/ "./node_modules/fs-extra/lib/fs/index.js": /*!***********************************************!*\ !*** ./node_modules/fs-extra/lib/fs/index.js ***! \***********************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // This is adapted from https://github.com/normalize/mz // Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors const u = (__webpack_require__(/*! universalify */ "./node_modules/fs-extra/node_modules/universalify/index.js").fromCallback) const fs = __webpack_require__(/*! graceful-fs */ "./node_modules/graceful-fs/graceful-fs.js") const api = [ 'access', 'appendFile', 'chmod', 'chown', 'close', 'copyFile', 'fchmod', 'fchown', 'fdatasync', 'fstat', 'fsync', 'ftruncate', 'futimes', 'lchmod', 'lchown', 'link', 'lstat', 'mkdir', 'mkdtemp', 'open', 'opendir', 'readdir', 'readFile', 'readlink', 'realpath', 'rename', 'rm', 'rmdir', 'stat', 'symlink', 'truncate', 'unlink', 'utimes', 'writeFile' ].filter(key => { // Some commands are not available on some systems. Ex: // fs.opendir was added in Node.js v12.12.0 // fs.rm was added in Node.js v14.14.0 // fs.lchown is not available on at least some Linux return typeof fs[key] === 'function' }) // Export cloned fs: Object.assign(exports, fs) // Universalify async methods: api.forEach(method => { exports[method] = u(fs[method]) }) exports.realpath.native = u(fs.realpath.native) // We differ from mz/fs in that we still ship the old, broken, fs.exists() // since we are a drop-in replacement for the native module exports.exists = function (filename, callback) { if (typeof callback === 'function') { return fs.exists(filename, callback) } return new Promise(resolve => { return fs.exists(filename, resolve) }) } // fs.read(), fs.write(), & fs.writev() need special treatment due to multiple callback args exports.read = function (fd, buffer, offset, length, position, callback) { if (typeof callback === 'function') { return fs.read(fd, buffer, offset, length, position, callback) } return new Promise((resolve, reject) => { fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => { if (err) return reject(err) resolve({ bytesRead, buffer }) }) }) } // Function signature can be // fs.write(fd, buffer[, offset[, length[, position]]], callback) // OR // fs.write(fd, string[, position[, encoding]], callback) // We need to handle both cases, so we use ...args exports.write = function (fd, buffer, ...args) { if (typeof args[args.length - 1] === 'function') { return fs.write(fd, buffer, ...args) } return new Promise((resolve, reject) => { fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => { if (err) return reject(err) resolve({ bytesWritten, buffer }) }) }) } // fs.writev only available in Node v12.9.0+ if (typeof fs.writev === 'function') { // Function signature is // s.writev(fd, buffers[, position], callback) // We need to handle the optional arg, so we use ...args exports.writev = function (fd, buffers, ...args) { if (typeof args[args.length - 1] === 'function') { return fs.writev(fd, buffers, ...args) } return new Promise((resolve, reject) => { fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => { if (err) return reject(err) resolve({ bytesWritten, buffers }) }) }) } } /***/ }), /***/ "./node_modules/fs-extra/lib/index.js": /*!********************************************!*\ !*** ./node_modules/fs-extra/lib/index.js ***! \********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = { // Export promiseified graceful-fs: ...__webpack_require__(/*! ./fs */ "./node_modules/fs-extra/lib/fs/index.js"), // Export extra methods: ...__webpack_require__(/*! ./copy */ "./node_modules/fs-extra/lib/copy/index.js"), ...__webpack_require__(/*! ./empty */ "./node_modules/fs-extra/lib/empty/index.js"), ...__webpack_require__(/*! ./ensure */ "./node_modules/fs-extra/lib/ensure/index.js"), ...__webpack_require__(/*! ./json */ "./node_modules/fs-extra/lib/json/index.js"), ...__webpack_require__(/*! ./mkdirs */ "./node_modules/fs-extra/lib/mkdirs/index.js"), ...__webpack_require__(/*! ./move */ "./node_modules/fs-extra/lib/move/index.js"), ...__webpack_require__(/*! ./output-file */ "./node_modules/fs-extra/lib/output-file/index.js"), ...__webpack_require__(/*! ./path-exists */ "./node_modules/fs-extra/lib/path-exists/index.js"), ...__webpack_require__(/*! ./remove */ "./node_modules/fs-extra/lib/remove/index.js") } /***/ }), /***/ "./node_modules/fs-extra/lib/json/index.js": /*!*************************************************!*\ !*** ./node_modules/fs-extra/lib/json/index.js ***! \*************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const u = (__webpack_require__(/*! universalify */ "./node_modules/fs-extra/node_modules/universalify/index.js").fromPromise) const jsonFile = __webpack_require__(/*! ./jsonfile */ "./node_modules/fs-extra/lib/json/jsonfile.js") jsonFile.outputJson = u(__webpack_require__(/*! ./output-json */ "./node_modules/fs-extra/lib/json/output-json.js")) jsonFile.outputJsonSync = __webpack_require__(/*! ./output-json-sync */ "./node_modules/fs-extra/lib/json/output-json-sync.js") // aliases jsonFile.outputJSON = jsonFile.outputJson jsonFile.outputJSONSync = jsonFile.outputJsonSync jsonFile.writeJSON = jsonFile.writeJson jsonFile.writeJSONSync = jsonFile.writeJsonSync jsonFile.readJSON = jsonFile.readJson jsonFile.readJSONSync = jsonFile.readJsonSync module.exports = jsonFile /***/ }), /***/ "./node_modules/fs-extra/lib/json/jsonfile.js": /*!****************************************************!*\ !*** ./node_modules/fs-extra/lib/json/jsonfile.js ***! \****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const jsonFile = __webpack_require__(/*! jsonfile */ "./node_modules/fs-extra/node_modules/jsonfile/index.js") module.exports = { // jsonfile exports readJson: jsonFile.readFile, readJsonSync: jsonFile.readFileSync, writeJson: jsonFile.writeFile, writeJsonSync: jsonFile.writeFileSync } /***/ }), /***/ "./node_modules/fs-extra/lib/json/output-json-sync.js": /*!************************************************************!*\ !*** ./node_modules/fs-extra/lib/json/output-json-sync.js ***! \************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const { stringify } = __webpack_require__(/*! jsonfile/utils */ "./node_modules/fs-extra/node_modules/jsonfile/utils.js") const { outputFileSync } = __webpack_require__(/*! ../output-file */ "./node_modules/fs-extra/lib/output-file/index.js") function outputJsonSync (file, data, options) { const str = stringify(data, options) outputFileSync(file, str, options) } module.exports = outputJsonSync /***/ }), /***/ "./node_modules/fs-extra/lib/json/output-json.js": /*!*******************************************************!*\ !*** ./node_modules/fs-extra/lib/json/output-json.js ***! \*******************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const { stringify } = __webpack_require__(/*! jsonfile/utils */ "./node_modules/fs-extra/node_modules/jsonfile/utils.js") const { outputFile } = __webpack_require__(/*! ../output-file */ "./node_modules/fs-extra/lib/output-file/index.js") async function outputJson (file, data, options = {}) { const str = stringify(data, options) await outputFile(file, str, options) } module.exports = outputJson /***/ }), /***/ "./node_modules/fs-extra/lib/mkdirs/index.js": /*!***************************************************!*\ !*** ./node_modules/fs-extra/lib/mkdirs/index.js ***! \***************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const u = (__webpack_require__(/*! universalify */ "./node_modules/fs-extra/node_modules/universalify/index.js").fromPromise) const { makeDir: _makeDir, makeDirSync } = __webpack_require__(/*! ./make-dir */ "./node_modules/fs-extra/lib/mkdirs/make-dir.js") const makeDir = u(_makeDir) module.exports = { mkdirs: makeDir, mkdirsSync: makeDirSync, // alias mkdirp: makeDir, mkdirpSync: makeDirSync, ensureDir: makeDir, ensureDirSync: makeDirSync } /***/ }), /***/ "./node_modules/fs-extra/lib/mkdirs/make-dir.js": /*!******************************************************!*\ !*** ./node_modules/fs-extra/lib/mkdirs/make-dir.js ***! \******************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const fs = __webpack_require__(/*! ../fs */ "./node_modules/fs-extra/lib/fs/index.js") const { checkPath } = __webpack_require__(/*! ./utils */ "./node_modules/fs-extra/lib/mkdirs/utils.js") const getMode = options => { const defaults = { mode: 0o777 } if (typeof options === 'number') return options return ({ ...defaults, ...options }).mode } module.exports.makeDir = async (dir, options) => { checkPath(dir) return fs.mkdir(dir, { mode: getMode(options), recursive: true }) } module.exports.makeDirSync = (dir, options) => { checkPath(dir) return fs.mkdirSync(dir, { mode: getMode(options), recursive: true }) } /***/ }), /***/ "./node_modules/fs-extra/lib/mkdirs/utils.js": /*!***************************************************!*\ !*** ./node_modules/fs-extra/lib/mkdirs/utils.js ***! \***************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Adapted from https://github.com/sindresorhus/make-dir // Copyright (c) Sindre Sorhus (sindresorhus.com) // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. const path = __webpack_require__(/*! path */ "path") // https://github.com/nodejs/node/issues/8987 // https://github.com/libuv/libuv/pull/1088 module.exports.checkPath = function checkPath (pth) { if (process.platform === 'win32') { const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, '')) if (pathHasInvalidWinCharacters) { const error = new Error(`Path contains invalid characters: ${pth}`) error.code = 'EINVAL' throw error } } } /***/ }), /***/ "./node_modules/fs-extra/lib/move/index.js": /*!*************************************************!*\ !*** ./node_modules/fs-extra/lib/move/index.js ***! \*************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const u = (__webpack_require__(/*! universalify */ "./node_modules/fs-extra/node_modules/universalify/index.js").fromCallback) module.exports = { move: u(__webpack_require__(/*! ./move */ "./node_modules/fs-extra/lib/move/move.js")), moveSync: __webpack_require__(/*! ./move-sync */ "./node_modules/fs-extra/lib/move/move-sync.js") } /***/ }), /***/ "./node_modules/fs-extra/lib/move/move-sync.js": /*!*****************************************************!*\ !*** ./node_modules/fs-extra/lib/move/move-sync.js ***! \*****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const fs = __webpack_require__(/*! graceful-fs */ "./node_modules/graceful-fs/graceful-fs.js") const path = __webpack_require__(/*! path */ "path") const copySync = (__webpack_require__(/*! ../copy */ "./node_modules/fs-extra/lib/copy/index.js").copySync) const removeSync = (__webpack_require__(/*! ../remove */ "./node_modules/fs-extra/lib/remove/index.js").removeSync) const mkdirpSync = (__webpack_require__(/*! ../mkdirs */ "./node_modules/fs-extra/lib/mkdirs/index.js").mkdirpSync) const stat = __webpack_require__(/*! ../util/stat */ "./node_modules/fs-extra/lib/util/stat.js") function moveSync (src, dest, opts) { opts = opts || {} const overwrite = opts.overwrite || opts.clobber || false const { srcStat, isChangingCase = false } = stat.checkPathsSync(src, dest, 'move', opts) stat.checkParentPathsSync(src, srcStat, dest, 'move') if (!isParentRoot(dest)) mkdirpSync(path.dirname(dest)) return doRename(src, dest, overwrite, isChangingCase) } function isParentRoot (dest) { const parent = path.dirname(dest) const parsedPath = path.parse(parent) return parsedPath.root === parent } function doRename (src, dest, overwrite, isChangingCase) { if (isChangingCase) return rename(src, dest, overwrite) if (overwrite) { removeSync(dest) return rename(src, dest, overwrite) } if (fs.existsSync(dest)) throw new Error('dest already exists.') return rename(src, dest, overwrite) } function rename (src, dest, overwrite) { try { fs.renameSync(src, dest) } catch (err) { if (err.code !== 'EXDEV') throw err return moveAcrossDevice(src, dest, overwrite) } } function moveAcrossDevice (src, dest, overwrite) { const opts = { overwrite, errorOnExist: true } copySync(src, dest, opts) return removeSync(src) } module.exports = moveSync /***/ }), /***/ "./node_modules/fs-extra/lib/move/move.js": /*!************************************************!*\ !*** ./node_modules/fs-extra/lib/move/move.js ***! \************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const fs = __webpack_require__(/*! graceful-fs */ "./node_modules/graceful-fs/graceful-fs.js") const path = __webpack_require__(/*! path */ "path") const copy = (__webpack_require__(/*! ../copy */ "./node_modules/fs-extra/lib/copy/index.js").copy) const remove = (__webpack_require__(/*! ../remove */ "./node_modules/fs-extra/lib/remove/index.js").remove) const mkdirp = (__webpack_require__(/*! ../mkdirs */ "./node_modules/fs-extra/lib/mkdirs/index.js").mkdirp) const pathExists = (__webpack_require__(/*! ../path-exists */ "./node_modules/fs-extra/lib/path-exists/index.js").pathExists) const stat = __webpack_require__(/*! ../util/stat */ "./node_modules/fs-extra/lib/util/stat.js") function move (src, dest, opts, cb) { if (typeof opts === 'function') { cb = opts opts = {} } const overwrite = opts.overwrite || opts.clobber || false stat.checkPaths(src, dest, 'move', opts, (err, stats) => { if (err) return cb(err) const { srcStat, isChangingCase = false } = stats stat.checkParentPaths(src, srcStat, dest, 'move', err => { if (err) return cb(err) if (isParentRoot(dest)) return doRename(src, dest, overwrite, isChangingCase, cb) mkdirp(path.dirname(dest), err => { if (err) return cb(err) return doRename(src, dest, overwrite, isChangingCase, cb) }) }) }) } function isParentRoot (dest) { const parent = path.dirname(dest) const parsedPath = path.parse(parent) return parsedPath.root === parent } function doRename (src, dest, overwrite, isChangingCase, cb) { if (isChangingCase) return rename(src, dest, overwrite, cb) if (overwrite) { return remove(dest, err => { if (err) return cb(err) return rename(src, dest, overwrite, cb) }) } pathExists(dest, (err, destExists) => { if (err) return cb(err) if (destExists) return cb(new Error('dest already exists.')) return rename(src, dest, overwrite, cb) }) } function rename (src, dest, overwrite, cb) { fs.rename(src, dest, err => { if (!err) return cb() if (err.code !== 'EXDEV') return cb(err) return moveAcrossDevice(src, dest, overwrite, cb) }) } function moveAcrossDevice (src, dest, overwrite, cb) { const opts = { overwrite, errorOnExist: true } copy(src, dest, opts, err => { if (err) return cb(err) return remove(src, cb) }) } module.exports = move /***/ }), /***/ "./node_modules/fs-extra/lib/output-file/index.js": /*!********************************************************!*\ !*** ./node_modules/fs-extra/lib/output-file/index.js ***! \********************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const u = (__webpack_require__(/*! universalify */ "./node_modules/fs-extra/node_modules/universalify/index.js").fromCallback) const fs = __webpack_require__(/*! graceful-fs */ "./node_modules/graceful-fs/graceful-fs.js") const path = __webpack_require__(/*! path */ "path") const mkdir = __webpack_require__(/*! ../mkdirs */ "./node_modules/fs-extra/lib/mkdirs/index.js") const pathExists = (__webpack_require__(/*! ../path-exists */ "./node_modules/fs-extra/lib/path-exists/index.js").pathExists) function outputFile (file, data, encoding, callback) { if (typeof encoding === 'function') { callback = encoding encoding = 'utf8' } const dir = path.dirname(file) pathExists(dir, (err, itDoes) => { if (err) return callback(err) if (itDoes) return fs.writeFile(file, data, encoding, callback) mkdir.mkdirs(dir, err => { if (err) return callback(err) fs.writeFile(file, data, encoding, callback) }) }) } function outputFileSync (file, ...args) { const dir = path.dirname(file) if (fs.existsSync(dir)) { return fs.writeFileSync(file, ...args) } mkdir.mkdirsSync(dir) fs.writeFileSync(file, ...args) } module.exports = { outputFile: u(outputFile), outputFileSync } /***/ }), /***/ "./node_modules/fs-extra/lib/path-exists/index.js": /*!********************************************************!*\ !*** ./node_modules/fs-extra/lib/path-exists/index.js ***! \********************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const u = (__webpack_require__(/*! universalify */ "./node_modules/fs-extra/node_modules/universalify/index.js").fromPromise) const fs = __webpack_require__(/*! ../fs */ "./node_modules/fs-extra/lib/fs/index.js") function pathExists (path) { return fs.access(path).then(() => true).catch(() => false) } module.exports = { pathExists: u(pathExists), pathExistsSync: fs.existsSync } /***/ }), /***/ "./node_modules/fs-extra/lib/remove/index.js": /*!***************************************************!*\ !*** ./node_modules/fs-extra/lib/remove/index.js ***! \***************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const fs = __webpack_require__(/*! graceful-fs */ "./node_modules/graceful-fs/graceful-fs.js") const u = (__webpack_require__(/*! universalify */ "./node_modules/fs-extra/node_modules/universalify/index.js").fromCallback) const rimraf = __webpack_require__(/*! ./rimraf */ "./node_modules/fs-extra/lib/remove/rimraf.js") function remove (path, callback) { // Node 14.14.0+ if (fs.rm) return fs.rm(path, { recursive: true, force: true }, callback) rimraf(path, callback) } function removeSync (path) { // Node 14.14.0+ if (fs.rmSync) return fs.rmSync(path, { recursive: true, force: true }) rimraf.sync(path) } module.exports = { remove: u(remove), removeSync } /***/ }), /***/ "./node_modules/fs-extra/lib/remove/rimraf.js": /*!****************************************************!*\ !*** ./node_modules/fs-extra/lib/remove/rimraf.js ***! \****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const fs = __webpack_require__(/*! graceful-fs */ "./node_modules/graceful-fs/graceful-fs.js") const path = __webpack_require__(/*! path */ "path") const assert = __webpack_require__(/*! assert */ "assert") const isWindows = (process.platform === 'win32') function defaults (options) { const methods = [ 'unlink', 'chmod', 'stat', 'lstat', 'rmdir', 'readdir' ] methods.forEach(m => { options[m] = options[m] || fs[m] m = m + 'Sync' options[m] = options[m] || fs[m] }) options.maxBusyTries = options.maxBusyTries || 3 } function rimraf (p, options, cb) { let busyTries = 0 if (typeof options === 'function') { cb = options options = {} } assert(p, 'rimraf: missing path') assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') assert.strictEqual(typeof cb, 'function', 'rimraf: callback function required') assert(options, 'rimraf: invalid options argument provided') assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') defaults(options) rimraf_(p, options, function CB (er) { if (er) { if ((er.code === 'EBUSY' || er.code === 'ENOTEMPTY' || er.code === 'EPERM') && busyTries < options.maxBusyTries) { busyTries++ const time = busyTries * 100 // try again, with the same exact callback as this one. return setTimeout(() => rimraf_(p, options, CB), time) } // already gone if (er.code === 'ENOENT') er = null } cb(er) }) } // Two possible strategies. // 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR // 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR // // Both result in an extra syscall when you guess wrong. However, there // are likely far more normal files in the world than directories. This // is based on the assumption that a the average number of files per // directory is >= 1. // // If anyone ever complains about this, then I guess the strategy could // be made configurable somehow. But until then, YAGNI. function rimraf_ (p, options, cb) { assert(p) assert(options) assert(typeof cb === 'function') // sunos lets the root user unlink directories, which is... weird. // so we have to lstat here and make sure it's not a dir. options.lstat(p, (er, st) => { if (er && er.code === 'ENOENT') { return cb(null) } // Windows can EPERM on stat. Life is suffering. if (er && er.code === 'EPERM' && isWindows) { return fixWinEPERM(p, options, er, cb) } if (st && st.isDirectory()) { return rmdir(p, options, er, cb) } options.unlink(p, er => { if (er) { if (er.code === 'ENOENT') { return cb(null) } if (er.code === 'EPERM') { return (isWindows) ? fixWinEPERM(p, options, er, cb) : rmdir(p, options, er, cb) } if (er.code === 'EISDIR') { return rmdir(p, options, er, cb) } } return cb(er) }) }) } function fixWinEPERM (p, options, er, cb) { assert(p) assert(options) assert(typeof cb === 'function') options.chmod(p, 0o666, er2 => { if (er2) { cb(er2.code === 'ENOENT' ? null : er) } else { options.stat(p, (er3, stats) => { if (er3) { cb(er3.code === 'ENOENT' ? null : er) } else if (stats.isDirectory()) { rmdir(p, options, er, cb) } else { options.unlink(p, cb) } }) } }) } function fixWinEPERMSync (p, options, er) { let stats assert(p) assert(options) try { options.chmodSync(p, 0o666) } catch (er2) { if (er2.code === 'ENOENT') { return } else { throw er } } try { stats = options.statSync(p) } catch (er3) { if (er3.code === 'ENOENT') { return } else { throw er } } if (stats.isDirectory()) { rmdirSync(p, options, er) } else { options.unlinkSync(p) } } function rmdir (p, options, originalEr, cb) { assert(p) assert(options) assert(typeof cb === 'function') // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) // if we guessed wrong, and it's not a directory, then // raise the original error. options.rmdir(p, er => { if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) { rmkids(p, options, cb) } else if (er && er.code === 'ENOTDIR') { cb(originalEr) } else { cb(er) } }) } function rmkids (p, options, cb) { assert(p) assert(options) assert(typeof cb === 'function') options.readdir(p, (er, files) => { if (er) return cb(er) let n = files.length let errState if (n === 0) return options.rmdir(p, cb) files.forEach(f => { rimraf(path.join(p, f), options, er => { if (errState) { return } if (er) return cb(errState = er) if (--n === 0) { options.rmdir(p, cb) } }) }) }) } // this looks simpler, and is strictly *faster*, but will // tie up the JavaScript thread and fail on excessively // deep directory trees. function rimrafSync (p, options) { let st options = options || {} defaults(options) assert(p, 'rimraf: missing path') assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') assert(options, 'rimraf: missing options') assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') try { st = options.lstatSync(p) } catch (er) { if (er.code === 'ENOENT') { return } // Windows can EPERM on stat. Life is suffering. if (er.code === 'EPERM' && isWindows) { fixWinEPERMSync(p, options, er) } } try { // sunos lets the root user unlink directories, which is... weird. if (st && st.isDirectory()) { rmdirSync(p, options, null) } else { options.unlinkSync(p) } } catch (er) { if (er.code === 'ENOENT') { return } else if (er.code === 'EPERM') { return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) } else if (er.code !== 'EISDIR') { throw er } rmdirSync(p, options, er) } } function rmdirSync (p, options, originalEr) { assert(p) assert(options) try { options.rmdirSync(p) } catch (er) { if (er.code === 'ENOTDIR') { throw originalEr } else if (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM') { rmkidsSync(p, options) } else if (er.code !== 'ENOENT') { throw er } } } function rmkidsSync (p, options) { assert(p) assert(options) options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) if (isWindows) { // We only end up here once we got ENOTEMPTY at least once, and // at this point, we are guaranteed to have removed all the kids. // So, we know that it won't be ENOENT or ENOTDIR or anything else. // try really hard to delete stuff on windows, because it has a // PROFOUNDLY annoying habit of not closing handles promptly when // files are deleted, resulting in spurious ENOTEMPTY errors. const startTime = Date.now() do { try { const ret = options.rmdirSync(p, options) return ret } catch {} } while (Date.now() - startTime < 500) // give up after 500ms } else { const ret = options.rmdirSync(p, options) return ret } } module.exports = rimraf rimraf.sync = rimrafSync /***/ }), /***/ "./node_modules/fs-extra/lib/util/stat.js": /*!************************************************!*\ !*** ./node_modules/fs-extra/lib/util/stat.js ***! \************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const fs = __webpack_require__(/*! ../fs */ "./node_modules/fs-extra/lib/fs/index.js") const path = __webpack_require__(/*! path */ "path") const util = __webpack_require__(/*! util */ "util") function getStats (src, dest, opts) { const statFunc = opts.dereference ? (file) => fs.stat(file, { bigint: true }) : (file) => fs.lstat(file, { bigint: true }) return Promise.all([ statFunc(src), statFunc(dest).catch(err => { if (err.code === 'ENOENT') return null throw err }) ]).then(([srcStat, destStat]) => ({ srcStat, destStat })) } function getStatsSync (src, dest, opts) { let destStat const statFunc = opts.dereference ? (file) => fs.statSync(file, { bigint: true }) : (file) => fs.lstatSync(file, { bigint: true }) const srcStat = statFunc(src) try { destStat = statFunc(dest) } catch (err) { if (err.code === 'ENOENT') return { srcStat, destStat: null } throw err } return { srcStat, destStat } } function checkPaths (src, dest, funcName, opts, cb) { util.callbackify(getStats)(src, dest, opts, (err, stats) => { if (err) return cb(err) const { srcStat, destStat } = stats if (destStat) { if (areIdentical(srcStat, destStat)) { const srcBaseName = path.basename(src) const destBaseName = path.basename(dest) if (funcName === 'move' && srcBaseName !== destBaseName && srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { return cb(null, { srcStat, destStat, isChangingCase: true }) } return cb(new Error('Source and destination must not be the same.')) } if (srcStat.isDirectory() && !destStat.isDirectory()) { return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)) } if (!srcStat.isDirectory() && destStat.isDirectory()) { return cb(new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)) } } if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { return cb(new Error(errMsg(src, dest, funcName))) } return cb(null, { srcStat, destStat }) }) } function checkPathsSync (src, dest, funcName, opts) { const { srcStat, destStat } = getStatsSync(src, dest, opts) if (destStat) { if (areIdentical(srcStat, destStat)) { const srcBaseName = path.basename(src) const destBaseName = path.basename(dest) if (funcName === 'move' && srcBaseName !== destBaseName && srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { return { srcStat, destStat, isChangingCase: true } } throw new Error('Source and destination must not be the same.') } if (srcStat.isDirectory() && !destStat.isDirectory()) { throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) } if (!srcStat.isDirectory() && destStat.isDirectory()) { throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`) } } if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { throw new Error(errMsg(src, dest, funcName)) } return { srcStat, destStat } } // recursively check if dest parent is a subdirectory of src. // It works for all file types including symlinks since it // checks the src and dest inodes. It starts from the deepest // parent and stops once it reaches the src parent or the root path. function checkParentPaths (src, srcStat, dest, funcName, cb) { const srcParent = path.resolve(path.dirname(src)) const destParent = path.resolve(path.dirname(dest)) if (destParent === srcParent || destParent === path.parse(destParent).root) return cb() fs.stat(destParent, { bigint: true }, (err, destStat) => { if (err) { if (err.code === 'ENOENT') return cb() return cb(err) } if (areIdentical(srcStat, destStat)) { return cb(new Error(errMsg(src, dest, funcName))) } return checkParentPaths(src, srcStat, destParent, funcName, cb) }) } function checkParentPathsSync (src, srcStat, dest, funcName) { const srcParent = path.resolve(path.dirname(src)) const destParent = path.resolve(path.dirname(dest)) if (destParent === srcParent || destParent === path.parse(destParent).root) return let destStat try { destStat = fs.statSync(destParent, { bigint: true }) } catch (err) { if (err.code === 'ENOENT') return throw err } if (areIdentical(srcStat, destStat)) { throw new Error(errMsg(src, dest, funcName)) } return checkParentPathsSync(src, srcStat, destParent, funcName) } function areIdentical (srcStat, destStat) { return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev } // return true if dest is a subdir of src, otherwise false. // It only checks the path strings. function isSrcSubdir (src, dest) { const srcArr = path.resolve(src).split(path.sep).filter(i => i) const destArr = path.resolve(dest).split(path.sep).filter(i => i) return srcArr.reduce((acc, cur, i) => acc && destArr[i] === cur, true) } function errMsg (src, dest, funcName) { return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.` } module.exports = { checkPaths, checkPathsSync, checkParentPaths, checkParentPathsSync, isSrcSubdir, areIdentical } /***/ }), /***/ "./node_modules/fs-extra/lib/util/utimes.js": /*!**************************************************!*\ !*** ./node_modules/fs-extra/lib/util/utimes.js ***! \**************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const fs = __webpack_require__(/*! graceful-fs */ "./node_modules/graceful-fs/graceful-fs.js") function utimesMillis (path, atime, mtime, callback) { // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback) fs.open(path, 'r+', (err, fd) => { if (err) return callback(err) fs.futimes(fd, atime, mtime, futimesErr => { fs.close(fd, closeErr => { if (callback) callback(futimesErr || closeErr) }) }) }) } function utimesMillisSync (path, atime, mtime) { const fd = fs.openSync(path, 'r+') fs.futimesSync(fd, atime, mtime) return fs.closeSync(fd) } module.exports = { utimesMillis, utimesMillisSync } /***/ }), /***/ "./node_modules/fs-extra/node_modules/jsonfile/index.js": /*!**************************************************************!*\ !*** ./node_modules/fs-extra/node_modules/jsonfile/index.js ***! \**************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { let _fs try { _fs = __webpack_require__(/*! graceful-fs */ "./node_modules/graceful-fs/graceful-fs.js") } catch (_) { _fs = __webpack_require__(/*! fs */ "fs") } const universalify = __webpack_require__(/*! universalify */ "./node_modules/fs-extra/node_modules/universalify/index.js") const { stringify, stripBom } = __webpack_require__(/*! ./utils */ "./node_modules/fs-extra/node_modules/jsonfile/utils.js") async function _readFile (file, options = {}) { if (typeof options === 'string') { options = { encoding: options } } const fs = options.fs || _fs const shouldThrow = 'throws' in options ? options.throws : true let data = await universalify.fromCallback(fs.readFile)(file, options) data = stripBom(data) let obj try { obj = JSON.parse(data, options ? options.reviver : null) } catch (err) { if (shouldThrow) { err.message = `${file}: ${err.message}` throw err } else { return null } } return obj } const readFile = universalify.fromPromise(_readFile) function readFileSync (file, options = {}) { if (typeof options === 'string') { options = { encoding: options } } const fs = options.fs || _fs const shouldThrow = 'throws' in options ? options.throws : true try { let content = fs.readFileSync(file, options) content = stripBom(content) return JSON.parse(content, options.reviver) } catch (err) { if (shouldThrow) { err.message = `${file}: ${err.message}` throw err } else { return null } } } async function _writeFile (file, obj, options = {}) { const fs = options.fs || _fs const str = stringify(obj, options) await universalify.fromCallback(fs.writeFile)(file, str, options) } const writeFile = universalify.fromPromise(_writeFile) function writeFileSync (file, obj, options = {}) { const fs = options.fs || _fs const str = stringify(obj, options) // not sure if fs.writeFileSync returns anything, but just in case return fs.writeFileSync(file, str, options) } const jsonfile = { readFile, readFileSync, writeFile, writeFileSync } module.exports = jsonfile /***/ }), /***/ "./node_modules/fs-extra/node_modules/jsonfile/utils.js": /*!**************************************************************!*\ !*** ./node_modules/fs-extra/node_modules/jsonfile/utils.js ***! \**************************************************************/ /***/ ((module) => { function stringify (obj, { EOL = '\n', finalEOL = true, replacer = null, spaces } = {}) { const EOF = finalEOL ? EOL : '' const str = JSON.stringify(obj, replacer, spaces) return str.replace(/\n/g, EOL) + EOF } function stripBom (content) { // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified if (Buffer.isBuffer(content)) content = content.toString('utf8') return content.replace(/^\uFEFF/, '') } module.exports = { stringify, stripBom } /***/ }), /***/ "./node_modules/fs-extra/node_modules/universalify/index.js": /*!******************************************************************!*\ !*** ./node_modules/fs-extra/node_modules/universalify/index.js ***! \******************************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; exports.fromCallback = function (fn) { return Object.defineProperty(function (...args) { if (typeof args[args.length - 1] === 'function') fn.apply(this, args) else { return new Promise((resolve, reject) => { fn.call( this, ...args, (err, res) => (err != null) ? reject(err) : resolve(res) ) }) } }, 'name', { value: fn.name }) } exports.fromPromise = function (fn) { return Object.defineProperty(function (...args) { const cb = args[args.length - 1] if (typeof cb !== 'function') return fn.apply(this, args) else fn.apply(this, args.slice(0, -1)).then(r => cb(null, r), cb) }, 'name', { value: fn.name }) } /***/ }), /***/ "./node_modules/fs-minipass/index.js": /*!*******************************************!*\ !*** ./node_modules/fs-minipass/index.js ***! \*******************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const MiniPass = __webpack_require__(/*! minipass */ "./node_modules/minipass/index.js") const EE = (__webpack_require__(/*! events */ "events").EventEmitter) const fs = __webpack_require__(/*! fs */ "fs") let writev = fs.writev /* istanbul ignore next */ if (!writev) { // This entire block can be removed if support for earlier than Node.js // 12.9.0 is not needed. const binding = process.binding('fs') const FSReqWrap = binding.FSReqWrap || binding.FSReqCallback writev = (fd, iovec, pos, cb) => { const done = (er, bw) => cb(er, bw, iovec) const req = new FSReqWrap() req.oncomplete = done binding.writeBuffers(fd, iovec, pos, req) } } const _autoClose = Symbol('_autoClose') const _close = Symbol('_close') const _ended = Symbol('_ended') const _fd = Symbol('_fd') const _finished = Symbol('_finished') const _flags = Symbol('_flags') const _flush = Symbol('_flush') const _handleChunk = Symbol('_handleChunk') const _makeBuf = Symbol('_makeBuf') const _mode = Symbol('_mode') const _needDrain = Symbol('_needDrain') const _onerror = Symbol('_onerror') const _onopen = Symbol('_onopen') const _onread = Symbol('_onread') const _onwrite = Symbol('_onwrite') const _open = Symbol('_open') const _path = Symbol('_path') const _pos = Symbol('_pos') const _queue = Symbol('_queue') const _read = Symbol('_read') const _readSize = Symbol('_readSize') const _reading = Symbol('_reading') const _remain = Symbol('_remain') const _size = Symbol('_size') const _write = Symbol('_write') const _writing = Symbol('_writing') const _defaultFlag = Symbol('_defaultFlag') const _errored = Symbol('_errored') class ReadStream extends MiniPass { constructor (path, opt) { opt = opt || {} super(opt) this.readable = true this.writable = false if (typeof path !== 'string') throw new TypeError('path must be a string') this[_errored] = false this[_fd] = typeof opt.fd === 'number' ? opt.fd : null this[_path] = path this[_readSize] = opt.readSize || 16*1024*1024 this[_reading] = false this[_size] = typeof opt.size === 'number' ? opt.size : Infinity this[_remain] = this[_size] this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true if (typeof this[_fd] === 'number') this[_read]() else this[_open]() } get fd () { return this[_fd] } get path () { return this[_path] } write () { throw new TypeError('this is a readable stream') } end () { throw new TypeError('this is a readable stream') } [_open] () { fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd)) } [_onopen] (er, fd) { if (er) this[_onerror](er) else { this[_fd] = fd this.emit('open', fd) this[_read]() } } [_makeBuf] () { return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])) } [_read] () { if (!this[_reading]) { this[_reading] = true const buf = this[_makeBuf]() /* istanbul ignore if */ if (buf.length === 0) return process.nextTick(() => this[_onread](null, 0, buf)) fs.read(this[_fd], buf, 0, buf.length, null, (er, br, buf) => this[_onread](er, br, buf)) } } [_onread] (er, br, buf) { this[_reading] = false if (er) this[_onerror](er) else if (this[_handleChunk](br, buf)) this[_read]() } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) } } [_onerror] (er) { this[_reading] = true this[_close]() this.emit('error', er) } [_handleChunk] (br, buf) { let ret = false // no effect if infinite this[_remain] -= br if (br > 0) ret = super.write(br < buf.length ? buf.slice(0, br) : buf) if (br === 0 || this[_remain] <= 0) { ret = false this[_close]() super.end() } return ret } emit (ev, data) { switch (ev) { case 'prefinish': case 'finish': break case 'drain': if (typeof this[_fd] === 'number') this[_read]() break case 'error': if (this[_errored]) return this[_errored] = true return super.emit(ev, data) default: return super.emit(ev, data) } } } class ReadStreamSync extends ReadStream { [_open] () { let threw = true try { this[_onopen](null, fs.openSync(this[_path], 'r')) threw = false } finally { if (threw) this[_close]() } } [_read] () { let threw = true try { if (!this[_reading]) { this[_reading] = true do { const buf = this[_makeBuf]() /* istanbul ignore next */ const br = buf.length === 0 ? 0 : fs.readSync(this[_fd], buf, 0, buf.length, null) if (!this[_handleChunk](br, buf)) break } while (true) this[_reading] = false } threw = false } finally { if (threw) this[_close]() } } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.closeSync(fd) this.emit('close') } } } class WriteStream extends EE { constructor (path, opt) { opt = opt || {} super(opt) this.readable = false this.writable = true this[_errored] = false this[_writing] = false this[_ended] = false this[_needDrain] = false this[_queue] = [] this[_path] = path this[_fd] = typeof opt.fd === 'number' ? opt.fd : null this[_mode] = opt.mode === undefined ? 0o666 : opt.mode this[_pos] = typeof opt.start === 'number' ? opt.start : null this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true // truncating makes no sense when writing into the middle const defaultFlag = this[_pos] !== null ? 'r+' : 'w' this[_defaultFlag] = opt.flags === undefined this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags if (this[_fd] === null) this[_open]() } emit (ev, data) { if (ev === 'error') { if (this[_errored]) return this[_errored] = true } return super.emit(ev, data) } get fd () { return this[_fd] } get path () { return this[_path] } [_onerror] (er) { this[_close]() this[_writing] = true this.emit('error', er) } [_open] () { fs.open(this[_path], this[_flags], this[_mode], (er, fd) => this[_onopen](er, fd)) } [_onopen] (er, fd) { if (this[_defaultFlag] && this[_flags] === 'r+' && er && er.code === 'ENOENT') { this[_flags] = 'w' this[_open]() } else if (er) this[_onerror](er) else { this[_fd] = fd this.emit('open', fd) this[_flush]() } } end (buf, enc) { if (buf) this.write(buf, enc) this[_ended] = true // synthetic after-write logic, where drain/finish live if (!this[_writing] && !this[_queue].length && typeof this[_fd] === 'number') this[_onwrite](null, 0) return this } write (buf, enc) { if (typeof buf === 'string') buf = Buffer.from(buf, enc) if (this[_ended]) { this.emit('error', new Error('write() after end()')) return false } if (this[_fd] === null || this[_writing] || this[_queue].length) { this[_queue].push(buf) this[_needDrain] = true return false } this[_writing] = true this[_write](buf) return true } [_write] (buf) { fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => this[_onwrite](er, bw)) } [_onwrite] (er, bw) { if (er) this[_onerror](er) else { if (this[_pos] !== null) this[_pos] += bw if (this[_queue].length) this[_flush]() else { this[_writing] = false if (this[_ended] && !this[_finished]) { this[_finished] = true this[_close]() this.emit('finish') } else if (this[_needDrain]) { this[_needDrain] = false this.emit('drain') } } } } [_flush] () { if (this[_queue].length === 0) { if (this[_ended]) this[_onwrite](null, 0) } else if (this[_queue].length === 1) this[_write](this[_queue].pop()) else { const iovec = this[_queue] this[_queue] = [] writev(this[_fd], iovec, this[_pos], (er, bw) => this[_onwrite](er, bw)) } } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) } } } class WriteStreamSync extends WriteStream { [_open] () { let fd // only wrap in a try{} block if we know we'll retry, to avoid // the rethrow obscuring the error's source frame in most cases. if (this[_defaultFlag] && this[_flags] === 'r+') { try { fd = fs.openSync(this[_path], this[_flags], this[_mode]) } catch (er) { if (er.code === 'ENOENT') { this[_flags] = 'w' return this[_open]() } else throw er } } else fd = fs.openSync(this[_path], this[_flags], this[_mode]) this[_onopen](null, fd) } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.closeSync(fd) this.emit('close') } } [_write] (buf) { // throw the original, but try to close if it fails let threw = true try { this[_onwrite](null, fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos])) threw = false } finally { if (threw) try { this[_close]() } catch (_) {} } } } exports.ReadStream = ReadStream exports.ReadStreamSync = ReadStreamSync exports.WriteStream = WriteStream exports.WriteStreamSync = WriteStreamSync /***/ }), /***/ "./node_modules/fs.realpath/index.js": /*!*******************************************!*\ !*** ./node_modules/fs.realpath/index.js ***! \*******************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = realpath realpath.realpath = realpath realpath.sync = realpathSync realpath.realpathSync = realpathSync realpath.monkeypatch = monkeypatch realpath.unmonkeypatch = unmonkeypatch var fs = __webpack_require__(/*! fs */ "fs") var origRealpath = fs.realpath var origRealpathSync = fs.realpathSync var version = process.version var ok = /^v[0-5]\./.test(version) var old = __webpack_require__(/*! ./old.js */ "./node_modules/fs.realpath/old.js") function newError (er) { return er && er.syscall === 'realpath' && ( er.code === 'ELOOP' || er.code === 'ENOMEM' || er.code === 'ENAMETOOLONG' ) } function realpath (p, cache, cb) { if (ok) { return origRealpath(p, cache, cb) } if (typeof cache === 'function') { cb = cache cache = null } origRealpath(p, cache, function (er, result) { if (newError(er)) { old.realpath(p, cache, cb) } else { cb(er, result) } }) } function realpathSync (p, cache) { if (ok) { return origRealpathSync(p, cache) } try { return origRealpathSync(p, cache) } catch (er) { if (newError(er)) { return old.realpathSync(p, cache) } else { throw er } } } function monkeypatch () { fs.realpath = realpath fs.realpathSync = realpathSync } function unmonkeypatch () { fs.realpath = origRealpath fs.realpathSync = origRealpathSync } /***/ }), /***/ "./node_modules/fs.realpath/old.js": /*!*****************************************!*\ !*** ./node_modules/fs.realpath/old.js ***! \*****************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { // Copyright Joyent, Inc. and other Node contributors. // // 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. var pathModule = __webpack_require__(/*! path */ "path"); var isWindows = process.platform === 'win32'; var fs = __webpack_require__(/*! fs */ "fs"); // JavaScript implementation of realpath, ported from node pre-v6 var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); function rethrow() { // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and // is fairly slow to generate. var callback; if (DEBUG) { var backtrace = new Error; callback = debugCallback; } else callback = missingCallback; return callback; function debugCallback(err) { if (err) { backtrace.message = err.message; err = backtrace; missingCallback(err); } } function missingCallback(err) { if (err) { if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs else if (!process.noDeprecation) { var msg = 'fs: missing callback ' + (err.stack || err.message); if (process.traceDeprecation) console.trace(msg); else console.error(msg); } } } } function maybeCallback(cb) { return typeof cb === 'function' ? cb : rethrow(); } var normalize = pathModule.normalize; // Regexp that finds the next partion of a (partial) path // result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] if (isWindows) { var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; } else { var nextPartRe = /(.*?)(?:[\/]+|$)/g; } // Regex to find the device root, including trailing slash. E.g. 'c:\\'. if (isWindows) { var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; } else { var splitRootRe = /^[\/]*/; } exports.realpathSync = function realpathSync(p, cache) { // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return cache[p]; } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstatSync(base); knownHard[base] = true; } } // walk down the path, swapping out linked pathparts for their real // values // NB: p.length changes. while (pos < p.length) { // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { continue; } var resolvedLink; if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // some known symbolic link. no need to stat again. resolvedLink = cache[base]; } else { var stat = fs.lstatSync(base); if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; continue; } // read the link if it wasn't read before // dev/ino always return 0 on windows, so skip the check. var linkTarget = null; if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { linkTarget = seenLinks[id]; } } if (linkTarget === null) { fs.statSync(base); linkTarget = fs.readlinkSync(base); } resolvedLink = pathModule.resolve(previous, linkTarget); // track this, if given a cache. if (cache) cache[base] = resolvedLink; if (!isWindows) seenLinks[id] = linkTarget; } // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } if (cache) cache[original] = p; return p; }; exports.realpath = function realpath(p, cache, cb) { if (typeof cb !== 'function') { cb = maybeCallback(cache); cache = null; } // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return process.nextTick(cb.bind(null, null, cache[p])); } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstat(base, function(err) { if (err) return cb(err); knownHard[base] = true; LOOP(); }); } else { process.nextTick(LOOP); } } // walk down the path, swapping out linked pathparts for their real // values function LOOP() { // stop if scanned past end of path if (pos >= p.length) { if (cache) cache[original] = p; return cb(null, p); } // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { return process.nextTick(LOOP); } if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // known symbolic link. no need to stat again. return gotResolvedLink(cache[base]); } return fs.lstat(base, gotStat); } function gotStat(err, stat) { if (err) return cb(err); // if not a symlink, skip to the next path part if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; return process.nextTick(LOOP); } // stat & read the link if not read before // call gotTarget as soon as the link target is known // dev/ino always return 0 on windows, so skip the check. if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { return gotTarget(null, seenLinks[id], base); } } fs.stat(base, function(err) { if (err) return cb(err); fs.readlink(base, function(err, target) { if (!isWindows) seenLinks[id] = target; gotTarget(err, target); }); }); } function gotTarget(err, target, base) { if (err) return cb(err); var resolvedLink = pathModule.resolve(previous, target); if (cache) cache[base] = resolvedLink; gotResolvedLink(resolvedLink); } function gotResolvedLink(resolvedLink) { // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } }; /***/ }), /***/ "./node_modules/glob/common.js": /*!*************************************!*\ !*** ./node_modules/glob/common.js ***! \*************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { exports.setopts = setopts exports.ownProp = ownProp exports.makeAbs = makeAbs exports.finish = finish exports.mark = mark exports.isIgnored = isIgnored exports.childrenIgnored = childrenIgnored function ownProp (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } var fs = __webpack_require__(/*! fs */ "fs") var path = __webpack_require__(/*! path */ "path") var minimatch = __webpack_require__(/*! minimatch */ "./node_modules/glob/node_modules/minimatch/minimatch.js") var isAbsolute = __webpack_require__(/*! path-is-absolute */ "./node_modules/path-is-absolute/index.js") var Minimatch = minimatch.Minimatch function alphasort (a, b) { return a.localeCompare(b, 'en') } function setupIgnores (self, options) { self.ignore = options.ignore || [] if (!Array.isArray(self.ignore)) self.ignore = [self.ignore] if (self.ignore.length) { self.ignore = self.ignore.map(ignoreMap) } } // ignore patterns are always in dot:true mode. function ignoreMap (pattern) { var gmatcher = null if (pattern.slice(-3) === '/**') { var gpattern = pattern.replace(/(\/\*\*)+$/, '') gmatcher = new Minimatch(gpattern, { dot: true }) } return { matcher: new Minimatch(pattern, { dot: true }), gmatcher: gmatcher } } function setopts (self, pattern, options) { if (!options) options = {} // base-matching: just use globstar for that. if (options.matchBase && -1 === pattern.indexOf("/")) { if (options.noglobstar) { throw new Error("base matching requires globstar") } pattern = "**/" + pattern } self.silent = !!options.silent self.pattern = pattern self.strict = options.strict !== false self.realpath = !!options.realpath self.realpathCache = options.realpathCache || Object.create(null) self.follow = !!options.follow self.dot = !!options.dot self.mark = !!options.mark self.nodir = !!options.nodir if (self.nodir) self.mark = true self.sync = !!options.sync self.nounique = !!options.nounique self.nonull = !!options.nonull self.nosort = !!options.nosort self.nocase = !!options.nocase self.stat = !!options.stat self.noprocess = !!options.noprocess self.absolute = !!options.absolute self.fs = options.fs || fs self.maxLength = options.maxLength || Infinity self.cache = options.cache || Object.create(null) self.statCache = options.statCache || Object.create(null) self.symlinks = options.symlinks || Object.create(null) setupIgnores(self, options) self.changedCwd = false var cwd = process.cwd() if (!ownProp(options, "cwd")) self.cwd = cwd else { self.cwd = path.resolve(options.cwd) self.changedCwd = self.cwd !== cwd } self.root = options.root || path.resolve(self.cwd, "/") self.root = path.resolve(self.root) if (process.platform === "win32") self.root = self.root.replace(/\\/g, "/") // TODO: is an absolute `cwd` supposed to be resolved against `root`? // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) if (process.platform === "win32") self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") self.nomount = !!options.nomount // disable comments and negation in Minimatch. // Note that they are not supported in Glob itself anyway. options.nonegate = true options.nocomment = true self.minimatch = new Minimatch(pattern, options) self.options = self.minimatch.options } function finish (self) { var nou = self.nounique var all = nou ? [] : Object.create(null) for (var i = 0, l = self.matches.length; i < l; i ++) { var matches = self.matches[i] if (!matches || Object.keys(matches).length === 0) { if (self.nonull) { // do like the shell, and spit out the literal glob var literal = self.minimatch.globSet[i] if (nou) all.push(literal) else all[literal] = true } } else { // had matches var m = Object.keys(matches) if (nou) all.push.apply(all, m) else m.forEach(function (m) { all[m] = true }) } } if (!nou) all = Object.keys(all) if (!self.nosort) all = all.sort(alphasort) // at *some* point we statted all of these if (self.mark) { for (var i = 0; i < all.length; i++) { all[i] = self._mark(all[i]) } if (self.nodir) { all = all.filter(function (e) { var notDir = !(/\/$/.test(e)) var c = self.cache[e] || self.cache[makeAbs(self, e)] if (notDir && c) notDir = c !== 'DIR' && !Array.isArray(c) return notDir }) } } if (self.ignore.length) all = all.filter(function(m) { return !isIgnored(self, m) }) self.found = all } function mark (self, p) { var abs = makeAbs(self, p) var c = self.cache[abs] var m = p if (c) { var isDir = c === 'DIR' || Array.isArray(c) var slash = p.slice(-1) === '/' if (isDir && !slash) m += '/' else if (!isDir && slash) m = m.slice(0, -1) if (m !== p) { var mabs = makeAbs(self, m) self.statCache[mabs] = self.statCache[abs] self.cache[mabs] = self.cache[abs] } } return m } // lotta situps... function makeAbs (self, f) { var abs = f if (f.charAt(0) === '/') { abs = path.join(self.root, f) } else if (isAbsolute(f) || f === '') { abs = f } else if (self.changedCwd) { abs = path.resolve(self.cwd, f) } else { abs = path.resolve(f) } if (process.platform === 'win32') abs = abs.replace(/\\/g, '/') return abs } // Return true, if pattern ends with globstar '**', for the accompanying parent directory. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents function isIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) }) } function childrenIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return !!(item.gmatcher && item.gmatcher.match(path)) }) } /***/ }), /***/ "./node_modules/glob/glob.js": /*!***********************************!*\ !*** ./node_modules/glob/glob.js ***! \***********************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Approach: // // 1. Get the minimatch set // 2. For each pattern in the set, PROCESS(pattern, false) // 3. Store matches per-set, then uniq them // // PROCESS(pattern, inGlobStar) // Get the first [n] items from pattern that are all strings // Join these together. This is PREFIX. // If there is no more remaining, then stat(PREFIX) and // add to matches if it succeeds. END. // // If inGlobStar and PREFIX is symlink and points to dir // set ENTRIES = [] // else readdir(PREFIX) as ENTRIES // If fail, END // // with ENTRIES // If pattern[n] is GLOBSTAR // // handle the case where the globstar match is empty // // by pruning it out, and testing the resulting pattern // PROCESS(pattern[0..n] + pattern[n+1 .. $], false) // // handle other cases. // for ENTRY in ENTRIES (not dotfiles) // // attach globstar + tail onto the entry // // Mark that this entry is a globstar match // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) // // else // not globstar // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) // Test ENTRY against pattern[n] // If fails, continue // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) // // Caveat: // Cache all stats and readdirs results to minimize syscall. Since all // we ever care about is existence and directory-ness, we can just keep // `true` for files, and [children,...] for directories, or `false` for // things that don't exist. module.exports = glob var rp = __webpack_require__(/*! fs.realpath */ "./node_modules/fs.realpath/index.js") var minimatch = __webpack_require__(/*! minimatch */ "./node_modules/glob/node_modules/minimatch/minimatch.js") var Minimatch = minimatch.Minimatch var inherits = __webpack_require__(/*! inherits */ "./node_modules/inherits/inherits.js") var EE = (__webpack_require__(/*! events */ "events").EventEmitter) var path = __webpack_require__(/*! path */ "path") var assert = __webpack_require__(/*! assert */ "assert") var isAbsolute = __webpack_require__(/*! path-is-absolute */ "./node_modules/path-is-absolute/index.js") var globSync = __webpack_require__(/*! ./sync.js */ "./node_modules/glob/sync.js") var common = __webpack_require__(/*! ./common.js */ "./node_modules/glob/common.js") var setopts = common.setopts var ownProp = common.ownProp var inflight = __webpack_require__(/*! inflight */ "./node_modules/inflight/inflight.js") var util = __webpack_require__(/*! util */ "util") var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored var once = __webpack_require__(/*! once */ "./node_modules/once/once.js") function glob (pattern, options, cb) { if (typeof options === 'function') cb = options, options = {} if (!options) options = {} if (options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return globSync(pattern, options) } return new Glob(pattern, options, cb) } glob.sync = globSync var GlobSync = glob.GlobSync = globSync.GlobSync // old api surface glob.glob = glob function extend (origin, add) { if (add === null || typeof add !== 'object') { return origin } var keys = Object.keys(add) var i = keys.length while (i--) { origin[keys[i]] = add[keys[i]] } return origin } glob.hasMagic = function (pattern, options_) { var options = extend({}, options_) options.noprocess = true var g = new Glob(pattern, options) var set = g.minimatch.set if (!pattern) return false if (set.length > 1) return true for (var j = 0; j < set[0].length; j++) { if (typeof set[0][j] !== 'string') return true } return false } glob.Glob = Glob inherits(Glob, EE) function Glob (pattern, options, cb) { if (typeof options === 'function') { cb = options options = null } if (options && options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return new GlobSync(pattern, options) } if (!(this instanceof Glob)) return new Glob(pattern, options, cb) setopts(this, pattern, options) this._didRealPath = false // process each pattern in the minimatch set var n = this.minimatch.set.length // The matches are stored as {: true,...} so that // duplicates are automagically pruned. // Later, we do an Object.keys() on these. // Keep them as a list so we can fill in when nonull is set. this.matches = new Array(n) if (typeof cb === 'function') { cb = once(cb) this.on('error', cb) this.on('end', function (matches) { cb(null, matches) }) } var self = this this._processing = 0 this._emitQueue = [] this._processQueue = [] this.paused = false if (this.noprocess) return this if (n === 0) return done() var sync = true for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false, done) } sync = false function done () { --self._processing if (self._processing <= 0) { if (sync) { process.nextTick(function () { self._finish() }) } else { self._finish() } } } } Glob.prototype._finish = function () { assert(this instanceof Glob) if (this.aborted) return if (this.realpath && !this._didRealpath) return this._realpath() common.finish(this) this.emit('end', this.found) } Glob.prototype._realpath = function () { if (this._didRealpath) return this._didRealpath = true var n = this.matches.length if (n === 0) return this._finish() var self = this for (var i = 0; i < this.matches.length; i++) this._realpathSet(i, next) function next () { if (--n === 0) self._finish() } } Glob.prototype._realpathSet = function (index, cb) { var matchset = this.matches[index] if (!matchset) return cb() var found = Object.keys(matchset) var self = this var n = found.length if (n === 0) return cb() var set = this.matches[index] = Object.create(null) found.forEach(function (p, i) { // If there's a problem with the stat, then it means that // one or more of the links in the realpath couldn't be // resolved. just return the abs value in that case. p = self._makeAbs(p) rp.realpath(p, self.realpathCache, function (er, real) { if (!er) set[real] = true else if (er.syscall === 'stat') set[p] = true else self.emit('error', er) // srsly wtf right here if (--n === 0) { self.matches[index] = set cb() } }) }) } Glob.prototype._mark = function (p) { return common.mark(this, p) } Glob.prototype._makeAbs = function (f) { return common.makeAbs(this, f) } Glob.prototype.abort = function () { this.aborted = true this.emit('abort') } Glob.prototype.pause = function () { if (!this.paused) { this.paused = true this.emit('pause') } } Glob.prototype.resume = function () { if (this.paused) { this.emit('resume') this.paused = false if (this._emitQueue.length) { var eq = this._emitQueue.slice(0) this._emitQueue.length = 0 for (var i = 0; i < eq.length; i ++) { var e = eq[i] this._emitMatch(e[0], e[1]) } } if (this._processQueue.length) { var pq = this._processQueue.slice(0) this._processQueue.length = 0 for (var i = 0; i < pq.length; i ++) { var p = pq[i] this._processing-- this._process(p[0], p[1], p[2], p[3]) } } } } Glob.prototype._process = function (pattern, index, inGlobStar, cb) { assert(this instanceof Glob) assert(typeof cb === 'function') if (this.aborted) return this._processing++ if (this.paused) { this._processQueue.push([pattern, index, inGlobStar, cb]) return } //console.error('PROCESS %d', this._processing, pattern) // Get the first [n] parts of pattern that are all strings. var n = 0 while (typeof pattern[n] === 'string') { n ++ } // now n is the index of the first one that is *not* a string. // see if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index, cb) return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/') break } var remain = pattern.slice(n) // get the list of entries. var read if (prefix === null) read = '.' else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix } else read = prefix var abs = this._makeAbs(read) //if ignored, skip _processing if (childrenIgnored(this, read)) return cb() var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) } Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { // if the abs isn't a dir, then nothing can match! if (!entries) return cb() // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0] var negate = !!this.minimatch.negate var rawGlob = pn._glob var dotOk = this.dot || rawGlob.charAt(0) === '.' var matchedEntries = [] for (var i = 0; i < entries.length; i++) { var e = entries[i] if (e.charAt(0) !== '.' || dotOk) { var m if (negate && !prefix) { m = !e.match(pn) } else { m = e.match(pn) } if (m) matchedEntries.push(e) } } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) return cb() // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null) for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e) } this._emitMatch(index, e) } // This was the last one, and no stats were needed return cb() } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift() for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } this._process([e].concat(remain), index, inGlobStar, cb) } cb() } Glob.prototype._emitMatch = function (index, e) { if (this.aborted) return if (isIgnored(this, e)) return if (this.paused) { this._emitQueue.push([index, e]) return } var abs = isAbsolute(e) ? e : this._makeAbs(e) if (this.mark) e = this._mark(e) if (this.absolute) e = abs if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs] if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true var st = this.statCache[abs] if (st) this.emit('stat', e, st) this.emit('match', e) } Glob.prototype._readdirInGlobStar = function (abs, cb) { if (this.aborted) return // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false, cb) var lstatkey = 'lstat\0' + abs var self = this var lstatcb = inflight(lstatkey, lstatcb_) if (lstatcb) self.fs.lstat(abs, lstatcb) function lstatcb_ (er, lstat) { if (er && er.code === 'ENOENT') return cb() var isSym = lstat && lstat.isSymbolicLink() self.symlinks[abs] = isSym // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) { self.cache[abs] = 'FILE' cb() } else self._readdir(abs, false, cb) } } Glob.prototype._readdir = function (abs, inGlobStar, cb) { if (this.aborted) return cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) if (!cb) return //console.error('RD %j %j', +inGlobStar, abs) if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') return cb() if (Array.isArray(c)) return cb(null, c) } var self = this self.fs.readdir(abs, readdirCb(this, abs, cb)) } function readdirCb (self, abs, cb) { return function (er, entries) { if (er) self._readdirError(abs, er, cb) else self._readdirEntries(abs, entries, cb) } } Glob.prototype._readdirEntries = function (abs, entries, cb) { if (this.aborted) return // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i] if (abs === '/') e = abs + e else e = abs + '/' + e this.cache[e] = true } } this.cache[abs] = entries return cb(null, entries) } Glob.prototype._readdirError = function (f, er, cb) { if (this.aborted) return // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f) this.cache[abs] = 'FILE' if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code this.emit('error', error) this.abort() } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false if (this.strict) { this.emit('error', er) // If the error is handled, then we abort // if not, we threw out of here this.abort() } if (!this.silent) console.error('glob error', er) break } return cb() } Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { //console.error('pgs2', prefix, remain[0], entries) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return cb() // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1) var gspref = prefix ? [ prefix ] : [] var noGlobStar = gspref.concat(remainWithoutGlobStar) // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false, cb) var isSym = this.symlinks[abs] var len = entries.length // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return cb() for (var i = 0; i < len; i++) { var e = entries[i] if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar) this._process(instead, index, true, cb) var below = gspref.concat(entries[i], remain) this._process(below, index, true, cb) } cb() } Glob.prototype._processSimple = function (prefix, index, cb) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var self = this this._stat(prefix, function (er, exists) { self._processSimple2(prefix, index, er, exists, cb) }) } Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { //console.error('ps2', prefix, exists) if (!this.matches[index]) this.matches[index] = Object.create(null) // If it doesn't exist, then just mark the lack of results if (!exists) return cb() if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix) if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix) } else { prefix = path.resolve(this.root, prefix) if (trail) prefix += '/' } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/') // Mark this as a match this._emitMatch(index, prefix) cb() } // Returns either 'DIR', 'FILE', or false Glob.prototype._stat = function (f, cb) { var abs = this._makeAbs(f) var needDir = f.slice(-1) === '/' if (f.length > this.maxLength) return cb() if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs] if (Array.isArray(c)) c = 'DIR' // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return cb(null, c) if (needDir && c === 'FILE') return cb() // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists var stat = this.statCache[abs] if (stat !== undefined) { if (stat === false) return cb(null, stat) else { var type = stat.isDirectory() ? 'DIR' : 'FILE' if (needDir && type === 'FILE') return cb() else return cb(null, type, stat) } } var self = this var statcb = inflight('stat\0' + abs, lstatcb_) if (statcb) self.fs.lstat(abs, statcb) function lstatcb_ (er, lstat) { if (lstat && lstat.isSymbolicLink()) { // If it's a symlink, then treat it as the target, unless // the target does not exist, then treat it as a file. return self.fs.stat(abs, function (er, stat) { if (er) self._stat2(f, abs, null, lstat, cb) else self._stat2(f, abs, er, stat, cb) }) } else { self._stat2(f, abs, er, lstat, cb) } } } Glob.prototype._stat2 = function (f, abs, er, stat, cb) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false return cb() } var needDir = f.slice(-1) === '/' this.statCache[abs] = stat if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat) var c = true if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE' this.cache[abs] = this.cache[abs] || c if (needDir && c === 'FILE') return cb() return cb(null, c, stat) } /***/ }), /***/ "./node_modules/glob/node_modules/minimatch/minimatch.js": /*!***************************************************************!*\ !*** ./node_modules/glob/node_modules/minimatch/minimatch.js ***! \***************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = minimatch minimatch.Minimatch = Minimatch var path = (function () { try { return __webpack_require__(/*! path */ "path") } catch (e) {}}()) || { sep: '/' } minimatch.sep = path.sep var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} var expand = __webpack_require__(/*! brace-expansion */ "./node_modules/brace-expansion/index.js") var plTypes = { '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, '?': { open: '(?:', close: ')?' }, '+': { open: '(?:', close: ')+' }, '*': { open: '(?:', close: ')*' }, '@': { open: '(?:', close: ')' } } // any single thing other than / // don't need to escape / when using new RegExp() var qmark = '[^/]' // * => any number of characters var star = qmark + '*?' // ** when dots are allowed. Anything goes, except .. and . // not (^ or / followed by one or two dots followed by $ or /), // followed by anything, any number of times. var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' // not a ^ or / followed by a dot, // followed by anything, any number of times. var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' // characters that need to be escaped in RegExp. var reSpecials = charSet('().*{}+?[]^$\\!') // "abc" -> { a:true, b:true, c:true } function charSet (s) { return s.split('').reduce(function (set, c) { set[c] = true return set }, {}) } // normalizes slashes. var slashSplit = /\/+/ minimatch.filter = filter function filter (pattern, options) { options = options || {} return function (p, i, list) { return minimatch(p, pattern, options) } } function ext (a, b) { b = b || {} var t = {} Object.keys(a).forEach(function (k) { t[k] = a[k] }) Object.keys(b).forEach(function (k) { t[k] = b[k] }) return t } minimatch.defaults = function (def) { if (!def || typeof def !== 'object' || !Object.keys(def).length) { return minimatch } var orig = minimatch var m = function minimatch (p, pattern, options) { return orig(p, pattern, ext(def, options)) } m.Minimatch = function Minimatch (pattern, options) { return new orig.Minimatch(pattern, ext(def, options)) } m.Minimatch.defaults = function defaults (options) { return orig.defaults(ext(def, options)).Minimatch } m.filter = function filter (pattern, options) { return orig.filter(pattern, ext(def, options)) } m.defaults = function defaults (options) { return orig.defaults(ext(def, options)) } m.makeRe = function makeRe (pattern, options) { return orig.makeRe(pattern, ext(def, options)) } m.braceExpand = function braceExpand (pattern, options) { return orig.braceExpand(pattern, ext(def, options)) } m.match = function (list, pattern, options) { return orig.match(list, pattern, ext(def, options)) } return m } Minimatch.defaults = function (def) { return minimatch.defaults(def).Minimatch } function minimatch (p, pattern, options) { assertValidPattern(pattern) if (!options) options = {} // shortcut: comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { return false } return new Minimatch(pattern, options).match(p) } function Minimatch (pattern, options) { if (!(this instanceof Minimatch)) { return new Minimatch(pattern, options) } assertValidPattern(pattern) if (!options) options = {} pattern = pattern.trim() // windows support: need to use /, not \ if (!options.allowWindowsEscape && path.sep !== '/') { pattern = pattern.split(path.sep).join('/') } this.options = options this.set = [] this.pattern = pattern this.regexp = null this.negate = false this.comment = false this.empty = false this.partial = !!options.partial // make the set of regexps etc. this.make() } Minimatch.prototype.debug = function () {} Minimatch.prototype.make = make function make () { var pattern = this.pattern var options = this.options // empty patterns and comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { this.comment = true return } if (!pattern) { this.empty = true return } // step 1: figure out negation, etc. this.parseNegate() // step 2: expand braces var set = this.globSet = this.braceExpand() if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } this.debug(this.pattern, set) // step 3: now we have a set, so turn each one into a series of path-portion // matching patterns. // These will be regexps, except in the case of "**", which is // set to the GLOBSTAR object for globstar behavior, // and will not contain any / characters set = this.globParts = set.map(function (s) { return s.split(slashSplit) }) this.debug(this.pattern, set) // glob --> regexps set = set.map(function (s, si, set) { return s.map(this.parse, this) }, this) this.debug(this.pattern, set) // filter out everything that didn't compile properly. set = set.filter(function (s) { return s.indexOf(false) === -1 }) this.debug(this.pattern, set) this.set = set } Minimatch.prototype.parseNegate = parseNegate function parseNegate () { var pattern = this.pattern var negate = false var options = this.options var negateOffset = 0 if (options.nonegate) return for (var i = 0, l = pattern.length ; i < l && pattern.charAt(i) === '!' ; i++) { negate = !negate negateOffset++ } if (negateOffset) this.pattern = pattern.substr(negateOffset) this.negate = negate } // Brace expansion: // a{b,c}d -> abd acd // a{b,}c -> abc ac // a{0..3}d -> a0d a1d a2d a3d // a{b,c{d,e}f}g -> abg acdfg acefg // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg // // Invalid sets are not expanded. // a{2..}b -> a{2..}b // a{b}c -> a{b}c minimatch.braceExpand = function (pattern, options) { return braceExpand(pattern, options) } Minimatch.prototype.braceExpand = braceExpand function braceExpand (pattern, options) { if (!options) { if (this instanceof Minimatch) { options = this.options } else { options = {} } } pattern = typeof pattern === 'undefined' ? this.pattern : pattern assertValidPattern(pattern) // Thanks to Yeting Li for // improving this regexp to avoid a ReDOS vulnerability. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { // shortcut. no need to expand. return [pattern] } return expand(pattern) } var MAX_PATTERN_LENGTH = 1024 * 64 var assertValidPattern = function (pattern) { if (typeof pattern !== 'string') { throw new TypeError('invalid pattern') } if (pattern.length > MAX_PATTERN_LENGTH) { throw new TypeError('pattern is too long') } } // parse a component of the expanded set. // At this point, no pattern may contain "/" in it // so we're going to return a 2d array, where each entry is the full // pattern, split on '/', and then turned into a regular expression. // A regexp is made at the end which joins each array with an // escaped /, and another full one which joins each regexp with |. // // Following the lead of Bash 4.1, note that "**" only has special meaning // when it is the *only* thing in a path portion. Otherwise, any series // of * is equivalent to a single *. Globstar behavior is enabled by // default, and can be disabled by setting options.noglobstar. Minimatch.prototype.parse = parse var SUBPARSE = {} function parse (pattern, isSub) { assertValidPattern(pattern) var options = this.options // shortcuts if (pattern === '**') { if (!options.noglobstar) return GLOBSTAR else pattern = '*' } if (pattern === '') return '' var re = '' var hasMagic = !!options.nocase var escaping = false // ? => one single character var patternListStack = [] var negativeLists = [] var stateChar var inClass = false var reClassStart = -1 var classStart = -1 // . and .. never match anything that doesn't start with ., // even when options.dot is set. var patternStart = pattern.charAt(0) === '.' ? '' // anything // not (start or / followed by . or .. followed by / or end) : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)' var self = this function clearStateChar () { if (stateChar) { // we had some state-tracking character // that wasn't consumed by this pass. switch (stateChar) { case '*': re += star hasMagic = true break case '?': re += qmark hasMagic = true break default: re += '\\' + stateChar break } self.debug('clearStateChar %j %j', stateChar, re) stateChar = false } } for (var i = 0, len = pattern.length, c ; (i < len) && (c = pattern.charAt(i)) ; i++) { this.debug('%s\t%s %s %j', pattern, i, re, c) // skip over any that are escaped. if (escaping && reSpecials[c]) { re += '\\' + c escaping = false continue } switch (c) { /* istanbul ignore next */ case '/': { // completely not allowed, even escaped. // Should already be path-split by now. return false } case '\\': clearStateChar() escaping = true continue // the various stateChar values // for the "extglob" stuff. case '?': case '*': case '+': case '@': case '!': this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) // all of those are literals inside a class, except that // the glob [!a] means [^a] in regexp if (inClass) { this.debug(' in class') if (c === '!' && i === classStart + 1) c = '^' re += c continue } // if we already have a stateChar, then it means // that there was something like ** or +? in there. // Handle the stateChar, then proceed with this one. self.debug('call clearStateChar %j', stateChar) clearStateChar() stateChar = c // if extglob is disabled, then +(asdf|foo) isn't a thing. // just clear the statechar *now*, rather than even diving into // the patternList stuff. if (options.noext) clearStateChar() continue case '(': if (inClass) { re += '(' continue } if (!stateChar) { re += '\\(' continue } patternListStack.push({ type: stateChar, start: i - 1, reStart: re.length, open: plTypes[stateChar].open, close: plTypes[stateChar].close }) // negation is (?:(?!js)[^/]*) re += stateChar === '!' ? '(?:(?!(?:' : '(?:' this.debug('plType %j %j', stateChar, re) stateChar = false continue case ')': if (inClass || !patternListStack.length) { re += '\\)' continue } clearStateChar() hasMagic = true var pl = patternListStack.pop() // negation is (?:(?!js)[^/]*) // The others are (?:) re += pl.close if (pl.type === '!') { negativeLists.push(pl) } pl.reEnd = re.length continue case '|': if (inClass || !patternListStack.length || escaping) { re += '\\|' escaping = false continue } clearStateChar() re += '|' continue // these are mostly the same in regexp and glob case '[': // swallow any state-tracking char before the [ clearStateChar() if (inClass) { re += '\\' + c continue } inClass = true classStart = i reClassStart = re.length re += c continue case ']': // a right bracket shall lose its special // meaning and represent itself in // a bracket expression if it occurs // first in the list. -- POSIX.2 2.8.3.2 if (i === classStart + 1 || !inClass) { re += '\\' + c escaping = false continue } // handle the case where we left a class open. // "[z-a]" is valid, equivalent to "\[z-a\]" // split where the last [ was, make sure we don't have // an invalid re. if so, re-walk the contents of the // would-be class to re-translate any characters that // were passed through as-is // TODO: It would probably be faster to determine this // without a try/catch and a new RegExp, but it's tricky // to do safely. For now, this is safe and works. var cs = pattern.substring(classStart + 1, i) try { RegExp('[' + cs + ']') } catch (er) { // not a valid class! var sp = this.parse(cs, SUBPARSE) re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' hasMagic = hasMagic || sp[1] inClass = false continue } // finish up the class. hasMagic = true inClass = false re += c continue default: // swallow any state char that wasn't consumed clearStateChar() if (escaping) { // no need escaping = false } else if (reSpecials[c] && !(c === '^' && inClass)) { re += '\\' } re += c } // switch } // for // handle the case where we left a class open. // "[abc" is valid, equivalent to "\[abc" if (inClass) { // split where the last [ was, and escape it // this is a huge pita. We now have to re-walk // the contents of the would-be class to re-translate // any characters that were passed through as-is cs = pattern.substr(classStart + 1) sp = this.parse(cs, SUBPARSE) re = re.substr(0, reClassStart) + '\\[' + sp[0] hasMagic = hasMagic || sp[1] } // handle the case where we had a +( thing at the *end* // of the pattern. // each pattern list stack adds 3 chars, and we need to go through // and escape any | chars that were passed through as-is for the regexp. // Go through and escape them, taking care not to double-escape any // | chars that were already escaped. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { var tail = re.slice(pl.reStart + pl.open.length) this.debug('setting tail', re, pl) // maybe some even number of \, then maybe 1 \, followed by a | tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { if (!$2) { // the | isn't already escaped, so escape it. $2 = '\\' } // need to escape all those slashes *again*, without escaping the // one that we need for escaping the | character. As it works out, // escaping an even number of slashes can be done by simply repeating // it exactly after itself. That's why this trick works. // // I am sorry that you have to see this. return $1 + $1 + $2 + '|' }) this.debug('tail=%j\n %s', tail, tail, pl, re) var t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type hasMagic = true re = re.slice(0, pl.reStart) + t + '\\(' + tail } // handle trailing things that only matter at the very end. clearStateChar() if (escaping) { // trailing \\ re += '\\\\' } // only need to apply the nodot start if the re starts with // something that could conceivably capture a dot var addPatternStart = false switch (re.charAt(0)) { case '[': case '.': case '(': addPatternStart = true } // Hack to work around lack of negative lookbehind in JS // A pattern like: *.!(x).!(y|z) needs to ensure that a name // like 'a.xyz.yz' doesn't match. So, the first negative // lookahead, has to look ALL the way ahead, to the end of // the pattern. for (var n = negativeLists.length - 1; n > -1; n--) { var nl = negativeLists[n] var nlBefore = re.slice(0, nl.reStart) var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) var nlAfter = re.slice(nl.reEnd) nlLast += nlAfter // Handle nested stuff like *(*.js|!(*.json)), where open parens // mean that we should *not* include the ) in the bit that is considered // "after" the negated section. var openParensBefore = nlBefore.split('(').length - 1 var cleanAfter = nlAfter for (i = 0; i < openParensBefore; i++) { cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') } nlAfter = cleanAfter var dollar = '' if (nlAfter === '' && isSub !== SUBPARSE) { dollar = '$' } var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast re = newRe } // if the re is not "" at this point, then we need to make sure // it doesn't match against an empty path part. // Otherwise a/* will match a/, which it should not. if (re !== '' && hasMagic) { re = '(?=.)' + re } if (addPatternStart) { re = patternStart + re } // parsing just a piece of a larger pattern. if (isSub === SUBPARSE) { return [re, hasMagic] } // skip the regexp for non-magical patterns // unescape anything in it, though, so that it'll be // an exact match against a file etc. if (!hasMagic) { return globUnescape(pattern) } var flags = options.nocase ? 'i' : '' try { var regExp = new RegExp('^' + re + '$', flags) } catch (er) /* istanbul ignore next - should be impossible */ { // If it was an invalid regular expression, then it can't match // anything. This trick looks for a character after the end of // the string, which is of course impossible, except in multi-line // mode, but it's not a /m regex. return new RegExp('$.') } regExp._glob = pattern regExp._src = re return regExp } minimatch.makeRe = function (pattern, options) { return new Minimatch(pattern, options || {}).makeRe() } Minimatch.prototype.makeRe = makeRe function makeRe () { if (this.regexp || this.regexp === false) return this.regexp // at this point, this.set is a 2d array of partial // pattern strings, or "**". // // It's better to use .match(). This function shouldn't // be used, really, but it's pretty convenient sometimes, // when you just want to work with a regex. var set = this.set if (!set.length) { this.regexp = false return this.regexp } var options = this.options var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot var flags = options.nocase ? 'i' : '' var re = set.map(function (pattern) { return pattern.map(function (p) { return (p === GLOBSTAR) ? twoStar : (typeof p === 'string') ? regExpEscape(p) : p._src }).join('\\\/') }).join('|') // must match entire pattern // ending in a * or ** will make it less strict. re = '^(?:' + re + ')$' // can match anything, as long as it's not this. if (this.negate) re = '^(?!' + re + ').*$' try { this.regexp = new RegExp(re, flags) } catch (ex) /* istanbul ignore next - should be impossible */ { this.regexp = false } return this.regexp } minimatch.match = function (list, pattern, options) { options = options || {} var mm = new Minimatch(pattern, options) list = list.filter(function (f) { return mm.match(f) }) if (mm.options.nonull && !list.length) { list.push(pattern) } return list } Minimatch.prototype.match = function match (f, partial) { if (typeof partial === 'undefined') partial = this.partial this.debug('match', f, this.pattern) // short-circuit in the case of busted things. // comments, etc. if (this.comment) return false if (this.empty) return f === '' if (f === '/' && partial) return true var options = this.options // windows: need to use /, not \ if (path.sep !== '/') { f = f.split(path.sep).join('/') } // treat the test path as a set of pathparts. f = f.split(slashSplit) this.debug(this.pattern, 'split', f) // just ONE of the pattern sets in this.set needs to match // in order for it to be valid. If negating, then just one // match means that we have failed. // Either way, return on the first hit. var set = this.set this.debug(this.pattern, 'set', set) // Find the basename of the path by looking for the last non-empty segment var filename var i for (i = f.length - 1; i >= 0; i--) { filename = f[i] if (filename) break } for (i = 0; i < set.length; i++) { var pattern = set[i] var file = f if (options.matchBase && pattern.length === 1) { file = [filename] } var hit = this.matchOne(file, pattern, partial) if (hit) { if (options.flipNegate) return true return !this.negate } } // didn't get any hits. this is success if it's a negative // pattern, failure otherwise. if (options.flipNegate) return false return this.negate } // set partial to true to test if, for example, // "/a/b" matches the start of "/*/b/*/d" // Partial means, if you run out of file before you run // out of pattern, then that's fine, as long as all // the parts match. Minimatch.prototype.matchOne = function (file, pattern, partial) { var options = this.options this.debug('matchOne', { 'this': this, file: file, pattern: pattern }) this.debug('matchOne', file.length, pattern.length) for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length ; (fi < fl) && (pi < pl) ; fi++, pi++) { this.debug('matchOne loop') var p = pattern[pi] var f = file[fi] this.debug(pattern, p, f) // should be impossible. // some invalid regexp stuff in the set. /* istanbul ignore if */ if (p === false) return false if (p === GLOBSTAR) { this.debug('GLOBSTAR', [pattern, p, f]) // "**" // a/**/b/**/c would match the following: // a/b/x/y/z/c // a/x/y/z/b/c // a/b/x/b/x/c // a/b/c // To do this, take the rest of the pattern after // the **, and see if it would match the file remainder. // If so, return success. // If not, the ** "swallows" a segment, and try again. // This is recursively awful. // // a/**/b/**/c matching a/b/x/y/z/c // - a matches a // - doublestar // - matchOne(b/x/y/z/c, b/**/c) // - b matches b // - doublestar // - matchOne(x/y/z/c, c) -> no // - matchOne(y/z/c, c) -> no // - matchOne(z/c, c) -> no // - matchOne(c, c) yes, hit var fr = fi var pr = pi + 1 if (pr === pl) { this.debug('** at the end') // a ** at the end will just swallow the rest. // We have found a match. // however, it will not swallow /.x, unless // options.dot is set. // . and .. are *never* matched by **, for explosively // exponential reasons. for (; fi < fl; fi++) { if (file[fi] === '.' || file[fi] === '..' || (!options.dot && file[fi].charAt(0) === '.')) return false } return true } // ok, let's see if we can swallow whatever we can. while (fr < fl) { var swallowee = file[fr] this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) // XXX remove this slice. Just pass the start index. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { this.debug('globstar found match!', fr, fl, swallowee) // found a match. return true } else { // can't swallow "." or ".." ever. // can only swallow ".foo" when explicitly asked. if (swallowee === '.' || swallowee === '..' || (!options.dot && swallowee.charAt(0) === '.')) { this.debug('dot detected!', file, fr, pattern, pr) break } // ** swallows a segment, and continue. this.debug('globstar swallow a segment, and continue') fr++ } } // no match was found. // However, in partial mode, we can't say this is necessarily over. // If there's more *pattern* left, then /* istanbul ignore if */ if (partial) { // ran out of file this.debug('\n>>> no match, partial?', file, fr, pattern, pr) if (fr === fl) return true } return false } // something other than ** // non-magic patterns just have to match exactly // patterns with magic have been turned into regexps. var hit if (typeof p === 'string') { hit = f === p this.debug('string match', p, f, hit) } else { hit = f.match(p) this.debug('pattern match', p, f, hit) } if (!hit) return false } // Note: ending in / means that we'll get a final "" // at the end of the pattern. This can only match a // corresponding "" at the end of the file. // If the file ends in /, then it can only match a // a pattern that ends in /, unless the pattern just // doesn't have any more for it. But, a/b/ should *not* // match "a/b/*", even though "" matches against the // [^/]*? pattern, except in partial mode, where it might // simply not be reached yet. // However, a/b/ should still satisfy a/* // now either we fell off the end of the pattern, or we're done. if (fi === fl && pi === pl) { // ran out of pattern and filename at the same time. // an exact hit! return true } else if (fi === fl) { // ran out of file, but still had pattern left. // this is ok if we're doing the match as part of // a glob fs traversal. return partial } else /* istanbul ignore else */ if (pi === pl) { // ran out of pattern, still have file left. // this is only acceptable if we're on the very last // empty segment of a file with a trailing slash. // a/* should match a/b/ return (fi === fl - 1) && (file[fi] === '') } // should be unreachable. /* istanbul ignore next */ throw new Error('wtf?') } // replace stuff like \* with * function globUnescape (s) { return s.replace(/\\(.)/g, '$1') } function regExpEscape (s) { return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') } /***/ }), /***/ "./node_modules/glob/sync.js": /*!***********************************!*\ !*** ./node_modules/glob/sync.js ***! \***********************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = globSync globSync.GlobSync = GlobSync var rp = __webpack_require__(/*! fs.realpath */ "./node_modules/fs.realpath/index.js") var minimatch = __webpack_require__(/*! minimatch */ "./node_modules/glob/node_modules/minimatch/minimatch.js") var Minimatch = minimatch.Minimatch var Glob = (__webpack_require__(/*! ./glob.js */ "./node_modules/glob/glob.js").Glob) var util = __webpack_require__(/*! util */ "util") var path = __webpack_require__(/*! path */ "path") var assert = __webpack_require__(/*! assert */ "assert") var isAbsolute = __webpack_require__(/*! path-is-absolute */ "./node_modules/path-is-absolute/index.js") var common = __webpack_require__(/*! ./common.js */ "./node_modules/glob/common.js") var setopts = common.setopts var ownProp = common.ownProp var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored function globSync (pattern, options) { if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') return new GlobSync(pattern, options).found } function GlobSync (pattern, options) { if (!pattern) throw new Error('must provide pattern') if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') if (!(this instanceof GlobSync)) return new GlobSync(pattern, options) setopts(this, pattern, options) if (this.noprocess) return this var n = this.minimatch.set.length this.matches = new Array(n) for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false) } this._finish() } GlobSync.prototype._finish = function () { assert(this instanceof GlobSync) if (this.realpath) { var self = this this.matches.forEach(function (matchset, index) { var set = self.matches[index] = Object.create(null) for (var p in matchset) { try { p = self._makeAbs(p) var real = rp.realpathSync(p, self.realpathCache) set[real] = true } catch (er) { if (er.syscall === 'stat') set[self._makeAbs(p)] = true else throw er } } }) } common.finish(this) } GlobSync.prototype._process = function (pattern, index, inGlobStar) { assert(this instanceof GlobSync) // Get the first [n] parts of pattern that are all strings. var n = 0 while (typeof pattern[n] === 'string') { n ++ } // now n is the index of the first one that is *not* a string. // See if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index) return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/') break } var remain = pattern.slice(n) // get the list of entries. var read if (prefix === null) read = '.' else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix } else read = prefix var abs = this._makeAbs(read) //if ignored, skip processing if (childrenIgnored(this, read)) return var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) else this._processReaddir(prefix, read, abs, remain, index, inGlobStar) } GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar) // if the abs isn't a dir, then nothing can match! if (!entries) return // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0] var negate = !!this.minimatch.negate var rawGlob = pn._glob var dotOk = this.dot || rawGlob.charAt(0) === '.' var matchedEntries = [] for (var i = 0; i < entries.length; i++) { var e = entries[i] if (e.charAt(0) !== '.' || dotOk) { var m if (negate && !prefix) { m = !e.match(pn) } else { m = e.match(pn) } if (m) matchedEntries.push(e) } } var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) return // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null) for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { if (prefix.slice(-1) !== '/') e = prefix + '/' + e else e = prefix + e } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e) } this._emitMatch(index, e) } // This was the last one, and no stats were needed return } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift() for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern if (prefix) newPattern = [prefix, e] else newPattern = [e] this._process(newPattern.concat(remain), index, inGlobStar) } } GlobSync.prototype._emitMatch = function (index, e) { if (isIgnored(this, e)) return var abs = this._makeAbs(e) if (this.mark) e = this._mark(e) if (this.absolute) { e = abs } if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs] if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true if (this.stat) this._stat(e) } GlobSync.prototype._readdirInGlobStar = function (abs) { // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false) var entries var lstat var stat try { lstat = this.fs.lstatSync(abs) } catch (er) { if (er.code === 'ENOENT') { // lstat failed, doesn't exist return null } } var isSym = lstat && lstat.isSymbolicLink() this.symlinks[abs] = isSym // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = 'FILE' else entries = this._readdir(abs, false) return entries } GlobSync.prototype._readdir = function (abs, inGlobStar) { var entries if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') return null if (Array.isArray(c)) return c } try { return this._readdirEntries(abs, this.fs.readdirSync(abs)) } catch (er) { this._readdirError(abs, er) return null } } GlobSync.prototype._readdirEntries = function (abs, entries) { // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i] if (abs === '/') e = abs + e else e = abs + '/' + e this.cache[e] = true } } this.cache[abs] = entries // mark and cache dir-ness return entries } GlobSync.prototype._readdirError = function (f, er) { // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f) this.cache[abs] = 'FILE' if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code throw error } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false if (this.strict) throw er if (!this.silent) console.error('glob error', er) break } } GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1) var gspref = prefix ? [ prefix ] : [] var noGlobStar = gspref.concat(remainWithoutGlobStar) // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false) var len = entries.length var isSym = this.symlinks[abs] // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return for (var i = 0; i < len; i++) { var e = entries[i] if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar) this._process(instead, index, true) var below = gspref.concat(entries[i], remain) this._process(below, index, true) } } GlobSync.prototype._processSimple = function (prefix, index) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var exists = this._stat(prefix) if (!this.matches[index]) this.matches[index] = Object.create(null) // If it doesn't exist, then just mark the lack of results if (!exists) return if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix) if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix) } else { prefix = path.resolve(this.root, prefix) if (trail) prefix += '/' } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/') // Mark this as a match this._emitMatch(index, prefix) } // Returns either 'DIR', 'FILE', or false GlobSync.prototype._stat = function (f) { var abs = this._makeAbs(f) var needDir = f.slice(-1) === '/' if (f.length > this.maxLength) return false if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs] if (Array.isArray(c)) c = 'DIR' // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return c if (needDir && c === 'FILE') return false // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists var stat = this.statCache[abs] if (!stat) { var lstat try { lstat = this.fs.lstatSync(abs) } catch (er) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false return false } } if (lstat && lstat.isSymbolicLink()) { try { stat = this.fs.statSync(abs) } catch (er) { stat = lstat } } else { stat = lstat } } this.statCache[abs] = stat var c = true if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE' this.cache[abs] = this.cache[abs] || c if (needDir && c === 'FILE') return false return c } GlobSync.prototype._mark = function (p) { return common.mark(this, p) } GlobSync.prototype._makeAbs = function (f) { return common.makeAbs(this, f) } /***/ }), /***/ "./node_modules/graceful-fs/clone.js": /*!*******************************************!*\ !*** ./node_modules/graceful-fs/clone.js ***! \*******************************************/ /***/ ((module) => { "use strict"; module.exports = clone var getPrototypeOf = Object.getPrototypeOf || function (obj) { return obj.__proto__ } function clone (obj) { if (obj === null || typeof obj !== 'object') return obj if (obj instanceof Object) var copy = { __proto__: getPrototypeOf(obj) } else var copy = Object.create(null) Object.getOwnPropertyNames(obj).forEach(function (key) { Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) }) return copy } /***/ }), /***/ "./node_modules/graceful-fs/graceful-fs.js": /*!*************************************************!*\ !*** ./node_modules/graceful-fs/graceful-fs.js ***! \*************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var fs = __webpack_require__(/*! fs */ "fs") var polyfills = __webpack_require__(/*! ./polyfills.js */ "./node_modules/graceful-fs/polyfills.js") var legacy = __webpack_require__(/*! ./legacy-streams.js */ "./node_modules/graceful-fs/legacy-streams.js") var clone = __webpack_require__(/*! ./clone.js */ "./node_modules/graceful-fs/clone.js") var util = __webpack_require__(/*! util */ "util") /* istanbul ignore next - node 0.x polyfill */ var gracefulQueue var previousSymbol /* istanbul ignore else - node 0.x polyfill */ if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { gracefulQueue = Symbol.for('graceful-fs.queue') // This is used in testing by future versions previousSymbol = Symbol.for('graceful-fs.previous') } else { gracefulQueue = '___graceful-fs.queue' previousSymbol = '___graceful-fs.previous' } function noop () {} function publishQueue(context, queue) { Object.defineProperty(context, gracefulQueue, { get: function() { return queue } }) } var debug = noop if (util.debuglog) debug = util.debuglog('gfs4') else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) debug = function() { var m = util.format.apply(util, arguments) m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') console.error(m) } // Once time initialization if (!fs[gracefulQueue]) { // This queue can be shared by multiple loaded instances var queue = global[gracefulQueue] || [] publishQueue(fs, queue) // Patch fs.close/closeSync to shared queue version, because we need // to retry() whenever a close happens *anywhere* in the program. // This is essential when multiple graceful-fs instances are // in play at the same time. fs.close = (function (fs$close) { function close (fd, cb) { return fs$close.call(fs, fd, function (err) { // This function uses the graceful-fs shared queue if (!err) { resetQueue() } if (typeof cb === 'function') cb.apply(this, arguments) }) } Object.defineProperty(close, previousSymbol, { value: fs$close }) return close })(fs.close) fs.closeSync = (function (fs$closeSync) { function closeSync (fd) { // This function uses the graceful-fs shared queue fs$closeSync.apply(fs, arguments) resetQueue() } Object.defineProperty(closeSync, previousSymbol, { value: fs$closeSync }) return closeSync })(fs.closeSync) if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { process.on('exit', function() { debug(fs[gracefulQueue]) __webpack_require__(/*! assert */ "assert").equal(fs[gracefulQueue].length, 0) }) } } if (!global[gracefulQueue]) { publishQueue(global, fs[gracefulQueue]); } module.exports = patch(clone(fs)) if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { module.exports = patch(fs) fs.__patched = true; } function patch (fs) { // Everything that references the open() function needs to be in here polyfills(fs) fs.gracefulify = patch fs.createReadStream = createReadStream fs.createWriteStream = createWriteStream var fs$readFile = fs.readFile fs.readFile = readFile function readFile (path, options, cb) { if (typeof options === 'function') cb = options, options = null return go$readFile(path, options, cb) function go$readFile (path, options, cb, startTime) { return fs$readFile(path, options, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } var fs$writeFile = fs.writeFile fs.writeFile = writeFile function writeFile (path, data, options, cb) { if (typeof options === 'function') cb = options, options = null return go$writeFile(path, data, options, cb) function go$writeFile (path, data, options, cb, startTime) { return fs$writeFile(path, data, options, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } var fs$appendFile = fs.appendFile if (fs$appendFile) fs.appendFile = appendFile function appendFile (path, data, options, cb) { if (typeof options === 'function') cb = options, options = null return go$appendFile(path, data, options, cb) function go$appendFile (path, data, options, cb, startTime) { return fs$appendFile(path, data, options, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } var fs$copyFile = fs.copyFile if (fs$copyFile) fs.copyFile = copyFile function copyFile (src, dest, flags, cb) { if (typeof flags === 'function') { cb = flags flags = 0 } return go$copyFile(src, dest, flags, cb) function go$copyFile (src, dest, flags, cb, startTime) { return fs$copyFile(src, dest, flags, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } var fs$readdir = fs.readdir fs.readdir = readdir function readdir (path, options, cb) { if (typeof options === 'function') cb = options, options = null return go$readdir(path, options, cb) function go$readdir (path, options, cb, startTime) { return fs$readdir(path, options, function (err, files) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$readdir, [path, options, cb], err, startTime || Date.now(), Date.now()]) else { if (files && files.sort) files.sort() if (typeof cb === 'function') cb.call(this, err, files) } }) } } if (process.version.substr(0, 4) === 'v0.8') { var legStreams = legacy(fs) ReadStream = legStreams.ReadStream WriteStream = legStreams.WriteStream } var fs$ReadStream = fs.ReadStream if (fs$ReadStream) { ReadStream.prototype = Object.create(fs$ReadStream.prototype) ReadStream.prototype.open = ReadStream$open } var fs$WriteStream = fs.WriteStream if (fs$WriteStream) { WriteStream.prototype = Object.create(fs$WriteStream.prototype) WriteStream.prototype.open = WriteStream$open } Object.defineProperty(fs, 'ReadStream', { get: function () { return ReadStream }, set: function (val) { ReadStream = val }, enumerable: true, configurable: true }) Object.defineProperty(fs, 'WriteStream', { get: function () { return WriteStream }, set: function (val) { WriteStream = val }, enumerable: true, configurable: true }) // legacy names var FileReadStream = ReadStream Object.defineProperty(fs, 'FileReadStream', { get: function () { return FileReadStream }, set: function (val) { FileReadStream = val }, enumerable: true, configurable: true }) var FileWriteStream = WriteStream Object.defineProperty(fs, 'FileWriteStream', { get: function () { return FileWriteStream }, set: function (val) { FileWriteStream = val }, enumerable: true, configurable: true }) function ReadStream (path, options) { if (this instanceof ReadStream) return fs$ReadStream.apply(this, arguments), this else return ReadStream.apply(Object.create(ReadStream.prototype), arguments) } function ReadStream$open () { var that = this open(that.path, that.flags, that.mode, function (err, fd) { if (err) { if (that.autoClose) that.destroy() that.emit('error', err) } else { that.fd = fd that.emit('open', fd) that.read() } }) } function WriteStream (path, options) { if (this instanceof WriteStream) return fs$WriteStream.apply(this, arguments), this else return WriteStream.apply(Object.create(WriteStream.prototype), arguments) } function WriteStream$open () { var that = this open(that.path, that.flags, that.mode, function (err, fd) { if (err) { that.destroy() that.emit('error', err) } else { that.fd = fd that.emit('open', fd) } }) } function createReadStream (path, options) { return new fs.ReadStream(path, options) } function createWriteStream (path, options) { return new fs.WriteStream(path, options) } var fs$open = fs.open fs.open = open function open (path, flags, mode, cb) { if (typeof mode === 'function') cb = mode, mode = null return go$open(path, flags, mode, cb) function go$open (path, flags, mode, cb, startTime) { return fs$open(path, flags, mode, function (err, fd) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } return fs } function enqueue (elem) { debug('ENQUEUE', elem[0].name, elem[1]) fs[gracefulQueue].push(elem) retry() } // keep track of the timeout between retry() calls var retryTimer // reset the startTime and lastTime to now // this resets the start of the 60 second overall timeout as well as the // delay between attempts so that we'll retry these jobs sooner function resetQueue () { var now = Date.now() for (var i = 0; i < fs[gracefulQueue].length; ++i) { // entries that are only a length of 2 are from an older version, don't // bother modifying those since they'll be retried anyway. if (fs[gracefulQueue][i].length > 2) { fs[gracefulQueue][i][3] = now // startTime fs[gracefulQueue][i][4] = now // lastTime } } // call retry to make sure we're actively processing the queue retry() } function retry () { // clear the timer and remove it to help prevent unintended concurrency clearTimeout(retryTimer) retryTimer = undefined if (fs[gracefulQueue].length === 0) return var elem = fs[gracefulQueue].shift() var fn = elem[0] var args = elem[1] // these items may be unset if they were added by an older graceful-fs var err = elem[2] var startTime = elem[3] var lastTime = elem[4] // if we don't have a startTime we have no way of knowing if we've waited // long enough, so go ahead and retry this item now if (startTime === undefined) { debug('RETRY', fn.name, args) fn.apply(null, args) } else if (Date.now() - startTime >= 60000) { // it's been more than 60 seconds total, bail now debug('TIMEOUT', fn.name, args) var cb = args.pop() if (typeof cb === 'function') cb.call(null, err) } else { // the amount of time between the last attempt and right now var sinceAttempt = Date.now() - lastTime // the amount of time between when we first tried, and when we last tried // rounded up to at least 1 var sinceStart = Math.max(lastTime - startTime, 1) // backoff. wait longer than the total time we've been retrying, but only // up to a maximum of 100ms var desiredDelay = Math.min(sinceStart * 1.2, 100) // it's been long enough since the last retry, do it again if (sinceAttempt >= desiredDelay) { debug('RETRY', fn.name, args) fn.apply(null, args.concat([startTime])) } else { // if we can't do this job yet, push it to the end of the queue // and let the next iteration check again fs[gracefulQueue].push(elem) } } // schedule our next run if one isn't already scheduled if (retryTimer === undefined) { retryTimer = setTimeout(retry, 0) } } /***/ }), /***/ "./node_modules/graceful-fs/legacy-streams.js": /*!****************************************************!*\ !*** ./node_modules/graceful-fs/legacy-streams.js ***! \****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var Stream = (__webpack_require__(/*! stream */ "stream").Stream) module.exports = legacy function legacy (fs) { return { ReadStream: ReadStream, WriteStream: WriteStream } function ReadStream (path, options) { if (!(this instanceof ReadStream)) return new ReadStream(path, options); Stream.call(this); var self = this; this.path = path; this.fd = null; this.readable = true; this.paused = false; this.flags = 'r'; this.mode = 438; /*=0666*/ this.bufferSize = 64 * 1024; options = options || {}; // Mixin options into this var keys = Object.keys(options); for (var index = 0, length = keys.length; index < length; index++) { var key = keys[index]; this[key] = options[key]; } if (this.encoding) this.setEncoding(this.encoding); if (this.start !== undefined) { if ('number' !== typeof this.start) { throw TypeError('start must be a Number'); } if (this.end === undefined) { this.end = Infinity; } else if ('number' !== typeof this.end) { throw TypeError('end must be a Number'); } if (this.start > this.end) { throw new Error('start must be <= end'); } this.pos = this.start; } if (this.fd !== null) { process.nextTick(function() { self._read(); }); return; } fs.open(this.path, this.flags, this.mode, function (err, fd) { if (err) { self.emit('error', err); self.readable = false; return; } self.fd = fd; self.emit('open', fd); self._read(); }) } function WriteStream (path, options) { if (!(this instanceof WriteStream)) return new WriteStream(path, options); Stream.call(this); this.path = path; this.fd = null; this.writable = true; this.flags = 'w'; this.encoding = 'binary'; this.mode = 438; /*=0666*/ this.bytesWritten = 0; options = options || {}; // Mixin options into this var keys = Object.keys(options); for (var index = 0, length = keys.length; index < length; index++) { var key = keys[index]; this[key] = options[key]; } if (this.start !== undefined) { if ('number' !== typeof this.start) { throw TypeError('start must be a Number'); } if (this.start < 0) { throw new Error('start must be >= zero'); } this.pos = this.start; } this.busy = false; this._queue = []; if (this.fd === null) { this._open = fs.open; this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); this.flush(); } } } /***/ }), /***/ "./node_modules/graceful-fs/polyfills.js": /*!***********************************************!*\ !*** ./node_modules/graceful-fs/polyfills.js ***! \***********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var constants = __webpack_require__(/*! constants */ "constants") var origCwd = process.cwd var cwd = null var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform process.cwd = function() { if (!cwd) cwd = origCwd.call(process) return cwd } try { process.cwd() } catch (er) {} // This check is needed until node.js 12 is required if (typeof process.chdir === 'function') { var chdir = process.chdir process.chdir = function (d) { cwd = null chdir.call(process, d) } if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) } module.exports = patch function patch (fs) { // (re-)implement some things that are known busted or missing. // lchmod, broken prior to 0.6.2 // back-port the fix here. if (constants.hasOwnProperty('O_SYMLINK') && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { patchLchmod(fs) } // lutimes implementation, or no-op if (!fs.lutimes) { patchLutimes(fs) } // https://github.com/isaacs/node-graceful-fs/issues/4 // Chown should not fail on einval or eperm if non-root. // It should not fail on enosys ever, as this just indicates // that a fs doesn't support the intended operation. fs.chown = chownFix(fs.chown) fs.fchown = chownFix(fs.fchown) fs.lchown = chownFix(fs.lchown) fs.chmod = chmodFix(fs.chmod) fs.fchmod = chmodFix(fs.fchmod) fs.lchmod = chmodFix(fs.lchmod) fs.chownSync = chownFixSync(fs.chownSync) fs.fchownSync = chownFixSync(fs.fchownSync) fs.lchownSync = chownFixSync(fs.lchownSync) fs.chmodSync = chmodFixSync(fs.chmodSync) fs.fchmodSync = chmodFixSync(fs.fchmodSync) fs.lchmodSync = chmodFixSync(fs.lchmodSync) fs.stat = statFix(fs.stat) fs.fstat = statFix(fs.fstat) fs.lstat = statFix(fs.lstat) fs.statSync = statFixSync(fs.statSync) fs.fstatSync = statFixSync(fs.fstatSync) fs.lstatSync = statFixSync(fs.lstatSync) // if lchmod/lchown do not exist, then make them no-ops if (!fs.lchmod) { fs.lchmod = function (path, mode, cb) { if (cb) process.nextTick(cb) } fs.lchmodSync = function () {} } if (!fs.lchown) { fs.lchown = function (path, uid, gid, cb) { if (cb) process.nextTick(cb) } fs.lchownSync = function () {} } // on Windows, A/V software can lock the directory, causing this // to fail with an EACCES or EPERM if the directory contains newly // created files. Try again on failure, for up to 60 seconds. // Set the timeout this long because some Windows Anti-Virus, such as Parity // bit9, may lock files for up to a minute, causing npm package install // failures. Also, take care to yield the scheduler. Windows scheduling gives // CPU to a busy looping process, which can cause the program causing the lock // contention to be starved of CPU by node, so the contention doesn't resolve. if (platform === "win32") { fs.rename = (function (fs$rename) { return function (from, to, cb) { var start = Date.now() var backoff = 0; fs$rename(from, to, function CB (er) { if (er && (er.code === "EACCES" || er.code === "EPERM") && Date.now() - start < 60000) { setTimeout(function() { fs.stat(to, function (stater, st) { if (stater && stater.code === "ENOENT") fs$rename(from, to, CB); else cb(er) }) }, backoff) if (backoff < 100) backoff += 10; return; } if (cb) cb(er) }) }})(fs.rename) } // if read() returns EAGAIN, then just try it again. fs.read = (function (fs$read) { function read (fd, buffer, offset, length, position, callback_) { var callback if (callback_ && typeof callback_ === 'function') { var eagCounter = 0 callback = function (er, _, __) { if (er && er.code === 'EAGAIN' && eagCounter < 10) { eagCounter ++ return fs$read.call(fs, fd, buffer, offset, length, position, callback) } callback_.apply(this, arguments) } } return fs$read.call(fs, fd, buffer, offset, length, position, callback) } // This ensures `util.promisify` works as it does for native `fs.read`. if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) return read })(fs.read) fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { var eagCounter = 0 while (true) { try { return fs$readSync.call(fs, fd, buffer, offset, length, position) } catch (er) { if (er.code === 'EAGAIN' && eagCounter < 10) { eagCounter ++ continue } throw er } } }})(fs.readSync) function patchLchmod (fs) { fs.lchmod = function (path, mode, callback) { fs.open( path , constants.O_WRONLY | constants.O_SYMLINK , mode , function (err, fd) { if (err) { if (callback) callback(err) return } // prefer to return the chmod error, if one occurs, // but still try to close, and report closing errors if they occur. fs.fchmod(fd, mode, function (err) { fs.close(fd, function(err2) { if (callback) callback(err || err2) }) }) }) } fs.lchmodSync = function (path, mode) { var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) // prefer to return the chmod error, if one occurs, // but still try to close, and report closing errors if they occur. var threw = true var ret try { ret = fs.fchmodSync(fd, mode) threw = false } finally { if (threw) { try { fs.closeSync(fd) } catch (er) {} } else { fs.closeSync(fd) } } return ret } } function patchLutimes (fs) { if (constants.hasOwnProperty("O_SYMLINK")) { fs.lutimes = function (path, at, mt, cb) { fs.open(path, constants.O_SYMLINK, function (er, fd) { if (er) { if (cb) cb(er) return } fs.futimes(fd, at, mt, function (er) { fs.close(fd, function (er2) { if (cb) cb(er || er2) }) }) }) } fs.lutimesSync = function (path, at, mt) { var fd = fs.openSync(path, constants.O_SYMLINK) var ret var threw = true try { ret = fs.futimesSync(fd, at, mt) threw = false } finally { if (threw) { try { fs.closeSync(fd) } catch (er) {} } else { fs.closeSync(fd) } } return ret } } else { fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } fs.lutimesSync = function () {} } } function chmodFix (orig) { if (!orig) return orig return function (target, mode, cb) { return orig.call(fs, target, mode, function (er) { if (chownErOk(er)) er = null if (cb) cb.apply(this, arguments) }) } } function chmodFixSync (orig) { if (!orig) return orig return function (target, mode) { try { return orig.call(fs, target, mode) } catch (er) { if (!chownErOk(er)) throw er } } } function chownFix (orig) { if (!orig) return orig return function (target, uid, gid, cb) { return orig.call(fs, target, uid, gid, function (er) { if (chownErOk(er)) er = null if (cb) cb.apply(this, arguments) }) } } function chownFixSync (orig) { if (!orig) return orig return function (target, uid, gid) { try { return orig.call(fs, target, uid, gid) } catch (er) { if (!chownErOk(er)) throw er } } } function statFix (orig) { if (!orig) return orig // Older versions of Node erroneously returned signed integers for // uid + gid. return function (target, options, cb) { if (typeof options === 'function') { cb = options options = null } function callback (er, stats) { if (stats) { if (stats.uid < 0) stats.uid += 0x100000000 if (stats.gid < 0) stats.gid += 0x100000000 } if (cb) cb.apply(this, arguments) } return options ? orig.call(fs, target, options, callback) : orig.call(fs, target, callback) } } function statFixSync (orig) { if (!orig) return orig // Older versions of Node erroneously returned signed integers for // uid + gid. return function (target, options) { var stats = options ? orig.call(fs, target, options) : orig.call(fs, target) if (stats) { if (stats.uid < 0) stats.uid += 0x100000000 if (stats.gid < 0) stats.gid += 0x100000000 } return stats; } } // ENOSYS means that the fs doesn't support the op. Just ignore // that, because it doesn't matter. // // if there's no getuid, or if getuid() is something other // than 0, and the error is EINVAL or EPERM, then just ignore // it. // // This specific case is a silent failure in cp, install, tar, // and most other unix tools that manage permissions. // // When running as root, or if other types of errors are // encountered, then it's strict. function chownErOk (er) { if (!er) return true if (er.code === "ENOSYS") return true var nonroot = !process.getuid || process.getuid() !== 0 if (nonroot) { if (er.code === "EINVAL" || er.code === "EPERM") return true } return false } } /***/ }), /***/ "./node_modules/har-schema/lib/index.js": /*!**********************************************!*\ !*** ./node_modules/har-schema/lib/index.js ***! \**********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = { afterRequest: __webpack_require__(/*! ./afterRequest.json */ "./node_modules/har-schema/lib/afterRequest.json"), beforeRequest: __webpack_require__(/*! ./beforeRequest.json */ "./node_modules/har-schema/lib/beforeRequest.json"), browser: __webpack_require__(/*! ./browser.json */ "./node_modules/har-schema/lib/browser.json"), cache: __webpack_require__(/*! ./cache.json */ "./node_modules/har-schema/lib/cache.json"), content: __webpack_require__(/*! ./content.json */ "./node_modules/har-schema/lib/content.json"), cookie: __webpack_require__(/*! ./cookie.json */ "./node_modules/har-schema/lib/cookie.json"), creator: __webpack_require__(/*! ./creator.json */ "./node_modules/har-schema/lib/creator.json"), entry: __webpack_require__(/*! ./entry.json */ "./node_modules/har-schema/lib/entry.json"), har: __webpack_require__(/*! ./har.json */ "./node_modules/har-schema/lib/har.json"), header: __webpack_require__(/*! ./header.json */ "./node_modules/har-schema/lib/header.json"), log: __webpack_require__(/*! ./log.json */ "./node_modules/har-schema/lib/log.json"), page: __webpack_require__(/*! ./page.json */ "./node_modules/har-schema/lib/page.json"), pageTimings: __webpack_require__(/*! ./pageTimings.json */ "./node_modules/har-schema/lib/pageTimings.json"), postData: __webpack_require__(/*! ./postData.json */ "./node_modules/har-schema/lib/postData.json"), query: __webpack_require__(/*! ./query.json */ "./node_modules/har-schema/lib/query.json"), request: __webpack_require__(/*! ./request.json */ "./node_modules/har-schema/lib/request.json"), response: __webpack_require__(/*! ./response.json */ "./node_modules/har-schema/lib/response.json"), timings: __webpack_require__(/*! ./timings.json */ "./node_modules/har-schema/lib/timings.json") } /***/ }), /***/ "./node_modules/har-validator/lib/error.js": /*!*************************************************!*\ !*** ./node_modules/har-validator/lib/error.js ***! \*************************************************/ /***/ ((module) => { function HARError (errors) { var message = 'validation failed' this.name = 'HARError' this.message = message this.errors = errors if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor) } else { this.stack = (new Error(message)).stack } } HARError.prototype = Error.prototype module.exports = HARError /***/ }), /***/ "./node_modules/har-validator/lib/promise.js": /*!***************************************************!*\ !*** ./node_modules/har-validator/lib/promise.js ***! \***************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var Ajv = __webpack_require__(/*! ajv */ "./node_modules/ajv/lib/ajv.js") var HARError = __webpack_require__(/*! ./error */ "./node_modules/har-validator/lib/error.js") var schemas = __webpack_require__(/*! har-schema */ "./node_modules/har-schema/lib/index.js") var ajv function createAjvInstance () { var ajv = new Ajv({ allErrors: true }) ajv.addMetaSchema(__webpack_require__(/*! ajv/lib/refs/json-schema-draft-06.json */ "./node_modules/ajv/lib/refs/json-schema-draft-06.json")) ajv.addSchema(schemas) return ajv } function validate (name, data) { data = data || {} // validator config ajv = ajv || createAjvInstance() var validate = ajv.getSchema(name + '.json') return new Promise(function (resolve, reject) { var valid = validate(data) !valid ? reject(new HARError(validate.errors)) : resolve(data) }) } exports.afterRequest = function (data) { return validate('afterRequest', data) } exports.beforeRequest = function (data) { return validate('beforeRequest', data) } exports.browser = function (data) { return validate('browser', data) } exports.cache = function (data) { return validate('cache', data) } exports.content = function (data) { return validate('content', data) } exports.cookie = function (data) { return validate('cookie', data) } exports.creator = function (data) { return validate('creator', data) } exports.entry = function (data) { return validate('entry', data) } exports.har = function (data) { return validate('har', data) } exports.header = function (data) { return validate('header', data) } exports.log = function (data) { return validate('log', data) } exports.page = function (data) { return validate('page', data) } exports.pageTimings = function (data) { return validate('pageTimings', data) } exports.postData = function (data) { return validate('postData', data) } exports.query = function (data) { return validate('query', data) } exports.request = function (data) { return validate('request', data) } exports.response = function (data) { return validate('response', data) } exports.timings = function (data) { return validate('timings', data) } /***/ }), /***/ "./node_modules/http-signature/lib/index.js": /*!**************************************************!*\ !*** ./node_modules/http-signature/lib/index.js ***! \**************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Copyright 2015 Joyent, Inc. var parser = __webpack_require__(/*! ./parser */ "./node_modules/http-signature/lib/parser.js"); var signer = __webpack_require__(/*! ./signer */ "./node_modules/http-signature/lib/signer.js"); var verify = __webpack_require__(/*! ./verify */ "./node_modules/http-signature/lib/verify.js"); var utils = __webpack_require__(/*! ./utils */ "./node_modules/http-signature/lib/utils.js"); ///--- API module.exports = { parse: parser.parseRequest, parseRequest: parser.parseRequest, sign: signer.signRequest, signRequest: signer.signRequest, createSigner: signer.createSigner, isSigner: signer.isSigner, sshKeyToPEM: utils.sshKeyToPEM, sshKeyFingerprint: utils.fingerprint, pemToRsaSSHKey: utils.pemToRsaSSHKey, verify: verify.verifySignature, verifySignature: verify.verifySignature, verifyHMAC: verify.verifyHMAC }; /***/ }), /***/ "./node_modules/http-signature/lib/parser.js": /*!***************************************************!*\ !*** ./node_modules/http-signature/lib/parser.js ***! \***************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Copyright 2012 Joyent, Inc. All rights reserved. var assert = __webpack_require__(/*! assert-plus */ "./node_modules/assert-plus/assert.js"); var util = __webpack_require__(/*! util */ "util"); var utils = __webpack_require__(/*! ./utils */ "./node_modules/http-signature/lib/utils.js"); ///--- Globals var HASH_ALGOS = utils.HASH_ALGOS; var PK_ALGOS = utils.PK_ALGOS; var HttpSignatureError = utils.HttpSignatureError; var InvalidAlgorithmError = utils.InvalidAlgorithmError; var validateAlgorithm = utils.validateAlgorithm; var State = { New: 0, Params: 1 }; var ParamsState = { Name: 0, Quote: 1, Value: 2, Comma: 3 }; ///--- Specific Errors function ExpiredRequestError(message) { HttpSignatureError.call(this, message, ExpiredRequestError); } util.inherits(ExpiredRequestError, HttpSignatureError); function InvalidHeaderError(message) { HttpSignatureError.call(this, message, InvalidHeaderError); } util.inherits(InvalidHeaderError, HttpSignatureError); function InvalidParamsError(message) { HttpSignatureError.call(this, message, InvalidParamsError); } util.inherits(InvalidParamsError, HttpSignatureError); function MissingHeaderError(message) { HttpSignatureError.call(this, message, MissingHeaderError); } util.inherits(MissingHeaderError, HttpSignatureError); function StrictParsingError(message) { HttpSignatureError.call(this, message, StrictParsingError); } util.inherits(StrictParsingError, HttpSignatureError); ///--- Exported API module.exports = { /** * Parses the 'Authorization' header out of an http.ServerRequest object. * * Note that this API will fully validate the Authorization header, and throw * on any error. It will not however check the signature, or the keyId format * as those are specific to your environment. You can use the options object * to pass in extra constraints. * * As a response object you can expect this: * * { * "scheme": "Signature", * "params": { * "keyId": "foo", * "algorithm": "rsa-sha256", * "headers": [ * "date" or "x-date", * "digest" * ], * "signature": "base64" * }, * "signingString": "ready to be passed to crypto.verify()" * } * * @param {Object} request an http.ServerRequest. * @param {Object} options an optional options object with: * - clockSkew: allowed clock skew in seconds (default 300). * - headers: required header names (def: date or x-date) * - algorithms: algorithms to support (default: all). * - strict: should enforce latest spec parsing * (default: false). * @return {Object} parsed out object (see above). * @throws {TypeError} on invalid input. * @throws {InvalidHeaderError} on an invalid Authorization header error. * @throws {InvalidParamsError} if the params in the scheme are invalid. * @throws {MissingHeaderError} if the params indicate a header not present, * either in the request headers from the params, * or not in the params from a required header * in options. * @throws {StrictParsingError} if old attributes are used in strict parsing * mode. * @throws {ExpiredRequestError} if the value of date or x-date exceeds skew. */ parseRequest: function parseRequest(request, options) { assert.object(request, 'request'); assert.object(request.headers, 'request.headers'); if (options === undefined) { options = {}; } if (options.headers === undefined) { options.headers = [request.headers['x-date'] ? 'x-date' : 'date']; } assert.object(options, 'options'); assert.arrayOfString(options.headers, 'options.headers'); assert.optionalFinite(options.clockSkew, 'options.clockSkew'); var authzHeaderName = options.authorizationHeaderName || 'authorization'; if (!request.headers[authzHeaderName]) { throw new MissingHeaderError('no ' + authzHeaderName + ' header ' + 'present in the request'); } options.clockSkew = options.clockSkew || 300; var i = 0; var state = State.New; var substate = ParamsState.Name; var tmpName = ''; var tmpValue = ''; var parsed = { scheme: '', params: {}, signingString: '' }; var authz = request.headers[authzHeaderName]; for (i = 0; i < authz.length; i++) { var c = authz.charAt(i); switch (Number(state)) { case State.New: if (c !== ' ') parsed.scheme += c; else state = State.Params; break; case State.Params: switch (Number(substate)) { case ParamsState.Name: var code = c.charCodeAt(0); // restricted name of A-Z / a-z if ((code >= 0x41 && code <= 0x5a) || // A-Z (code >= 0x61 && code <= 0x7a)) { // a-z tmpName += c; } else if (c === '=') { if (tmpName.length === 0) throw new InvalidHeaderError('bad param format'); substate = ParamsState.Quote; } else { throw new InvalidHeaderError('bad param format'); } break; case ParamsState.Quote: if (c === '"') { tmpValue = ''; substate = ParamsState.Value; } else { throw new InvalidHeaderError('bad param format'); } break; case ParamsState.Value: if (c === '"') { parsed.params[tmpName] = tmpValue; substate = ParamsState.Comma; } else { tmpValue += c; } break; case ParamsState.Comma: if (c === ',') { tmpName = ''; substate = ParamsState.Name; } else { throw new InvalidHeaderError('bad param format'); } break; default: throw new Error('Invalid substate'); } break; default: throw new Error('Invalid substate'); } } if (!parsed.params.headers || parsed.params.headers === '') { if (request.headers['x-date']) { parsed.params.headers = ['x-date']; } else { parsed.params.headers = ['date']; } } else { parsed.params.headers = parsed.params.headers.split(' '); } // Minimally validate the parsed object if (!parsed.scheme || parsed.scheme !== 'Signature') throw new InvalidHeaderError('scheme was not "Signature"'); if (!parsed.params.keyId) throw new InvalidHeaderError('keyId was not specified'); if (!parsed.params.algorithm) throw new InvalidHeaderError('algorithm was not specified'); if (!parsed.params.signature) throw new InvalidHeaderError('signature was not specified'); // Check the algorithm against the official list parsed.params.algorithm = parsed.params.algorithm.toLowerCase(); try { validateAlgorithm(parsed.params.algorithm); } catch (e) { if (e instanceof InvalidAlgorithmError) throw (new InvalidParamsError(parsed.params.algorithm + ' is not ' + 'supported')); else throw (e); } // Build the signingString for (i = 0; i < parsed.params.headers.length; i++) { var h = parsed.params.headers[i].toLowerCase(); parsed.params.headers[i] = h; if (h === 'request-line') { if (!options.strict) { /* * We allow headers from the older spec drafts if strict parsing isn't * specified in options. */ parsed.signingString += request.method + ' ' + request.url + ' HTTP/' + request.httpVersion; } else { /* Strict parsing doesn't allow older draft headers. */ throw (new StrictParsingError('request-line is not a valid header ' + 'with strict parsing enabled.')); } } else if (h === '(request-target)') { parsed.signingString += '(request-target): ' + request.method.toLowerCase() + ' ' + request.url; } else { var value = request.headers[h]; if (value === undefined) throw new MissingHeaderError(h + ' was not in the request'); parsed.signingString += h + ': ' + value; } if ((i + 1) < parsed.params.headers.length) parsed.signingString += '\n'; } // Check against the constraints var date; if (request.headers.date || request.headers['x-date']) { if (request.headers['x-date']) { date = new Date(request.headers['x-date']); } else { date = new Date(request.headers.date); } var now = new Date(); var skew = Math.abs(now.getTime() - date.getTime()); if (skew > options.clockSkew * 1000) { throw new ExpiredRequestError('clock skew of ' + (skew / 1000) + 's was greater than ' + options.clockSkew + 's'); } } options.headers.forEach(function (hdr) { // Remember that we already checked any headers in the params // were in the request, so if this passes we're good. if (parsed.params.headers.indexOf(hdr.toLowerCase()) < 0) throw new MissingHeaderError(hdr + ' was not a signed header'); }); if (options.algorithms) { if (options.algorithms.indexOf(parsed.params.algorithm) === -1) throw new InvalidParamsError(parsed.params.algorithm + ' is not a supported algorithm'); } parsed.algorithm = parsed.params.algorithm.toUpperCase(); parsed.keyId = parsed.params.keyId; return parsed; } }; /***/ }), /***/ "./node_modules/http-signature/lib/signer.js": /*!***************************************************!*\ !*** ./node_modules/http-signature/lib/signer.js ***! \***************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Copyright 2012 Joyent, Inc. All rights reserved. var assert = __webpack_require__(/*! assert-plus */ "./node_modules/assert-plus/assert.js"); var crypto = __webpack_require__(/*! crypto */ "crypto"); var http = __webpack_require__(/*! http */ "http"); var util = __webpack_require__(/*! util */ "util"); var sshpk = __webpack_require__(/*! sshpk */ "./node_modules/sshpk/lib/index.js"); var jsprim = __webpack_require__(/*! jsprim */ "./node_modules/jsprim/lib/jsprim.js"); var utils = __webpack_require__(/*! ./utils */ "./node_modules/http-signature/lib/utils.js"); var sprintf = (__webpack_require__(/*! util */ "util").format); var HASH_ALGOS = utils.HASH_ALGOS; var PK_ALGOS = utils.PK_ALGOS; var InvalidAlgorithmError = utils.InvalidAlgorithmError; var HttpSignatureError = utils.HttpSignatureError; var validateAlgorithm = utils.validateAlgorithm; ///--- Globals var AUTHZ_FMT = 'Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"'; ///--- Specific Errors function MissingHeaderError(message) { HttpSignatureError.call(this, message, MissingHeaderError); } util.inherits(MissingHeaderError, HttpSignatureError); function StrictParsingError(message) { HttpSignatureError.call(this, message, StrictParsingError); } util.inherits(StrictParsingError, HttpSignatureError); /* See createSigner() */ function RequestSigner(options) { assert.object(options, 'options'); var alg = []; if (options.algorithm !== undefined) { assert.string(options.algorithm, 'options.algorithm'); alg = validateAlgorithm(options.algorithm); } this.rs_alg = alg; /* * RequestSigners come in two varieties: ones with an rs_signFunc, and ones * with an rs_signer. * * rs_signFunc-based RequestSigners have to build up their entire signing * string within the rs_lines array and give it to rs_signFunc as a single * concat'd blob. rs_signer-based RequestSigners can add a line at a time to * their signing state by using rs_signer.update(), thus only needing to * buffer the hash function state and one line at a time. */ if (options.sign !== undefined) { assert.func(options.sign, 'options.sign'); this.rs_signFunc = options.sign; } else if (alg[0] === 'hmac' && options.key !== undefined) { assert.string(options.keyId, 'options.keyId'); this.rs_keyId = options.keyId; if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key)) throw (new TypeError('options.key for HMAC must be a string or Buffer')); /* * Make an rs_signer for HMACs, not a rs_signFunc -- HMACs digest their * data in chunks rather than requiring it all to be given in one go * at the end, so they are more similar to signers than signFuncs. */ this.rs_signer = crypto.createHmac(alg[1].toUpperCase(), options.key); this.rs_signer.sign = function () { var digest = this.digest('base64'); return ({ hashAlgorithm: alg[1], toString: function () { return (digest); } }); }; } else if (options.key !== undefined) { var key = options.key; if (typeof (key) === 'string' || Buffer.isBuffer(key)) key = sshpk.parsePrivateKey(key); assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), 'options.key must be a sshpk.PrivateKey'); this.rs_key = key; assert.string(options.keyId, 'options.keyId'); this.rs_keyId = options.keyId; if (!PK_ALGOS[key.type]) { throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' + 'keys are not supported')); } if (alg[0] !== undefined && key.type !== alg[0]) { throw (new InvalidAlgorithmError('options.key must be a ' + alg[0].toUpperCase() + ' key, was given a ' + key.type.toUpperCase() + ' key instead')); } this.rs_signer = key.createSign(alg[1]); } else { throw (new TypeError('options.sign (func) or options.key is required')); } this.rs_headers = []; this.rs_lines = []; } /** * Adds a header to be signed, with its value, into this signer. * * @param {String} header * @param {String} value * @return {String} value written */ RequestSigner.prototype.writeHeader = function (header, value) { assert.string(header, 'header'); header = header.toLowerCase(); assert.string(value, 'value'); this.rs_headers.push(header); if (this.rs_signFunc) { this.rs_lines.push(header + ': ' + value); } else { var line = header + ': ' + value; if (this.rs_headers.length > 0) line = '\n' + line; this.rs_signer.update(line); } return (value); }; /** * Adds a default Date header, returning its value. * * @return {String} */ RequestSigner.prototype.writeDateHeader = function () { return (this.writeHeader('date', jsprim.rfc1123(new Date()))); }; /** * Adds the request target line to be signed. * * @param {String} method, HTTP method (e.g. 'get', 'post', 'put') * @param {String} path */ RequestSigner.prototype.writeTarget = function (method, path) { assert.string(method, 'method'); assert.string(path, 'path'); method = method.toLowerCase(); this.writeHeader('(request-target)', method + ' ' + path); }; /** * Calculate the value for the Authorization header on this request * asynchronously. * * @param {Func} callback (err, authz) */ RequestSigner.prototype.sign = function (cb) { assert.func(cb, 'callback'); if (this.rs_headers.length < 1) throw (new Error('At least one header must be signed')); var alg, authz; if (this.rs_signFunc) { var data = this.rs_lines.join('\n'); var self = this; this.rs_signFunc(data, function (err, sig) { if (err) { cb(err); return; } try { assert.object(sig, 'signature'); assert.string(sig.keyId, 'signature.keyId'); assert.string(sig.algorithm, 'signature.algorithm'); assert.string(sig.signature, 'signature.signature'); alg = validateAlgorithm(sig.algorithm); authz = sprintf(AUTHZ_FMT, sig.keyId, sig.algorithm, self.rs_headers.join(' '), sig.signature); } catch (e) { cb(e); return; } cb(null, authz); }); } else { try { var sigObj = this.rs_signer.sign(); } catch (e) { cb(e); return; } alg = (this.rs_alg[0] || this.rs_key.type) + '-' + sigObj.hashAlgorithm; var signature = sigObj.toString(); authz = sprintf(AUTHZ_FMT, this.rs_keyId, alg, this.rs_headers.join(' '), signature); cb(null, authz); } }; ///--- Exported API module.exports = { /** * Identifies whether a given object is a request signer or not. * * @param {Object} object, the object to identify * @returns {Boolean} */ isSigner: function (obj) { if (typeof (obj) === 'object' && obj instanceof RequestSigner) return (true); return (false); }, /** * Creates a request signer, used to asynchronously build a signature * for a request (does not have to be an http.ClientRequest). * * @param {Object} options, either: * - {String} keyId * - {String|Buffer} key * - {String} algorithm (optional, required for HMAC) * or: * - {Func} sign (data, cb) * @return {RequestSigner} */ createSigner: function createSigner(options) { return (new RequestSigner(options)); }, /** * Adds an 'Authorization' header to an http.ClientRequest object. * * Note that this API will add a Date header if it's not already set. Any * other headers in the options.headers array MUST be present, or this * will throw. * * You shouldn't need to check the return type; it's just there if you want * to be pedantic. * * The optional flag indicates whether parsing should use strict enforcement * of the version draft-cavage-http-signatures-04 of the spec or beyond. * The default is to be loose and support * older versions for compatibility. * * @param {Object} request an instance of http.ClientRequest. * @param {Object} options signing parameters object: * - {String} keyId required. * - {String} key required (either a PEM or HMAC key). * - {Array} headers optional; defaults to ['date']. * - {String} algorithm optional (unless key is HMAC); * default is the same as the sshpk default * signing algorithm for the type of key given * - {String} httpVersion optional; defaults to '1.1'. * - {Boolean} strict optional; defaults to 'false'. * @return {Boolean} true if Authorization (and optionally Date) were added. * @throws {TypeError} on bad parameter types (input). * @throws {InvalidAlgorithmError} if algorithm was bad or incompatible with * the given key. * @throws {sshpk.KeyParseError} if key was bad. * @throws {MissingHeaderError} if a header to be signed was specified but * was not present. */ signRequest: function signRequest(request, options) { assert.object(request, 'request'); assert.object(options, 'options'); assert.optionalString(options.algorithm, 'options.algorithm'); assert.string(options.keyId, 'options.keyId'); assert.optionalArrayOfString(options.headers, 'options.headers'); assert.optionalString(options.httpVersion, 'options.httpVersion'); if (!request.getHeader('Date')) request.setHeader('Date', jsprim.rfc1123(new Date())); if (!options.headers) options.headers = ['date']; if (!options.httpVersion) options.httpVersion = '1.1'; var alg = []; if (options.algorithm) { options.algorithm = options.algorithm.toLowerCase(); alg = validateAlgorithm(options.algorithm); } var i; var stringToSign = ''; for (i = 0; i < options.headers.length; i++) { if (typeof (options.headers[i]) !== 'string') throw new TypeError('options.headers must be an array of Strings'); var h = options.headers[i].toLowerCase(); if (h === 'request-line') { if (!options.strict) { /** * We allow headers from the older spec drafts if strict parsing isn't * specified in options. */ stringToSign += request.method + ' ' + request.path + ' HTTP/' + options.httpVersion; } else { /* Strict parsing doesn't allow older draft headers. */ throw (new StrictParsingError('request-line is not a valid header ' + 'with strict parsing enabled.')); } } else if (h === '(request-target)') { stringToSign += '(request-target): ' + request.method.toLowerCase() + ' ' + request.path; } else { var value = request.getHeader(h); if (value === undefined || value === '') { throw new MissingHeaderError(h + ' was not in the request'); } stringToSign += h + ': ' + value; } if ((i + 1) < options.headers.length) stringToSign += '\n'; } /* This is just for unit tests. */ if (request.hasOwnProperty('_stringToSign')) { request._stringToSign = stringToSign; } var signature; if (alg[0] === 'hmac') { if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key)) throw (new TypeError('options.key must be a string or Buffer')); var hmac = crypto.createHmac(alg[1].toUpperCase(), options.key); hmac.update(stringToSign); signature = hmac.digest('base64'); } else { var key = options.key; if (typeof (key) === 'string' || Buffer.isBuffer(key)) key = sshpk.parsePrivateKey(options.key); assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), 'options.key must be a sshpk.PrivateKey'); if (!PK_ALGOS[key.type]) { throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' + 'keys are not supported')); } if (alg[0] !== undefined && key.type !== alg[0]) { throw (new InvalidAlgorithmError('options.key must be a ' + alg[0].toUpperCase() + ' key, was given a ' + key.type.toUpperCase() + ' key instead')); } var signer = key.createSign(alg[1]); signer.update(stringToSign); var sigObj = signer.sign(); if (!HASH_ALGOS[sigObj.hashAlgorithm]) { throw (new InvalidAlgorithmError(sigObj.hashAlgorithm.toUpperCase() + ' is not a supported hash algorithm')); } options.algorithm = key.type + '-' + sigObj.hashAlgorithm; signature = sigObj.toString(); assert.notStrictEqual(signature, '', 'empty signature produced'); } var authzHeaderName = options.authorizationHeaderName || 'Authorization'; request.setHeader(authzHeaderName, sprintf(AUTHZ_FMT, options.keyId, options.algorithm, options.headers.join(' '), signature)); return true; } }; /***/ }), /***/ "./node_modules/http-signature/lib/utils.js": /*!**************************************************!*\ !*** ./node_modules/http-signature/lib/utils.js ***! \**************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Copyright 2012 Joyent, Inc. All rights reserved. var assert = __webpack_require__(/*! assert-plus */ "./node_modules/assert-plus/assert.js"); var sshpk = __webpack_require__(/*! sshpk */ "./node_modules/sshpk/lib/index.js"); var util = __webpack_require__(/*! util */ "util"); var HASH_ALGOS = { 'sha1': true, 'sha256': true, 'sha512': true }; var PK_ALGOS = { 'rsa': true, 'dsa': true, 'ecdsa': true }; function HttpSignatureError(message, caller) { if (Error.captureStackTrace) Error.captureStackTrace(this, caller || HttpSignatureError); this.message = message; this.name = caller.name; } util.inherits(HttpSignatureError, Error); function InvalidAlgorithmError(message) { HttpSignatureError.call(this, message, InvalidAlgorithmError); } util.inherits(InvalidAlgorithmError, HttpSignatureError); function validateAlgorithm(algorithm) { var alg = algorithm.toLowerCase().split('-'); if (alg.length !== 2) { throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' is not a ' + 'valid algorithm')); } if (alg[0] !== 'hmac' && !PK_ALGOS[alg[0]]) { throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' type keys ' + 'are not supported')); } if (!HASH_ALGOS[alg[1]]) { throw (new InvalidAlgorithmError(alg[1].toUpperCase() + ' is not a ' + 'supported hash algorithm')); } return (alg); } ///--- API module.exports = { HASH_ALGOS: HASH_ALGOS, PK_ALGOS: PK_ALGOS, HttpSignatureError: HttpSignatureError, InvalidAlgorithmError: InvalidAlgorithmError, validateAlgorithm: validateAlgorithm, /** * Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file. * * The intent of this module is to interoperate with OpenSSL only, * specifically the node crypto module's `verify` method. * * @param {String} key an OpenSSH public key. * @return {String} PEM encoded form of the RSA public key. * @throws {TypeError} on bad input. * @throws {Error} on invalid ssh key formatted data. */ sshKeyToPEM: function sshKeyToPEM(key) { assert.string(key, 'ssh_key'); var k = sshpk.parseKey(key, 'ssh'); return (k.toString('pem')); }, /** * Generates an OpenSSH fingerprint from an ssh public key. * * @param {String} key an OpenSSH public key. * @return {String} key fingerprint. * @throws {TypeError} on bad input. * @throws {Error} if what you passed doesn't look like an ssh public key. */ fingerprint: function fingerprint(key) { assert.string(key, 'ssh_key'); var k = sshpk.parseKey(key, 'ssh'); return (k.fingerprint('md5').toString('hex')); }, /** * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa) * * The reverse of the above function. */ pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) { assert.equal('string', typeof (pem), 'typeof pem'); var k = sshpk.parseKey(pem, 'pem'); k.comment = comment; return (k.toString('ssh')); } }; /***/ }), /***/ "./node_modules/http-signature/lib/verify.js": /*!***************************************************!*\ !*** ./node_modules/http-signature/lib/verify.js ***! \***************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Copyright 2015 Joyent, Inc. var assert = __webpack_require__(/*! assert-plus */ "./node_modules/assert-plus/assert.js"); var crypto = __webpack_require__(/*! crypto */ "crypto"); var sshpk = __webpack_require__(/*! sshpk */ "./node_modules/sshpk/lib/index.js"); var utils = __webpack_require__(/*! ./utils */ "./node_modules/http-signature/lib/utils.js"); var HASH_ALGOS = utils.HASH_ALGOS; var PK_ALGOS = utils.PK_ALGOS; var InvalidAlgorithmError = utils.InvalidAlgorithmError; var HttpSignatureError = utils.HttpSignatureError; var validateAlgorithm = utils.validateAlgorithm; ///--- Exported API module.exports = { /** * Verify RSA/DSA signature against public key. You are expected to pass in * an object that was returned from `parse()`. * * @param {Object} parsedSignature the object you got from `parse`. * @param {String} pubkey RSA/DSA private key PEM. * @return {Boolean} true if valid, false otherwise. * @throws {TypeError} if you pass in bad arguments. * @throws {InvalidAlgorithmError} */ verifySignature: function verifySignature(parsedSignature, pubkey) { assert.object(parsedSignature, 'parsedSignature'); if (typeof (pubkey) === 'string' || Buffer.isBuffer(pubkey)) pubkey = sshpk.parseKey(pubkey); assert.ok(sshpk.Key.isKey(pubkey, [1, 1]), 'pubkey must be a sshpk.Key'); var alg = validateAlgorithm(parsedSignature.algorithm); if (alg[0] === 'hmac' || alg[0] !== pubkey.type) return (false); var v = pubkey.createVerify(alg[1]); v.update(parsedSignature.signingString); return (v.verify(parsedSignature.params.signature, 'base64')); }, /** * Verify HMAC against shared secret. You are expected to pass in an object * that was returned from `parse()`. * * @param {Object} parsedSignature the object you got from `parse`. * @param {String} secret HMAC shared secret. * @return {Boolean} true if valid, false otherwise. * @throws {TypeError} if you pass in bad arguments. * @throws {InvalidAlgorithmError} */ verifyHMAC: function verifyHMAC(parsedSignature, secret) { assert.object(parsedSignature, 'parsedHMAC'); assert.string(secret, 'secret'); var alg = validateAlgorithm(parsedSignature.algorithm); if (alg[0] !== 'hmac') return (false); var hashAlg = alg[1].toUpperCase(); var hmac = crypto.createHmac(hashAlg, secret); hmac.update(parsedSignature.signingString); /* * Now double-hash to avoid leaking timing information - there's * no easy constant-time compare in JS, so we use this approach * instead. See for more info: * https://www.isecpartners.com/blog/2011/february/double-hmac- * verification.aspx */ var h1 = crypto.createHmac(hashAlg, secret); h1.update(hmac.digest()); h1 = h1.digest(); var h2 = crypto.createHmac(hashAlg, secret); h2.update(new Buffer(parsedSignature.params.signature, 'base64')); h2 = h2.digest(); /* Node 0.8 returns strings from .digest(). */ if (typeof (h1) === 'string') return (h1 === h2); /* And node 0.10 lacks the .equals() method on Buffers. */ if (Buffer.isBuffer(h1) && !h1.equals) return (h1.toString('binary') === h2.toString('binary')); return (h1.equals(h2)); } }; /***/ }), /***/ "./node_modules/iconv-lite/encodings/dbcs-codec.js": /*!*********************************************************!*\ !*** ./node_modules/iconv-lite/encodings/dbcs-codec.js ***! \*********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var Buffer = (__webpack_require__(/*! safer-buffer */ "./node_modules/safer-buffer/safer.js").Buffer); // Multibyte codec. In this scheme, a character is represented by 1 or more bytes. // Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. // To save memory and loading time, we read table files only when requested. exports._dbcs = DBCSCodec; var UNASSIGNED = -1, GB18030_CODE = -2, SEQ_START = -10, NODE_START = -1000, UNASSIGNED_NODE = new Array(0x100), DEF_CHAR = -1; for (var i = 0; i < 0x100; i++) UNASSIGNED_NODE[i] = UNASSIGNED; // Class DBCSCodec reads and initializes mapping tables. function DBCSCodec(codecOptions, iconv) { this.encodingName = codecOptions.encodingName; if (!codecOptions) throw new Error("DBCS codec is called without the data.") if (!codecOptions.table) throw new Error("Encoding '" + this.encodingName + "' has no data."); // Load tables. var mappingTable = codecOptions.table(); // Decode tables: MBCS -> Unicode. // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. // Trie root is decodeTables[0]. // Values: >= 0 -> unicode character code. can be > 0xFFFF // == UNASSIGNED -> unknown/unassigned sequence. // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. // <= NODE_START -> index of the next node in our trie to process next byte. // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. this.decodeTables = []; this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. this.decodeTableSeq = []; // Actual mapping tables consist of chunks. Use them to fill up decode tables. for (var i = 0; i < mappingTable.length; i++) this._addDecodeChunk(mappingTable[i]); // Load & create GB18030 tables when needed. if (typeof codecOptions.gb18030 === 'function') { this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. // Add GB18030 common decode nodes. var commonThirdByteNodeIdx = this.decodeTables.length; this.decodeTables.push(UNASSIGNED_NODE.slice(0)); var commonFourthByteNodeIdx = this.decodeTables.length; this.decodeTables.push(UNASSIGNED_NODE.slice(0)); // Fill out the tree var firstByteNode = this.decodeTables[0]; for (var i = 0x81; i <= 0xFE; i++) { var secondByteNode = this.decodeTables[NODE_START - firstByteNode[i]]; for (var j = 0x30; j <= 0x39; j++) { if (secondByteNode[j] === UNASSIGNED) { secondByteNode[j] = NODE_START - commonThirdByteNodeIdx; } else if (secondByteNode[j] > NODE_START) { throw new Error("gb18030 decode tables conflict at byte 2"); } var thirdByteNode = this.decodeTables[NODE_START - secondByteNode[j]]; for (var k = 0x81; k <= 0xFE; k++) { if (thirdByteNode[k] === UNASSIGNED) { thirdByteNode[k] = NODE_START - commonFourthByteNodeIdx; } else if (thirdByteNode[k] === NODE_START - commonFourthByteNodeIdx) { continue; } else if (thirdByteNode[k] > NODE_START) { throw new Error("gb18030 decode tables conflict at byte 3"); } var fourthByteNode = this.decodeTables[NODE_START - thirdByteNode[k]]; for (var l = 0x30; l <= 0x39; l++) { if (fourthByteNode[l] === UNASSIGNED) fourthByteNode[l] = GB18030_CODE; } } } } } this.defaultCharUnicode = iconv.defaultCharUnicode; // Encode tables: Unicode -> DBCS. // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). // == UNASSIGNED -> no conversion found. Output a default char. // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. this.encodeTable = []; // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key // means end of sequence (needed when one sequence is a strict subsequence of another). // Objects are kept separately from encodeTable to increase performance. this.encodeTableSeq = []; // Some chars can be decoded, but need not be encoded. var skipEncodeChars = {}; if (codecOptions.encodeSkipVals) for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { var val = codecOptions.encodeSkipVals[i]; if (typeof val === 'number') skipEncodeChars[val] = true; else for (var j = val.from; j <= val.to; j++) skipEncodeChars[j] = true; } // Use decode trie to recursively fill out encode tables. this._fillEncodeTable(0, 0, skipEncodeChars); // Add more encoding pairs when needed. if (codecOptions.encodeAdd) { for (var uChar in codecOptions.encodeAdd) if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); } this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); } DBCSCodec.prototype.encoder = DBCSEncoder; DBCSCodec.prototype.decoder = DBCSDecoder; // Decoder helpers DBCSCodec.prototype._getDecodeTrieNode = function(addr) { var bytes = []; for (; addr > 0; addr >>>= 8) bytes.push(addr & 0xFF); if (bytes.length == 0) bytes.push(0); var node = this.decodeTables[0]; for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. var val = node[bytes[i]]; if (val == UNASSIGNED) { // Create new node. node[bytes[i]] = NODE_START - this.decodeTables.length; this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); } else if (val <= NODE_START) { // Existing node. node = this.decodeTables[NODE_START - val]; } else throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); } return node; } DBCSCodec.prototype._addDecodeChunk = function(chunk) { // First element of chunk is the hex mbcs code where we start. var curAddr = parseInt(chunk[0], 16); // Choose the decoding node where we'll write our chars. var writeTable = this._getDecodeTrieNode(curAddr); curAddr = curAddr & 0xFF; // Write all other elements of the chunk to the table. for (var k = 1; k < chunk.length; k++) { var part = chunk[k]; if (typeof part === "string") { // String, write as-is. for (var l = 0; l < part.length;) { var code = part.charCodeAt(l++); if (0xD800 <= code && code < 0xDC00) { // Decode surrogate var codeTrail = part.charCodeAt(l++); if (0xDC00 <= codeTrail && codeTrail < 0xE000) writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); else throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); } else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) var len = 0xFFF - code + 2; var seq = []; for (var m = 0; m < len; m++) seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; this.decodeTableSeq.push(seq); } else writeTable[curAddr++] = code; // Basic char } } else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. var charCode = writeTable[curAddr - 1] + 1; for (var l = 0; l < part; l++) writeTable[curAddr++] = charCode++; } else throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); } if (curAddr > 0xFF) throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); } // Encoder helpers DBCSCodec.prototype._getEncodeBucket = function(uCode) { var high = uCode >> 8; // This could be > 0xFF because of astral characters. if (this.encodeTable[high] === undefined) this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. return this.encodeTable[high]; } DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { var bucket = this._getEncodeBucket(uCode); var low = uCode & 0xFF; if (bucket[low] <= SEQ_START) this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. else if (bucket[low] == UNASSIGNED) bucket[low] = dbcsCode; } DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { // Get the root of character tree according to first character of the sequence. var uCode = seq[0]; var bucket = this._getEncodeBucket(uCode); var low = uCode & 0xFF; var node; if (bucket[low] <= SEQ_START) { // There's already a sequence with - use it. node = this.encodeTableSeq[SEQ_START-bucket[low]]; } else { // There was no sequence object - allocate a new one. node = {}; if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. bucket[low] = SEQ_START - this.encodeTableSeq.length; this.encodeTableSeq.push(node); } // Traverse the character tree, allocating new nodes as needed. for (var j = 1; j < seq.length-1; j++) { var oldVal = node[uCode]; if (typeof oldVal === 'object') node = oldVal; else { node = node[uCode] = {} if (oldVal !== undefined) node[DEF_CHAR] = oldVal } } // Set the leaf to given dbcsCode. uCode = seq[seq.length-1]; node[uCode] = dbcsCode; } DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { var node = this.decodeTables[nodeIdx]; var hasValues = false; var subNodeEmpty = {}; for (var i = 0; i < 0x100; i++) { var uCode = node[i]; var mbCode = prefix + i; if (skipEncodeChars[mbCode]) continue; if (uCode >= 0) { this._setEncodeChar(uCode, mbCode); hasValues = true; } else if (uCode <= NODE_START) { var subNodeIdx = NODE_START - uCode; if (!subNodeEmpty[subNodeIdx]) { // Skip empty subtrees (they are too large in gb18030). var newPrefix = (mbCode << 8) >>> 0; // NOTE: '>>> 0' keeps 32-bit num positive. if (this._fillEncodeTable(subNodeIdx, newPrefix, skipEncodeChars)) hasValues = true; else subNodeEmpty[subNodeIdx] = true; } } else if (uCode <= SEQ_START) { this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); hasValues = true; } } return hasValues; } // == Encoder ================================================================== function DBCSEncoder(options, codec) { // Encoder state this.leadSurrogate = -1; this.seqObj = undefined; // Static data this.encodeTable = codec.encodeTable; this.encodeTableSeq = codec.encodeTableSeq; this.defaultCharSingleByte = codec.defCharSB; this.gb18030 = codec.gb18030; } DBCSEncoder.prototype.write = function(str) { var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), leadSurrogate = this.leadSurrogate, seqObj = this.seqObj, nextChar = -1, i = 0, j = 0; while (true) { // 0. Get next character. if (nextChar === -1) { if (i == str.length) break; var uCode = str.charCodeAt(i++); } else { var uCode = nextChar; nextChar = -1; } // 1. Handle surrogates. if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. if (uCode < 0xDC00) { // We've got lead surrogate. if (leadSurrogate === -1) { leadSurrogate = uCode; continue; } else { leadSurrogate = uCode; // Double lead surrogate found. uCode = UNASSIGNED; } } else { // We've got trail surrogate. if (leadSurrogate !== -1) { uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); leadSurrogate = -1; } else { // Incomplete surrogate pair - only trail surrogate found. uCode = UNASSIGNED; } } } else if (leadSurrogate !== -1) { // Incomplete surrogate pair - only lead surrogate found. nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. leadSurrogate = -1; } // 2. Convert uCode character. var dbcsCode = UNASSIGNED; if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence var resCode = seqObj[uCode]; if (typeof resCode === 'object') { // Sequence continues. seqObj = resCode; continue; } else if (typeof resCode == 'number') { // Sequence finished. Write it. dbcsCode = resCode; } else if (resCode == undefined) { // Current character is not part of the sequence. // Try default character for this sequence resCode = seqObj[DEF_CHAR]; if (resCode !== undefined) { dbcsCode = resCode; // Found. Write it. nextChar = uCode; // Current character will be written too in the next iteration. } else { // TODO: What if we have no default? (resCode == undefined) // Then, we should write first char of the sequence as-is and try the rest recursively. // Didn't do it for now because no encoding has this situation yet. // Currently, just skip the sequence and write current char. } } seqObj = undefined; } else if (uCode >= 0) { // Regular character var subtable = this.encodeTable[uCode >> 8]; if (subtable !== undefined) dbcsCode = subtable[uCode & 0xFF]; if (dbcsCode <= SEQ_START) { // Sequence start seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; continue; } if (dbcsCode == UNASSIGNED && this.gb18030) { // Use GB18030 algorithm to find character(s) to write. var idx = findIdx(this.gb18030.uChars, uCode); if (idx != -1) { var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; newBuf[j++] = 0x30 + dbcsCode; continue; } } } // 3. Write dbcsCode character. if (dbcsCode === UNASSIGNED) dbcsCode = this.defaultCharSingleByte; if (dbcsCode < 0x100) { newBuf[j++] = dbcsCode; } else if (dbcsCode < 0x10000) { newBuf[j++] = dbcsCode >> 8; // high byte newBuf[j++] = dbcsCode & 0xFF; // low byte } else if (dbcsCode < 0x1000000) { newBuf[j++] = dbcsCode >> 16; newBuf[j++] = (dbcsCode >> 8) & 0xFF; newBuf[j++] = dbcsCode & 0xFF; } else { newBuf[j++] = dbcsCode >>> 24; newBuf[j++] = (dbcsCode >>> 16) & 0xFF; newBuf[j++] = (dbcsCode >>> 8) & 0xFF; newBuf[j++] = dbcsCode & 0xFF; } } this.seqObj = seqObj; this.leadSurrogate = leadSurrogate; return newBuf.slice(0, j); } DBCSEncoder.prototype.end = function() { if (this.leadSurrogate === -1 && this.seqObj === undefined) return; // All clean. Most often case. var newBuf = Buffer.alloc(10), j = 0; if (this.seqObj) { // We're in the sequence. var dbcsCode = this.seqObj[DEF_CHAR]; if (dbcsCode !== undefined) { // Write beginning of the sequence. if (dbcsCode < 0x100) { newBuf[j++] = dbcsCode; } else { newBuf[j++] = dbcsCode >> 8; // high byte newBuf[j++] = dbcsCode & 0xFF; // low byte } } else { // See todo above. } this.seqObj = undefined; } if (this.leadSurrogate !== -1) { // Incomplete surrogate pair - only lead surrogate found. newBuf[j++] = this.defaultCharSingleByte; this.leadSurrogate = -1; } return newBuf.slice(0, j); } // Export for testing DBCSEncoder.prototype.findIdx = findIdx; // == Decoder ================================================================== function DBCSDecoder(options, codec) { // Decoder state this.nodeIdx = 0; this.prevBytes = []; // Static data this.decodeTables = codec.decodeTables; this.decodeTableSeq = codec.decodeTableSeq; this.defaultCharUnicode = codec.defaultCharUnicode; this.gb18030 = codec.gb18030; } DBCSDecoder.prototype.write = function(buf) { var newBuf = Buffer.alloc(buf.length*2), nodeIdx = this.nodeIdx, prevBytes = this.prevBytes, prevOffset = this.prevBytes.length, seqStart = -this.prevBytes.length, // idx of the start of current parsed sequence. uCode; for (var i = 0, j = 0; i < buf.length; i++) { var curByte = (i >= 0) ? buf[i] : prevBytes[i + prevOffset]; // Lookup in current trie node. var uCode = this.decodeTables[nodeIdx][curByte]; if (uCode >= 0) { // Normal character, just use it. } else if (uCode === UNASSIGNED) { // Unknown char. // TODO: Callback with seq. uCode = this.defaultCharUnicode.charCodeAt(0); i = seqStart; // Skip one byte ('i' will be incremented by the for loop) and try to parse again. } else if (uCode === GB18030_CODE) { if (i >= 3) { var ptr = (buf[i-3]-0x81)*12600 + (buf[i-2]-0x30)*1260 + (buf[i-1]-0x81)*10 + (curByte-0x30); } else { var ptr = (prevBytes[i-3+prevOffset]-0x81)*12600 + (((i-2 >= 0) ? buf[i-2] : prevBytes[i-2+prevOffset])-0x30)*1260 + (((i-1 >= 0) ? buf[i-1] : prevBytes[i-1+prevOffset])-0x81)*10 + (curByte-0x30); } var idx = findIdx(this.gb18030.gbChars, ptr); uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; } else if (uCode <= NODE_START) { // Go to next trie node. nodeIdx = NODE_START - uCode; continue; } else if (uCode <= SEQ_START) { // Output a sequence of chars. var seq = this.decodeTableSeq[SEQ_START - uCode]; for (var k = 0; k < seq.length - 1; k++) { uCode = seq[k]; newBuf[j++] = uCode & 0xFF; newBuf[j++] = uCode >> 8; } uCode = seq[seq.length-1]; } else throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); // Write the character to buffer, handling higher planes using surrogate pair. if (uCode >= 0x10000) { uCode -= 0x10000; var uCodeLead = 0xD800 | (uCode >> 10); newBuf[j++] = uCodeLead & 0xFF; newBuf[j++] = uCodeLead >> 8; uCode = 0xDC00 | (uCode & 0x3FF); } newBuf[j++] = uCode & 0xFF; newBuf[j++] = uCode >> 8; // Reset trie node. nodeIdx = 0; seqStart = i+1; } this.nodeIdx = nodeIdx; this.prevBytes = (seqStart >= 0) ? Array.prototype.slice.call(buf, seqStart) : prevBytes.slice(seqStart + prevOffset).concat(Array.prototype.slice.call(buf)); return newBuf.slice(0, j).toString('ucs2'); } DBCSDecoder.prototype.end = function() { var ret = ''; // Try to parse all remaining chars. while (this.prevBytes.length > 0) { // Skip 1 character in the buffer. ret += this.defaultCharUnicode; var bytesArr = this.prevBytes.slice(1); // Parse remaining as usual. this.prevBytes = []; this.nodeIdx = 0; if (bytesArr.length > 0) ret += this.write(bytesArr); } this.prevBytes = []; this.nodeIdx = 0; return ret; } // Binary search for GB18030. Returns largest i such that table[i] <= val. function findIdx(table, val) { if (table[0] > val) return -1; var l = 0, r = table.length; while (l < r-1) { // always table[l] <= val < table[r] var mid = l + ((r-l+1) >> 1); if (table[mid] <= val) l = mid; else r = mid; } return l; } /***/ }), /***/ "./node_modules/iconv-lite/encodings/dbcs-data.js": /*!********************************************************!*\ !*** ./node_modules/iconv-lite/encodings/dbcs-data.js ***! \********************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Description of supported double byte encodings and aliases. // Tables are not require()-d until they are needed to speed up library load. // require()-s are direct to support Browserify. module.exports = { // == Japanese/ShiftJIS ==================================================== // All japanese encodings are based on JIS X set of standards: // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. // Has several variations in 1978, 1983, 1990 and 1997. // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. // 2 planes, first is superset of 0208, second - revised 0212. // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) // Byte encodings are: // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. // 0x00-0x7F - lower part of 0201 // 0x8E, 0xA1-0xDF - upper part of 0201 // (0xA1-0xFE)x2 - 0208 plane (94x94). // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. // Used as-is in ISO2022 family. // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, // 0201-1976 Roman, 0208-1978, 0208-1983. // * ISO2022-JP-1: Adds esc seq for 0212-1990. // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. // // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. // // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html 'shiftjis': { type: '_dbcs', table: function() { return __webpack_require__(/*! ./tables/shiftjis.json */ "./node_modules/iconv-lite/encodings/tables/shiftjis.json") }, encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, encodeSkipVals: [{from: 0xED40, to: 0xF940}], }, 'csshiftjis': 'shiftjis', 'mskanji': 'shiftjis', 'sjis': 'shiftjis', 'windows31j': 'shiftjis', 'ms31j': 'shiftjis', 'xsjis': 'shiftjis', 'windows932': 'shiftjis', 'ms932': 'shiftjis', '932': 'shiftjis', 'cp932': 'shiftjis', 'eucjp': { type: '_dbcs', table: function() { return __webpack_require__(/*! ./tables/eucjp.json */ "./node_modules/iconv-lite/encodings/tables/eucjp.json") }, encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, }, // TODO: KDDI extension to Shift_JIS // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. // == Chinese/GBK ========================================================== // http://en.wikipedia.org/wiki/GBK // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 'gb2312': 'cp936', 'gb231280': 'cp936', 'gb23121980': 'cp936', 'csgb2312': 'cp936', 'csiso58gb231280': 'cp936', 'euccn': 'cp936', // Microsoft's CP936 is a subset and approximation of GBK. 'windows936': 'cp936', 'ms936': 'cp936', '936': 'cp936', 'cp936': { type: '_dbcs', table: function() { return __webpack_require__(/*! ./tables/cp936.json */ "./node_modules/iconv-lite/encodings/tables/cp936.json") }, }, // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. 'gbk': { type: '_dbcs', table: function() { return (__webpack_require__(/*! ./tables/cp936.json */ "./node_modules/iconv-lite/encodings/tables/cp936.json").concat)(__webpack_require__(/*! ./tables/gbk-added.json */ "./node_modules/iconv-lite/encodings/tables/gbk-added.json")) }, }, 'xgbk': 'gbk', 'isoir58': 'gbk', // GB18030 is an algorithmic extension of GBK. // Main source: https://www.w3.org/TR/encoding/#gbk-encoder // http://icu-project.org/docs/papers/gb18030.html // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 'gb18030': { type: '_dbcs', table: function() { return (__webpack_require__(/*! ./tables/cp936.json */ "./node_modules/iconv-lite/encodings/tables/cp936.json").concat)(__webpack_require__(/*! ./tables/gbk-added.json */ "./node_modules/iconv-lite/encodings/tables/gbk-added.json")) }, gb18030: function() { return __webpack_require__(/*! ./tables/gb18030-ranges.json */ "./node_modules/iconv-lite/encodings/tables/gb18030-ranges.json") }, encodeSkipVals: [0x80], encodeAdd: {'€': 0xA2E3}, }, 'chinese': 'gb18030', // == Korean =============================================================== // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. 'windows949': 'cp949', 'ms949': 'cp949', '949': 'cp949', 'cp949': { type: '_dbcs', table: function() { return __webpack_require__(/*! ./tables/cp949.json */ "./node_modules/iconv-lite/encodings/tables/cp949.json") }, }, 'cseuckr': 'cp949', 'csksc56011987': 'cp949', 'euckr': 'cp949', 'isoir149': 'cp949', 'korean': 'cp949', 'ksc56011987': 'cp949', 'ksc56011989': 'cp949', 'ksc5601': 'cp949', // == Big5/Taiwan/Hong Kong ================================================ // There are lots of tables for Big5 and cp950. Please see the following links for history: // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html // Variations, in roughly number of defined chars: // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ // * Big5-2003 (Taiwan standard) almost superset of cp950. // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. // Plus, it has 4 combining sequences. // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. // Implementations are not consistent within browsers; sometimes labeled as just big5. // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt // // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. 'windows950': 'cp950', 'ms950': 'cp950', '950': 'cp950', 'cp950': { type: '_dbcs', table: function() { return __webpack_require__(/*! ./tables/cp950.json */ "./node_modules/iconv-lite/encodings/tables/cp950.json") }, }, // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. 'big5': 'big5hkscs', 'big5hkscs': { type: '_dbcs', table: function() { return (__webpack_require__(/*! ./tables/cp950.json */ "./node_modules/iconv-lite/encodings/tables/cp950.json").concat)(__webpack_require__(/*! ./tables/big5-added.json */ "./node_modules/iconv-lite/encodings/tables/big5-added.json")) }, encodeSkipVals: [ // Although Encoding Standard says we should avoid encoding to HKSCS area (See Step 1 of // https://encoding.spec.whatwg.org/#index-big5-pointer), we still do it to increase compatibility with ICU. // But if a single unicode point can be encoded both as HKSCS and regular Big5, we prefer the latter. 0x8e69, 0x8e6f, 0x8e7e, 0x8eab, 0x8eb4, 0x8ecd, 0x8ed0, 0x8f57, 0x8f69, 0x8f6e, 0x8fcb, 0x8ffe, 0x906d, 0x907a, 0x90c4, 0x90dc, 0x90f1, 0x91bf, 0x92af, 0x92b0, 0x92b1, 0x92b2, 0x92d1, 0x9447, 0x94ca, 0x95d9, 0x96fc, 0x9975, 0x9b76, 0x9b78, 0x9b7b, 0x9bc6, 0x9bde, 0x9bec, 0x9bf6, 0x9c42, 0x9c53, 0x9c62, 0x9c68, 0x9c6b, 0x9c77, 0x9cbc, 0x9cbd, 0x9cd0, 0x9d57, 0x9d5a, 0x9dc4, 0x9def, 0x9dfb, 0x9ea9, 0x9eef, 0x9efd, 0x9f60, 0x9fcb, 0xa077, 0xa0dc, 0xa0df, 0x8fcc, 0x92c8, 0x9644, 0x96ed, // Step 2 of https://encoding.spec.whatwg.org/#index-big5-pointer: Use last pointer for U+2550, U+255E, U+2561, U+256A, U+5341, or U+5345 0xa2a4, 0xa2a5, 0xa2a7, 0xa2a6, 0xa2cc, 0xa2ce, ], }, 'cnbig5': 'big5hkscs', 'csbig5': 'big5hkscs', 'xxbig5': 'big5hkscs', }; /***/ }), /***/ "./node_modules/iconv-lite/encodings/index.js": /*!****************************************************!*\ !*** ./node_modules/iconv-lite/encodings/index.js ***! \****************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Update this array if you add/rename/remove files in this directory. // We support Browserify by skipping automatic module discovery and requiring modules directly. var modules = [ __webpack_require__(/*! ./internal */ "./node_modules/iconv-lite/encodings/internal.js"), __webpack_require__(/*! ./utf32 */ "./node_modules/iconv-lite/encodings/utf32.js"), __webpack_require__(/*! ./utf16 */ "./node_modules/iconv-lite/encodings/utf16.js"), __webpack_require__(/*! ./utf7 */ "./node_modules/iconv-lite/encodings/utf7.js"), __webpack_require__(/*! ./sbcs-codec */ "./node_modules/iconv-lite/encodings/sbcs-codec.js"), __webpack_require__(/*! ./sbcs-data */ "./node_modules/iconv-lite/encodings/sbcs-data.js"), __webpack_require__(/*! ./sbcs-data-generated */ "./node_modules/iconv-lite/encodings/sbcs-data-generated.js"), __webpack_require__(/*! ./dbcs-codec */ "./node_modules/iconv-lite/encodings/dbcs-codec.js"), __webpack_require__(/*! ./dbcs-data */ "./node_modules/iconv-lite/encodings/dbcs-data.js"), ]; // Put all encoding/alias/codec definitions to single object and export it. for (var i = 0; i < modules.length; i++) { var module = modules[i]; for (var enc in module) if (Object.prototype.hasOwnProperty.call(module, enc)) exports[enc] = module[enc]; } /***/ }), /***/ "./node_modules/iconv-lite/encodings/internal.js": /*!*******************************************************!*\ !*** ./node_modules/iconv-lite/encodings/internal.js ***! \*******************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Buffer = (__webpack_require__(/*! safer-buffer */ "./node_modules/safer-buffer/safer.js").Buffer); // Export Node.js internal encodings. module.exports = { // Encodings utf8: { type: "_internal", bomAware: true}, cesu8: { type: "_internal", bomAware: true}, unicode11utf8: "utf8", ucs2: { type: "_internal", bomAware: true}, utf16le: "ucs2", binary: { type: "_internal" }, base64: { type: "_internal" }, hex: { type: "_internal" }, // Codec. _internal: InternalCodec, }; //------------------------------------------------------------------------------ function InternalCodec(codecOptions, iconv) { this.enc = codecOptions.encodingName; this.bomAware = codecOptions.bomAware; if (this.enc === "base64") this.encoder = InternalEncoderBase64; else if (this.enc === "cesu8") { this.enc = "utf8"; // Use utf8 for decoding. this.encoder = InternalEncoderCesu8; // Add decoder for versions of Node not supporting CESU-8 if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { this.decoder = InternalDecoderCesu8; this.defaultCharUnicode = iconv.defaultCharUnicode; } } } InternalCodec.prototype.encoder = InternalEncoder; InternalCodec.prototype.decoder = InternalDecoder; //------------------------------------------------------------------------------ // We use node.js internal decoder. Its signature is the same as ours. var StringDecoder = (__webpack_require__(/*! string_decoder */ "string_decoder").StringDecoder); if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. StringDecoder.prototype.end = function() {}; function InternalDecoder(options, codec) { this.decoder = new StringDecoder(codec.enc); } InternalDecoder.prototype.write = function(buf) { if (!Buffer.isBuffer(buf)) { buf = Buffer.from(buf); } return this.decoder.write(buf); } InternalDecoder.prototype.end = function() { return this.decoder.end(); } //------------------------------------------------------------------------------ // Encoder is mostly trivial function InternalEncoder(options, codec) { this.enc = codec.enc; } InternalEncoder.prototype.write = function(str) { return Buffer.from(str, this.enc); } InternalEncoder.prototype.end = function() { } //------------------------------------------------------------------------------ // Except base64 encoder, which must keep its state. function InternalEncoderBase64(options, codec) { this.prevStr = ''; } InternalEncoderBase64.prototype.write = function(str) { str = this.prevStr + str; var completeQuads = str.length - (str.length % 4); this.prevStr = str.slice(completeQuads); str = str.slice(0, completeQuads); return Buffer.from(str, "base64"); } InternalEncoderBase64.prototype.end = function() { return Buffer.from(this.prevStr, "base64"); } //------------------------------------------------------------------------------ // CESU-8 encoder is also special. function InternalEncoderCesu8(options, codec) { } InternalEncoderCesu8.prototype.write = function(str) { var buf = Buffer.alloc(str.length * 3), bufIdx = 0; for (var i = 0; i < str.length; i++) { var charCode = str.charCodeAt(i); // Naive implementation, but it works because CESU-8 is especially easy // to convert from UTF-16 (which all JS strings are encoded in). if (charCode < 0x80) buf[bufIdx++] = charCode; else if (charCode < 0x800) { buf[bufIdx++] = 0xC0 + (charCode >>> 6); buf[bufIdx++] = 0x80 + (charCode & 0x3f); } else { // charCode will always be < 0x10000 in javascript. buf[bufIdx++] = 0xE0 + (charCode >>> 12); buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); buf[bufIdx++] = 0x80 + (charCode & 0x3f); } } return buf.slice(0, bufIdx); } InternalEncoderCesu8.prototype.end = function() { } //------------------------------------------------------------------------------ // CESU-8 decoder is not implemented in Node v4.0+ function InternalDecoderCesu8(options, codec) { this.acc = 0; this.contBytes = 0; this.accBytes = 0; this.defaultCharUnicode = codec.defaultCharUnicode; } InternalDecoderCesu8.prototype.write = function(buf) { var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, res = ''; for (var i = 0; i < buf.length; i++) { var curByte = buf[i]; if ((curByte & 0xC0) !== 0x80) { // Leading byte if (contBytes > 0) { // Previous code is invalid res += this.defaultCharUnicode; contBytes = 0; } if (curByte < 0x80) { // Single-byte code res += String.fromCharCode(curByte); } else if (curByte < 0xE0) { // Two-byte code acc = curByte & 0x1F; contBytes = 1; accBytes = 1; } else if (curByte < 0xF0) { // Three-byte code acc = curByte & 0x0F; contBytes = 2; accBytes = 1; } else { // Four or more are not supported for CESU-8. res += this.defaultCharUnicode; } } else { // Continuation byte if (contBytes > 0) { // We're waiting for it. acc = (acc << 6) | (curByte & 0x3f); contBytes--; accBytes++; if (contBytes === 0) { // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) if (accBytes === 2 && acc < 0x80 && acc > 0) res += this.defaultCharUnicode; else if (accBytes === 3 && acc < 0x800) res += this.defaultCharUnicode; else // Actually add character. res += String.fromCharCode(acc); } } else { // Unexpected continuation byte res += this.defaultCharUnicode; } } } this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; return res; } InternalDecoderCesu8.prototype.end = function() { var res = 0; if (this.contBytes > 0) res += this.defaultCharUnicode; return res; } /***/ }), /***/ "./node_modules/iconv-lite/encodings/sbcs-codec.js": /*!*********************************************************!*\ !*** ./node_modules/iconv-lite/encodings/sbcs-codec.js ***! \*********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var Buffer = (__webpack_require__(/*! safer-buffer */ "./node_modules/safer-buffer/safer.js").Buffer); // Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that // correspond to encoded bytes (if 128 - then lower half is ASCII). exports._sbcs = SBCSCodec; function SBCSCodec(codecOptions, iconv) { if (!codecOptions) throw new Error("SBCS codec is called without the data.") // Prepare char buffer for decoding. if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); if (codecOptions.chars.length === 128) { var asciiString = ""; for (var i = 0; i < 128; i++) asciiString += String.fromCharCode(i); codecOptions.chars = asciiString + codecOptions.chars; } this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); // Encoding buffer. var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); for (var i = 0; i < codecOptions.chars.length; i++) encodeBuf[codecOptions.chars.charCodeAt(i)] = i; this.encodeBuf = encodeBuf; } SBCSCodec.prototype.encoder = SBCSEncoder; SBCSCodec.prototype.decoder = SBCSDecoder; function SBCSEncoder(options, codec) { this.encodeBuf = codec.encodeBuf; } SBCSEncoder.prototype.write = function(str) { var buf = Buffer.alloc(str.length); for (var i = 0; i < str.length; i++) buf[i] = this.encodeBuf[str.charCodeAt(i)]; return buf; } SBCSEncoder.prototype.end = function() { } function SBCSDecoder(options, codec) { this.decodeBuf = codec.decodeBuf; } SBCSDecoder.prototype.write = function(buf) { // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. var decodeBuf = this.decodeBuf; var newBuf = Buffer.alloc(buf.length*2); var idx1 = 0, idx2 = 0; for (var i = 0; i < buf.length; i++) { idx1 = buf[i]*2; idx2 = i*2; newBuf[idx2] = decodeBuf[idx1]; newBuf[idx2+1] = decodeBuf[idx1+1]; } return newBuf.toString('ucs2'); } SBCSDecoder.prototype.end = function() { } /***/ }), /***/ "./node_modules/iconv-lite/encodings/sbcs-data-generated.js": /*!******************************************************************!*\ !*** ./node_modules/iconv-lite/encodings/sbcs-data-generated.js ***! \******************************************************************/ /***/ ((module) => { "use strict"; // Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. module.exports = { "437": "cp437", "737": "cp737", "775": "cp775", "850": "cp850", "852": "cp852", "855": "cp855", "856": "cp856", "857": "cp857", "858": "cp858", "860": "cp860", "861": "cp861", "862": "cp862", "863": "cp863", "864": "cp864", "865": "cp865", "866": "cp866", "869": "cp869", "874": "windows874", "922": "cp922", "1046": "cp1046", "1124": "cp1124", "1125": "cp1125", "1129": "cp1129", "1133": "cp1133", "1161": "cp1161", "1162": "cp1162", "1163": "cp1163", "1250": "windows1250", "1251": "windows1251", "1252": "windows1252", "1253": "windows1253", "1254": "windows1254", "1255": "windows1255", "1256": "windows1256", "1257": "windows1257", "1258": "windows1258", "28591": "iso88591", "28592": "iso88592", "28593": "iso88593", "28594": "iso88594", "28595": "iso88595", "28596": "iso88596", "28597": "iso88597", "28598": "iso88598", "28599": "iso88599", "28600": "iso885910", "28601": "iso885911", "28603": "iso885913", "28604": "iso885914", "28605": "iso885915", "28606": "iso885916", "windows874": { "type": "_sbcs", "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" }, "win874": "windows874", "cp874": "windows874", "windows1250": { "type": "_sbcs", "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" }, "win1250": "windows1250", "cp1250": "windows1250", "windows1251": { "type": "_sbcs", "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" }, "win1251": "windows1251", "cp1251": "windows1251", "windows1252": { "type": "_sbcs", "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" }, "win1252": "windows1252", "cp1252": "windows1252", "windows1253": { "type": "_sbcs", "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" }, "win1253": "windows1253", "cp1253": "windows1253", "windows1254": { "type": "_sbcs", "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" }, "win1254": "windows1254", "cp1254": "windows1254", "windows1255": { "type": "_sbcs", "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" }, "win1255": "windows1255", "cp1255": "windows1255", "windows1256": { "type": "_sbcs", "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" }, "win1256": "windows1256", "cp1256": "windows1256", "windows1257": { "type": "_sbcs", "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" }, "win1257": "windows1257", "cp1257": "windows1257", "windows1258": { "type": "_sbcs", "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" }, "win1258": "windows1258", "cp1258": "windows1258", "iso88591": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" }, "cp28591": "iso88591", "iso88592": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" }, "cp28592": "iso88592", "iso88593": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" }, "cp28593": "iso88593", "iso88594": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤Ĩϧ¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" }, "cp28594": "iso88594", "iso88595": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" }, "cp28595": "iso88595", "iso88596": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" }, "cp28596": "iso88596", "iso88597": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" }, "cp28597": "iso88597", "iso88598": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" }, "cp28598": "iso88598", "iso88599": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" }, "cp28599": "iso88599", "iso885910": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨͧĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" }, "cp28600": "iso885910", "iso885911": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" }, "cp28601": "iso885911", "iso885913": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" }, "cp28603": "iso885913", "iso885914": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" }, "cp28604": "iso885914", "iso885915": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" }, "cp28605": "iso885915", "iso885916": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Чš©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" }, "cp28606": "iso885916", "cp437": { "type": "_sbcs", "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " }, "ibm437": "cp437", "csibm437": "cp437", "cp737": { "type": "_sbcs", "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " }, "ibm737": "cp737", "csibm737": "cp737", "cp775": { "type": "_sbcs", "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " }, "ibm775": "cp775", "csibm775": "cp775", "cp850": { "type": "_sbcs", "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " }, "ibm850": "cp850", "csibm850": "cp850", "cp852": { "type": "_sbcs", "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " }, "ibm852": "cp852", "csibm852": "cp852", "cp855": { "type": "_sbcs", "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " }, "ibm855": "cp855", "csibm855": "cp855", "cp856": { "type": "_sbcs", "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " }, "ibm856": "cp856", "csibm856": "cp856", "cp857": { "type": "_sbcs", "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " }, "ibm857": "cp857", "csibm857": "cp857", "cp858": { "type": "_sbcs", "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " }, "ibm858": "cp858", "csibm858": "cp858", "cp860": { "type": "_sbcs", "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " }, "ibm860": "cp860", "csibm860": "cp860", "cp861": { "type": "_sbcs", "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " }, "ibm861": "cp861", "csibm861": "cp861", "cp862": { "type": "_sbcs", "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " }, "ibm862": "cp862", "csibm862": "cp862", "cp863": { "type": "_sbcs", "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " }, "ibm863": "cp863", "csibm863": "cp863", "cp864": { "type": "_sbcs", "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" }, "ibm864": "cp864", "csibm864": "cp864", "cp865": { "type": "_sbcs", "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " }, "ibm865": "cp865", "csibm865": "cp865", "cp866": { "type": "_sbcs", "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " }, "ibm866": "cp866", "csibm866": "cp866", "cp869": { "type": "_sbcs", "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " }, "ibm869": "cp869", "csibm869": "cp869", "cp922": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" }, "ibm922": "cp922", "csibm922": "cp922", "cp1046": { "type": "_sbcs", "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" }, "ibm1046": "cp1046", "csibm1046": "cp1046", "cp1124": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" }, "ibm1124": "cp1124", "csibm1124": "cp1124", "cp1125": { "type": "_sbcs", "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " }, "ibm1125": "cp1125", "csibm1125": "cp1125", "cp1129": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" }, "ibm1129": "cp1129", "csibm1129": "cp1129", "cp1133": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" }, "ibm1133": "cp1133", "csibm1133": "cp1133", "cp1161": { "type": "_sbcs", "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " }, "ibm1161": "cp1161", "csibm1161": "cp1161", "cp1162": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" }, "ibm1162": "cp1162", "csibm1162": "cp1162", "cp1163": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" }, "ibm1163": "cp1163", "csibm1163": "cp1163", "maccroatian": { "type": "_sbcs", "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" }, "maccyrillic": { "type": "_sbcs", "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" }, "macgreek": { "type": "_sbcs", "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" }, "maciceland": { "type": "_sbcs", "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" }, "macroman": { "type": "_sbcs", "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" }, "macromania": { "type": "_sbcs", "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" }, "macthai": { "type": "_sbcs", "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" }, "macturkish": { "type": "_sbcs", "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" }, "macukraine": { "type": "_sbcs", "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" }, "koi8r": { "type": "_sbcs", "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" }, "koi8u": { "type": "_sbcs", "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" }, "koi8ru": { "type": "_sbcs", "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" }, "koi8t": { "type": "_sbcs", "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" }, "armscii8": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" }, "rk1048": { "type": "_sbcs", "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" }, "tcvn": { "type": "_sbcs", "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" }, "georgianacademy": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" }, "georgianps": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" }, "pt154": { "type": "_sbcs", "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" }, "viscii": { "type": "_sbcs", "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" }, "iso646cn": { "type": "_sbcs", "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" }, "iso646jp": { "type": "_sbcs", "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" }, "hproman8": { "type": "_sbcs", "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" }, "macintosh": { "type": "_sbcs", "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" }, "ascii": { "type": "_sbcs", "chars": "��������������������������������������������������������������������������������������������������������������������������������" }, "tis620": { "type": "_sbcs", "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" } } /***/ }), /***/ "./node_modules/iconv-lite/encodings/sbcs-data.js": /*!********************************************************!*\ !*** ./node_modules/iconv-lite/encodings/sbcs-data.js ***! \********************************************************/ /***/ ((module) => { "use strict"; // Manually added data to be used by sbcs codec in addition to generated one. module.exports = { // Not supported by iconv, not sure why. "10029": "maccenteuro", "maccenteuro": { "type": "_sbcs", "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" }, "808": "cp808", "ibm808": "cp808", "cp808": { "type": "_sbcs", "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " }, "mik": { "type": "_sbcs", "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " }, "cp720": { "type": "_sbcs", "chars": "\x80\x81éâ\x84à\x86çêëèïî\x8d\x8e\x8f\x90\u0651\u0652ô¤ـûùءآأؤ£إئابةتثجحخدذرزسشص«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ضطظعغفµقكلمنهوىي≡\u064b\u064c\u064d\u064e\u064f\u0650≈°∙·√ⁿ²■\u00a0" }, // Aliases of generated encodings. "ascii8bit": "ascii", "usascii": "ascii", "ansix34": "ascii", "ansix341968": "ascii", "ansix341986": "ascii", "csascii": "ascii", "cp367": "ascii", "ibm367": "ascii", "isoir6": "ascii", "iso646us": "ascii", "iso646irv": "ascii", "us": "ascii", "latin1": "iso88591", "latin2": "iso88592", "latin3": "iso88593", "latin4": "iso88594", "latin5": "iso88599", "latin6": "iso885910", "latin7": "iso885913", "latin8": "iso885914", "latin9": "iso885915", "latin10": "iso885916", "csisolatin1": "iso88591", "csisolatin2": "iso88592", "csisolatin3": "iso88593", "csisolatin4": "iso88594", "csisolatincyrillic": "iso88595", "csisolatinarabic": "iso88596", "csisolatingreek" : "iso88597", "csisolatinhebrew": "iso88598", "csisolatin5": "iso88599", "csisolatin6": "iso885910", "l1": "iso88591", "l2": "iso88592", "l3": "iso88593", "l4": "iso88594", "l5": "iso88599", "l6": "iso885910", "l7": "iso885913", "l8": "iso885914", "l9": "iso885915", "l10": "iso885916", "isoir14": "iso646jp", "isoir57": "iso646cn", "isoir100": "iso88591", "isoir101": "iso88592", "isoir109": "iso88593", "isoir110": "iso88594", "isoir144": "iso88595", "isoir127": "iso88596", "isoir126": "iso88597", "isoir138": "iso88598", "isoir148": "iso88599", "isoir157": "iso885910", "isoir166": "tis620", "isoir179": "iso885913", "isoir199": "iso885914", "isoir203": "iso885915", "isoir226": "iso885916", "cp819": "iso88591", "ibm819": "iso88591", "cyrillic": "iso88595", "arabic": "iso88596", "arabic8": "iso88596", "ecma114": "iso88596", "asmo708": "iso88596", "greek" : "iso88597", "greek8" : "iso88597", "ecma118" : "iso88597", "elot928" : "iso88597", "hebrew": "iso88598", "hebrew8": "iso88598", "turkish": "iso88599", "turkish8": "iso88599", "thai": "iso885911", "thai8": "iso885911", "celtic": "iso885914", "celtic8": "iso885914", "isoceltic": "iso885914", "tis6200": "tis620", "tis62025291": "tis620", "tis62025330": "tis620", "10000": "macroman", "10006": "macgreek", "10007": "maccyrillic", "10079": "maciceland", "10081": "macturkish", "cspc8codepage437": "cp437", "cspc775baltic": "cp775", "cspc850multilingual": "cp850", "cspcp852": "cp852", "cspc862latinhebrew": "cp862", "cpgr": "cp869", "msee": "cp1250", "mscyrl": "cp1251", "msansi": "cp1252", "msgreek": "cp1253", "msturk": "cp1254", "mshebr": "cp1255", "msarab": "cp1256", "winbaltrim": "cp1257", "cp20866": "koi8r", "20866": "koi8r", "ibm878": "koi8r", "cskoi8r": "koi8r", "cp21866": "koi8u", "21866": "koi8u", "ibm1168": "koi8u", "strk10482002": "rk1048", "tcvn5712": "tcvn", "tcvn57121": "tcvn", "gb198880": "iso646cn", "cn": "iso646cn", "csiso14jisc6220ro": "iso646jp", "jisc62201969ro": "iso646jp", "jp": "iso646jp", "cshproman8": "hproman8", "r8": "hproman8", "roman8": "hproman8", "xroman8": "hproman8", "ibm1051": "hproman8", "mac": "macintosh", "csmacintosh": "macintosh", }; /***/ }), /***/ "./node_modules/iconv-lite/encodings/utf16.js": /*!****************************************************!*\ !*** ./node_modules/iconv-lite/encodings/utf16.js ***! \****************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var Buffer = (__webpack_require__(/*! safer-buffer */ "./node_modules/safer-buffer/safer.js").Buffer); // Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js // == UTF16-BE codec. ========================================================== exports.utf16be = Utf16BECodec; function Utf16BECodec() { } Utf16BECodec.prototype.encoder = Utf16BEEncoder; Utf16BECodec.prototype.decoder = Utf16BEDecoder; Utf16BECodec.prototype.bomAware = true; // -- Encoding function Utf16BEEncoder() { } Utf16BEEncoder.prototype.write = function(str) { var buf = Buffer.from(str, 'ucs2'); for (var i = 0; i < buf.length; i += 2) { var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; } return buf; } Utf16BEEncoder.prototype.end = function() { } // -- Decoding function Utf16BEDecoder() { this.overflowByte = -1; } Utf16BEDecoder.prototype.write = function(buf) { if (buf.length == 0) return ''; var buf2 = Buffer.alloc(buf.length + 1), i = 0, j = 0; if (this.overflowByte !== -1) { buf2[0] = buf[0]; buf2[1] = this.overflowByte; i = 1; j = 2; } for (; i < buf.length-1; i += 2, j+= 2) { buf2[j] = buf[i+1]; buf2[j+1] = buf[i]; } this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; return buf2.slice(0, j).toString('ucs2'); } Utf16BEDecoder.prototype.end = function() { this.overflowByte = -1; } // == UTF-16 codec ============================================================= // Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. // Defaults to UTF-16LE, as it's prevalent and default in Node. // http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le // Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); // Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). exports.utf16 = Utf16Codec; function Utf16Codec(codecOptions, iconv) { this.iconv = iconv; } Utf16Codec.prototype.encoder = Utf16Encoder; Utf16Codec.prototype.decoder = Utf16Decoder; // -- Encoding (pass-through) function Utf16Encoder(options, codec) { options = options || {}; if (options.addBOM === undefined) options.addBOM = true; this.encoder = codec.iconv.getEncoder('utf-16le', options); } Utf16Encoder.prototype.write = function(str) { return this.encoder.write(str); } Utf16Encoder.prototype.end = function() { return this.encoder.end(); } // -- Decoding function Utf16Decoder(options, codec) { this.decoder = null; this.initialBufs = []; this.initialBufsLen = 0; this.options = options || {}; this.iconv = codec.iconv; } Utf16Decoder.prototype.write = function(buf) { if (!this.decoder) { // Codec is not chosen yet. Accumulate initial bytes. this.initialBufs.push(buf); this.initialBufsLen += buf.length; if (this.initialBufsLen < 16) // We need more bytes to use space heuristic (see below) return ''; // We have enough bytes -> detect endianness. var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); this.decoder = this.iconv.getDecoder(encoding, this.options); var resStr = ''; for (var i = 0; i < this.initialBufs.length; i++) resStr += this.decoder.write(this.initialBufs[i]); this.initialBufs.length = this.initialBufsLen = 0; return resStr; } return this.decoder.write(buf); } Utf16Decoder.prototype.end = function() { if (!this.decoder) { var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); this.decoder = this.iconv.getDecoder(encoding, this.options); var resStr = ''; for (var i = 0; i < this.initialBufs.length; i++) resStr += this.decoder.write(this.initialBufs[i]); var trail = this.decoder.end(); if (trail) resStr += trail; this.initialBufs.length = this.initialBufsLen = 0; return resStr; } return this.decoder.end(); } function detectEncoding(bufs, defaultEncoding) { var b = []; var charsProcessed = 0; var asciiCharsLE = 0, asciiCharsBE = 0; // Number of ASCII chars when decoded as LE or BE. outer_loop: for (var i = 0; i < bufs.length; i++) { var buf = bufs[i]; for (var j = 0; j < buf.length; j++) { b.push(buf[j]); if (b.length === 2) { if (charsProcessed === 0) { // Check BOM first. if (b[0] === 0xFF && b[1] === 0xFE) return 'utf-16le'; if (b[0] === 0xFE && b[1] === 0xFF) return 'utf-16be'; } if (b[0] === 0 && b[1] !== 0) asciiCharsBE++; if (b[0] !== 0 && b[1] === 0) asciiCharsLE++; b.length = 0; charsProcessed++; if (charsProcessed >= 100) { break outer_loop; } } } } // Make decisions. // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. // So, we count ASCII as if it was LE or BE, and decide from that. if (asciiCharsBE > asciiCharsLE) return 'utf-16be'; if (asciiCharsBE < asciiCharsLE) return 'utf-16le'; // Couldn't decide (likely all zeros or not enough data). return defaultEncoding || 'utf-16le'; } /***/ }), /***/ "./node_modules/iconv-lite/encodings/utf32.js": /*!****************************************************!*\ !*** ./node_modules/iconv-lite/encodings/utf32.js ***! \****************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var Buffer = (__webpack_require__(/*! safer-buffer */ "./node_modules/safer-buffer/safer.js").Buffer); // == UTF32-LE/BE codec. ========================================================== exports._utf32 = Utf32Codec; function Utf32Codec(codecOptions, iconv) { this.iconv = iconv; this.bomAware = true; this.isLE = codecOptions.isLE; } exports.utf32le = { type: '_utf32', isLE: true }; exports.utf32be = { type: '_utf32', isLE: false }; // Aliases exports.ucs4le = 'utf32le'; exports.ucs4be = 'utf32be'; Utf32Codec.prototype.encoder = Utf32Encoder; Utf32Codec.prototype.decoder = Utf32Decoder; // -- Encoding function Utf32Encoder(options, codec) { this.isLE = codec.isLE; this.highSurrogate = 0; } Utf32Encoder.prototype.write = function(str) { var src = Buffer.from(str, 'ucs2'); var dst = Buffer.alloc(src.length * 2); var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE; var offset = 0; for (var i = 0; i < src.length; i += 2) { var code = src.readUInt16LE(i); var isHighSurrogate = (0xD800 <= code && code < 0xDC00); var isLowSurrogate = (0xDC00 <= code && code < 0xE000); if (this.highSurrogate) { if (isHighSurrogate || !isLowSurrogate) { // There shouldn't be two high surrogates in a row, nor a high surrogate which isn't followed by a low // surrogate. If this happens, keep the pending high surrogate as a stand-alone semi-invalid character // (technically wrong, but expected by some applications, like Windows file names). write32.call(dst, this.highSurrogate, offset); offset += 4; } else { // Create 32-bit value from high and low surrogates; var codepoint = (((this.highSurrogate - 0xD800) << 10) | (code - 0xDC00)) + 0x10000; write32.call(dst, codepoint, offset); offset += 4; this.highSurrogate = 0; continue; } } if (isHighSurrogate) this.highSurrogate = code; else { // Even if the current character is a low surrogate, with no previous high surrogate, we'll // encode it as a semi-invalid stand-alone character for the same reasons expressed above for // unpaired high surrogates. write32.call(dst, code, offset); offset += 4; this.highSurrogate = 0; } } if (offset < dst.length) dst = dst.slice(0, offset); return dst; }; Utf32Encoder.prototype.end = function() { // Treat any leftover high surrogate as a semi-valid independent character. if (!this.highSurrogate) return; var buf = Buffer.alloc(4); if (this.isLE) buf.writeUInt32LE(this.highSurrogate, 0); else buf.writeUInt32BE(this.highSurrogate, 0); this.highSurrogate = 0; return buf; }; // -- Decoding function Utf32Decoder(options, codec) { this.isLE = codec.isLE; this.badChar = codec.iconv.defaultCharUnicode.charCodeAt(0); this.overflow = []; } Utf32Decoder.prototype.write = function(src) { if (src.length === 0) return ''; var i = 0; var codepoint = 0; var dst = Buffer.alloc(src.length + 4); var offset = 0; var isLE = this.isLE; var overflow = this.overflow; var badChar = this.badChar; if (overflow.length > 0) { for (; i < src.length && overflow.length < 4; i++) overflow.push(src[i]); if (overflow.length === 4) { // NOTE: codepoint is a signed int32 and can be negative. // NOTE: We copied this block from below to help V8 optimize it (it works with array, not buffer). if (isLE) { codepoint = overflow[i] | (overflow[i+1] << 8) | (overflow[i+2] << 16) | (overflow[i+3] << 24); } else { codepoint = overflow[i+3] | (overflow[i+2] << 8) | (overflow[i+1] << 16) | (overflow[i] << 24); } overflow.length = 0; offset = _writeCodepoint(dst, offset, codepoint, badChar); } } // Main loop. Should be as optimized as possible. for (; i < src.length - 3; i += 4) { // NOTE: codepoint is a signed int32 and can be negative. if (isLE) { codepoint = src[i] | (src[i+1] << 8) | (src[i+2] << 16) | (src[i+3] << 24); } else { codepoint = src[i+3] | (src[i+2] << 8) | (src[i+1] << 16) | (src[i] << 24); } offset = _writeCodepoint(dst, offset, codepoint, badChar); } // Keep overflowing bytes. for (; i < src.length; i++) { overflow.push(src[i]); } return dst.slice(0, offset).toString('ucs2'); }; function _writeCodepoint(dst, offset, codepoint, badChar) { // NOTE: codepoint is signed int32 and can be negative. We keep it that way to help V8 with optimizations. if (codepoint < 0 || codepoint > 0x10FFFF) { // Not a valid Unicode codepoint codepoint = badChar; } // Ephemeral Planes: Write high surrogate. if (codepoint >= 0x10000) { codepoint -= 0x10000; var high = 0xD800 | (codepoint >> 10); dst[offset++] = high & 0xff; dst[offset++] = high >> 8; // Low surrogate is written below. var codepoint = 0xDC00 | (codepoint & 0x3FF); } // Write BMP char or low surrogate. dst[offset++] = codepoint & 0xff; dst[offset++] = codepoint >> 8; return offset; }; Utf32Decoder.prototype.end = function() { this.overflow.length = 0; }; // == UTF-32 Auto codec ============================================================= // Decoder chooses automatically from UTF-32LE and UTF-32BE using BOM and space-based heuristic. // Defaults to UTF-32LE. http://en.wikipedia.org/wiki/UTF-32 // Encoder/decoder default can be changed: iconv.decode(buf, 'utf32', {defaultEncoding: 'utf-32be'}); // Encoder prepends BOM (which can be overridden with (addBOM: false}). exports.utf32 = Utf32AutoCodec; exports.ucs4 = 'utf32'; function Utf32AutoCodec(options, iconv) { this.iconv = iconv; } Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder; Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder; // -- Encoding function Utf32AutoEncoder(options, codec) { options = options || {}; if (options.addBOM === undefined) options.addBOM = true; this.encoder = codec.iconv.getEncoder(options.defaultEncoding || 'utf-32le', options); } Utf32AutoEncoder.prototype.write = function(str) { return this.encoder.write(str); }; Utf32AutoEncoder.prototype.end = function() { return this.encoder.end(); }; // -- Decoding function Utf32AutoDecoder(options, codec) { this.decoder = null; this.initialBufs = []; this.initialBufsLen = 0; this.options = options || {}; this.iconv = codec.iconv; } Utf32AutoDecoder.prototype.write = function(buf) { if (!this.decoder) { // Codec is not chosen yet. Accumulate initial bytes. this.initialBufs.push(buf); this.initialBufsLen += buf.length; if (this.initialBufsLen < 32) // We need more bytes to use space heuristic (see below) return ''; // We have enough bytes -> detect endianness. var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); this.decoder = this.iconv.getDecoder(encoding, this.options); var resStr = ''; for (var i = 0; i < this.initialBufs.length; i++) resStr += this.decoder.write(this.initialBufs[i]); this.initialBufs.length = this.initialBufsLen = 0; return resStr; } return this.decoder.write(buf); }; Utf32AutoDecoder.prototype.end = function() { if (!this.decoder) { var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); this.decoder = this.iconv.getDecoder(encoding, this.options); var resStr = ''; for (var i = 0; i < this.initialBufs.length; i++) resStr += this.decoder.write(this.initialBufs[i]); var trail = this.decoder.end(); if (trail) resStr += trail; this.initialBufs.length = this.initialBufsLen = 0; return resStr; } return this.decoder.end(); }; function detectEncoding(bufs, defaultEncoding) { var b = []; var charsProcessed = 0; var invalidLE = 0, invalidBE = 0; // Number of invalid chars when decoded as LE or BE. var bmpCharsLE = 0, bmpCharsBE = 0; // Number of BMP chars when decoded as LE or BE. outer_loop: for (var i = 0; i < bufs.length; i++) { var buf = bufs[i]; for (var j = 0; j < buf.length; j++) { b.push(buf[j]); if (b.length === 4) { if (charsProcessed === 0) { // Check BOM first. if (b[0] === 0xFF && b[1] === 0xFE && b[2] === 0 && b[3] === 0) { return 'utf-32le'; } if (b[0] === 0 && b[1] === 0 && b[2] === 0xFE && b[3] === 0xFF) { return 'utf-32be'; } } if (b[0] !== 0 || b[1] > 0x10) invalidBE++; if (b[3] !== 0 || b[2] > 0x10) invalidLE++; if (b[0] === 0 && b[1] === 0 && (b[2] !== 0 || b[3] !== 0)) bmpCharsBE++; if ((b[0] !== 0 || b[1] !== 0) && b[2] === 0 && b[3] === 0) bmpCharsLE++; b.length = 0; charsProcessed++; if (charsProcessed >= 100) { break outer_loop; } } } } // Make decisions. if (bmpCharsBE - invalidBE > bmpCharsLE - invalidLE) return 'utf-32be'; if (bmpCharsBE - invalidBE < bmpCharsLE - invalidLE) return 'utf-32le'; // Couldn't decide (likely all zeros or not enough data). return defaultEncoding || 'utf-32le'; } /***/ }), /***/ "./node_modules/iconv-lite/encodings/utf7.js": /*!***************************************************!*\ !*** ./node_modules/iconv-lite/encodings/utf7.js ***! \***************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var Buffer = (__webpack_require__(/*! safer-buffer */ "./node_modules/safer-buffer/safer.js").Buffer); // UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 // See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 exports.utf7 = Utf7Codec; exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 function Utf7Codec(codecOptions, iconv) { this.iconv = iconv; }; Utf7Codec.prototype.encoder = Utf7Encoder; Utf7Codec.prototype.decoder = Utf7Decoder; Utf7Codec.prototype.bomAware = true; // -- Encoding var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; function Utf7Encoder(options, codec) { this.iconv = codec.iconv; } Utf7Encoder.prototype.write = function(str) { // Naive implementation. // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". return Buffer.from(str.replace(nonDirectChars, function(chunk) { return "+" + (chunk === '+' ? '' : this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) + "-"; }.bind(this))); } Utf7Encoder.prototype.end = function() { } // -- Decoding function Utf7Decoder(options, codec) { this.iconv = codec.iconv; this.inBase64 = false; this.base64Accum = ''; } var base64Regex = /[A-Za-z0-9\/+]/; var base64Chars = []; for (var i = 0; i < 256; i++) base64Chars[i] = base64Regex.test(String.fromCharCode(i)); var plusChar = '+'.charCodeAt(0), minusChar = '-'.charCodeAt(0), andChar = '&'.charCodeAt(0); Utf7Decoder.prototype.write = function(buf) { var res = "", lastI = 0, inBase64 = this.inBase64, base64Accum = this.base64Accum; // The decoder is more involved as we must handle chunks in stream. for (var i = 0; i < buf.length; i++) { if (!inBase64) { // We're in direct mode. // Write direct chars until '+' if (buf[i] == plusChar) { res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. lastI = i+1; inBase64 = true; } } else { // We decode base64. if (!base64Chars[buf[i]]) { // Base64 ended. if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" res += "+"; } else { var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii"); res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } if (buf[i] != minusChar) // Minus is absorbed after base64. i--; lastI = i+1; inBase64 = false; base64Accum = ''; } } } if (!inBase64) { res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. } else { var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii"); var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. b64str = b64str.slice(0, canBeDecoded); res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } this.inBase64 = inBase64; this.base64Accum = base64Accum; return res; } Utf7Decoder.prototype.end = function() { var res = ""; if (this.inBase64 && this.base64Accum.length > 0) res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); this.inBase64 = false; this.base64Accum = ''; return res; } // UTF-7-IMAP codec. // RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) // Differences: // * Base64 part is started by "&" instead of "+" // * Direct characters are 0x20-0x7E, except "&" (0x26) // * In Base64, "," is used instead of "/" // * Base64 must not be used to represent direct characters. // * No implicit shift back from Base64 (should always end with '-') // * String must end in non-shifted position. // * "-&" while in base64 is not allowed. exports.utf7imap = Utf7IMAPCodec; function Utf7IMAPCodec(codecOptions, iconv) { this.iconv = iconv; }; Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; Utf7IMAPCodec.prototype.bomAware = true; // -- Encoding function Utf7IMAPEncoder(options, codec) { this.iconv = codec.iconv; this.inBase64 = false; this.base64Accum = Buffer.alloc(6); this.base64AccumIdx = 0; } Utf7IMAPEncoder.prototype.write = function(str) { var inBase64 = this.inBase64, base64Accum = this.base64Accum, base64AccumIdx = this.base64AccumIdx, buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; for (var i = 0; i < str.length; i++) { var uChar = str.charCodeAt(i); if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. if (inBase64) { if (base64AccumIdx > 0) { bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); base64AccumIdx = 0; } buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. inBase64 = false; } if (!inBase64) { buf[bufIdx++] = uChar; // Write direct character if (uChar === andChar) // Ampersand -> '&-' buf[bufIdx++] = minusChar; } } else { // Non-direct character if (!inBase64) { buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. inBase64 = true; } if (inBase64) { base64Accum[base64AccumIdx++] = uChar >> 8; base64Accum[base64AccumIdx++] = uChar & 0xFF; if (base64AccumIdx == base64Accum.length) { bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); base64AccumIdx = 0; } } } } this.inBase64 = inBase64; this.base64AccumIdx = base64AccumIdx; return buf.slice(0, bufIdx); } Utf7IMAPEncoder.prototype.end = function() { var buf = Buffer.alloc(10), bufIdx = 0; if (this.inBase64) { if (this.base64AccumIdx > 0) { bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); this.base64AccumIdx = 0; } buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. this.inBase64 = false; } return buf.slice(0, bufIdx); } // -- Decoding function Utf7IMAPDecoder(options, codec) { this.iconv = codec.iconv; this.inBase64 = false; this.base64Accum = ''; } var base64IMAPChars = base64Chars.slice(); base64IMAPChars[','.charCodeAt(0)] = true; Utf7IMAPDecoder.prototype.write = function(buf) { var res = "", lastI = 0, inBase64 = this.inBase64, base64Accum = this.base64Accum; // The decoder is more involved as we must handle chunks in stream. // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). for (var i = 0; i < buf.length; i++) { if (!inBase64) { // We're in direct mode. // Write direct chars until '&' if (buf[i] == andChar) { res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. lastI = i+1; inBase64 = true; } } else { // We decode base64. if (!base64IMAPChars[buf[i]]) { // Base64 ended. if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" res += "&"; } else { var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii").replace(/,/g, '/'); res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } if (buf[i] != minusChar) // Minus may be absorbed after base64. i--; lastI = i+1; inBase64 = false; base64Accum = ''; } } } if (!inBase64) { res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. } else { var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii").replace(/,/g, '/'); var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. b64str = b64str.slice(0, canBeDecoded); res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } this.inBase64 = inBase64; this.base64Accum = base64Accum; return res; } Utf7IMAPDecoder.prototype.end = function() { var res = ""; if (this.inBase64 && this.base64Accum.length > 0) res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); this.inBase64 = false; this.base64Accum = ''; return res; } /***/ }), /***/ "./node_modules/iconv-lite/lib/bom-handling.js": /*!*****************************************************!*\ !*** ./node_modules/iconv-lite/lib/bom-handling.js ***! \*****************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; var BOMChar = '\uFEFF'; exports.PrependBOM = PrependBOMWrapper function PrependBOMWrapper(encoder, options) { this.encoder = encoder; this.addBOM = true; } PrependBOMWrapper.prototype.write = function(str) { if (this.addBOM) { str = BOMChar + str; this.addBOM = false; } return this.encoder.write(str); } PrependBOMWrapper.prototype.end = function() { return this.encoder.end(); } //------------------------------------------------------------------------------ exports.StripBOM = StripBOMWrapper; function StripBOMWrapper(decoder, options) { this.decoder = decoder; this.pass = false; this.options = options || {}; } StripBOMWrapper.prototype.write = function(buf) { var res = this.decoder.write(buf); if (this.pass || !res) return res; if (res[0] === BOMChar) { res = res.slice(1); if (typeof this.options.stripBOM === 'function') this.options.stripBOM(); } this.pass = true; return res; } StripBOMWrapper.prototype.end = function() { return this.decoder.end(); } /***/ }), /***/ "./node_modules/iconv-lite/lib/index.js": /*!**********************************************!*\ !*** ./node_modules/iconv-lite/lib/index.js ***! \**********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Buffer = (__webpack_require__(/*! safer-buffer */ "./node_modules/safer-buffer/safer.js").Buffer); var bomHandling = __webpack_require__(/*! ./bom-handling */ "./node_modules/iconv-lite/lib/bom-handling.js"), iconv = module.exports; // All codecs and aliases are kept here, keyed by encoding name/alias. // They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. iconv.encodings = null; // Characters emitted in case of error. iconv.defaultCharUnicode = '�'; iconv.defaultCharSingleByte = '?'; // Public API. iconv.encode = function encode(str, encoding, options) { str = "" + (str || ""); // Ensure string. var encoder = iconv.getEncoder(encoding, options); var res = encoder.write(str); var trail = encoder.end(); return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; } iconv.decode = function decode(buf, encoding, options) { if (typeof buf === 'string') { if (!iconv.skipDecodeWarning) { console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); iconv.skipDecodeWarning = true; } buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. } var decoder = iconv.getDecoder(encoding, options); var res = decoder.write(buf); var trail = decoder.end(); return trail ? (res + trail) : res; } iconv.encodingExists = function encodingExists(enc) { try { iconv.getCodec(enc); return true; } catch (e) { return false; } } // Legacy aliases to convert functions iconv.toEncoding = iconv.encode; iconv.fromEncoding = iconv.decode; // Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. iconv._codecDataCache = {}; iconv.getCodec = function getCodec(encoding) { if (!iconv.encodings) iconv.encodings = __webpack_require__(/*! ../encodings */ "./node_modules/iconv-lite/encodings/index.js"); // Lazy load all encoding definitions. // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. var enc = iconv._canonicalizeEncoding(encoding); // Traverse iconv.encodings to find actual codec. var codecOptions = {}; while (true) { var codec = iconv._codecDataCache[enc]; if (codec) return codec; var codecDef = iconv.encodings[enc]; switch (typeof codecDef) { case "string": // Direct alias to other encoding. enc = codecDef; break; case "object": // Alias with options. Can be layered. for (var key in codecDef) codecOptions[key] = codecDef[key]; if (!codecOptions.encodingName) codecOptions.encodingName = enc; enc = codecDef.type; break; case "function": // Codec itself. if (!codecOptions.encodingName) codecOptions.encodingName = enc; // The codec function must load all tables and return object with .encoder and .decoder methods. // It'll be called only once (for each different options object). codec = new codecDef(codecOptions, iconv); iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. return codec; default: throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); } } } iconv._canonicalizeEncoding = function(encoding) { // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); } iconv.getEncoder = function getEncoder(encoding, options) { var codec = iconv.getCodec(encoding), encoder = new codec.encoder(options, codec); if (codec.bomAware && options && options.addBOM) encoder = new bomHandling.PrependBOM(encoder, options); return encoder; } iconv.getDecoder = function getDecoder(encoding, options) { var codec = iconv.getCodec(encoding), decoder = new codec.decoder(options, codec); if (codec.bomAware && !(options && options.stripBOM === false)) decoder = new bomHandling.StripBOM(decoder, options); return decoder; } // Streaming API // NOTE: Streaming API naturally depends on 'stream' module from Node.js. Unfortunately in browser environments this module can add // up to 100Kb to the output bundle. To avoid unnecessary code bloat, we don't enable Streaming API in browser by default. // If you would like to enable it explicitly, please add the following code to your app: // > iconv.enableStreamingAPI(require('stream')); iconv.enableStreamingAPI = function enableStreamingAPI(stream_module) { if (iconv.supportsStreams) return; // Dependency-inject stream module to create IconvLite stream classes. var streams = __webpack_require__(/*! ./streams */ "./node_modules/iconv-lite/lib/streams.js")(stream_module); // Not public API yet, but expose the stream classes. iconv.IconvLiteEncoderStream = streams.IconvLiteEncoderStream; iconv.IconvLiteDecoderStream = streams.IconvLiteDecoderStream; // Streaming API. iconv.encodeStream = function encodeStream(encoding, options) { return new iconv.IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); } iconv.decodeStream = function decodeStream(encoding, options) { return new iconv.IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); } iconv.supportsStreams = true; } // Enable Streaming API automatically if 'stream' module is available and non-empty (the majority of environments). var stream_module; try { stream_module = __webpack_require__(/*! stream */ "stream"); } catch (e) {} if (stream_module && stream_module.Transform) { iconv.enableStreamingAPI(stream_module); } else { // In rare cases where 'stream' module is not available by default, throw a helpful exception. iconv.encodeStream = iconv.decodeStream = function() { throw new Error("iconv-lite Streaming API is not enabled. Use iconv.enableStreamingAPI(require('stream')); to enable it."); }; } if (false) {} /***/ }), /***/ "./node_modules/iconv-lite/lib/streams.js": /*!************************************************!*\ !*** ./node_modules/iconv-lite/lib/streams.js ***! \************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Buffer = (__webpack_require__(/*! safer-buffer */ "./node_modules/safer-buffer/safer.js").Buffer); // NOTE: Due to 'stream' module being pretty large (~100Kb, significant in browser environments), // we opt to dependency-inject it instead of creating a hard dependency. module.exports = function(stream_module) { var Transform = stream_module.Transform; // == Encoder stream ======================================================= function IconvLiteEncoderStream(conv, options) { this.conv = conv; options = options || {}; options.decodeStrings = false; // We accept only strings, so we don't need to decode them. Transform.call(this, options); } IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { constructor: { value: IconvLiteEncoderStream } }); IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { if (typeof chunk != 'string') return done(new Error("Iconv encoding stream needs strings as its input.")); try { var res = this.conv.write(chunk); if (res && res.length) this.push(res); done(); } catch (e) { done(e); } } IconvLiteEncoderStream.prototype._flush = function(done) { try { var res = this.conv.end(); if (res && res.length) this.push(res); done(); } catch (e) { done(e); } } IconvLiteEncoderStream.prototype.collect = function(cb) { var chunks = []; this.on('error', cb); this.on('data', function(chunk) { chunks.push(chunk); }); this.on('end', function() { cb(null, Buffer.concat(chunks)); }); return this; } // == Decoder stream ======================================================= function IconvLiteDecoderStream(conv, options) { this.conv = conv; options = options || {}; options.encoding = this.encoding = 'utf8'; // We output strings. Transform.call(this, options); } IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { constructor: { value: IconvLiteDecoderStream } }); IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { if (!Buffer.isBuffer(chunk) && !(chunk instanceof Uint8Array)) return done(new Error("Iconv decoding stream needs buffers as its input.")); try { var res = this.conv.write(chunk); if (res && res.length) this.push(res, this.encoding); done(); } catch (e) { done(e); } } IconvLiteDecoderStream.prototype._flush = function(done) { try { var res = this.conv.end(); if (res && res.length) this.push(res, this.encoding); done(); } catch (e) { done(e); } } IconvLiteDecoderStream.prototype.collect = function(cb) { var res = ''; this.on('error', cb); this.on('data', function(chunk) { res += chunk; }); this.on('end', function() { cb(null, res); }); return this; } return { IconvLiteEncoderStream: IconvLiteEncoderStream, IconvLiteDecoderStream: IconvLiteDecoderStream, }; }; /***/ }), /***/ "./node_modules/inflight/inflight.js": /*!*******************************************!*\ !*** ./node_modules/inflight/inflight.js ***! \*******************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var wrappy = __webpack_require__(/*! wrappy */ "./node_modules/wrappy/wrappy.js") var reqs = Object.create(null) var once = __webpack_require__(/*! once */ "./node_modules/once/once.js") module.exports = wrappy(inflight) function inflight (key, cb) { if (reqs[key]) { reqs[key].push(cb) return null } else { reqs[key] = [cb] return makeres(key) } } function makeres (key) { return once(function RES () { var cbs = reqs[key] var len = cbs.length var args = slice(arguments) // XXX It's somewhat ambiguous whether a new callback added in this // pass should be queued for later execution if something in the // list of callbacks throws, or if it should just be discarded. // However, it's such an edge case that it hardly matters, and either // choice is likely as surprising as the other. // As it happens, we do go ahead and schedule it for later execution. try { for (var i = 0; i < len; i++) { cbs[i].apply(null, args) } } finally { if (cbs.length > len) { // added more in the interim. // de-zalgo, just in case, but don't call again. cbs.splice(0, len) process.nextTick(function () { RES.apply(null, args) }) } else { delete reqs[key] } } }) } function slice (args) { var length = args.length var array = [] for (var i = 0; i < length; i++) array[i] = args[i] return array } /***/ }), /***/ "./node_modules/inherits/inherits.js": /*!*******************************************!*\ !*** ./node_modules/inherits/inherits.js ***! \*******************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { try { var util = __webpack_require__(/*! util */ "util"); /* istanbul ignore next */ if (typeof util.inherits !== 'function') throw ''; module.exports = util.inherits; } catch (e) { /* istanbul ignore next */ module.exports = __webpack_require__(/*! ./inherits_browser.js */ "./node_modules/inherits/inherits_browser.js"); } /***/ }), /***/ "./node_modules/inherits/inherits_browser.js": /*!***************************************************!*\ !*** ./node_modules/inherits/inherits_browser.js ***! \***************************************************/ /***/ ((module) => { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }) } }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } } /***/ }), /***/ "./node_modules/inversify/lib/annotation/decorator_utils.js": /*!******************************************************************!*\ !*** ./node_modules/inversify/lib/annotation/decorator_utils.js ***! \******************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.tagProperty = exports.tagParameter = exports.decorate = void 0; var ERROR_MSGS = __webpack_require__(/*! ../constants/error_msgs */ "./node_modules/inversify/lib/constants/error_msgs.js"); var METADATA_KEY = __webpack_require__(/*! ../constants/metadata_keys */ "./node_modules/inversify/lib/constants/metadata_keys.js"); function tagParameter(annotationTarget, propertyName, parameterIndex, metadata) { var metadataKey = METADATA_KEY.TAGGED; _tagParameterOrProperty(metadataKey, annotationTarget, propertyName, metadata, parameterIndex); } exports.tagParameter = tagParameter; function tagProperty(annotationTarget, propertyName, metadata) { var metadataKey = METADATA_KEY.TAGGED_PROP; _tagParameterOrProperty(metadataKey, annotationTarget.constructor, propertyName, metadata); } exports.tagProperty = tagProperty; function _tagParameterOrProperty(metadataKey, annotationTarget, propertyName, metadata, parameterIndex) { var paramsOrPropertiesMetadata = {}; var isParameterDecorator = (typeof parameterIndex === "number"); var key = (parameterIndex !== undefined && isParameterDecorator) ? parameterIndex.toString() : propertyName; if (isParameterDecorator && propertyName !== undefined) { throw new Error(ERROR_MSGS.INVALID_DECORATOR_OPERATION); } if (Reflect.hasOwnMetadata(metadataKey, annotationTarget)) { paramsOrPropertiesMetadata = Reflect.getMetadata(metadataKey, annotationTarget); } var paramOrPropertyMetadata = paramsOrPropertiesMetadata[key]; if (!Array.isArray(paramOrPropertyMetadata)) { paramOrPropertyMetadata = []; } else { for (var _i = 0, paramOrPropertyMetadata_1 = paramOrPropertyMetadata; _i < paramOrPropertyMetadata_1.length; _i++) { var m = paramOrPropertyMetadata_1[_i]; if (m.key === metadata.key) { throw new Error(ERROR_MSGS.DUPLICATED_METADATA + " " + m.key.toString()); } } } paramOrPropertyMetadata.push(metadata); paramsOrPropertiesMetadata[key] = paramOrPropertyMetadata; Reflect.defineMetadata(metadataKey, paramsOrPropertiesMetadata, annotationTarget); } function _decorate(decorators, target) { Reflect.decorate(decorators, target); } function _param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); }; } function decorate(decorator, target, parameterIndex) { if (typeof parameterIndex === "number") { _decorate([_param(parameterIndex, decorator)], target); } else if (typeof parameterIndex === "string") { Reflect.decorate([decorator], target, parameterIndex); } else { _decorate([decorator], target); } } exports.decorate = decorate; /***/ }), /***/ "./node_modules/inversify/lib/annotation/inject.js": /*!*********************************************************!*\ !*** ./node_modules/inversify/lib/annotation/inject.js ***! \*********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.inject = exports.LazyServiceIdentifer = void 0; var error_msgs_1 = __webpack_require__(/*! ../constants/error_msgs */ "./node_modules/inversify/lib/constants/error_msgs.js"); var METADATA_KEY = __webpack_require__(/*! ../constants/metadata_keys */ "./node_modules/inversify/lib/constants/metadata_keys.js"); var metadata_1 = __webpack_require__(/*! ../planning/metadata */ "./node_modules/inversify/lib/planning/metadata.js"); var decorator_utils_1 = __webpack_require__(/*! ./decorator_utils */ "./node_modules/inversify/lib/annotation/decorator_utils.js"); var LazyServiceIdentifer = (function () { function LazyServiceIdentifer(cb) { this._cb = cb; } LazyServiceIdentifer.prototype.unwrap = function () { return this._cb(); }; return LazyServiceIdentifer; }()); exports.LazyServiceIdentifer = LazyServiceIdentifer; function inject(serviceIdentifier) { return function (target, targetKey, index) { if (serviceIdentifier === undefined) { throw new Error(error_msgs_1.UNDEFINED_INJECT_ANNOTATION(target.name)); } var metadata = new metadata_1.Metadata(METADATA_KEY.INJECT_TAG, serviceIdentifier); if (typeof index === "number") { decorator_utils_1.tagParameter(target, targetKey, index, metadata); } else { decorator_utils_1.tagProperty(target, targetKey, metadata); } }; } exports.inject = inject; /***/ }), /***/ "./node_modules/inversify/lib/annotation/injectable.js": /*!*************************************************************!*\ !*** ./node_modules/inversify/lib/annotation/injectable.js ***! \*************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.injectable = void 0; var ERRORS_MSGS = __webpack_require__(/*! ../constants/error_msgs */ "./node_modules/inversify/lib/constants/error_msgs.js"); var METADATA_KEY = __webpack_require__(/*! ../constants/metadata_keys */ "./node_modules/inversify/lib/constants/metadata_keys.js"); function injectable() { return function (target) { if (Reflect.hasOwnMetadata(METADATA_KEY.PARAM_TYPES, target)) { throw new Error(ERRORS_MSGS.DUPLICATED_INJECTABLE_DECORATOR); } var types = Reflect.getMetadata(METADATA_KEY.DESIGN_PARAM_TYPES, target) || []; Reflect.defineMetadata(METADATA_KEY.PARAM_TYPES, types, target); return target; }; } exports.injectable = injectable; /***/ }), /***/ "./node_modules/inversify/lib/annotation/multi_inject.js": /*!***************************************************************!*\ !*** ./node_modules/inversify/lib/annotation/multi_inject.js ***! \***************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.multiInject = void 0; var METADATA_KEY = __webpack_require__(/*! ../constants/metadata_keys */ "./node_modules/inversify/lib/constants/metadata_keys.js"); var metadata_1 = __webpack_require__(/*! ../planning/metadata */ "./node_modules/inversify/lib/planning/metadata.js"); var decorator_utils_1 = __webpack_require__(/*! ./decorator_utils */ "./node_modules/inversify/lib/annotation/decorator_utils.js"); function multiInject(serviceIdentifier) { return function (target, targetKey, index) { var metadata = new metadata_1.Metadata(METADATA_KEY.MULTI_INJECT_TAG, serviceIdentifier); if (typeof index === "number") { decorator_utils_1.tagParameter(target, targetKey, index, metadata); } else { decorator_utils_1.tagProperty(target, targetKey, metadata); } }; } exports.multiInject = multiInject; /***/ }), /***/ "./node_modules/inversify/lib/annotation/named.js": /*!********************************************************!*\ !*** ./node_modules/inversify/lib/annotation/named.js ***! \********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.named = void 0; var METADATA_KEY = __webpack_require__(/*! ../constants/metadata_keys */ "./node_modules/inversify/lib/constants/metadata_keys.js"); var metadata_1 = __webpack_require__(/*! ../planning/metadata */ "./node_modules/inversify/lib/planning/metadata.js"); var decorator_utils_1 = __webpack_require__(/*! ./decorator_utils */ "./node_modules/inversify/lib/annotation/decorator_utils.js"); function named(name) { return function (target, targetKey, index) { var metadata = new metadata_1.Metadata(METADATA_KEY.NAMED_TAG, name); if (typeof index === "number") { decorator_utils_1.tagParameter(target, targetKey, index, metadata); } else { decorator_utils_1.tagProperty(target, targetKey, metadata); } }; } exports.named = named; /***/ }), /***/ "./node_modules/inversify/lib/annotation/optional.js": /*!***********************************************************!*\ !*** ./node_modules/inversify/lib/annotation/optional.js ***! \***********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.optional = void 0; var METADATA_KEY = __webpack_require__(/*! ../constants/metadata_keys */ "./node_modules/inversify/lib/constants/metadata_keys.js"); var metadata_1 = __webpack_require__(/*! ../planning/metadata */ "./node_modules/inversify/lib/planning/metadata.js"); var decorator_utils_1 = __webpack_require__(/*! ./decorator_utils */ "./node_modules/inversify/lib/annotation/decorator_utils.js"); function optional() { return function (target, targetKey, index) { var metadata = new metadata_1.Metadata(METADATA_KEY.OPTIONAL_TAG, true); if (typeof index === "number") { decorator_utils_1.tagParameter(target, targetKey, index, metadata); } else { decorator_utils_1.tagProperty(target, targetKey, metadata); } }; } exports.optional = optional; /***/ }), /***/ "./node_modules/inversify/lib/annotation/post_construct.js": /*!*****************************************************************!*\ !*** ./node_modules/inversify/lib/annotation/post_construct.js ***! \*****************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.postConstruct = void 0; var ERRORS_MSGS = __webpack_require__(/*! ../constants/error_msgs */ "./node_modules/inversify/lib/constants/error_msgs.js"); var METADATA_KEY = __webpack_require__(/*! ../constants/metadata_keys */ "./node_modules/inversify/lib/constants/metadata_keys.js"); var metadata_1 = __webpack_require__(/*! ../planning/metadata */ "./node_modules/inversify/lib/planning/metadata.js"); function postConstruct() { return function (target, propertyKey, descriptor) { var metadata = new metadata_1.Metadata(METADATA_KEY.POST_CONSTRUCT, propertyKey); if (Reflect.hasOwnMetadata(METADATA_KEY.POST_CONSTRUCT, target.constructor)) { throw new Error(ERRORS_MSGS.MULTIPLE_POST_CONSTRUCT_METHODS); } Reflect.defineMetadata(METADATA_KEY.POST_CONSTRUCT, metadata, target.constructor); }; } exports.postConstruct = postConstruct; /***/ }), /***/ "./node_modules/inversify/lib/annotation/tagged.js": /*!*********************************************************!*\ !*** ./node_modules/inversify/lib/annotation/tagged.js ***! \*********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.tagged = void 0; var metadata_1 = __webpack_require__(/*! ../planning/metadata */ "./node_modules/inversify/lib/planning/metadata.js"); var decorator_utils_1 = __webpack_require__(/*! ./decorator_utils */ "./node_modules/inversify/lib/annotation/decorator_utils.js"); function tagged(metadataKey, metadataValue) { return function (target, targetKey, index) { var metadata = new metadata_1.Metadata(metadataKey, metadataValue); if (typeof index === "number") { decorator_utils_1.tagParameter(target, targetKey, index, metadata); } else { decorator_utils_1.tagProperty(target, targetKey, metadata); } }; } exports.tagged = tagged; /***/ }), /***/ "./node_modules/inversify/lib/annotation/target_name.js": /*!**************************************************************!*\ !*** ./node_modules/inversify/lib/annotation/target_name.js ***! \**************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.targetName = void 0; var METADATA_KEY = __webpack_require__(/*! ../constants/metadata_keys */ "./node_modules/inversify/lib/constants/metadata_keys.js"); var metadata_1 = __webpack_require__(/*! ../planning/metadata */ "./node_modules/inversify/lib/planning/metadata.js"); var decorator_utils_1 = __webpack_require__(/*! ./decorator_utils */ "./node_modules/inversify/lib/annotation/decorator_utils.js"); function targetName(name) { return function (target, targetKey, index) { var metadata = new metadata_1.Metadata(METADATA_KEY.NAME_TAG, name); decorator_utils_1.tagParameter(target, targetKey, index, metadata); }; } exports.targetName = targetName; /***/ }), /***/ "./node_modules/inversify/lib/annotation/unmanaged.js": /*!************************************************************!*\ !*** ./node_modules/inversify/lib/annotation/unmanaged.js ***! \************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.unmanaged = void 0; var METADATA_KEY = __webpack_require__(/*! ../constants/metadata_keys */ "./node_modules/inversify/lib/constants/metadata_keys.js"); var metadata_1 = __webpack_require__(/*! ../planning/metadata */ "./node_modules/inversify/lib/planning/metadata.js"); var decorator_utils_1 = __webpack_require__(/*! ./decorator_utils */ "./node_modules/inversify/lib/annotation/decorator_utils.js"); function unmanaged() { return function (target, targetKey, index) { var metadata = new metadata_1.Metadata(METADATA_KEY.UNMANAGED_TAG, true); decorator_utils_1.tagParameter(target, targetKey, index, metadata); }; } exports.unmanaged = unmanaged; /***/ }), /***/ "./node_modules/inversify/lib/bindings/binding.js": /*!********************************************************!*\ !*** ./node_modules/inversify/lib/bindings/binding.js ***! \********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Binding = void 0; var literal_types_1 = __webpack_require__(/*! ../constants/literal_types */ "./node_modules/inversify/lib/constants/literal_types.js"); var id_1 = __webpack_require__(/*! ../utils/id */ "./node_modules/inversify/lib/utils/id.js"); var Binding = (function () { function Binding(serviceIdentifier, scope) { this.id = id_1.id(); this.activated = false; this.serviceIdentifier = serviceIdentifier; this.scope = scope; this.type = literal_types_1.BindingTypeEnum.Invalid; this.constraint = function (request) { return true; }; this.implementationType = null; this.cache = null; this.factory = null; this.provider = null; this.onActivation = null; this.dynamicValue = null; } Binding.prototype.clone = function () { var clone = new Binding(this.serviceIdentifier, this.scope); clone.activated = false; clone.implementationType = this.implementationType; clone.dynamicValue = this.dynamicValue; clone.scope = this.scope; clone.type = this.type; clone.factory = this.factory; clone.provider = this.provider; clone.constraint = this.constraint; clone.onActivation = this.onActivation; clone.cache = this.cache; return clone; }; return Binding; }()); exports.Binding = Binding; /***/ }), /***/ "./node_modules/inversify/lib/bindings/binding_count.js": /*!**************************************************************!*\ !*** ./node_modules/inversify/lib/bindings/binding_count.js ***! \**************************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BindingCount = void 0; var BindingCount = { MultipleBindingsAvailable: 2, NoBindingsAvailable: 0, OnlyOneBindingAvailable: 1 }; exports.BindingCount = BindingCount; /***/ }), /***/ "./node_modules/inversify/lib/constants/error_msgs.js": /*!************************************************************!*\ !*** ./node_modules/inversify/lib/constants/error_msgs.js ***! \************************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.STACK_OVERFLOW = exports.CIRCULAR_DEPENDENCY_IN_FACTORY = exports.POST_CONSTRUCT_ERROR = exports.MULTIPLE_POST_CONSTRUCT_METHODS = exports.CONTAINER_OPTIONS_INVALID_SKIP_BASE_CHECK = exports.CONTAINER_OPTIONS_INVALID_AUTO_BIND_INJECTABLE = exports.CONTAINER_OPTIONS_INVALID_DEFAULT_SCOPE = exports.CONTAINER_OPTIONS_MUST_BE_AN_OBJECT = exports.ARGUMENTS_LENGTH_MISMATCH = exports.INVALID_DECORATOR_OPERATION = exports.INVALID_TO_SELF_VALUE = exports.INVALID_FUNCTION_BINDING = exports.INVALID_MIDDLEWARE_RETURN = exports.NO_MORE_SNAPSHOTS_AVAILABLE = exports.INVALID_BINDING_TYPE = exports.NOT_IMPLEMENTED = exports.CIRCULAR_DEPENDENCY = exports.UNDEFINED_INJECT_ANNOTATION = exports.MISSING_INJECT_ANNOTATION = exports.MISSING_INJECTABLE_ANNOTATION = exports.NOT_REGISTERED = exports.CANNOT_UNBIND = exports.AMBIGUOUS_MATCH = exports.KEY_NOT_FOUND = exports.NULL_ARGUMENT = exports.DUPLICATED_METADATA = exports.DUPLICATED_INJECTABLE_DECORATOR = void 0; exports.DUPLICATED_INJECTABLE_DECORATOR = "Cannot apply @injectable decorator multiple times."; exports.DUPLICATED_METADATA = "Metadata key was used more than once in a parameter:"; exports.NULL_ARGUMENT = "NULL argument"; exports.KEY_NOT_FOUND = "Key Not Found"; exports.AMBIGUOUS_MATCH = "Ambiguous match found for serviceIdentifier:"; exports.CANNOT_UNBIND = "Could not unbind serviceIdentifier:"; exports.NOT_REGISTERED = "No matching bindings found for serviceIdentifier:"; exports.MISSING_INJECTABLE_ANNOTATION = "Missing required @injectable annotation in:"; exports.MISSING_INJECT_ANNOTATION = "Missing required @inject or @multiInject annotation in:"; exports.UNDEFINED_INJECT_ANNOTATION = function (name) { return "@inject called with undefined this could mean that the class " + name + " has " + "a circular dependency problem. You can use a LazyServiceIdentifer to " + "overcome this limitation."; }; exports.CIRCULAR_DEPENDENCY = "Circular dependency found:"; exports.NOT_IMPLEMENTED = "Sorry, this feature is not fully implemented yet."; exports.INVALID_BINDING_TYPE = "Invalid binding type:"; exports.NO_MORE_SNAPSHOTS_AVAILABLE = "No snapshot available to restore."; exports.INVALID_MIDDLEWARE_RETURN = "Invalid return type in middleware. Middleware must return!"; exports.INVALID_FUNCTION_BINDING = "Value provided to function binding must be a function!"; exports.INVALID_TO_SELF_VALUE = "The toSelf function can only be applied when a constructor is " + "used as service identifier"; exports.INVALID_DECORATOR_OPERATION = "The @inject @multiInject @tagged and @named decorators " + "must be applied to the parameters of a class constructor or a class property."; exports.ARGUMENTS_LENGTH_MISMATCH = function () { var values = []; for (var _i = 0; _i < arguments.length; _i++) { values[_i] = arguments[_i]; } return "The number of constructor arguments in the derived class " + (values[0] + " must be >= than the number of constructor arguments of its base class."); }; exports.CONTAINER_OPTIONS_MUST_BE_AN_OBJECT = "Invalid Container constructor argument. Container options " + "must be an object."; exports.CONTAINER_OPTIONS_INVALID_DEFAULT_SCOPE = "Invalid Container option. Default scope must " + "be a string ('singleton' or 'transient')."; exports.CONTAINER_OPTIONS_INVALID_AUTO_BIND_INJECTABLE = "Invalid Container option. Auto bind injectable must " + "be a boolean"; exports.CONTAINER_OPTIONS_INVALID_SKIP_BASE_CHECK = "Invalid Container option. Skip base check must " + "be a boolean"; exports.MULTIPLE_POST_CONSTRUCT_METHODS = "Cannot apply @postConstruct decorator multiple times in the same class"; exports.POST_CONSTRUCT_ERROR = function () { var values = []; for (var _i = 0; _i < arguments.length; _i++) { values[_i] = arguments[_i]; } return "@postConstruct error in class " + values[0] + ": " + values[1]; }; exports.CIRCULAR_DEPENDENCY_IN_FACTORY = function () { var values = []; for (var _i = 0; _i < arguments.length; _i++) { values[_i] = arguments[_i]; } return "It looks like there is a circular dependency " + ("in one of the '" + values[0] + "' bindings. Please investigate bindings with") + ("service identifier '" + values[1] + "'."); }; exports.STACK_OVERFLOW = "Maximum call stack size exceeded"; /***/ }), /***/ "./node_modules/inversify/lib/constants/literal_types.js": /*!***************************************************************!*\ !*** ./node_modules/inversify/lib/constants/literal_types.js ***! \***************************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TargetTypeEnum = exports.BindingTypeEnum = exports.BindingScopeEnum = void 0; var BindingScopeEnum = { Request: "Request", Singleton: "Singleton", Transient: "Transient" }; exports.BindingScopeEnum = BindingScopeEnum; var BindingTypeEnum = { ConstantValue: "ConstantValue", Constructor: "Constructor", DynamicValue: "DynamicValue", Factory: "Factory", Function: "Function", Instance: "Instance", Invalid: "Invalid", Provider: "Provider" }; exports.BindingTypeEnum = BindingTypeEnum; var TargetTypeEnum = { ClassProperty: "ClassProperty", ConstructorArgument: "ConstructorArgument", Variable: "Variable" }; exports.TargetTypeEnum = TargetTypeEnum; /***/ }), /***/ "./node_modules/inversify/lib/constants/metadata_keys.js": /*!***************************************************************!*\ !*** ./node_modules/inversify/lib/constants/metadata_keys.js ***! \***************************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.POST_CONSTRUCT = exports.DESIGN_PARAM_TYPES = exports.PARAM_TYPES = exports.TAGGED_PROP = exports.TAGGED = exports.MULTI_INJECT_TAG = exports.INJECT_TAG = exports.OPTIONAL_TAG = exports.UNMANAGED_TAG = exports.NAME_TAG = exports.NAMED_TAG = void 0; exports.NAMED_TAG = "named"; exports.NAME_TAG = "name"; exports.UNMANAGED_TAG = "unmanaged"; exports.OPTIONAL_TAG = "optional"; exports.INJECT_TAG = "inject"; exports.MULTI_INJECT_TAG = "multi_inject"; exports.TAGGED = "inversify:tagged"; exports.TAGGED_PROP = "inversify:tagged_props"; exports.PARAM_TYPES = "inversify:paramtypes"; exports.DESIGN_PARAM_TYPES = "design:paramtypes"; exports.POST_CONSTRUCT = "post_construct"; /***/ }), /***/ "./node_modules/inversify/lib/container/container.js": /*!***********************************************************!*\ !*** ./node_modules/inversify/lib/container/container.js ***! \***********************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; 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 __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Container = void 0; var binding_1 = __webpack_require__(/*! ../bindings/binding */ "./node_modules/inversify/lib/bindings/binding.js"); var ERROR_MSGS = __webpack_require__(/*! ../constants/error_msgs */ "./node_modules/inversify/lib/constants/error_msgs.js"); var literal_types_1 = __webpack_require__(/*! ../constants/literal_types */ "./node_modules/inversify/lib/constants/literal_types.js"); var METADATA_KEY = __webpack_require__(/*! ../constants/metadata_keys */ "./node_modules/inversify/lib/constants/metadata_keys.js"); var metadata_reader_1 = __webpack_require__(/*! ../planning/metadata_reader */ "./node_modules/inversify/lib/planning/metadata_reader.js"); var planner_1 = __webpack_require__(/*! ../planning/planner */ "./node_modules/inversify/lib/planning/planner.js"); var resolver_1 = __webpack_require__(/*! ../resolution/resolver */ "./node_modules/inversify/lib/resolution/resolver.js"); var binding_to_syntax_1 = __webpack_require__(/*! ../syntax/binding_to_syntax */ "./node_modules/inversify/lib/syntax/binding_to_syntax.js"); var id_1 = __webpack_require__(/*! ../utils/id */ "./node_modules/inversify/lib/utils/id.js"); var serialization_1 = __webpack_require__(/*! ../utils/serialization */ "./node_modules/inversify/lib/utils/serialization.js"); var container_snapshot_1 = __webpack_require__(/*! ./container_snapshot */ "./node_modules/inversify/lib/container/container_snapshot.js"); var lookup_1 = __webpack_require__(/*! ./lookup */ "./node_modules/inversify/lib/container/lookup.js"); var Container = (function () { function Container(containerOptions) { var options = containerOptions || {}; if (typeof options !== "object") { throw new Error("" + ERROR_MSGS.CONTAINER_OPTIONS_MUST_BE_AN_OBJECT); } if (options.defaultScope === undefined) { options.defaultScope = literal_types_1.BindingScopeEnum.Transient; } else if (options.defaultScope !== literal_types_1.BindingScopeEnum.Singleton && options.defaultScope !== literal_types_1.BindingScopeEnum.Transient && options.defaultScope !== literal_types_1.BindingScopeEnum.Request) { throw new Error("" + ERROR_MSGS.CONTAINER_OPTIONS_INVALID_DEFAULT_SCOPE); } if (options.autoBindInjectable === undefined) { options.autoBindInjectable = false; } else if (typeof options.autoBindInjectable !== "boolean") { throw new Error("" + ERROR_MSGS.CONTAINER_OPTIONS_INVALID_AUTO_BIND_INJECTABLE); } if (options.skipBaseClassChecks === undefined) { options.skipBaseClassChecks = false; } else if (typeof options.skipBaseClassChecks !== "boolean") { throw new Error("" + ERROR_MSGS.CONTAINER_OPTIONS_INVALID_SKIP_BASE_CHECK); } this.options = { autoBindInjectable: options.autoBindInjectable, defaultScope: options.defaultScope, skipBaseClassChecks: options.skipBaseClassChecks }; this.id = id_1.id(); this._bindingDictionary = new lookup_1.Lookup(); this._snapshots = []; this._middleware = null; this.parent = null; this._metadataReader = new metadata_reader_1.MetadataReader(); } Container.merge = function (container1, container2) { var container = new Container(); var bindingDictionary = planner_1.getBindingDictionary(container); var bindingDictionary1 = planner_1.getBindingDictionary(container1); var bindingDictionary2 = planner_1.getBindingDictionary(container2); function copyDictionary(origin, destination) { origin.traverse(function (key, value) { value.forEach(function (binding) { destination.add(binding.serviceIdentifier, binding.clone()); }); }); } copyDictionary(bindingDictionary1, bindingDictionary); copyDictionary(bindingDictionary2, bindingDictionary); return container; }; Container.prototype.load = function () { var modules = []; for (var _i = 0; _i < arguments.length; _i++) { modules[_i] = arguments[_i]; } var getHelpers = this._getContainerModuleHelpersFactory(); for (var _a = 0, modules_1 = modules; _a < modules_1.length; _a++) { var currentModule = modules_1[_a]; var containerModuleHelpers = getHelpers(currentModule.id); currentModule.registry(containerModuleHelpers.bindFunction, containerModuleHelpers.unbindFunction, containerModuleHelpers.isboundFunction, containerModuleHelpers.rebindFunction); } }; Container.prototype.loadAsync = function () { var modules = []; for (var _i = 0; _i < arguments.length; _i++) { modules[_i] = arguments[_i]; } return __awaiter(this, void 0, void 0, function () { var getHelpers, _a, modules_2, currentModule, containerModuleHelpers; return __generator(this, function (_b) { switch (_b.label) { case 0: getHelpers = this._getContainerModuleHelpersFactory(); _a = 0, modules_2 = modules; _b.label = 1; case 1: if (!(_a < modules_2.length)) return [3, 4]; currentModule = modules_2[_a]; containerModuleHelpers = getHelpers(currentModule.id); return [4, currentModule.registry(containerModuleHelpers.bindFunction, containerModuleHelpers.unbindFunction, containerModuleHelpers.isboundFunction, containerModuleHelpers.rebindFunction)]; case 2: _b.sent(); _b.label = 3; case 3: _a++; return [3, 1]; case 4: return [2]; } }); }); }; Container.prototype.unload = function () { var _this = this; var modules = []; for (var _i = 0; _i < arguments.length; _i++) { modules[_i] = arguments[_i]; } var conditionFactory = function (expected) { return function (item) { return item.moduleId === expected; }; }; modules.forEach(function (module) { var condition = conditionFactory(module.id); _this._bindingDictionary.removeByCondition(condition); }); }; Container.prototype.bind = function (serviceIdentifier) { var scope = this.options.defaultScope || literal_types_1.BindingScopeEnum.Transient; var binding = new binding_1.Binding(serviceIdentifier, scope); this._bindingDictionary.add(serviceIdentifier, binding); return new binding_to_syntax_1.BindingToSyntax(binding); }; Container.prototype.rebind = function (serviceIdentifier) { this.unbind(serviceIdentifier); return this.bind(serviceIdentifier); }; Container.prototype.unbind = function (serviceIdentifier) { try { this._bindingDictionary.remove(serviceIdentifier); } catch (e) { throw new Error(ERROR_MSGS.CANNOT_UNBIND + " " + serialization_1.getServiceIdentifierAsString(serviceIdentifier)); } }; Container.prototype.unbindAll = function () { this._bindingDictionary = new lookup_1.Lookup(); }; Container.prototype.isBound = function (serviceIdentifier) { var bound = this._bindingDictionary.hasKey(serviceIdentifier); if (!bound && this.parent) { bound = this.parent.isBound(serviceIdentifier); } return bound; }; Container.prototype.isBoundNamed = function (serviceIdentifier, named) { return this.isBoundTagged(serviceIdentifier, METADATA_KEY.NAMED_TAG, named); }; Container.prototype.isBoundTagged = function (serviceIdentifier, key, value) { var bound = false; if (this._bindingDictionary.hasKey(serviceIdentifier)) { var bindings = this._bindingDictionary.get(serviceIdentifier); var request_1 = planner_1.createMockRequest(this, serviceIdentifier, key, value); bound = bindings.some(function (b) { return b.constraint(request_1); }); } if (!bound && this.parent) { bound = this.parent.isBoundTagged(serviceIdentifier, key, value); } return bound; }; Container.prototype.snapshot = function () { this._snapshots.push(container_snapshot_1.ContainerSnapshot.of(this._bindingDictionary.clone(), this._middleware)); }; Container.prototype.restore = function () { var snapshot = this._snapshots.pop(); if (snapshot === undefined) { throw new Error(ERROR_MSGS.NO_MORE_SNAPSHOTS_AVAILABLE); } this._bindingDictionary = snapshot.bindings; this._middleware = snapshot.middleware; }; Container.prototype.createChild = function (containerOptions) { var child = new Container(containerOptions || this.options); child.parent = this; return child; }; Container.prototype.applyMiddleware = function () { var middlewares = []; for (var _i = 0; _i < arguments.length; _i++) { middlewares[_i] = arguments[_i]; } var initial = (this._middleware) ? this._middleware : this._planAndResolve(); this._middleware = middlewares.reduce(function (prev, curr) { return curr(prev); }, initial); }; Container.prototype.applyCustomMetadataReader = function (metadataReader) { this._metadataReader = metadataReader; }; Container.prototype.get = function (serviceIdentifier) { return this._get(false, false, literal_types_1.TargetTypeEnum.Variable, serviceIdentifier); }; Container.prototype.getTagged = function (serviceIdentifier, key, value) { return this._get(false, false, literal_types_1.TargetTypeEnum.Variable, serviceIdentifier, key, value); }; Container.prototype.getNamed = function (serviceIdentifier, named) { return this.getTagged(serviceIdentifier, METADATA_KEY.NAMED_TAG, named); }; Container.prototype.getAll = function (serviceIdentifier) { return this._get(true, true, literal_types_1.TargetTypeEnum.Variable, serviceIdentifier); }; Container.prototype.getAllTagged = function (serviceIdentifier, key, value) { return this._get(false, true, literal_types_1.TargetTypeEnum.Variable, serviceIdentifier, key, value); }; Container.prototype.getAllNamed = function (serviceIdentifier, named) { return this.getAllTagged(serviceIdentifier, METADATA_KEY.NAMED_TAG, named); }; Container.prototype.resolve = function (constructorFunction) { var tempContainer = this.createChild(); tempContainer.bind(constructorFunction).toSelf(); return tempContainer.get(constructorFunction); }; Container.prototype._getContainerModuleHelpersFactory = function () { var _this = this; var setModuleId = function (bindingToSyntax, moduleId) { bindingToSyntax._binding.moduleId = moduleId; }; var getBindFunction = function (moduleId) { return function (serviceIdentifier) { var _bind = _this.bind.bind(_this); var bindingToSyntax = _bind(serviceIdentifier); setModuleId(bindingToSyntax, moduleId); return bindingToSyntax; }; }; var getUnbindFunction = function (moduleId) { return function (serviceIdentifier) { var _unbind = _this.unbind.bind(_this); _unbind(serviceIdentifier); }; }; var getIsboundFunction = function (moduleId) { return function (serviceIdentifier) { var _isBound = _this.isBound.bind(_this); return _isBound(serviceIdentifier); }; }; var getRebindFunction = function (moduleId) { return function (serviceIdentifier) { var _rebind = _this.rebind.bind(_this); var bindingToSyntax = _rebind(serviceIdentifier); setModuleId(bindingToSyntax, moduleId); return bindingToSyntax; }; }; return function (mId) { return ({ bindFunction: getBindFunction(mId), isboundFunction: getIsboundFunction(mId), rebindFunction: getRebindFunction(mId), unbindFunction: getUnbindFunction(mId) }); }; }; Container.prototype._get = function (avoidConstraints, isMultiInject, targetType, serviceIdentifier, key, value) { var result = null; var defaultArgs = { avoidConstraints: avoidConstraints, contextInterceptor: function (context) { return context; }, isMultiInject: isMultiInject, key: key, serviceIdentifier: serviceIdentifier, targetType: targetType, value: value }; if (this._middleware) { result = this._middleware(defaultArgs); if (result === undefined || result === null) { throw new Error(ERROR_MSGS.INVALID_MIDDLEWARE_RETURN); } } else { result = this._planAndResolve()(defaultArgs); } return result; }; Container.prototype._planAndResolve = function () { var _this = this; return function (args) { var context = planner_1.plan(_this._metadataReader, _this, args.isMultiInject, args.targetType, args.serviceIdentifier, args.key, args.value, args.avoidConstraints); context = args.contextInterceptor(context); var result = resolver_1.resolve(context); return result; }; }; return Container; }()); exports.Container = Container; /***/ }), /***/ "./node_modules/inversify/lib/container/container_module.js": /*!******************************************************************!*\ !*** ./node_modules/inversify/lib/container/container_module.js ***! \******************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AsyncContainerModule = exports.ContainerModule = void 0; var id_1 = __webpack_require__(/*! ../utils/id */ "./node_modules/inversify/lib/utils/id.js"); var ContainerModule = (function () { function ContainerModule(registry) { this.id = id_1.id(); this.registry = registry; } return ContainerModule; }()); exports.ContainerModule = ContainerModule; var AsyncContainerModule = (function () { function AsyncContainerModule(registry) { this.id = id_1.id(); this.registry = registry; } return AsyncContainerModule; }()); exports.AsyncContainerModule = AsyncContainerModule; /***/ }), /***/ "./node_modules/inversify/lib/container/container_snapshot.js": /*!********************************************************************!*\ !*** ./node_modules/inversify/lib/container/container_snapshot.js ***! \********************************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ContainerSnapshot = void 0; var ContainerSnapshot = (function () { function ContainerSnapshot() { } ContainerSnapshot.of = function (bindings, middleware) { var snapshot = new ContainerSnapshot(); snapshot.bindings = bindings; snapshot.middleware = middleware; return snapshot; }; return ContainerSnapshot; }()); exports.ContainerSnapshot = ContainerSnapshot; /***/ }), /***/ "./node_modules/inversify/lib/container/lookup.js": /*!********************************************************!*\ !*** ./node_modules/inversify/lib/container/lookup.js ***! \********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Lookup = void 0; var ERROR_MSGS = __webpack_require__(/*! ../constants/error_msgs */ "./node_modules/inversify/lib/constants/error_msgs.js"); var Lookup = (function () { function Lookup() { this._map = new Map(); } Lookup.prototype.getMap = function () { return this._map; }; Lookup.prototype.add = function (serviceIdentifier, value) { if (serviceIdentifier === null || serviceIdentifier === undefined) { throw new Error(ERROR_MSGS.NULL_ARGUMENT); } if (value === null || value === undefined) { throw new Error(ERROR_MSGS.NULL_ARGUMENT); } var entry = this._map.get(serviceIdentifier); if (entry !== undefined) { entry.push(value); this._map.set(serviceIdentifier, entry); } else { this._map.set(serviceIdentifier, [value]); } }; Lookup.prototype.get = function (serviceIdentifier) { if (serviceIdentifier === null || serviceIdentifier === undefined) { throw new Error(ERROR_MSGS.NULL_ARGUMENT); } var entry = this._map.get(serviceIdentifier); if (entry !== undefined) { return entry; } else { throw new Error(ERROR_MSGS.KEY_NOT_FOUND); } }; Lookup.prototype.remove = function (serviceIdentifier) { if (serviceIdentifier === null || serviceIdentifier === undefined) { throw new Error(ERROR_MSGS.NULL_ARGUMENT); } if (!this._map.delete(serviceIdentifier)) { throw new Error(ERROR_MSGS.KEY_NOT_FOUND); } }; Lookup.prototype.removeByCondition = function (condition) { var _this = this; this._map.forEach(function (entries, key) { var updatedEntries = entries.filter(function (entry) { return !condition(entry); }); if (updatedEntries.length > 0) { _this._map.set(key, updatedEntries); } else { _this._map.delete(key); } }); }; Lookup.prototype.hasKey = function (serviceIdentifier) { if (serviceIdentifier === null || serviceIdentifier === undefined) { throw new Error(ERROR_MSGS.NULL_ARGUMENT); } return this._map.has(serviceIdentifier); }; Lookup.prototype.clone = function () { var copy = new Lookup(); this._map.forEach(function (value, key) { value.forEach(function (b) { return copy.add(key, b.clone()); }); }); return copy; }; Lookup.prototype.traverse = function (func) { this._map.forEach(function (value, key) { func(key, value); }); }; return Lookup; }()); exports.Lookup = Lookup; /***/ }), /***/ "./node_modules/inversify/lib/inversify.js": /*!*************************************************!*\ !*** ./node_modules/inversify/lib/inversify.js ***! \*************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.METADATA_KEY = void 0; var keys = __webpack_require__(/*! ./constants/metadata_keys */ "./node_modules/inversify/lib/constants/metadata_keys.js"); exports.METADATA_KEY = keys; var container_1 = __webpack_require__(/*! ./container/container */ "./node_modules/inversify/lib/container/container.js"); Object.defineProperty(exports, "Container", ({ enumerable: true, get: function () { return container_1.Container; } })); var literal_types_1 = __webpack_require__(/*! ./constants/literal_types */ "./node_modules/inversify/lib/constants/literal_types.js"); Object.defineProperty(exports, "BindingScopeEnum", ({ enumerable: true, get: function () { return literal_types_1.BindingScopeEnum; } })); Object.defineProperty(exports, "BindingTypeEnum", ({ enumerable: true, get: function () { return literal_types_1.BindingTypeEnum; } })); Object.defineProperty(exports, "TargetTypeEnum", ({ enumerable: true, get: function () { return literal_types_1.TargetTypeEnum; } })); var container_module_1 = __webpack_require__(/*! ./container/container_module */ "./node_modules/inversify/lib/container/container_module.js"); Object.defineProperty(exports, "AsyncContainerModule", ({ enumerable: true, get: function () { return container_module_1.AsyncContainerModule; } })); Object.defineProperty(exports, "ContainerModule", ({ enumerable: true, get: function () { return container_module_1.ContainerModule; } })); var injectable_1 = __webpack_require__(/*! ./annotation/injectable */ "./node_modules/inversify/lib/annotation/injectable.js"); Object.defineProperty(exports, "injectable", ({ enumerable: true, get: function () { return injectable_1.injectable; } })); var tagged_1 = __webpack_require__(/*! ./annotation/tagged */ "./node_modules/inversify/lib/annotation/tagged.js"); Object.defineProperty(exports, "tagged", ({ enumerable: true, get: function () { return tagged_1.tagged; } })); var named_1 = __webpack_require__(/*! ./annotation/named */ "./node_modules/inversify/lib/annotation/named.js"); Object.defineProperty(exports, "named", ({ enumerable: true, get: function () { return named_1.named; } })); var inject_1 = __webpack_require__(/*! ./annotation/inject */ "./node_modules/inversify/lib/annotation/inject.js"); Object.defineProperty(exports, "inject", ({ enumerable: true, get: function () { return inject_1.inject; } })); Object.defineProperty(exports, "LazyServiceIdentifer", ({ enumerable: true, get: function () { return inject_1.LazyServiceIdentifer; } })); var optional_1 = __webpack_require__(/*! ./annotation/optional */ "./node_modules/inversify/lib/annotation/optional.js"); Object.defineProperty(exports, "optional", ({ enumerable: true, get: function () { return optional_1.optional; } })); var unmanaged_1 = __webpack_require__(/*! ./annotation/unmanaged */ "./node_modules/inversify/lib/annotation/unmanaged.js"); Object.defineProperty(exports, "unmanaged", ({ enumerable: true, get: function () { return unmanaged_1.unmanaged; } })); var multi_inject_1 = __webpack_require__(/*! ./annotation/multi_inject */ "./node_modules/inversify/lib/annotation/multi_inject.js"); Object.defineProperty(exports, "multiInject", ({ enumerable: true, get: function () { return multi_inject_1.multiInject; } })); var target_name_1 = __webpack_require__(/*! ./annotation/target_name */ "./node_modules/inversify/lib/annotation/target_name.js"); Object.defineProperty(exports, "targetName", ({ enumerable: true, get: function () { return target_name_1.targetName; } })); var post_construct_1 = __webpack_require__(/*! ./annotation/post_construct */ "./node_modules/inversify/lib/annotation/post_construct.js"); Object.defineProperty(exports, "postConstruct", ({ enumerable: true, get: function () { return post_construct_1.postConstruct; } })); var metadata_reader_1 = __webpack_require__(/*! ./planning/metadata_reader */ "./node_modules/inversify/lib/planning/metadata_reader.js"); Object.defineProperty(exports, "MetadataReader", ({ enumerable: true, get: function () { return metadata_reader_1.MetadataReader; } })); var id_1 = __webpack_require__(/*! ./utils/id */ "./node_modules/inversify/lib/utils/id.js"); Object.defineProperty(exports, "id", ({ enumerable: true, get: function () { return id_1.id; } })); var decorator_utils_1 = __webpack_require__(/*! ./annotation/decorator_utils */ "./node_modules/inversify/lib/annotation/decorator_utils.js"); Object.defineProperty(exports, "decorate", ({ enumerable: true, get: function () { return decorator_utils_1.decorate; } })); var constraint_helpers_1 = __webpack_require__(/*! ./syntax/constraint_helpers */ "./node_modules/inversify/lib/syntax/constraint_helpers.js"); Object.defineProperty(exports, "traverseAncerstors", ({ enumerable: true, get: function () { return constraint_helpers_1.traverseAncerstors; } })); Object.defineProperty(exports, "taggedConstraint", ({ enumerable: true, get: function () { return constraint_helpers_1.taggedConstraint; } })); Object.defineProperty(exports, "namedConstraint", ({ enumerable: true, get: function () { return constraint_helpers_1.namedConstraint; } })); Object.defineProperty(exports, "typeConstraint", ({ enumerable: true, get: function () { return constraint_helpers_1.typeConstraint; } })); var serialization_1 = __webpack_require__(/*! ./utils/serialization */ "./node_modules/inversify/lib/utils/serialization.js"); Object.defineProperty(exports, "getServiceIdentifierAsString", ({ enumerable: true, get: function () { return serialization_1.getServiceIdentifierAsString; } })); var binding_utils_1 = __webpack_require__(/*! ./utils/binding_utils */ "./node_modules/inversify/lib/utils/binding_utils.js"); Object.defineProperty(exports, "multiBindToService", ({ enumerable: true, get: function () { return binding_utils_1.multiBindToService; } })); /***/ }), /***/ "./node_modules/inversify/lib/planning/context.js": /*!********************************************************!*\ !*** ./node_modules/inversify/lib/planning/context.js ***! \********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Context = void 0; var id_1 = __webpack_require__(/*! ../utils/id */ "./node_modules/inversify/lib/utils/id.js"); var Context = (function () { function Context(container) { this.id = id_1.id(); this.container = container; } Context.prototype.addPlan = function (plan) { this.plan = plan; }; Context.prototype.setCurrentRequest = function (currentRequest) { this.currentRequest = currentRequest; }; return Context; }()); exports.Context = Context; /***/ }), /***/ "./node_modules/inversify/lib/planning/metadata.js": /*!*********************************************************!*\ !*** ./node_modules/inversify/lib/planning/metadata.js ***! \*********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Metadata = void 0; var METADATA_KEY = __webpack_require__(/*! ../constants/metadata_keys */ "./node_modules/inversify/lib/constants/metadata_keys.js"); var Metadata = (function () { function Metadata(key, value) { this.key = key; this.value = value; } Metadata.prototype.toString = function () { if (this.key === METADATA_KEY.NAMED_TAG) { return "named: " + this.value.toString() + " "; } else { return "tagged: { key:" + this.key.toString() + ", value: " + this.value + " }"; } }; return Metadata; }()); exports.Metadata = Metadata; /***/ }), /***/ "./node_modules/inversify/lib/planning/metadata_reader.js": /*!****************************************************************!*\ !*** ./node_modules/inversify/lib/planning/metadata_reader.js ***! \****************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MetadataReader = void 0; var METADATA_KEY = __webpack_require__(/*! ../constants/metadata_keys */ "./node_modules/inversify/lib/constants/metadata_keys.js"); var MetadataReader = (function () { function MetadataReader() { } MetadataReader.prototype.getConstructorMetadata = function (constructorFunc) { var compilerGeneratedMetadata = Reflect.getMetadata(METADATA_KEY.PARAM_TYPES, constructorFunc); var userGeneratedMetadata = Reflect.getMetadata(METADATA_KEY.TAGGED, constructorFunc); return { compilerGeneratedMetadata: compilerGeneratedMetadata, userGeneratedMetadata: userGeneratedMetadata || {} }; }; MetadataReader.prototype.getPropertiesMetadata = function (constructorFunc) { var userGeneratedMetadata = Reflect.getMetadata(METADATA_KEY.TAGGED_PROP, constructorFunc) || []; return userGeneratedMetadata; }; return MetadataReader; }()); exports.MetadataReader = MetadataReader; /***/ }), /***/ "./node_modules/inversify/lib/planning/plan.js": /*!*****************************************************!*\ !*** ./node_modules/inversify/lib/planning/plan.js ***! \*****************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Plan = void 0; var Plan = (function () { function Plan(parentContext, rootRequest) { this.parentContext = parentContext; this.rootRequest = rootRequest; } return Plan; }()); exports.Plan = Plan; /***/ }), /***/ "./node_modules/inversify/lib/planning/planner.js": /*!********************************************************!*\ !*** ./node_modules/inversify/lib/planning/planner.js ***! \********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getBindingDictionary = exports.createMockRequest = exports.plan = void 0; var binding_count_1 = __webpack_require__(/*! ../bindings/binding_count */ "./node_modules/inversify/lib/bindings/binding_count.js"); var ERROR_MSGS = __webpack_require__(/*! ../constants/error_msgs */ "./node_modules/inversify/lib/constants/error_msgs.js"); var literal_types_1 = __webpack_require__(/*! ../constants/literal_types */ "./node_modules/inversify/lib/constants/literal_types.js"); var METADATA_KEY = __webpack_require__(/*! ../constants/metadata_keys */ "./node_modules/inversify/lib/constants/metadata_keys.js"); var exceptions_1 = __webpack_require__(/*! ../utils/exceptions */ "./node_modules/inversify/lib/utils/exceptions.js"); var serialization_1 = __webpack_require__(/*! ../utils/serialization */ "./node_modules/inversify/lib/utils/serialization.js"); var context_1 = __webpack_require__(/*! ./context */ "./node_modules/inversify/lib/planning/context.js"); var metadata_1 = __webpack_require__(/*! ./metadata */ "./node_modules/inversify/lib/planning/metadata.js"); var plan_1 = __webpack_require__(/*! ./plan */ "./node_modules/inversify/lib/planning/plan.js"); var reflection_utils_1 = __webpack_require__(/*! ./reflection_utils */ "./node_modules/inversify/lib/planning/reflection_utils.js"); var request_1 = __webpack_require__(/*! ./request */ "./node_modules/inversify/lib/planning/request.js"); var target_1 = __webpack_require__(/*! ./target */ "./node_modules/inversify/lib/planning/target.js"); function getBindingDictionary(cntnr) { return cntnr._bindingDictionary; } exports.getBindingDictionary = getBindingDictionary; function _createTarget(isMultiInject, targetType, serviceIdentifier, name, key, value) { var metadataKey = isMultiInject ? METADATA_KEY.MULTI_INJECT_TAG : METADATA_KEY.INJECT_TAG; var injectMetadata = new metadata_1.Metadata(metadataKey, serviceIdentifier); var target = new target_1.Target(targetType, name, serviceIdentifier, injectMetadata); if (key !== undefined) { var tagMetadata = new metadata_1.Metadata(key, value); target.metadata.push(tagMetadata); } return target; } function _getActiveBindings(metadataReader, avoidConstraints, context, parentRequest, target) { var bindings = getBindings(context.container, target.serviceIdentifier); var activeBindings = []; if (bindings.length === binding_count_1.BindingCount.NoBindingsAvailable && context.container.options.autoBindInjectable && typeof target.serviceIdentifier === "function" && metadataReader.getConstructorMetadata(target.serviceIdentifier).compilerGeneratedMetadata) { context.container.bind(target.serviceIdentifier).toSelf(); bindings = getBindings(context.container, target.serviceIdentifier); } if (!avoidConstraints) { activeBindings = bindings.filter(function (binding) { var request = new request_1.Request(binding.serviceIdentifier, context, parentRequest, binding, target); return binding.constraint(request); }); } else { activeBindings = bindings; } _validateActiveBindingCount(target.serviceIdentifier, activeBindings, target, context.container); return activeBindings; } function _validateActiveBindingCount(serviceIdentifier, bindings, target, container) { switch (bindings.length) { case binding_count_1.BindingCount.NoBindingsAvailable: if (target.isOptional()) { return bindings; } else { var serviceIdentifierString = serialization_1.getServiceIdentifierAsString(serviceIdentifier); var msg = ERROR_MSGS.NOT_REGISTERED; msg += serialization_1.listMetadataForTarget(serviceIdentifierString, target); msg += serialization_1.listRegisteredBindingsForServiceIdentifier(container, serviceIdentifierString, getBindings); throw new Error(msg); } case binding_count_1.BindingCount.OnlyOneBindingAvailable: if (!target.isArray()) { return bindings; } case binding_count_1.BindingCount.MultipleBindingsAvailable: default: if (!target.isArray()) { var serviceIdentifierString = serialization_1.getServiceIdentifierAsString(serviceIdentifier); var msg = ERROR_MSGS.AMBIGUOUS_MATCH + " " + serviceIdentifierString; msg += serialization_1.listRegisteredBindingsForServiceIdentifier(container, serviceIdentifierString, getBindings); throw new Error(msg); } else { return bindings; } } } function _createSubRequests(metadataReader, avoidConstraints, serviceIdentifier, context, parentRequest, target) { var activeBindings; var childRequest; if (parentRequest === null) { activeBindings = _getActiveBindings(metadataReader, avoidConstraints, context, null, target); childRequest = new request_1.Request(serviceIdentifier, context, null, activeBindings, target); var thePlan = new plan_1.Plan(context, childRequest); context.addPlan(thePlan); } else { activeBindings = _getActiveBindings(metadataReader, avoidConstraints, context, parentRequest, target); childRequest = parentRequest.addChildRequest(target.serviceIdentifier, activeBindings, target); } activeBindings.forEach(function (binding) { var subChildRequest = null; if (target.isArray()) { subChildRequest = childRequest.addChildRequest(binding.serviceIdentifier, binding, target); } else { if (binding.cache) { return; } subChildRequest = childRequest; } if (binding.type === literal_types_1.BindingTypeEnum.Instance && binding.implementationType !== null) { var dependencies = reflection_utils_1.getDependencies(metadataReader, binding.implementationType); if (!context.container.options.skipBaseClassChecks) { var baseClassDependencyCount = reflection_utils_1.getBaseClassDependencyCount(metadataReader, binding.implementationType); if (dependencies.length < baseClassDependencyCount) { var error = ERROR_MSGS.ARGUMENTS_LENGTH_MISMATCH(reflection_utils_1.getFunctionName(binding.implementationType)); throw new Error(error); } } dependencies.forEach(function (dependency) { _createSubRequests(metadataReader, false, dependency.serviceIdentifier, context, subChildRequest, dependency); }); } }); } function getBindings(container, serviceIdentifier) { var bindings = []; var bindingDictionary = getBindingDictionary(container); if (bindingDictionary.hasKey(serviceIdentifier)) { bindings = bindingDictionary.get(serviceIdentifier); } else if (container.parent !== null) { bindings = getBindings(container.parent, serviceIdentifier); } return bindings; } function plan(metadataReader, container, isMultiInject, targetType, serviceIdentifier, key, value, avoidConstraints) { if (avoidConstraints === void 0) { avoidConstraints = false; } var context = new context_1.Context(container); var target = _createTarget(isMultiInject, targetType, serviceIdentifier, "", key, value); try { _createSubRequests(metadataReader, avoidConstraints, serviceIdentifier, context, null, target); return context; } catch (error) { if (exceptions_1.isStackOverflowExeption(error)) { if (context.plan) { serialization_1.circularDependencyToException(context.plan.rootRequest); } } throw error; } } exports.plan = plan; function createMockRequest(container, serviceIdentifier, key, value) { var target = new target_1.Target(literal_types_1.TargetTypeEnum.Variable, "", serviceIdentifier, new metadata_1.Metadata(key, value)); var context = new context_1.Context(container); var request = new request_1.Request(serviceIdentifier, context, null, [], target); return request; } exports.createMockRequest = createMockRequest; /***/ }), /***/ "./node_modules/inversify/lib/planning/queryable_string.js": /*!*****************************************************************!*\ !*** ./node_modules/inversify/lib/planning/queryable_string.js ***! \*****************************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.QueryableString = void 0; var QueryableString = (function () { function QueryableString(str) { this.str = str; } QueryableString.prototype.startsWith = function (searchString) { return this.str.indexOf(searchString) === 0; }; QueryableString.prototype.endsWith = function (searchString) { var reverseString = ""; var reverseSearchString = searchString.split("").reverse().join(""); reverseString = this.str.split("").reverse().join(""); return this.startsWith.call({ str: reverseString }, reverseSearchString); }; QueryableString.prototype.contains = function (searchString) { return (this.str.indexOf(searchString) !== -1); }; QueryableString.prototype.equals = function (compareString) { return this.str === compareString; }; QueryableString.prototype.value = function () { return this.str; }; return QueryableString; }()); exports.QueryableString = QueryableString; /***/ }), /***/ "./node_modules/inversify/lib/planning/reflection_utils.js": /*!*****************************************************************!*\ !*** ./node_modules/inversify/lib/planning/reflection_utils.js ***! \*****************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __spreadArrays = (this && this.__spreadArrays) || function () { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getFunctionName = exports.getBaseClassDependencyCount = exports.getDependencies = void 0; var inject_1 = __webpack_require__(/*! ../annotation/inject */ "./node_modules/inversify/lib/annotation/inject.js"); var ERROR_MSGS = __webpack_require__(/*! ../constants/error_msgs */ "./node_modules/inversify/lib/constants/error_msgs.js"); var literal_types_1 = __webpack_require__(/*! ../constants/literal_types */ "./node_modules/inversify/lib/constants/literal_types.js"); var METADATA_KEY = __webpack_require__(/*! ../constants/metadata_keys */ "./node_modules/inversify/lib/constants/metadata_keys.js"); var serialization_1 = __webpack_require__(/*! ../utils/serialization */ "./node_modules/inversify/lib/utils/serialization.js"); Object.defineProperty(exports, "getFunctionName", ({ enumerable: true, get: function () { return serialization_1.getFunctionName; } })); var target_1 = __webpack_require__(/*! ./target */ "./node_modules/inversify/lib/planning/target.js"); function getDependencies(metadataReader, func) { var constructorName = serialization_1.getFunctionName(func); var targets = getTargets(metadataReader, constructorName, func, false); return targets; } exports.getDependencies = getDependencies; function getTargets(metadataReader, constructorName, func, isBaseClass) { var metadata = metadataReader.getConstructorMetadata(func); var serviceIdentifiers = metadata.compilerGeneratedMetadata; if (serviceIdentifiers === undefined) { var msg = ERROR_MSGS.MISSING_INJECTABLE_ANNOTATION + " " + constructorName + "."; throw new Error(msg); } var constructorArgsMetadata = metadata.userGeneratedMetadata; var keys = Object.keys(constructorArgsMetadata); var hasUserDeclaredUnknownInjections = (func.length === 0 && keys.length > 0); var iterations = (hasUserDeclaredUnknownInjections) ? keys.length : func.length; var constructorTargets = getConstructorArgsAsTargets(isBaseClass, constructorName, serviceIdentifiers, constructorArgsMetadata, iterations); var propertyTargets = getClassPropsAsTargets(metadataReader, func); var targets = __spreadArrays(constructorTargets, propertyTargets); return targets; } function getConstructorArgsAsTarget(index, isBaseClass, constructorName, serviceIdentifiers, constructorArgsMetadata) { var targetMetadata = constructorArgsMetadata[index.toString()] || []; var metadata = formatTargetMetadata(targetMetadata); var isManaged = metadata.unmanaged !== true; var serviceIdentifier = serviceIdentifiers[index]; var injectIdentifier = (metadata.inject || metadata.multiInject); serviceIdentifier = (injectIdentifier) ? (injectIdentifier) : serviceIdentifier; if (serviceIdentifier instanceof inject_1.LazyServiceIdentifer) { serviceIdentifier = serviceIdentifier.unwrap(); } if (isManaged) { var isObject = serviceIdentifier === Object; var isFunction = serviceIdentifier === Function; var isUndefined = serviceIdentifier === undefined; var isUnknownType = (isObject || isFunction || isUndefined); if (!isBaseClass && isUnknownType) { var msg = ERROR_MSGS.MISSING_INJECT_ANNOTATION + " argument " + index + " in class " + constructorName + "."; throw new Error(msg); } var target = new target_1.Target(literal_types_1.TargetTypeEnum.ConstructorArgument, metadata.targetName, serviceIdentifier); target.metadata = targetMetadata; return target; } return null; } function getConstructorArgsAsTargets(isBaseClass, constructorName, serviceIdentifiers, constructorArgsMetadata, iterations) { var targets = []; for (var i = 0; i < iterations; i++) { var index = i; var target = getConstructorArgsAsTarget(index, isBaseClass, constructorName, serviceIdentifiers, constructorArgsMetadata); if (target !== null) { targets.push(target); } } return targets; } function getClassPropsAsTargets(metadataReader, constructorFunc) { var classPropsMetadata = metadataReader.getPropertiesMetadata(constructorFunc); var targets = []; var keys = Object.keys(classPropsMetadata); for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) { var key = keys_1[_i]; var targetMetadata = classPropsMetadata[key]; var metadata = formatTargetMetadata(classPropsMetadata[key]); var targetName = metadata.targetName || key; var serviceIdentifier = (metadata.inject || metadata.multiInject); var target = new target_1.Target(literal_types_1.TargetTypeEnum.ClassProperty, targetName, serviceIdentifier); target.metadata = targetMetadata; targets.push(target); } var baseConstructor = Object.getPrototypeOf(constructorFunc.prototype).constructor; if (baseConstructor !== Object) { var baseTargets = getClassPropsAsTargets(metadataReader, baseConstructor); targets = __spreadArrays(targets, baseTargets); } return targets; } function getBaseClassDependencyCount(metadataReader, func) { var baseConstructor = Object.getPrototypeOf(func.prototype).constructor; if (baseConstructor !== Object) { var baseConstructorName = serialization_1.getFunctionName(baseConstructor); var targets = getTargets(metadataReader, baseConstructorName, baseConstructor, true); var metadata = targets.map(function (t) { return t.metadata.filter(function (m) { return m.key === METADATA_KEY.UNMANAGED_TAG; }); }); var unmanagedCount = [].concat.apply([], metadata).length; var dependencyCount = targets.length - unmanagedCount; if (dependencyCount > 0) { return dependencyCount; } else { return getBaseClassDependencyCount(metadataReader, baseConstructor); } } else { return 0; } } exports.getBaseClassDependencyCount = getBaseClassDependencyCount; function formatTargetMetadata(targetMetadata) { var targetMetadataMap = {}; targetMetadata.forEach(function (m) { targetMetadataMap[m.key.toString()] = m.value; }); return { inject: targetMetadataMap[METADATA_KEY.INJECT_TAG], multiInject: targetMetadataMap[METADATA_KEY.MULTI_INJECT_TAG], targetName: targetMetadataMap[METADATA_KEY.NAME_TAG], unmanaged: targetMetadataMap[METADATA_KEY.UNMANAGED_TAG] }; } /***/ }), /***/ "./node_modules/inversify/lib/planning/request.js": /*!********************************************************!*\ !*** ./node_modules/inversify/lib/planning/request.js ***! \********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Request = void 0; var id_1 = __webpack_require__(/*! ../utils/id */ "./node_modules/inversify/lib/utils/id.js"); var Request = (function () { function Request(serviceIdentifier, parentContext, parentRequest, bindings, target) { this.id = id_1.id(); this.serviceIdentifier = serviceIdentifier; this.parentContext = parentContext; this.parentRequest = parentRequest; this.target = target; this.childRequests = []; this.bindings = (Array.isArray(bindings) ? bindings : [bindings]); this.requestScope = parentRequest === null ? new Map() : null; } Request.prototype.addChildRequest = function (serviceIdentifier, bindings, target) { var child = new Request(serviceIdentifier, this.parentContext, this, bindings, target); this.childRequests.push(child); return child; }; return Request; }()); exports.Request = Request; /***/ }), /***/ "./node_modules/inversify/lib/planning/target.js": /*!*******************************************************!*\ !*** ./node_modules/inversify/lib/planning/target.js ***! \*******************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Target = void 0; var METADATA_KEY = __webpack_require__(/*! ../constants/metadata_keys */ "./node_modules/inversify/lib/constants/metadata_keys.js"); var id_1 = __webpack_require__(/*! ../utils/id */ "./node_modules/inversify/lib/utils/id.js"); var metadata_1 = __webpack_require__(/*! ./metadata */ "./node_modules/inversify/lib/planning/metadata.js"); var queryable_string_1 = __webpack_require__(/*! ./queryable_string */ "./node_modules/inversify/lib/planning/queryable_string.js"); var Target = (function () { function Target(type, name, serviceIdentifier, namedOrTagged) { this.id = id_1.id(); this.type = type; this.serviceIdentifier = serviceIdentifier; this.name = new queryable_string_1.QueryableString(name || ""); this.metadata = new Array(); var metadataItem = null; if (typeof namedOrTagged === "string") { metadataItem = new metadata_1.Metadata(METADATA_KEY.NAMED_TAG, namedOrTagged); } else if (namedOrTagged instanceof metadata_1.Metadata) { metadataItem = namedOrTagged; } if (metadataItem !== null) { this.metadata.push(metadataItem); } } Target.prototype.hasTag = function (key) { for (var _i = 0, _a = this.metadata; _i < _a.length; _i++) { var m = _a[_i]; if (m.key === key) { return true; } } return false; }; Target.prototype.isArray = function () { return this.hasTag(METADATA_KEY.MULTI_INJECT_TAG); }; Target.prototype.matchesArray = function (name) { return this.matchesTag(METADATA_KEY.MULTI_INJECT_TAG)(name); }; Target.prototype.isNamed = function () { return this.hasTag(METADATA_KEY.NAMED_TAG); }; Target.prototype.isTagged = function () { return this.metadata.some(function (m) { return (m.key !== METADATA_KEY.INJECT_TAG) && (m.key !== METADATA_KEY.MULTI_INJECT_TAG) && (m.key !== METADATA_KEY.NAME_TAG) && (m.key !== METADATA_KEY.UNMANAGED_TAG) && (m.key !== METADATA_KEY.NAMED_TAG); }); }; Target.prototype.isOptional = function () { return this.matchesTag(METADATA_KEY.OPTIONAL_TAG)(true); }; Target.prototype.getNamedTag = function () { if (this.isNamed()) { return this.metadata.filter(function (m) { return m.key === METADATA_KEY.NAMED_TAG; })[0]; } return null; }; Target.prototype.getCustomTags = function () { if (this.isTagged()) { return this.metadata.filter(function (m) { return (m.key !== METADATA_KEY.INJECT_TAG) && (m.key !== METADATA_KEY.MULTI_INJECT_TAG) && (m.key !== METADATA_KEY.NAME_TAG) && (m.key !== METADATA_KEY.UNMANAGED_TAG) && (m.key !== METADATA_KEY.NAMED_TAG); }); } return null; }; Target.prototype.matchesNamedTag = function (name) { return this.matchesTag(METADATA_KEY.NAMED_TAG)(name); }; Target.prototype.matchesTag = function (key) { var _this = this; return function (value) { for (var _i = 0, _a = _this.metadata; _i < _a.length; _i++) { var m = _a[_i]; if (m.key === key && m.value === value) { return true; } } return false; }; }; return Target; }()); exports.Target = Target; /***/ }), /***/ "./node_modules/inversify/lib/resolution/instantiation.js": /*!****************************************************************!*\ !*** ./node_modules/inversify/lib/resolution/instantiation.js ***! \****************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __spreadArrays = (this && this.__spreadArrays) || function () { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveInstance = void 0; var error_msgs_1 = __webpack_require__(/*! ../constants/error_msgs */ "./node_modules/inversify/lib/constants/error_msgs.js"); var literal_types_1 = __webpack_require__(/*! ../constants/literal_types */ "./node_modules/inversify/lib/constants/literal_types.js"); var METADATA_KEY = __webpack_require__(/*! ../constants/metadata_keys */ "./node_modules/inversify/lib/constants/metadata_keys.js"); function _injectProperties(instance, childRequests, resolveRequest) { var propertyInjectionsRequests = childRequests.filter(function (childRequest) { return (childRequest.target !== null && childRequest.target.type === literal_types_1.TargetTypeEnum.ClassProperty); }); var propertyInjections = propertyInjectionsRequests.map(resolveRequest); propertyInjectionsRequests.forEach(function (r, index) { var propertyName = ""; propertyName = r.target.name.value(); var injection = propertyInjections[index]; instance[propertyName] = injection; }); return instance; } function _createInstance(Func, injections) { return new (Func.bind.apply(Func, __spreadArrays([void 0], injections)))(); } function _postConstruct(constr, result) { if (Reflect.hasMetadata(METADATA_KEY.POST_CONSTRUCT, constr)) { var data = Reflect.getMetadata(METADATA_KEY.POST_CONSTRUCT, constr); try { result[data.value](); } catch (e) { throw new Error(error_msgs_1.POST_CONSTRUCT_ERROR(constr.name, e.message)); } } } function resolveInstance(constr, childRequests, resolveRequest) { var result = null; if (childRequests.length > 0) { var constructorInjectionsRequests = childRequests.filter(function (childRequest) { return (childRequest.target !== null && childRequest.target.type === literal_types_1.TargetTypeEnum.ConstructorArgument); }); var constructorInjections = constructorInjectionsRequests.map(resolveRequest); result = _createInstance(constr, constructorInjections); result = _injectProperties(result, childRequests, resolveRequest); } else { result = new constr(); } _postConstruct(constr, result); return result; } exports.resolveInstance = resolveInstance; /***/ }), /***/ "./node_modules/inversify/lib/resolution/resolver.js": /*!***********************************************************!*\ !*** ./node_modules/inversify/lib/resolution/resolver.js ***! \***********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolve = void 0; var ERROR_MSGS = __webpack_require__(/*! ../constants/error_msgs */ "./node_modules/inversify/lib/constants/error_msgs.js"); var literal_types_1 = __webpack_require__(/*! ../constants/literal_types */ "./node_modules/inversify/lib/constants/literal_types.js"); var exceptions_1 = __webpack_require__(/*! ../utils/exceptions */ "./node_modules/inversify/lib/utils/exceptions.js"); var serialization_1 = __webpack_require__(/*! ../utils/serialization */ "./node_modules/inversify/lib/utils/serialization.js"); var instantiation_1 = __webpack_require__(/*! ./instantiation */ "./node_modules/inversify/lib/resolution/instantiation.js"); var invokeFactory = function (factoryType, serviceIdentifier, fn) { try { return fn(); } catch (error) { if (exceptions_1.isStackOverflowExeption(error)) { throw new Error(ERROR_MSGS.CIRCULAR_DEPENDENCY_IN_FACTORY(factoryType, serviceIdentifier.toString())); } else { throw error; } } }; var _resolveRequest = function (requestScope) { return function (request) { request.parentContext.setCurrentRequest(request); var bindings = request.bindings; var childRequests = request.childRequests; var targetIsAnArray = request.target && request.target.isArray(); var targetParentIsNotAnArray = !request.parentRequest || !request.parentRequest.target || !request.target || !request.parentRequest.target.matchesArray(request.target.serviceIdentifier); if (targetIsAnArray && targetParentIsNotAnArray) { return childRequests.map(function (childRequest) { var _f = _resolveRequest(requestScope); return _f(childRequest); }); } else { var result = null; if (request.target.isOptional() && bindings.length === 0) { return undefined; } var binding_1 = bindings[0]; var isSingleton = binding_1.scope === literal_types_1.BindingScopeEnum.Singleton; var isRequestSingleton = binding_1.scope === literal_types_1.BindingScopeEnum.Request; if (isSingleton && binding_1.activated) { return binding_1.cache; } if (isRequestSingleton && requestScope !== null && requestScope.has(binding_1.id)) { return requestScope.get(binding_1.id); } if (binding_1.type === literal_types_1.BindingTypeEnum.ConstantValue) { result = binding_1.cache; } else if (binding_1.type === literal_types_1.BindingTypeEnum.Function) { result = binding_1.cache; } else if (binding_1.type === literal_types_1.BindingTypeEnum.Constructor) { result = binding_1.implementationType; } else if (binding_1.type === literal_types_1.BindingTypeEnum.DynamicValue && binding_1.dynamicValue !== null) { result = invokeFactory("toDynamicValue", binding_1.serviceIdentifier, function () { return binding_1.dynamicValue(request.parentContext); }); } else if (binding_1.type === literal_types_1.BindingTypeEnum.Factory && binding_1.factory !== null) { result = invokeFactory("toFactory", binding_1.serviceIdentifier, function () { return binding_1.factory(request.parentContext); }); } else if (binding_1.type === literal_types_1.BindingTypeEnum.Provider && binding_1.provider !== null) { result = invokeFactory("toProvider", binding_1.serviceIdentifier, function () { return binding_1.provider(request.parentContext); }); } else if (binding_1.type === literal_types_1.BindingTypeEnum.Instance && binding_1.implementationType !== null) { result = instantiation_1.resolveInstance(binding_1.implementationType, childRequests, _resolveRequest(requestScope)); } else { var serviceIdentifier = serialization_1.getServiceIdentifierAsString(request.serviceIdentifier); throw new Error(ERROR_MSGS.INVALID_BINDING_TYPE + " " + serviceIdentifier); } if (typeof binding_1.onActivation === "function") { result = binding_1.onActivation(request.parentContext, result); } if (isSingleton) { binding_1.cache = result; binding_1.activated = true; } if (isRequestSingleton && requestScope !== null && !requestScope.has(binding_1.id)) { requestScope.set(binding_1.id, result); } return result; } }; }; function resolve(context) { var _f = _resolveRequest(context.plan.rootRequest.requestScope); return _f(context.plan.rootRequest); } exports.resolve = resolve; /***/ }), /***/ "./node_modules/inversify/lib/syntax/binding_in_syntax.js": /*!****************************************************************!*\ !*** ./node_modules/inversify/lib/syntax/binding_in_syntax.js ***! \****************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BindingInSyntax = void 0; var literal_types_1 = __webpack_require__(/*! ../constants/literal_types */ "./node_modules/inversify/lib/constants/literal_types.js"); var binding_when_on_syntax_1 = __webpack_require__(/*! ./binding_when_on_syntax */ "./node_modules/inversify/lib/syntax/binding_when_on_syntax.js"); var BindingInSyntax = (function () { function BindingInSyntax(binding) { this._binding = binding; } BindingInSyntax.prototype.inRequestScope = function () { this._binding.scope = literal_types_1.BindingScopeEnum.Request; return new binding_when_on_syntax_1.BindingWhenOnSyntax(this._binding); }; BindingInSyntax.prototype.inSingletonScope = function () { this._binding.scope = literal_types_1.BindingScopeEnum.Singleton; return new binding_when_on_syntax_1.BindingWhenOnSyntax(this._binding); }; BindingInSyntax.prototype.inTransientScope = function () { this._binding.scope = literal_types_1.BindingScopeEnum.Transient; return new binding_when_on_syntax_1.BindingWhenOnSyntax(this._binding); }; return BindingInSyntax; }()); exports.BindingInSyntax = BindingInSyntax; /***/ }), /***/ "./node_modules/inversify/lib/syntax/binding_in_when_on_syntax.js": /*!************************************************************************!*\ !*** ./node_modules/inversify/lib/syntax/binding_in_when_on_syntax.js ***! \************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BindingInWhenOnSyntax = void 0; var binding_in_syntax_1 = __webpack_require__(/*! ./binding_in_syntax */ "./node_modules/inversify/lib/syntax/binding_in_syntax.js"); var binding_on_syntax_1 = __webpack_require__(/*! ./binding_on_syntax */ "./node_modules/inversify/lib/syntax/binding_on_syntax.js"); var binding_when_syntax_1 = __webpack_require__(/*! ./binding_when_syntax */ "./node_modules/inversify/lib/syntax/binding_when_syntax.js"); var BindingInWhenOnSyntax = (function () { function BindingInWhenOnSyntax(binding) { this._binding = binding; this._bindingWhenSyntax = new binding_when_syntax_1.BindingWhenSyntax(this._binding); this._bindingOnSyntax = new binding_on_syntax_1.BindingOnSyntax(this._binding); this._bindingInSyntax = new binding_in_syntax_1.BindingInSyntax(binding); } BindingInWhenOnSyntax.prototype.inRequestScope = function () { return this._bindingInSyntax.inRequestScope(); }; BindingInWhenOnSyntax.prototype.inSingletonScope = function () { return this._bindingInSyntax.inSingletonScope(); }; BindingInWhenOnSyntax.prototype.inTransientScope = function () { return this._bindingInSyntax.inTransientScope(); }; BindingInWhenOnSyntax.prototype.when = function (constraint) { return this._bindingWhenSyntax.when(constraint); }; BindingInWhenOnSyntax.prototype.whenTargetNamed = function (name) { return this._bindingWhenSyntax.whenTargetNamed(name); }; BindingInWhenOnSyntax.prototype.whenTargetIsDefault = function () { return this._bindingWhenSyntax.whenTargetIsDefault(); }; BindingInWhenOnSyntax.prototype.whenTargetTagged = function (tag, value) { return this._bindingWhenSyntax.whenTargetTagged(tag, value); }; BindingInWhenOnSyntax.prototype.whenInjectedInto = function (parent) { return this._bindingWhenSyntax.whenInjectedInto(parent); }; BindingInWhenOnSyntax.prototype.whenParentNamed = function (name) { return this._bindingWhenSyntax.whenParentNamed(name); }; BindingInWhenOnSyntax.prototype.whenParentTagged = function (tag, value) { return this._bindingWhenSyntax.whenParentTagged(tag, value); }; BindingInWhenOnSyntax.prototype.whenAnyAncestorIs = function (ancestor) { return this._bindingWhenSyntax.whenAnyAncestorIs(ancestor); }; BindingInWhenOnSyntax.prototype.whenNoAncestorIs = function (ancestor) { return this._bindingWhenSyntax.whenNoAncestorIs(ancestor); }; BindingInWhenOnSyntax.prototype.whenAnyAncestorNamed = function (name) { return this._bindingWhenSyntax.whenAnyAncestorNamed(name); }; BindingInWhenOnSyntax.prototype.whenAnyAncestorTagged = function (tag, value) { return this._bindingWhenSyntax.whenAnyAncestorTagged(tag, value); }; BindingInWhenOnSyntax.prototype.whenNoAncestorNamed = function (name) { return this._bindingWhenSyntax.whenNoAncestorNamed(name); }; BindingInWhenOnSyntax.prototype.whenNoAncestorTagged = function (tag, value) { return this._bindingWhenSyntax.whenNoAncestorTagged(tag, value); }; BindingInWhenOnSyntax.prototype.whenAnyAncestorMatches = function (constraint) { return this._bindingWhenSyntax.whenAnyAncestorMatches(constraint); }; BindingInWhenOnSyntax.prototype.whenNoAncestorMatches = function (constraint) { return this._bindingWhenSyntax.whenNoAncestorMatches(constraint); }; BindingInWhenOnSyntax.prototype.onActivation = function (handler) { return this._bindingOnSyntax.onActivation(handler); }; return BindingInWhenOnSyntax; }()); exports.BindingInWhenOnSyntax = BindingInWhenOnSyntax; /***/ }), /***/ "./node_modules/inversify/lib/syntax/binding_on_syntax.js": /*!****************************************************************!*\ !*** ./node_modules/inversify/lib/syntax/binding_on_syntax.js ***! \****************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BindingOnSyntax = void 0; var binding_when_syntax_1 = __webpack_require__(/*! ./binding_when_syntax */ "./node_modules/inversify/lib/syntax/binding_when_syntax.js"); var BindingOnSyntax = (function () { function BindingOnSyntax(binding) { this._binding = binding; } BindingOnSyntax.prototype.onActivation = function (handler) { this._binding.onActivation = handler; return new binding_when_syntax_1.BindingWhenSyntax(this._binding); }; return BindingOnSyntax; }()); exports.BindingOnSyntax = BindingOnSyntax; /***/ }), /***/ "./node_modules/inversify/lib/syntax/binding_to_syntax.js": /*!****************************************************************!*\ !*** ./node_modules/inversify/lib/syntax/binding_to_syntax.js ***! \****************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BindingToSyntax = void 0; var ERROR_MSGS = __webpack_require__(/*! ../constants/error_msgs */ "./node_modules/inversify/lib/constants/error_msgs.js"); var literal_types_1 = __webpack_require__(/*! ../constants/literal_types */ "./node_modules/inversify/lib/constants/literal_types.js"); var binding_in_when_on_syntax_1 = __webpack_require__(/*! ./binding_in_when_on_syntax */ "./node_modules/inversify/lib/syntax/binding_in_when_on_syntax.js"); var binding_when_on_syntax_1 = __webpack_require__(/*! ./binding_when_on_syntax */ "./node_modules/inversify/lib/syntax/binding_when_on_syntax.js"); var BindingToSyntax = (function () { function BindingToSyntax(binding) { this._binding = binding; } BindingToSyntax.prototype.to = function (constructor) { this._binding.type = literal_types_1.BindingTypeEnum.Instance; this._binding.implementationType = constructor; return new binding_in_when_on_syntax_1.BindingInWhenOnSyntax(this._binding); }; BindingToSyntax.prototype.toSelf = function () { if (typeof this._binding.serviceIdentifier !== "function") { throw new Error("" + ERROR_MSGS.INVALID_TO_SELF_VALUE); } var self = this._binding.serviceIdentifier; return this.to(self); }; BindingToSyntax.prototype.toConstantValue = function (value) { this._binding.type = literal_types_1.BindingTypeEnum.ConstantValue; this._binding.cache = value; this._binding.dynamicValue = null; this._binding.implementationType = null; return new binding_when_on_syntax_1.BindingWhenOnSyntax(this._binding); }; BindingToSyntax.prototype.toDynamicValue = function (func) { this._binding.type = literal_types_1.BindingTypeEnum.DynamicValue; this._binding.cache = null; this._binding.dynamicValue = func; this._binding.implementationType = null; return new binding_in_when_on_syntax_1.BindingInWhenOnSyntax(this._binding); }; BindingToSyntax.prototype.toConstructor = function (constructor) { this._binding.type = literal_types_1.BindingTypeEnum.Constructor; this._binding.implementationType = constructor; return new binding_when_on_syntax_1.BindingWhenOnSyntax(this._binding); }; BindingToSyntax.prototype.toFactory = function (factory) { this._binding.type = literal_types_1.BindingTypeEnum.Factory; this._binding.factory = factory; return new binding_when_on_syntax_1.BindingWhenOnSyntax(this._binding); }; BindingToSyntax.prototype.toFunction = function (func) { if (typeof func !== "function") { throw new Error(ERROR_MSGS.INVALID_FUNCTION_BINDING); } var bindingWhenOnSyntax = this.toConstantValue(func); this._binding.type = literal_types_1.BindingTypeEnum.Function; return bindingWhenOnSyntax; }; BindingToSyntax.prototype.toAutoFactory = function (serviceIdentifier) { this._binding.type = literal_types_1.BindingTypeEnum.Factory; this._binding.factory = function (context) { var autofactory = function () { return context.container.get(serviceIdentifier); }; return autofactory; }; return new binding_when_on_syntax_1.BindingWhenOnSyntax(this._binding); }; BindingToSyntax.prototype.toProvider = function (provider) { this._binding.type = literal_types_1.BindingTypeEnum.Provider; this._binding.provider = provider; return new binding_when_on_syntax_1.BindingWhenOnSyntax(this._binding); }; BindingToSyntax.prototype.toService = function (service) { this.toDynamicValue(function (context) { return context.container.get(service); }); }; return BindingToSyntax; }()); exports.BindingToSyntax = BindingToSyntax; /***/ }), /***/ "./node_modules/inversify/lib/syntax/binding_when_on_syntax.js": /*!*********************************************************************!*\ !*** ./node_modules/inversify/lib/syntax/binding_when_on_syntax.js ***! \*********************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BindingWhenOnSyntax = void 0; var binding_on_syntax_1 = __webpack_require__(/*! ./binding_on_syntax */ "./node_modules/inversify/lib/syntax/binding_on_syntax.js"); var binding_when_syntax_1 = __webpack_require__(/*! ./binding_when_syntax */ "./node_modules/inversify/lib/syntax/binding_when_syntax.js"); var BindingWhenOnSyntax = (function () { function BindingWhenOnSyntax(binding) { this._binding = binding; this._bindingWhenSyntax = new binding_when_syntax_1.BindingWhenSyntax(this._binding); this._bindingOnSyntax = new binding_on_syntax_1.BindingOnSyntax(this._binding); } BindingWhenOnSyntax.prototype.when = function (constraint) { return this._bindingWhenSyntax.when(constraint); }; BindingWhenOnSyntax.prototype.whenTargetNamed = function (name) { return this._bindingWhenSyntax.whenTargetNamed(name); }; BindingWhenOnSyntax.prototype.whenTargetIsDefault = function () { return this._bindingWhenSyntax.whenTargetIsDefault(); }; BindingWhenOnSyntax.prototype.whenTargetTagged = function (tag, value) { return this._bindingWhenSyntax.whenTargetTagged(tag, value); }; BindingWhenOnSyntax.prototype.whenInjectedInto = function (parent) { return this._bindingWhenSyntax.whenInjectedInto(parent); }; BindingWhenOnSyntax.prototype.whenParentNamed = function (name) { return this._bindingWhenSyntax.whenParentNamed(name); }; BindingWhenOnSyntax.prototype.whenParentTagged = function (tag, value) { return this._bindingWhenSyntax.whenParentTagged(tag, value); }; BindingWhenOnSyntax.prototype.whenAnyAncestorIs = function (ancestor) { return this._bindingWhenSyntax.whenAnyAncestorIs(ancestor); }; BindingWhenOnSyntax.prototype.whenNoAncestorIs = function (ancestor) { return this._bindingWhenSyntax.whenNoAncestorIs(ancestor); }; BindingWhenOnSyntax.prototype.whenAnyAncestorNamed = function (name) { return this._bindingWhenSyntax.whenAnyAncestorNamed(name); }; BindingWhenOnSyntax.prototype.whenAnyAncestorTagged = function (tag, value) { return this._bindingWhenSyntax.whenAnyAncestorTagged(tag, value); }; BindingWhenOnSyntax.prototype.whenNoAncestorNamed = function (name) { return this._bindingWhenSyntax.whenNoAncestorNamed(name); }; BindingWhenOnSyntax.prototype.whenNoAncestorTagged = function (tag, value) { return this._bindingWhenSyntax.whenNoAncestorTagged(tag, value); }; BindingWhenOnSyntax.prototype.whenAnyAncestorMatches = function (constraint) { return this._bindingWhenSyntax.whenAnyAncestorMatches(constraint); }; BindingWhenOnSyntax.prototype.whenNoAncestorMatches = function (constraint) { return this._bindingWhenSyntax.whenNoAncestorMatches(constraint); }; BindingWhenOnSyntax.prototype.onActivation = function (handler) { return this._bindingOnSyntax.onActivation(handler); }; return BindingWhenOnSyntax; }()); exports.BindingWhenOnSyntax = BindingWhenOnSyntax; /***/ }), /***/ "./node_modules/inversify/lib/syntax/binding_when_syntax.js": /*!******************************************************************!*\ !*** ./node_modules/inversify/lib/syntax/binding_when_syntax.js ***! \******************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BindingWhenSyntax = void 0; var binding_on_syntax_1 = __webpack_require__(/*! ./binding_on_syntax */ "./node_modules/inversify/lib/syntax/binding_on_syntax.js"); var constraint_helpers_1 = __webpack_require__(/*! ./constraint_helpers */ "./node_modules/inversify/lib/syntax/constraint_helpers.js"); var BindingWhenSyntax = (function () { function BindingWhenSyntax(binding) { this._binding = binding; } BindingWhenSyntax.prototype.when = function (constraint) { this._binding.constraint = constraint; return new binding_on_syntax_1.BindingOnSyntax(this._binding); }; BindingWhenSyntax.prototype.whenTargetNamed = function (name) { this._binding.constraint = constraint_helpers_1.namedConstraint(name); return new binding_on_syntax_1.BindingOnSyntax(this._binding); }; BindingWhenSyntax.prototype.whenTargetIsDefault = function () { this._binding.constraint = function (request) { var targetIsDefault = (request.target !== null) && (!request.target.isNamed()) && (!request.target.isTagged()); return targetIsDefault; }; return new binding_on_syntax_1.BindingOnSyntax(this._binding); }; BindingWhenSyntax.prototype.whenTargetTagged = function (tag, value) { this._binding.constraint = constraint_helpers_1.taggedConstraint(tag)(value); return new binding_on_syntax_1.BindingOnSyntax(this._binding); }; BindingWhenSyntax.prototype.whenInjectedInto = function (parent) { this._binding.constraint = function (request) { return constraint_helpers_1.typeConstraint(parent)(request.parentRequest); }; return new binding_on_syntax_1.BindingOnSyntax(this._binding); }; BindingWhenSyntax.prototype.whenParentNamed = function (name) { this._binding.constraint = function (request) { return constraint_helpers_1.namedConstraint(name)(request.parentRequest); }; return new binding_on_syntax_1.BindingOnSyntax(this._binding); }; BindingWhenSyntax.prototype.whenParentTagged = function (tag, value) { this._binding.constraint = function (request) { return constraint_helpers_1.taggedConstraint(tag)(value)(request.parentRequest); }; return new binding_on_syntax_1.BindingOnSyntax(this._binding); }; BindingWhenSyntax.prototype.whenAnyAncestorIs = function (ancestor) { this._binding.constraint = function (request) { return constraint_helpers_1.traverseAncerstors(request, constraint_helpers_1.typeConstraint(ancestor)); }; return new binding_on_syntax_1.BindingOnSyntax(this._binding); }; BindingWhenSyntax.prototype.whenNoAncestorIs = function (ancestor) { this._binding.constraint = function (request) { return !constraint_helpers_1.traverseAncerstors(request, constraint_helpers_1.typeConstraint(ancestor)); }; return new binding_on_syntax_1.BindingOnSyntax(this._binding); }; BindingWhenSyntax.prototype.whenAnyAncestorNamed = function (name) { this._binding.constraint = function (request) { return constraint_helpers_1.traverseAncerstors(request, constraint_helpers_1.namedConstraint(name)); }; return new binding_on_syntax_1.BindingOnSyntax(this._binding); }; BindingWhenSyntax.prototype.whenNoAncestorNamed = function (name) { this._binding.constraint = function (request) { return !constraint_helpers_1.traverseAncerstors(request, constraint_helpers_1.namedConstraint(name)); }; return new binding_on_syntax_1.BindingOnSyntax(this._binding); }; BindingWhenSyntax.prototype.whenAnyAncestorTagged = function (tag, value) { this._binding.constraint = function (request) { return constraint_helpers_1.traverseAncerstors(request, constraint_helpers_1.taggedConstraint(tag)(value)); }; return new binding_on_syntax_1.BindingOnSyntax(this._binding); }; BindingWhenSyntax.prototype.whenNoAncestorTagged = function (tag, value) { this._binding.constraint = function (request) { return !constraint_helpers_1.traverseAncerstors(request, constraint_helpers_1.taggedConstraint(tag)(value)); }; return new binding_on_syntax_1.BindingOnSyntax(this._binding); }; BindingWhenSyntax.prototype.whenAnyAncestorMatches = function (constraint) { this._binding.constraint = function (request) { return constraint_helpers_1.traverseAncerstors(request, constraint); }; return new binding_on_syntax_1.BindingOnSyntax(this._binding); }; BindingWhenSyntax.prototype.whenNoAncestorMatches = function (constraint) { this._binding.constraint = function (request) { return !constraint_helpers_1.traverseAncerstors(request, constraint); }; return new binding_on_syntax_1.BindingOnSyntax(this._binding); }; return BindingWhenSyntax; }()); exports.BindingWhenSyntax = BindingWhenSyntax; /***/ }), /***/ "./node_modules/inversify/lib/syntax/constraint_helpers.js": /*!*****************************************************************!*\ !*** ./node_modules/inversify/lib/syntax/constraint_helpers.js ***! \*****************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.typeConstraint = exports.namedConstraint = exports.taggedConstraint = exports.traverseAncerstors = void 0; var METADATA_KEY = __webpack_require__(/*! ../constants/metadata_keys */ "./node_modules/inversify/lib/constants/metadata_keys.js"); var metadata_1 = __webpack_require__(/*! ../planning/metadata */ "./node_modules/inversify/lib/planning/metadata.js"); var traverseAncerstors = function (request, constraint) { var parent = request.parentRequest; if (parent !== null) { return constraint(parent) ? true : traverseAncerstors(parent, constraint); } else { return false; } }; exports.traverseAncerstors = traverseAncerstors; var taggedConstraint = function (key) { return function (value) { var constraint = function (request) { return request !== null && request.target !== null && request.target.matchesTag(key)(value); }; constraint.metaData = new metadata_1.Metadata(key, value); return constraint; }; }; exports.taggedConstraint = taggedConstraint; var namedConstraint = taggedConstraint(METADATA_KEY.NAMED_TAG); exports.namedConstraint = namedConstraint; var typeConstraint = function (type) { return function (request) { var binding = null; if (request !== null) { binding = request.bindings[0]; if (typeof type === "string") { var serviceIdentifier = binding.serviceIdentifier; return serviceIdentifier === type; } else { var constructor = request.bindings[0].implementationType; return type === constructor; } } return false; }; }; exports.typeConstraint = typeConstraint; /***/ }), /***/ "./node_modules/inversify/lib/utils/binding_utils.js": /*!***********************************************************!*\ !*** ./node_modules/inversify/lib/utils/binding_utils.js ***! \***********************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.multiBindToService = void 0; exports.multiBindToService = function (container) { return function (service) { return function () { var types = []; for (var _i = 0; _i < arguments.length; _i++) { types[_i] = arguments[_i]; } return types.forEach(function (t) { return container.bind(t).toService(service); }); }; }; }; /***/ }), /***/ "./node_modules/inversify/lib/utils/exceptions.js": /*!********************************************************!*\ !*** ./node_modules/inversify/lib/utils/exceptions.js ***! \********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isStackOverflowExeption = void 0; var ERROR_MSGS = __webpack_require__(/*! ../constants/error_msgs */ "./node_modules/inversify/lib/constants/error_msgs.js"); function isStackOverflowExeption(error) { return (error instanceof RangeError || error.message === ERROR_MSGS.STACK_OVERFLOW); } exports.isStackOverflowExeption = isStackOverflowExeption; /***/ }), /***/ "./node_modules/inversify/lib/utils/id.js": /*!************************************************!*\ !*** ./node_modules/inversify/lib/utils/id.js ***! \************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.id = void 0; var idCounter = 0; function id() { return idCounter++; } exports.id = id; /***/ }), /***/ "./node_modules/inversify/lib/utils/serialization.js": /*!***********************************************************!*\ !*** ./node_modules/inversify/lib/utils/serialization.js ***! \***********************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.circularDependencyToException = exports.listMetadataForTarget = exports.listRegisteredBindingsForServiceIdentifier = exports.getServiceIdentifierAsString = exports.getFunctionName = void 0; var ERROR_MSGS = __webpack_require__(/*! ../constants/error_msgs */ "./node_modules/inversify/lib/constants/error_msgs.js"); function getServiceIdentifierAsString(serviceIdentifier) { if (typeof serviceIdentifier === "function") { var _serviceIdentifier = serviceIdentifier; return _serviceIdentifier.name; } else if (typeof serviceIdentifier === "symbol") { return serviceIdentifier.toString(); } else { var _serviceIdentifier = serviceIdentifier; return _serviceIdentifier; } } exports.getServiceIdentifierAsString = getServiceIdentifierAsString; function listRegisteredBindingsForServiceIdentifier(container, serviceIdentifier, getBindings) { var registeredBindingsList = ""; var registeredBindings = getBindings(container, serviceIdentifier); if (registeredBindings.length !== 0) { registeredBindingsList = "\nRegistered bindings:"; registeredBindings.forEach(function (binding) { var name = "Object"; if (binding.implementationType !== null) { name = getFunctionName(binding.implementationType); } registeredBindingsList = registeredBindingsList + "\n " + name; if (binding.constraint.metaData) { registeredBindingsList = registeredBindingsList + " - " + binding.constraint.metaData; } }); } return registeredBindingsList; } exports.listRegisteredBindingsForServiceIdentifier = listRegisteredBindingsForServiceIdentifier; function alreadyDependencyChain(request, serviceIdentifier) { if (request.parentRequest === null) { return false; } else if (request.parentRequest.serviceIdentifier === serviceIdentifier) { return true; } else { return alreadyDependencyChain(request.parentRequest, serviceIdentifier); } } function dependencyChainToString(request) { function _createStringArr(req, result) { if (result === void 0) { result = []; } var serviceIdentifier = getServiceIdentifierAsString(req.serviceIdentifier); result.push(serviceIdentifier); if (req.parentRequest !== null) { return _createStringArr(req.parentRequest, result); } return result; } var stringArr = _createStringArr(request); return stringArr.reverse().join(" --> "); } function circularDependencyToException(request) { request.childRequests.forEach(function (childRequest) { if (alreadyDependencyChain(childRequest, childRequest.serviceIdentifier)) { var services = dependencyChainToString(childRequest); throw new Error(ERROR_MSGS.CIRCULAR_DEPENDENCY + " " + services); } else { circularDependencyToException(childRequest); } }); } exports.circularDependencyToException = circularDependencyToException; function listMetadataForTarget(serviceIdentifierString, target) { if (target.isTagged() || target.isNamed()) { var m_1 = ""; var namedTag = target.getNamedTag(); var otherTags = target.getCustomTags(); if (namedTag !== null) { m_1 += namedTag.toString() + "\n"; } if (otherTags !== null) { otherTags.forEach(function (tag) { m_1 += tag.toString() + "\n"; }); } return " " + serviceIdentifierString + "\n " + serviceIdentifierString + " - " + m_1; } else { return " " + serviceIdentifierString; } } exports.listMetadataForTarget = listMetadataForTarget; function getFunctionName(v) { if (v.name) { return v.name; } else { var name_1 = v.toString(); var match = name_1.match(/^function\s*([^\s(]+)/); return match ? match[1] : "Anonymous function: " + name_1; } } exports.getFunctionName = getFunctionName; /***/ }), /***/ "./node_modules/is-buffer/index.js": /*!*****************************************!*\ !*** ./node_modules/is-buffer/index.js ***! \*****************************************/ /***/ ((module) => { /*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh * @license MIT */ // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually module.exports = function (obj) { return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) } function isBuffer (obj) { return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) } // For Node v0.10 support. Remove this eventually. function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } /***/ }), /***/ "./node_modules/is-docker/index.js": /*!*****************************************!*\ !*** ./node_modules/is-docker/index.js ***! \*****************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const fs = __webpack_require__(/*! fs */ "fs"); let isDocker; function hasDockerEnv() { try { fs.statSync('/.dockerenv'); return true; } catch (_) { return false; } } function hasDockerCGroup() { try { return fs.readFileSync('/proc/self/cgroup', 'utf8').includes('docker'); } catch (_) { return false; } } module.exports = () => { if (isDocker === undefined) { isDocker = hasDockerEnv() || hasDockerCGroup(); } return isDocker; }; /***/ }), /***/ "./node_modules/is-typedarray/index.js": /*!*********************************************!*\ !*** ./node_modules/is-typedarray/index.js ***! \*********************************************/ /***/ ((module) => { module.exports = isTypedArray isTypedArray.strict = isStrictTypedArray isTypedArray.loose = isLooseTypedArray var toString = Object.prototype.toString var names = { '[object Int8Array]': true , '[object Int16Array]': true , '[object Int32Array]': true , '[object Uint8Array]': true , '[object Uint8ClampedArray]': true , '[object Uint16Array]': true , '[object Uint32Array]': true , '[object Float32Array]': true , '[object Float64Array]': true } function isTypedArray(arr) { return ( isStrictTypedArray(arr) || isLooseTypedArray(arr) ) } function isStrictTypedArray(arr) { return ( arr instanceof Int8Array || arr instanceof Int16Array || arr instanceof Int32Array || arr instanceof Uint8Array || arr instanceof Uint8ClampedArray || arr instanceof Uint16Array || arr instanceof Uint32Array || arr instanceof Float32Array || arr instanceof Float64Array ) } function isLooseTypedArray(arr) { return names[toString.call(arr)] } /***/ }), /***/ "./node_modules/is-wsl/index.js": /*!**************************************!*\ !*** ./node_modules/is-wsl/index.js ***! \**************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const os = __webpack_require__(/*! os */ "os"); const fs = __webpack_require__(/*! fs */ "fs"); const isDocker = __webpack_require__(/*! is-docker */ "./node_modules/is-docker/index.js"); const isWsl = () => { if (process.platform !== 'linux') { return false; } if (os.release().toLowerCase().includes('microsoft')) { if (isDocker()) { return false; } return true; } try { return fs.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ? !isDocker() : false; } catch (_) { return false; } }; if (process.env.__IS_WSL_TEST__) { module.exports = isWsl; } else { module.exports = isWsl(); } /***/ }), /***/ "./node_modules/isstream/isstream.js": /*!*******************************************!*\ !*** ./node_modules/isstream/isstream.js ***! \*******************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var stream = __webpack_require__(/*! stream */ "stream") function isStream (obj) { return obj instanceof stream.Stream } function isReadable (obj) { return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object' } function isWritable (obj) { return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object' } function isDuplex (obj) { return isReadable(obj) && isWritable(obj) } module.exports = isStream module.exports.isReadable = isReadable module.exports.isWritable = isWritable module.exports.isDuplex = isDuplex /***/ }), /***/ "./node_modules/jsbn/index.js": /*!************************************!*\ !*** ./node_modules/jsbn/index.js ***! \************************************/ /***/ (function(module, exports) { (function(){ // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } var inBrowser = typeof navigator !== "undefined"; if(inBrowser && j_lm && (navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(inBrowser && j_lm && (navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+this.DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); } else this[this.t-1] |= x<= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1< 0) { if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); } while(i >= 0) { if(p < k) { d = (this[i]&((1<>(p+=this.DB-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r += int2char(d); } } return m?r:"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; r = i-a.t; if(r != 0) return (this.s<0)?-r:r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<= 0; --i) { r[i+ds+1] = (this[i]>>cbs)|c; c = (this[i]&bm)<= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { r.s = this.s; var ds = Math.floor(n/this.DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<>bs; for(var i = ds+1; i < this.t; ++i) { r[i-ds-1] |= (this[i]&bm)<>bs; } if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<>= this.DB; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c -= a[i]; r[i++] = c&this.DM; c >>= this.DB; } c -= a.s; } r.s = (c<0)?-1:0; if(c < -1) r[i++] = this.DV+c; else if(c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a,r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i+y.t; while(--i >= 0) r[i] = 0; for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); r.s = 0; r.clamp(); if(this.s != a.s) BigInteger.ZERO.subTo(r,r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2*x.t; while(--i >= 0) r[i] = 0; for(i = 0; i < x.t-1; ++i) { var c = x.am(i,x[i],r,2*i,0,1); if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { r[i+x.t] -= x.DV; r[i+x.t+1] = 1; } } if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m,q,r) { var pm = m.abs(); if(pm.t <= 0) return; var pt = this.abs(); if(pt.t < pm.t) { if(q != null) q.fromInt(0); if(r != null) this.copyTo(r); return; } if(r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys-1]; if(y0 == 0) return; var yt = y0*(1<1)?y[ys-2]>>this.F2:0); var d1 = this.FV/yt, d2 = (1<= 0) { r[r.t++] = 1; r.subTo(t,r); } BigInteger.ONE.dlShiftTo(ys,t); t.subTo(y,y); // "negative" y so we can replace sub with am later while(y.t < ys) y[y.t++] = 0; while(--j >= 0) { // Estimate quotient digit var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out y.dlShiftTo(j,t); r.subTo(t,r); while(r[i] < --qd) r.subTo(t,r); } } if(q != null) { r.drShiftTo(ys,q); if(ts != ms) BigInteger.ZERO.subTo(q,q); } r.t = ys; r.clamp(); if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder if(ts < 0) BigInteger.ZERO.subTo(r,r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a,null,r); if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); return r; } // Modular reduction using "classic" algorithm function Classic(m) { this.m = m; } function cConvert(x) { if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; } function cRevert(x) { return x; } function cReduce(x) { x.divRemTo(this.m,null,x); } function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } Classic.prototype.convert = cConvert; Classic.prototype.revert = cRevert; Classic.prototype.reduce = cReduce; Classic.prototype.mulTo = cMulTo; Classic.prototype.sqrTo = cSqrTo; // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if(this.t < 1) return 0; var x = this[0]; if((x&1) == 0) return 0; var y = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?this.DV-y:-y; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp&0x7fff; this.mph = this.mp>>15; this.um = (1<<(m.DB-15))-1; this.mt2 = 2*m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t,r); r.divRemTo(this.m,null,r); if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) function montReduce(x) { while(x.t <= this.mt2) // pad x so am has enough room later x[x.t++] = 0; for(var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x[i]&0x7fff; var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM; // use am to combine the multiply-shift-add into one call j = i+this.m.t; x[j] += this.m.am(0,u0,x,i,0,this.m.t); // propagate carry while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } } x.clamp(); x.drShiftTo(this.m.t,x); if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = "x^2/R mod m"; x != r function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = "xy/R mod m"; x,y != r function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Montgomery.prototype.convert = montConvert; Montgomery.prototype.revert = montRevert; Montgomery.prototype.reduce = montReduce; Montgomery.prototype.mulTo = montMulTo; Montgomery.prototype.sqrTo = montSqrTo; // (protected) true iff this is even function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) function bnpExp(e,z) { if(e > 0xffffffff || e < 1) return BigInteger.ONE; var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; g.copyTo(r); while(--i >= 0) { z.sqrTo(r,r2); if((e&(1< 0) z.mulTo(r2,g,r); else { var t = r; r = r2; r2 = t; } } return z.revert(r); } // (public) this^e % m, 0 <= e < 2^32 function bnModPowInt(e,m) { var z; if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); return this.exp(e,z); } // protected BigInteger.prototype.copyTo = bnpCopyTo; BigInteger.prototype.fromInt = bnpFromInt; BigInteger.prototype.fromString = bnpFromString; BigInteger.prototype.clamp = bnpClamp; BigInteger.prototype.dlShiftTo = bnpDLShiftTo; BigInteger.prototype.drShiftTo = bnpDRShiftTo; BigInteger.prototype.lShiftTo = bnpLShiftTo; BigInteger.prototype.rShiftTo = bnpRShiftTo; BigInteger.prototype.subTo = bnpSubTo; BigInteger.prototype.multiplyTo = bnpMultiplyTo; BigInteger.prototype.squareTo = bnpSquareTo; BigInteger.prototype.divRemTo = bnpDivRemTo; BigInteger.prototype.invDigit = bnpInvDigit; BigInteger.prototype.isEven = bnpIsEven; BigInteger.prototype.exp = bnpExp; // public BigInteger.prototype.toString = bnToString; BigInteger.prototype.negate = bnNegate; BigInteger.prototype.abs = bnAbs; BigInteger.prototype.compareTo = bnCompareTo; BigInteger.prototype.bitLength = bnBitLength; BigInteger.prototype.mod = bnMod; BigInteger.prototype.modPowInt = bnModPowInt; // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); // Copyright (c) 2005-2009 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Extended JavaScript BN functions, required for RSA private ops. // Version 1.1: new BigInteger("0", 10) returns "proper" zero // Version 1.2: square() API, isProbablePrime fix // (public) function bnClone() { var r = nbi(); this.copyTo(r); return r; } // (public) return value as integer function bnIntValue() { if(this.s < 0) { if(this.t == 1) return this[0]-this.DV; else if(this.t == 0) return -1; } else if(this.t == 1) return this[0]; else if(this.t == 0) return 0; // assumes 16 < DB < 32 return ((this[1]&((1<<(32-this.DB))-1))<>24; } // (public) return value as short (assumes DB>=16) function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; } // (protected) return x s.t. r^x < DV function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } // (public) 0 if this == 0, 1 if this > 0 function bnSigNum() { if(this.s < 0) return -1; else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; else return 1; } // (protected) convert to radix string function bnpToRadix(b) { if(b == null) b = 10; if(this.signum() == 0 || b < 2 || b > 36) return "0"; var cs = this.chunkSize(b); var a = Math.pow(b,cs); var d = nbv(a), y = nbi(), z = nbi(), r = ""; this.divRemTo(d,y,z); while(y.signum() > 0) { r = (a+z.intValue()).toString(b).substr(1) + r; y.divRemTo(d,y,z); } return z.intValue().toString(b) + r; } // (protected) convert from radix string function bnpFromRadix(s,b) { this.fromInt(0); if(b == null) b = 10; var cs = this.chunkSize(b); var d = Math.pow(b,cs), mi = false, j = 0, w = 0; for(var i = 0; i < s.length; ++i) { var x = intAt(s,i); if(x < 0) { if(s.charAt(i) == "-" && this.signum() == 0) mi = true; continue; } w = b*w+x; if(++j >= cs) { this.dMultiply(d); this.dAddOffset(w,0); j = 0; w = 0; } } if(j > 0) { this.dMultiply(Math.pow(b,j)); this.dAddOffset(w,0); } if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) alternate constructor function bnpFromNumber(a,b,c) { if("number" == typeof b) { // new BigInteger(int,int,RNG) if(a < 2) this.fromInt(1); else { this.fromNumber(a,c); if(!this.testBit(a-1)) // force MSB set this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); if(this.isEven()) this.dAddOffset(1,0); // force odd while(!this.isProbablePrime(b)) { this.dAddOffset(2,0); if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); } } } else { // new BigInteger(int,RNG) var x = new Array(), t = a&7; x.length = (a>>3)+1; b.nextBytes(x); if(t > 0) x[0] &= ((1< 0) { if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p) r[k++] = d|(this.s<<(this.DB-p)); while(i >= 0) { if(p < 8) { d = (this[i]&((1<>(p+=this.DB-8); } else { d = (this[i]>>(p-=8))&0xff; if(p <= 0) { p += this.DB; --i; } } if((d&0x80) != 0) d |= -256; if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; if(k > 0 || d != this.s) r[k++] = d; } } return r; } function bnEquals(a) { return(this.compareTo(a)==0); } function bnMin(a) { return(this.compareTo(a)<0)?this:a; } function bnMax(a) { return(this.compareTo(a)>0)?this:a; } // (protected) r = this op a (bitwise) function bnpBitwiseTo(a,op,r) { var i, f, m = Math.min(a.t,this.t); for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]); if(a.t < this.t) { f = a.s&this.DM; for(i = m; i < this.t; ++i) r[i] = op(this[i],f); r.t = this.t; } else { f = this.s&this.DM; for(i = m; i < a.t; ++i) r[i] = op(f,a[i]); r.t = a.t; } r.s = op(this.s,a.s); r.clamp(); } // (public) this & a function op_and(x,y) { return x&y; } function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } // (public) this | a function op_or(x,y) { return x|y; } function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } // (public) this ^ a function op_xor(x,y) { return x^y; } function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } // (public) this & ~a function op_andnot(x,y) { return x&~y; } function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } // (public) ~this function bnNot() { var r = nbi(); for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i]; r.t = this.t; r.s = ~this.s; return r; } // (public) this << n function bnShiftLeft(n) { var r = nbi(); if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); return r; } // (public) this >> n function bnShiftRight(n) { var r = nbi(); if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); return r; } // return index of lowest 1-bit in x, x < 2^31 function lbit(x) { if(x == 0) return -1; var r = 0; if((x&0xffff) == 0) { x >>= 16; r += 16; } if((x&0xff) == 0) { x >>= 8; r += 8; } if((x&0xf) == 0) { x >>= 4; r += 4; } if((x&3) == 0) { x >>= 2; r += 2; } if((x&1) == 0) ++r; return r; } // (public) returns index of lowest 1-bit (or -1 if none) function bnGetLowestSetBit() { for(var i = 0; i < this.t; ++i) if(this[i] != 0) return i*this.DB+lbit(this[i]); if(this.s < 0) return this.t*this.DB; return -1; } // return number of 1 bits in x function cbit(x) { var r = 0; while(x != 0) { x &= x-1; ++r; } return r; } // (public) return number of set bits function bnBitCount() { var r = 0, x = this.s&this.DM; for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x); return r; } // (public) true iff nth bit is set function bnTestBit(n) { var j = Math.floor(n/this.DB); if(j >= this.t) return(this.s!=0); return((this[j]&(1<<(n%this.DB)))!=0); } // (protected) this op (1<>= this.DB; } if(a.t < this.t) { c += a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c += a[i]; r[i++] = c&this.DM; c >>= this.DB; } c += a.s; } r.s = (c<0)?-1:0; if(c > 0) r[i++] = c; else if(c < -1) r[i++] = this.DV+c; r.t = i; r.clamp(); } // (public) this + a function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } // (public) this - a function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } // (public) this * a function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } // (public) this^2 function bnSquare() { var r = nbi(); this.squareTo(r); return r; } // (public) this / a function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } // (public) this % a function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } // (public) [this/a,this%a] function bnDivideAndRemainder(a) { var q = nbi(), r = nbi(); this.divRemTo(a,q,r); return new Array(q,r); } // (protected) this *= n, this >= 0, 1 < n < DV function bnpDMultiply(n) { this[this.t] = this.am(0,n-1,this,0,0,this.t); ++this.t; this.clamp(); } // (protected) this += n << w words, this >= 0 function bnpDAddOffset(n,w) { if(n == 0) return; while(this.t <= w) this[this.t++] = 0; this[w] += n; while(this[w] >= this.DV) { this[w] -= this.DV; if(++w >= this.t) this[this.t++] = 0; ++this[w]; } } // A "null" reducer function NullExp() {} function nNop(x) { return x; } function nMulTo(x,y,r) { x.multiplyTo(y,r); } function nSqrTo(x,r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; // (public) this^e function bnPow(e) { return this.exp(e,new NullExp()); } // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a,n,r) { var i = Math.min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r[--i] = 0; var j; for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); r.clamp(); } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } // Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } // x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j])-1; while(j >= 0) { if(i >= k1) w = (e[j]>>(i-k1))&km; else { w = (e[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e[j]&(1< 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { //Pick bases at random, instead of starting at 2 a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // JSBN-specific extension BigInteger.prototype.square = bnSquare; // Expose the Barrett function BigInteger.prototype.Barrett = Barrett // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) // Random number generator - requires a PRNG backend, e.g. prng4.js // For best results, put code like // // in your main HTML document. var rng_state; var rng_pool; var rng_pptr; // Mix in a 32-bit integer into the pool function rng_seed_int(x) { rng_pool[rng_pptr++] ^= x & 255; rng_pool[rng_pptr++] ^= (x >> 8) & 255; rng_pool[rng_pptr++] ^= (x >> 16) & 255; rng_pool[rng_pptr++] ^= (x >> 24) & 255; if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; } // Mix in the current time (w/milliseconds) into the pool function rng_seed_time() { rng_seed_int(new Date().getTime()); } // Initialize the pool with junk if needed. if(rng_pool == null) { rng_pool = new Array(); rng_pptr = 0; var t; if(typeof window !== "undefined" && window.crypto) { if (window.crypto.getRandomValues) { // Use webcrypto if available var ua = new Uint8Array(32); window.crypto.getRandomValues(ua); for(t = 0; t < 32; ++t) rng_pool[rng_pptr++] = ua[t]; } else if(navigator.appName == "Netscape" && navigator.appVersion < "5") { // Extract entropy (256 bits) from NS4 RNG if available var z = window.crypto.random(32); for(t = 0; t < z.length; ++t) rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; } } while(rng_pptr < rng_psize) { // extract some randomness from Math.random() t = Math.floor(65536 * Math.random()); rng_pool[rng_pptr++] = t >>> 8; rng_pool[rng_pptr++] = t & 255; } rng_pptr = 0; rng_seed_time(); //rng_seed_int(window.screenX); //rng_seed_int(window.screenY); } function rng_get_byte() { if(rng_state == null) { rng_seed_time(); rng_state = prng_newstate(); rng_state.init(rng_pool); for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) rng_pool[rng_pptr] = 0; rng_pptr = 0; //rng_pool = null; } // TODO: allow reseeding after first request return rng_state.next(); } function rng_get_bytes(ba) { var i; for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); } function SecureRandom() {} SecureRandom.prototype.nextBytes = rng_get_bytes; // prng4.js - uses Arcfour as a PRNG function Arcfour() { this.i = 0; this.j = 0; this.S = new Array(); } // Initialize arcfour context from key, an array of ints, each from [0..255] function ARC4init(key) { var i, j, t; for(i = 0; i < 256; ++i) this.S[i] = i; j = 0; for(i = 0; i < 256; ++i) { j = (j + this.S[i] + key[i % key.length]) & 255; t = this.S[i]; this.S[i] = this.S[j]; this.S[j] = t; } this.i = 0; this.j = 0; } function ARC4next() { var t; this.i = (this.i + 1) & 255; this.j = (this.j + this.S[this.i]) & 255; t = this.S[this.i]; this.S[this.i] = this.S[this.j]; this.S[this.j] = t; return this.S[(t + this.S[this.i]) & 255]; } Arcfour.prototype.init = ARC4init; Arcfour.prototype.next = ARC4next; // Plug in your RNG constructor here function prng_newstate() { return new Arcfour(); } // Pool size must be a multiple of 4 and greater than 32. // An array of bytes the size of the pool will be passed to init() var rng_psize = 256; BigInteger.SecureRandom = SecureRandom; BigInteger.BigInteger = BigInteger; if (true) { exports = module.exports = BigInteger; } else {} }).call(this); /***/ }), /***/ "./node_modules/json-schema-traverse/index.js": /*!****************************************************!*\ !*** ./node_modules/json-schema-traverse/index.js ***! \****************************************************/ /***/ ((module) => { "use strict"; var traverse = module.exports = function (schema, opts, cb) { // Legacy support for v0.3.1 and earlier. if (typeof opts == 'function') { cb = opts; opts = {}; } cb = opts.cb || cb; var pre = (typeof cb == 'function') ? cb : cb.pre || function() {}; var post = cb.post || function() {}; _traverse(opts, pre, post, schema, '', schema); }; traverse.keywords = { additionalItems: true, items: true, contains: true, additionalProperties: true, propertyNames: true, not: true }; traverse.arrayKeywords = { items: true, allOf: true, anyOf: true, oneOf: true }; traverse.propsKeywords = { definitions: true, properties: true, patternProperties: true, dependencies: true }; traverse.skipKeywords = { default: true, enum: true, const: true, required: true, maximum: true, minimum: true, exclusiveMaximum: true, exclusiveMinimum: true, multipleOf: true, maxLength: true, minLength: true, pattern: true, format: true, maxItems: true, minItems: true, uniqueItems: true, maxProperties: true, minProperties: true }; function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { if (schema && typeof schema == 'object' && !Array.isArray(schema)) { pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); for (var key in schema) { var sch = schema[key]; if (Array.isArray(sch)) { if (key in traverse.arrayKeywords) { for (var i=0; i schema.maxItems){ addError("There must be a maximum of " + schema.maxItems + " in the array"); } }else if(schema.properties || schema.additionalProperties){ errors.concat(checkObj(value, schema.properties, path, schema.additionalProperties)); } if(schema.pattern && typeof value == 'string' && !value.match(schema.pattern)){ addError("does not match the regex pattern " + schema.pattern); } if(schema.maxLength && typeof value == 'string' && value.length > schema.maxLength){ addError("may only be " + schema.maxLength + " characters long"); } if(schema.minLength && typeof value == 'string' && value.length < schema.minLength){ addError("must be at least " + schema.minLength + " characters long"); } if(typeof schema.minimum !== 'undefined' && typeof value == typeof schema.minimum && schema.minimum > value){ addError("must have a minimum value of " + schema.minimum); } if(typeof schema.maximum !== 'undefined' && typeof value == typeof schema.maximum && schema.maximum < value){ addError("must have a maximum value of " + schema.maximum); } if(schema['enum']){ var enumer = schema['enum']; l = enumer.length; var found; for(var j = 0; j < l; j++){ if(enumer[j]===value){ found=1; break; } } if(!found){ addError("does not have a value in the enumeration " + enumer.join(", ")); } } if(typeof schema.maxDecimal == 'number' && (value.toString().match(new RegExp("\\.[0-9]{" + (schema.maxDecimal + 1) + ",}")))){ addError("may only have " + schema.maxDecimal + " digits of decimal places"); } } } return null; } // validate an object against a schema function checkObj(instance,objTypeDef,path,additionalProp){ if(typeof objTypeDef =='object'){ if(typeof instance != 'object' || instance instanceof Array){ errors.push({property:path,message:"an object is required"}); } for(var i in objTypeDef){ if(objTypeDef.hasOwnProperty(i) && i != '__proto__' && i != 'constructor'){ var value = instance.hasOwnProperty(i) ? instance[i] : undefined; // skip _not_ specified properties if (value === undefined && options.existingOnly) continue; var propDef = objTypeDef[i]; // set default if(value === undefined && propDef["default"]){ value = instance[i] = propDef["default"]; } if(options.coerce && i in instance){ value = instance[i] = options.coerce(value, propDef); } checkProp(value,propDef,path,i); } } } for(i in instance){ if(instance.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && objTypeDef && !objTypeDef[i] && additionalProp===false){ if (options.filter) { delete instance[i]; continue; } else { errors.push({property:path,message:"The property " + i + " is not defined in the schema and the schema does not allow additional properties"}); } } var requires = objTypeDef && objTypeDef[i] && objTypeDef[i].requires; if(requires && !(requires in instance)){ errors.push({property:path,message:"the presence of the property " + i + " requires that " + requires + " also be present"}); } value = instance[i]; if(additionalProp && (!(objTypeDef && typeof objTypeDef == 'object') || !(i in objTypeDef))){ if(options.coerce){ value = instance[i] = options.coerce(value, additionalProp); } checkProp(value,additionalProp,path,i); } if(!_changing && value && value.$schema){ errors = errors.concat(checkProp(value,value.$schema,path,i)); } } return errors; } if(schema){ checkProp(instance,schema,'',_changing || ''); } if(!_changing && instance && instance.$schema){ checkProp(instance,instance.$schema,'',''); } return {valid:!errors.length,errors:errors}; }; exports.mustBeValid = function(result){ // summary: // This checks to ensure that the result is valid and will throw an appropriate error message if it is not // result: the result returned from checkPropertyChange or validate if(!result.valid){ throw new TypeError(result.errors.map(function(error){return "for property " + error.property + ': ' + error.message;}).join(", \n")); } } return exports; })); /***/ }), /***/ "./node_modules/json-stringify-safe/stringify.js": /*!*******************************************************!*\ !*** ./node_modules/json-stringify-safe/stringify.js ***! \*******************************************************/ /***/ ((module, exports) => { exports = module.exports = stringify exports.getSerialize = serializer function stringify(obj, replacer, spaces, cycleReplacer) { return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces) } function serializer(replacer, cycleReplacer) { var stack = [], keys = [] if (cycleReplacer == null) cycleReplacer = function(key, value) { if (stack[0] === value) return "[Circular ~]" return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]" } return function(key, value) { if (stack.length > 0) { var thisPos = stack.indexOf(this) ~thisPos ? stack.splice(thisPos + 1) : stack.push(this) ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key) if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value) } else stack.push(value) return replacer == null ? value : replacer.call(this, key, value) } } /***/ }), /***/ "./node_modules/jsprim/lib/jsprim.js": /*!*******************************************!*\ !*** ./node_modules/jsprim/lib/jsprim.js ***! \*******************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { /* * lib/jsprim.js: utilities for primitive JavaScript types */ var mod_assert = __webpack_require__(/*! assert-plus */ "./node_modules/assert-plus/assert.js"); var mod_util = __webpack_require__(/*! util */ "util"); var mod_extsprintf = __webpack_require__(/*! extsprintf */ "./node_modules/extsprintf/lib/extsprintf.js"); var mod_verror = __webpack_require__(/*! verror */ "./node_modules/verror/lib/verror.js"); var mod_jsonschema = __webpack_require__(/*! json-schema */ "./node_modules/json-schema/lib/validate.js"); /* * Public interface */ exports.deepCopy = deepCopy; exports.deepEqual = deepEqual; exports.isEmpty = isEmpty; exports.hasKey = hasKey; exports.forEachKey = forEachKey; exports.pluck = pluck; exports.flattenObject = flattenObject; exports.flattenIter = flattenIter; exports.validateJsonObject = validateJsonObjectJS; exports.validateJsonObjectJS = validateJsonObjectJS; exports.randElt = randElt; exports.extraProperties = extraProperties; exports.mergeObjects = mergeObjects; exports.startsWith = startsWith; exports.endsWith = endsWith; exports.parseInteger = parseInteger; exports.iso8601 = iso8601; exports.rfc1123 = rfc1123; exports.parseDateTime = parseDateTime; exports.hrtimediff = hrtimeDiff; exports.hrtimeDiff = hrtimeDiff; exports.hrtimeAccum = hrtimeAccum; exports.hrtimeAdd = hrtimeAdd; exports.hrtimeNanosec = hrtimeNanosec; exports.hrtimeMicrosec = hrtimeMicrosec; exports.hrtimeMillisec = hrtimeMillisec; /* * Deep copy an acyclic *basic* Javascript object. This only handles basic * scalars (strings, numbers, booleans) and arbitrarily deep arrays and objects * containing these. This does *not* handle instances of other classes. */ function deepCopy(obj) { var ret, key; var marker = '__deepCopy'; if (obj && obj[marker]) throw (new Error('attempted deep copy of cyclic object')); if (obj && obj.constructor == Object) { ret = {}; obj[marker] = true; for (key in obj) { if (key == marker) continue; ret[key] = deepCopy(obj[key]); } delete (obj[marker]); return (ret); } if (obj && obj.constructor == Array) { ret = []; obj[marker] = true; for (key = 0; key < obj.length; key++) ret.push(deepCopy(obj[key])); delete (obj[marker]); return (ret); } /* * It must be a primitive type -- just return it. */ return (obj); } function deepEqual(obj1, obj2) { if (typeof (obj1) != typeof (obj2)) return (false); if (obj1 === null || obj2 === null || typeof (obj1) != 'object') return (obj1 === obj2); if (obj1.constructor != obj2.constructor) return (false); var k; for (k in obj1) { if (!obj2.hasOwnProperty(k)) return (false); if (!deepEqual(obj1[k], obj2[k])) return (false); } for (k in obj2) { if (!obj1.hasOwnProperty(k)) return (false); } return (true); } function isEmpty(obj) { var key; for (key in obj) return (false); return (true); } function hasKey(obj, key) { mod_assert.equal(typeof (key), 'string'); return (Object.prototype.hasOwnProperty.call(obj, key)); } function forEachKey(obj, callback) { for (var key in obj) { if (hasKey(obj, key)) { callback(key, obj[key]); } } } function pluck(obj, key) { mod_assert.equal(typeof (key), 'string'); return (pluckv(obj, key)); } function pluckv(obj, key) { if (obj === null || typeof (obj) !== 'object') return (undefined); if (obj.hasOwnProperty(key)) return (obj[key]); var i = key.indexOf('.'); if (i == -1) return (undefined); var key1 = key.substr(0, i); if (!obj.hasOwnProperty(key1)) return (undefined); return (pluckv(obj[key1], key.substr(i + 1))); } /* * Invoke callback(row) for each entry in the array that would be returned by * flattenObject(data, depth). This is just like flattenObject(data, * depth).forEach(callback), except that the intermediate array is never * created. */ function flattenIter(data, depth, callback) { doFlattenIter(data, depth, [], callback); } function doFlattenIter(data, depth, accum, callback) { var each; var key; if (depth === 0) { each = accum.slice(0); each.push(data); callback(each); return; } mod_assert.ok(data !== null); mod_assert.equal(typeof (data), 'object'); mod_assert.equal(typeof (depth), 'number'); mod_assert.ok(depth >= 0); for (key in data) { each = accum.slice(0); each.push(key); doFlattenIter(data[key], depth - 1, each, callback); } } function flattenObject(data, depth) { if (depth === 0) return ([ data ]); mod_assert.ok(data !== null); mod_assert.equal(typeof (data), 'object'); mod_assert.equal(typeof (depth), 'number'); mod_assert.ok(depth >= 0); var rv = []; var key; for (key in data) { flattenObject(data[key], depth - 1).forEach(function (p) { rv.push([ key ].concat(p)); }); } return (rv); } function startsWith(str, prefix) { return (str.substr(0, prefix.length) == prefix); } function endsWith(str, suffix) { return (str.substr( str.length - suffix.length, suffix.length) == suffix); } function iso8601(d) { if (typeof (d) == 'number') d = new Date(d); mod_assert.ok(d.constructor === Date); return (mod_extsprintf.sprintf('%4d-%02d-%02dT%02d:%02d:%02d.%03dZ', d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds())); } var RFC1123_MONTHS = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; var RFC1123_DAYS = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; function rfc1123(date) { return (mod_extsprintf.sprintf('%s, %02d %s %04d %02d:%02d:%02d GMT', RFC1123_DAYS[date.getUTCDay()], date.getUTCDate(), RFC1123_MONTHS[date.getUTCMonth()], date.getUTCFullYear(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds())); } /* * Parses a date expressed as a string, as either a number of milliseconds since * the epoch or any string format that Date accepts, giving preference to the * former where these two sets overlap (e.g., small numbers). */ function parseDateTime(str) { /* * This is irritatingly implicit, but significantly more concise than * alternatives. The "+str" will convert a string containing only a * number directly to a Number, or NaN for other strings. Thus, if the * conversion succeeds, we use it (this is the milliseconds-since-epoch * case). Otherwise, we pass the string directly to the Date * constructor to parse. */ var numeric = +str; if (!isNaN(numeric)) { return (new Date(numeric)); } else { return (new Date(str)); } } /* * Number.*_SAFE_INTEGER isn't present before node v0.12, so we hardcode * the ES6 definitions here, while allowing for them to someday be higher. */ var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991; /* * Default options for parseInteger(). */ var PI_DEFAULTS = { base: 10, allowSign: true, allowPrefix: false, allowTrailing: false, allowImprecise: false, trimWhitespace: false, leadingZeroIsOctal: false }; var CP_0 = 0x30; var CP_9 = 0x39; var CP_A = 0x41; var CP_B = 0x42; var CP_O = 0x4f; var CP_T = 0x54; var CP_X = 0x58; var CP_Z = 0x5a; var CP_a = 0x61; var CP_b = 0x62; var CP_o = 0x6f; var CP_t = 0x74; var CP_x = 0x78; var CP_z = 0x7a; var PI_CONV_DEC = 0x30; var PI_CONV_UC = 0x37; var PI_CONV_LC = 0x57; /* * A stricter version of parseInt() that provides options for changing what * is an acceptable string (for example, disallowing trailing characters). */ function parseInteger(str, uopts) { mod_assert.string(str, 'str'); mod_assert.optionalObject(uopts, 'options'); var baseOverride = false; var options = PI_DEFAULTS; if (uopts) { baseOverride = hasKey(uopts, 'base'); options = mergeObjects(options, uopts); mod_assert.number(options.base, 'options.base'); mod_assert.ok(options.base >= 2, 'options.base >= 2'); mod_assert.ok(options.base <= 36, 'options.base <= 36'); mod_assert.bool(options.allowSign, 'options.allowSign'); mod_assert.bool(options.allowPrefix, 'options.allowPrefix'); mod_assert.bool(options.allowTrailing, 'options.allowTrailing'); mod_assert.bool(options.allowImprecise, 'options.allowImprecise'); mod_assert.bool(options.trimWhitespace, 'options.trimWhitespace'); mod_assert.bool(options.leadingZeroIsOctal, 'options.leadingZeroIsOctal'); if (options.leadingZeroIsOctal) { mod_assert.ok(!baseOverride, '"base" and "leadingZeroIsOctal" are ' + 'mutually exclusive'); } } var c; var pbase = -1; var base = options.base; var start; var mult = 1; var value = 0; var idx = 0; var len = str.length; /* Trim any whitespace on the left side. */ if (options.trimWhitespace) { while (idx < len && isSpace(str.charCodeAt(idx))) { ++idx; } } /* Check the number for a leading sign. */ if (options.allowSign) { if (str[idx] === '-') { idx += 1; mult = -1; } else if (str[idx] === '+') { idx += 1; } } /* Parse the base-indicating prefix if there is one. */ if (str[idx] === '0') { if (options.allowPrefix) { pbase = prefixToBase(str.charCodeAt(idx + 1)); if (pbase !== -1 && (!baseOverride || pbase === base)) { base = pbase; idx += 2; } } if (pbase === -1 && options.leadingZeroIsOctal) { base = 8; } } /* Parse the actual digits. */ for (start = idx; idx < len; ++idx) { c = translateDigit(str.charCodeAt(idx)); if (c !== -1 && c < base) { value *= base; value += c; } else { break; } } /* If we didn't parse any digits, we have an invalid number. */ if (start === idx) { return (new Error('invalid number: ' + JSON.stringify(str))); } /* Trim any whitespace on the right side. */ if (options.trimWhitespace) { while (idx < len && isSpace(str.charCodeAt(idx))) { ++idx; } } /* Check for trailing characters. */ if (idx < len && !options.allowTrailing) { return (new Error('trailing characters after number: ' + JSON.stringify(str.slice(idx)))); } /* If our value is 0, we return now, to avoid returning -0. */ if (value === 0) { return (0); } /* Calculate our final value. */ var result = value * mult; /* * If the string represents a value that cannot be precisely represented * by JavaScript, then we want to check that: * * - We never increased the value past MAX_SAFE_INTEGER * - We don't make the result negative and below MIN_SAFE_INTEGER * * Because we only ever increment the value during parsing, there's no * chance of moving past MAX_SAFE_INTEGER and then dropping below it * again, losing precision in the process. This means that we only need * to do our checks here, at the end. */ if (!options.allowImprecise && (value > MAX_SAFE_INTEGER || result < MIN_SAFE_INTEGER)) { return (new Error('number is outside of the supported range: ' + JSON.stringify(str.slice(start, idx)))); } return (result); } /* * Interpret a character code as a base-36 digit. */ function translateDigit(d) { if (d >= CP_0 && d <= CP_9) { /* '0' to '9' -> 0 to 9 */ return (d - PI_CONV_DEC); } else if (d >= CP_A && d <= CP_Z) { /* 'A' - 'Z' -> 10 to 35 */ return (d - PI_CONV_UC); } else if (d >= CP_a && d <= CP_z) { /* 'a' - 'z' -> 10 to 35 */ return (d - PI_CONV_LC); } else { /* Invalid character code */ return (-1); } } /* * Test if a value matches the ECMAScript definition of trimmable whitespace. */ function isSpace(c) { return (c === 0x20) || (c >= 0x0009 && c <= 0x000d) || (c === 0x00a0) || (c === 0x1680) || (c === 0x180e) || (c >= 0x2000 && c <= 0x200a) || (c === 0x2028) || (c === 0x2029) || (c === 0x202f) || (c === 0x205f) || (c === 0x3000) || (c === 0xfeff); } /* * Determine which base a character indicates (e.g., 'x' indicates hex). */ function prefixToBase(c) { if (c === CP_b || c === CP_B) { /* 0b/0B (binary) */ return (2); } else if (c === CP_o || c === CP_O) { /* 0o/0O (octal) */ return (8); } else if (c === CP_t || c === CP_T) { /* 0t/0T (decimal) */ return (10); } else if (c === CP_x || c === CP_X) { /* 0x/0X (hexadecimal) */ return (16); } else { /* Not a meaningful character */ return (-1); } } function validateJsonObjectJS(schema, input) { var report = mod_jsonschema.validate(input, schema); if (report.errors.length === 0) return (null); /* Currently, we only do anything useful with the first error. */ var error = report.errors[0]; /* The failed property is given by a URI with an irrelevant prefix. */ var propname = error['property']; var reason = error['message'].toLowerCase(); var i, j; /* * There's at least one case where the property error message is * confusing at best. We work around this here. */ if ((i = reason.indexOf('the property ')) != -1 && (j = reason.indexOf(' is not defined in the schema and the ' + 'schema does not allow additional properties')) != -1) { i += 'the property '.length; if (propname === '') propname = reason.substr(i, j - i); else propname = propname + '.' + reason.substr(i, j - i); reason = 'unsupported property'; } var rv = new mod_verror.VError('property "%s": %s', propname, reason); rv.jsv_details = error; return (rv); } function randElt(arr) { mod_assert.ok(Array.isArray(arr) && arr.length > 0, 'randElt argument must be a non-empty array'); return (arr[Math.floor(Math.random() * arr.length)]); } function assertHrtime(a) { mod_assert.ok(a[0] >= 0 && a[1] >= 0, 'negative numbers not allowed in hrtimes'); mod_assert.ok(a[1] < 1e9, 'nanoseconds column overflow'); } /* * Compute the time elapsed between hrtime readings A and B, where A is later * than B. hrtime readings come from Node's process.hrtime(). There is no * defined way to represent negative deltas, so it's illegal to diff B from A * where the time denoted by B is later than the time denoted by A. If this * becomes valuable, we can define a representation and extend the * implementation to support it. */ function hrtimeDiff(a, b) { assertHrtime(a); assertHrtime(b); mod_assert.ok(a[0] > b[0] || (a[0] == b[0] && a[1] >= b[1]), 'negative differences not allowed'); var rv = [ a[0] - b[0], 0 ]; if (a[1] >= b[1]) { rv[1] = a[1] - b[1]; } else { rv[0]--; rv[1] = 1e9 - (b[1] - a[1]); } return (rv); } /* * Convert a hrtime reading from the array format returned by Node's * process.hrtime() into a scalar number of nanoseconds. */ function hrtimeNanosec(a) { assertHrtime(a); return (Math.floor(a[0] * 1e9 + a[1])); } /* * Convert a hrtime reading from the array format returned by Node's * process.hrtime() into a scalar number of microseconds. */ function hrtimeMicrosec(a) { assertHrtime(a); return (Math.floor(a[0] * 1e6 + a[1] / 1e3)); } /* * Convert a hrtime reading from the array format returned by Node's * process.hrtime() into a scalar number of milliseconds. */ function hrtimeMillisec(a) { assertHrtime(a); return (Math.floor(a[0] * 1e3 + a[1] / 1e6)); } /* * Add two hrtime readings A and B, overwriting A with the result of the * addition. This function is useful for accumulating several hrtime intervals * into a counter. Returns A. */ function hrtimeAccum(a, b) { assertHrtime(a); assertHrtime(b); /* * Accumulate the nanosecond component. */ a[1] += b[1]; if (a[1] >= 1e9) { /* * The nanosecond component overflowed, so carry to the seconds * field. */ a[0]++; a[1] -= 1e9; } /* * Accumulate the seconds component. */ a[0] += b[0]; return (a); } /* * Add two hrtime readings A and B, returning the result as a new hrtime array. * Does not modify either input argument. */ function hrtimeAdd(a, b) { assertHrtime(a); var rv = [ a[0], a[1] ]; return (hrtimeAccum(rv, b)); } /* * Check an object for unexpected properties. Accepts the object to check, and * an array of allowed property names (strings). Returns an array of key names * that were found on the object, but did not appear in the list of allowed * properties. If no properties were found, the returned array will be of * zero length. */ function extraProperties(obj, allowed) { mod_assert.ok(typeof (obj) === 'object' && obj !== null, 'obj argument must be a non-null object'); mod_assert.ok(Array.isArray(allowed), 'allowed argument must be an array of strings'); for (var i = 0; i < allowed.length; i++) { mod_assert.ok(typeof (allowed[i]) === 'string', 'allowed argument must be an array of strings'); } return (Object.keys(obj).filter(function (key) { return (allowed.indexOf(key) === -1); })); } /* * Given three sets of properties "provided" (may be undefined), "overrides" * (required), and "defaults" (may be undefined), construct an object containing * the union of these sets with "overrides" overriding "provided", and * "provided" overriding "defaults". None of the input objects are modified. */ function mergeObjects(provided, overrides, defaults) { var rv, k; rv = {}; if (defaults) { for (k in defaults) rv[k] = defaults[k]; } if (provided) { for (k in provided) rv[k] = provided[k]; } if (overrides) { for (k in overrides) rv[k] = overrides[k]; } return (rv); } /***/ }), /***/ "./node_modules/lodash/_Symbol.js": /*!****************************************!*\ !*** ./node_modules/lodash/_Symbol.js ***! \****************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var root = __webpack_require__(/*! ./_root */ "./node_modules/lodash/_root.js"); /** Built-in value references. */ var Symbol = root.Symbol; module.exports = Symbol; /***/ }), /***/ "./node_modules/lodash/_baseGetTag.js": /*!********************************************!*\ !*** ./node_modules/lodash/_baseGetTag.js ***! \********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var Symbol = __webpack_require__(/*! ./_Symbol */ "./node_modules/lodash/_Symbol.js"), getRawTag = __webpack_require__(/*! ./_getRawTag */ "./node_modules/lodash/_getRawTag.js"), objectToString = __webpack_require__(/*! ./_objectToString */ "./node_modules/lodash/_objectToString.js"); /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } module.exports = baseGetTag; /***/ }), /***/ "./node_modules/lodash/_baseTrim.js": /*!******************************************!*\ !*** ./node_modules/lodash/_baseTrim.js ***! \******************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var trimmedEndIndex = __webpack_require__(/*! ./_trimmedEndIndex */ "./node_modules/lodash/_trimmedEndIndex.js"); /** Used to match leading whitespace. */ var reTrimStart = /^\s+/; /** * The base implementation of `_.trim`. * * @private * @param {string} string The string to trim. * @returns {string} Returns the trimmed string. */ function baseTrim(string) { return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') : string; } module.exports = baseTrim; /***/ }), /***/ "./node_modules/lodash/_freeGlobal.js": /*!********************************************!*\ !*** ./node_modules/lodash/_freeGlobal.js ***! \********************************************/ /***/ ((module) => { /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; module.exports = freeGlobal; /***/ }), /***/ "./node_modules/lodash/_getRawTag.js": /*!*******************************************!*\ !*** ./node_modules/lodash/_getRawTag.js ***! \*******************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var Symbol = __webpack_require__(/*! ./_Symbol */ "./node_modules/lodash/_Symbol.js"); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } module.exports = getRawTag; /***/ }), /***/ "./node_modules/lodash/_objectToString.js": /*!************************************************!*\ !*** ./node_modules/lodash/_objectToString.js ***! \************************************************/ /***/ ((module) => { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } module.exports = objectToString; /***/ }), /***/ "./node_modules/lodash/_root.js": /*!**************************************!*\ !*** ./node_modules/lodash/_root.js ***! \**************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var freeGlobal = __webpack_require__(/*! ./_freeGlobal */ "./node_modules/lodash/_freeGlobal.js"); /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); module.exports = root; /***/ }), /***/ "./node_modules/lodash/_trimmedEndIndex.js": /*!*************************************************!*\ !*** ./node_modules/lodash/_trimmedEndIndex.js ***! \*************************************************/ /***/ ((module) => { /** Used to match a single whitespace character. */ var reWhitespace = /\s/; /** * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace * character of `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the index of the last non-whitespace character. */ function trimmedEndIndex(string) { var index = string.length; while (index-- && reWhitespace.test(string.charAt(index))) {} return index; } module.exports = trimmedEndIndex; /***/ }), /***/ "./node_modules/lodash/debounce.js": /*!*****************************************!*\ !*** ./node_modules/lodash/debounce.js ***! \*****************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var isObject = __webpack_require__(/*! ./isObject */ "./node_modules/lodash/isObject.js"), now = __webpack_require__(/*! ./now */ "./node_modules/lodash/now.js"), toNumber = __webpack_require__(/*! ./toNumber */ "./node_modules/lodash/toNumber.js"); /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max, nativeMin = Math.min; /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed `func` invocations and a `flush` method to immediately invoke them. * Provide `options` to indicate whether `func` should be invoked on the * leading and/or trailing edge of the `wait` timeout. The `func` is invoked * with the last arguments provided to the debounced function. Subsequent * calls to the debounced function return the result of the last `func` * invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the debounced function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=false] * Specify invoking on the leading edge of the timeout. * @param {number} [options.maxWait] * The maximum time `func` is allowed to be delayed before it's invoked. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // Avoid costly calculations while the window size is in flux. * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // Invoke `sendMail` when clicked, debouncing subsequent calls. * jQuery(element).on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // Ensure `batchLog` is invoked once after 1 second of debounced calls. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); * var source = new EventSource('/stream'); * jQuery(source).on('message', debounced); * * // Cancel the trailing debounced invocation. * jQuery(window).on('popstate', debounced.cancel); */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = 'maxWait' in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = 'trailing' in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { // Reset any `maxWait` timer. lastInvokeTime = time; // Start the timer for the trailing edge. timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall; return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the // trailing edge, the system time has gone backwards and we're treating // it as the trailing edge, or we've hit the `maxWait` limit. return (lastCallTime === undefined || (timeSinceLastCall >= wait) || (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } // Restart the timer. timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been // debounced at least once. if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = undefined; return result; } function cancel() { if (timerId !== undefined) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = undefined; } function flush() { return timerId === undefined ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === undefined) { return leadingEdge(lastCallTime); } if (maxing) { // Handle invocations in a tight loop. clearTimeout(timerId); timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } module.exports = debounce; /***/ }), /***/ "./node_modules/lodash/isObject.js": /*!*****************************************!*\ !*** ./node_modules/lodash/isObject.js ***! \*****************************************/ /***/ ((module) => { /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } module.exports = isObject; /***/ }), /***/ "./node_modules/lodash/isObjectLike.js": /*!*********************************************!*\ !*** ./node_modules/lodash/isObjectLike.js ***! \*********************************************/ /***/ ((module) => { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } module.exports = isObjectLike; /***/ }), /***/ "./node_modules/lodash/isSymbol.js": /*!*****************************************!*\ !*** ./node_modules/lodash/isSymbol.js ***! \*****************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var baseGetTag = __webpack_require__(/*! ./_baseGetTag */ "./node_modules/lodash/_baseGetTag.js"), isObjectLike = __webpack_require__(/*! ./isObjectLike */ "./node_modules/lodash/isObjectLike.js"); /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } module.exports = isSymbol; /***/ }), /***/ "./node_modules/lodash/lodash.js": /*!***************************************!*\ !*** ./node_modules/lodash/lodash.js ***! \***************************************/ /***/ (function(module, exports, __webpack_require__) { /* module decorator */ module = __webpack_require__.nmd(module); var __WEBPACK_AMD_DEFINE_RESULT__;/** * @license * Lodash * Copyright OpenJS Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ ;(function() { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; /** Used as the semantic version number. */ var VERSION = '4.17.21'; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Error message constants. */ var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', FUNC_ERROR_TEXT = 'Expected a function', INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`'; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used as default options for `_.truncate`. */ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = '...'; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /** Used to indicate the type of lazy iteratees. */ var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e+308, NAN = 0 / 0; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', asyncTag = '[object AsyncFunction]', boolTag = '[object Boolean]', dateTag = '[object Date]', domExcTag = '[object DOMException]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', nullTag = '[object Null]', objectTag = '[object Object]', promiseTag = '[object Promise]', proxyTag = '[object Proxy]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', undefinedTag = '[object Undefined]', weakMapTag = '[object WeakMap]', weakSetTag = '[object WeakSet]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to match empty string literals in compiled template source. */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** Used to match HTML entities and HTML characters. */ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); /** Used to match template delimiters. */ var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); /** Used to match leading whitespace. */ var reTrimStart = /^\s+/; /** Used to match a single whitespace character. */ var reWhitespace = /\s/; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** Used to match words composed of alphanumeric characters. */ var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; /** * Used to validate the `validate` option in `_.template` variable. * * Forbids characters which could potentially change the meaning of the function argument definition: * - "()," (modification of function parameters) * - "=" (default value) * - "[]{}" (destructuring of function parameters) * - "/" (beginning of a comment) * - whitespace */ var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Used to match * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to match Latin Unicode letters (excluding mathematical operators). */ var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; /** Used to ensure capturing order of template delimiters. */ var reNoMatch = /($^)/; /** Used to match unescaped characters in compiled string literals. */ var reUnescapedString = /['\n\r\u2028\u2029\\]/g; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = '\\u2700-\\u27bf', rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', rsPunctuationRange = '\\u2000-\\u206f', rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', rsVarRange = '\\ufe0e\\ufe0f', rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; /** Used to compose unicode capture groups. */ var rsApos = "['\u2019]", rsAstral = '[' + rsAstralRange + ']', rsBreak = '[' + rsBreakRange + ']', rsCombo = '[' + rsComboRange + ']', rsDigits = '\\d+', rsDingbat = '[' + rsDingbatRange + ']', rsLower = '[' + rsLowerRange + ']', rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsUpper = '[' + rsUpperRange + ']', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match apostrophes. */ var reApos = RegExp(rsApos, 'g'); /** * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). */ var reComboMark = RegExp(rsCombo, 'g'); /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** Used to match complex or compound words. */ var reUnicodeWord = RegExp([ rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, rsUpper + '+' + rsOptContrUpper, rsOrdUpper, rsOrdLower, rsDigits, rsEmoji ].join('|'), 'g'); /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** Used to detect strings that need a more robust regexp to match words. */ var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; /** Used to assign default `context` object properties. */ var contextProps = [ 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' ]; /** Used to make template sourceURLs easier to identify. */ var templateCounter = -1; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** Used to map Latin Unicode letters to basic Latin letters. */ var deburredLetters = { // Latin-1 Supplement block. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', '\xc7': 'C', '\xe7': 'c', '\xd0': 'D', '\xf0': 'd', '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', '\xd1': 'N', '\xf1': 'n', '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', '\xc6': 'Ae', '\xe6': 'ae', '\xde': 'Th', '\xfe': 'th', '\xdf': 'ss', // Latin Extended-A block. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', '\u0134': 'J', '\u0135': 'j', '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', '\u0163': 't', '\u0165': 't', '\u0167': 't', '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', '\u0174': 'W', '\u0175': 'w', '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', '\u0132': 'IJ', '\u0133': 'ij', '\u0152': 'Oe', '\u0153': 'oe', '\u0149': "'n", '\u017f': 's' }; /** Used to map characters to HTML entities. */ var htmlEscapes = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; /** Used to map HTML entities to characters. */ var htmlUnescapes = { '&': '&', '<': '<', '>': '>', '"': '"', ''': "'" }; /** Used to escape characters for inclusion in compiled string literals. */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Built-in method references without a dependency on `root`. */ var freeParseFloat = parseFloat, freeParseInt = parseInt; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = true && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { // Use `util.types` for Node.js 10+. var types = freeModule && freeModule.require && freeModule.require('util').types; if (types) { return types; } // Legacy `process.binding('util')` for Node.js < 10. return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); /* Node.js helper references. */ var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /*--------------------------------------------------------------------------*/ /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } /** * A specialized version of `baseAggregator` for arrays. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function arrayAggregator(array, setter, iteratee, accumulator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { var value = array[index]; setter(accumulator, value, iteratee(value), array); } return accumulator; } /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } /** * A specialized version of `_.forEachRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEachRight(array, iteratee) { var length = array == null ? 0 : array.length; while (length--) { if (iteratee(array[length], length, array) === false) { break; } } return array; } /** * A specialized version of `_.every` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. */ function arrayEvery(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (!predicate(array[index], index, array)) { return false; } } return true; } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; } /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } /** * A specialized version of `_.reduceRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the last element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduceRight(array, iteratee, accumulator, initAccum) { var length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[--length]; } while (length--) { accumulator = iteratee(accumulator, array[length], length, array); } return accumulator; } /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * Gets the size of an ASCII `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ var asciiSize = baseProperty('length'); /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } /** * Splits an ASCII `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function asciiWords(string) { return string.match(reAsciiWord) || []; } /** * The base implementation of methods like `_.findKey` and `_.findLastKey`, * without support for iteratee shorthands, which iterates over `collection` * using `eachFunc`. * * @private * @param {Array|Object} collection The collection to inspect. * @param {Function} predicate The function invoked per iteration. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the found element or its key, else `undefined`. */ function baseFindKey(collection, predicate, eachFunc) { var result; eachFunc(collection, function(value, key, collection) { if (predicate(value, key, collection)) { result = key; return false; } }); return result; } /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } /** * This function is like `baseIndexOf` except that it accepts a comparator. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @param {Function} comparator The comparator invoked per element. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOfWith(array, value, fromIndex, comparator) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (comparator(array[index], value)) { return index; } } return -1; } /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } /** * The base implementation of `_.mean` and `_.meanBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the mean. */ function baseMean(array, iteratee) { var length = array == null ? 0 : array.length; return length ? (baseSum(array, iteratee) / length) : NAN; } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.propertyOf` without support for deep paths. * * @private * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. */ function basePropertyOf(object) { return function(key) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array * of key-value pairs for `object` corresponding to the property names of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the key-value pairs. */ function baseToPairs(object, props) { return arrayMap(props, function(key) { return [key, object[key]]; }); } /** * The base implementation of `_.trim`. * * @private * @param {string} string The string to trim. * @returns {string} Returns the trimmed string. */ function baseTrim(string) { return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') : string; } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } /** * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A * letters to basic Latin letters. * * @private * @param {string} letter The matched letter to deburr. * @returns {string} Returns the deburred letter. */ var deburrLetter = basePropertyOf(deburredLetters); /** * Used by `_.escape` to convert characters to HTML entities. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ var escapeHtmlChar = basePropertyOf(htmlEscapes); /** * Used by `_.template` to escape characters for inclusion in compiled string literals. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(chr) { return '\\' + stringEscapes[chr]; } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } /** * Checks if `string` contains a word composed of Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a word is found, else `false`. */ function hasUnicodeWord(string) { return reHasUnicodeWord.test(string); } /** * Converts `iterator` to an array. * * @private * @param {Object} iterator The iterator to convert. * @returns {Array} Returns the converted array. */ function iteratorToArray(iterator) { var data, result = []; while (!(data = iterator.next()).done) { result.push(data.value); } return result; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** * Converts `set` to its value-value pairs. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the value-value pairs. */ function setToPairs(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = [value, value]; }); return result; } /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * A specialized version of `_.lastIndexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictLastIndexOf(array, value, fromIndex) { var index = fromIndex + 1; while (index--) { if (array[index] === value) { return index; } } return index; } /** * Gets the number of symbols in `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the string size. */ function stringSize(string) { return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); } /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } /** * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace * character of `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the index of the last non-whitespace character. */ function trimmedEndIndex(string) { var index = string.length; while (index-- && reWhitespace.test(string.charAt(index))) {} return index; } /** * Used by `_.unescape` to convert HTML entities to characters. * * @private * @param {string} chr The matched character to unescape. * @returns {string} Returns the unescaped character. */ var unescapeHtmlChar = basePropertyOf(htmlUnescapes); /** * Gets the size of a Unicode `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ function unicodeSize(string) { var result = reUnicode.lastIndex = 0; while (reUnicode.test(string)) { ++result; } return result; } /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } /** * Splits a Unicode `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function unicodeWords(string) { return string.match(reUnicodeWord) || []; } /*--------------------------------------------------------------------------*/ /** * Create a new pristine `lodash` function using the `context` object. * * @static * @memberOf _ * @since 1.1.0 * @category Util * @param {Object} [context=root] The context object. * @returns {Function} Returns a new `lodash` function. * @example * * _.mixin({ 'foo': _.constant('foo') }); * * var lodash = _.runInContext(); * lodash.mixin({ 'bar': lodash.constant('bar') }); * * _.isFunction(_.foo); * // => true * _.isFunction(_.bar); * // => false * * lodash.isFunction(lodash.foo); * // => false * lodash.isFunction(lodash.bar); * // => true * * // Create a suped-up `defer` in Node.js. * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; */ var runInContext = (function runInContext(context) { context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); /** Built-in constructor references. */ var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = context['__core-js_shared__']; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to generate unique IDs. */ var idCounter = 0; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** Used to restore the original `_` reference in `_.noConflict`. */ var oldDash = root._; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Buffer = moduleExports ? context.Buffer : undefined, Symbol = context.Symbol, Uint8Array = context.Uint8Array, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, getPrototype = overArg(Object.getPrototypeOf, Object), objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, symIterator = Symbol ? Symbol.iterator : undefined, symToStringTag = Symbol ? Symbol.toStringTag : undefined; var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); /** Mocked built-ins. */ var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date && Date.now !== root.Date.now && Date.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeFloor = Math.floor, nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max, nativeMin = Math.min, nativeNow = Date.now, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeReverse = arrayProto.reverse; /* Built-in method references that are verified to be native. */ var DataView = getNative(context, 'DataView'), Map = getNative(context, 'Map'), Promise = getNative(context, 'Promise'), Set = getNative(context, 'Set'), WeakMap = getNative(context, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; /** Used to lookup unminified function names. */ var realNames = {}; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /*------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } /** * By default, the template delimiters used by lodash are like those in * embedded Ruby (ERB) as well as ES2015 template strings. Change the * following template settings to use alternative delimiters. * * @static * @memberOf _ * @type {Object} */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type {RegExp} */ 'escape': reEscape, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type {RegExp} */ 'evaluate': reEvaluate, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type {RegExp} */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type {string} */ 'variable': '', /** * Used to import variables into the compiled template. * * @memberOf _.templateSettings * @type {Object} */ 'imports': { /** * A reference to the `lodash` function. * * @memberOf _.templateSettings.imports * @type {Function} */ '_': lodash } }; // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; /*------------------------------------------------------------------------*/ /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } /** * Creates a clone of the lazy wrapper object. * * @private * @name clone * @memberOf LazyWrapper * @returns {Object} Returns the cloned `LazyWrapper` object. */ function lazyClone() { var result = new LazyWrapper(this.__wrapped__); result.__actions__ = copyArray(this.__actions__); result.__dir__ = this.__dir__; result.__filtered__ = this.__filtered__; result.__iteratees__ = copyArray(this.__iteratees__); result.__takeCount__ = this.__takeCount__; result.__views__ = copyArray(this.__views__); return result; } /** * Reverses the direction of lazy iteration. * * @private * @name reverse * @memberOf LazyWrapper * @returns {Object} Returns the new reversed `LazyWrapper` object. */ function lazyReverse() { if (this.__filtered__) { var result = new LazyWrapper(this); result.__dir__ = -1; result.__filtered__ = true; } else { result = this.clone(); result.__dir__ *= -1; } return result; } /** * Extracts the unwrapped value from its lazy wrapper. * * @private * @name value * @memberOf LazyWrapper * @returns {*} Returns the unwrapped value. */ function lazyValue() { var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : (start - 1), iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); if (!isArr || (!isRight && arrLength == length && takeCount == length)) { return baseWrapperValue(array, this.__actions__); } var result = []; outer: while (length-- && resIndex < takeCount) { index += dir; var iterIndex = -1, value = array[index]; while (++iterIndex < iterLength) { var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type, computed = iteratee(value); if (type == LAZY_MAP_FLAG) { value = computed; } else if (!computed) { if (type == LAZY_FILTER_FLAG) { continue outer; } else { break outer; } } } result[resIndex++] = value; } return result; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; /*------------------------------------------------------------------------*/ /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /*------------------------------------------------------------------------*/ /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /*------------------------------------------------------------------------*/ /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /*------------------------------------------------------------------------*/ /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /*------------------------------------------------------------------------*/ /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /*------------------------------------------------------------------------*/ /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } /** * A specialized version of `_.sample` for arrays. * * @private * @param {Array} array The array to sample. * @returns {*} Returns the random element. */ function arraySample(array) { var length = array.length; return length ? array[baseRandom(0, length - 1)] : undefined; } /** * A specialized version of `_.sampleSize` for arrays. * * @private * @param {Array} array The array to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function arraySampleSize(array, n) { return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); } /** * A specialized version of `_.shuffle` for arrays. * * @private * @param {Array} array The array to shuffle. * @returns {Array} Returns the new shuffled array. */ function arrayShuffle(array) { return shuffleSelf(copyArray(array)); } /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq(object[key], value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * Aggregates elements of `collection` on `accumulator` with keys transformed * by `iteratee` and values set by `setter`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function baseAggregator(collection, setter, iteratee, accumulator) { baseEach(collection, function(value, key, collection) { setter(accumulator, value, iteratee(value), collection); }); return accumulator; } /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } /** * The base implementation of `_.at` without support for individual paths. * * @private * @param {Object} object The object to iterate over. * @param {string[]} paths The property paths to pick. * @returns {Array} Returns the picked elements. */ function baseAt(object, paths) { var index = -1, length = paths.length, result = Array(length), skip = object == null; while (++index < length) { result[index] = skip ? undefined : get(object, paths[index]); } return result; } /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (isSet(value)) { value.forEach(function(subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); } else if (isMap(value)) { value.forEach(function(subValue, key) { result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); } var keysFunc = isFull ? (isFlat ? getAllKeysIn : getAllKeys) : (isFlat ? keysIn : keys); var props = isArr ? undefined : keysFunc(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } /** * The base implementation of `_.conforms` which doesn't clone `source`. * * @private * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. */ function baseConforms(source) { var props = keys(source); return function(object) { return baseConformsTo(object, source, props); }; } /** * The base implementation of `_.conformsTo` which accepts `props` to check. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. */ function baseConformsTo(object, source, props) { var length = props.length; if (object == null) { return !length; } object = Object(object); while (length--) { var key = props[length], predicate = source[key], value = object[key]; if ((value === undefined && !(key in object)) || !predicate(value)) { return false; } } return true; } /** * The base implementation of `_.delay` and `_.defer` which accepts `args` * to provide to `func`. * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {Array} args The arguments to provide to `func`. * @returns {number|Object} Returns the timer id or timeout object. */ function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * The base implementation of `_.forEachRight` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEachRight = createBaseEach(baseForOwnRight, true); /** * The base implementation of `_.every` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false` */ function baseEvery(collection, predicate) { var result = true; baseEach(collection, function(value, index, collection) { result = !!predicate(value, index, collection); return result; }); return result; } /** * The base implementation of methods like `_.max` and `_.min` which accepts a * `comparator` to determine the extremum value. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The iteratee invoked per iteration. * @param {Function} comparator The comparator used to compare values. * @returns {*} Returns the extremum value. */ function baseExtremum(array, iteratee, comparator) { var index = -1, length = array.length; while (++index < length) { var value = array[index], current = iteratee(value); if (current != null && (computed === undefined ? (current === current && !isSymbol(current)) : comparator(current, computed) )) { var computed = current, result = value; } } return result; } /** * The base implementation of `_.fill` without an iteratee call guard. * * @private * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. */ function baseFill(array, value, start, end) { var length = array.length; start = toInteger(start); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : toInteger(end); if (end < 0) { end += length; } end = start > end ? 0 : toLength(end); while (start < end) { array[start++] = value; } return array; } /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * This function is like `baseFor` except that it iterates over properties * in the opposite order. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseForRight = createBaseFor(true); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } /** * The base implementation of `_.forOwnRight` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwnRight(object, iteratee) { return object && baseForRight(object, iteratee, keys); } /** * The base implementation of `_.functions` which creates an array of * `object` function property names filtered from `props`. * * @private * @param {Object} object The object to inspect. * @param {Array} props The property names to filter. * @returns {Array} Returns the function names. */ function baseFunctions(object, props) { return arrayFilter(props, function(key) { return isFunction(object[key]); }); } /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } /** * The base implementation of `_.gt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. */ function baseGt(value, other) { return value > other; } /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty.call(object, key); } /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } /** * The base implementation of `_.inRange` which doesn't coerce arguments. * * @private * @param {number} number The number to check. * @param {number} start The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. */ function baseInRange(number, start, end) { return number >= nativeMin(start, end) && number < nativeMax(start, end); } /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } /** * The base implementation of `_.invoke` without support for individual * method arguments. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {Array} args The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. */ function baseInvoke(object, path, args) { path = castPath(path, object); object = parent(object, path); var func = object == null ? object : object[toKey(last(path))]; return func == null ? undefined : apply(func, object, args); } /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } /** * The base implementation of `_.isArrayBuffer` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. */ function baseIsArrayBuffer(value) { return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; } /** * The base implementation of `_.isDate` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. */ function baseIsDate(value) { return isObjectLike(value) && baseGetTag(value) == dateTag; } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike(value) && getTag(value) == mapTag; } /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isRegExp` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. */ function baseIsRegExp(value) { return isObjectLike(value) && baseGetTag(value) == regexpTag; } /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike(value) && getTag(value) == setTag; } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } /** * The base implementation of `_.lt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. */ function baseLt(value, other) { return value < other; } /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor(source, function(srcValue, key) { stack || (stack = new Stack); if (isObject(srcValue)) { baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }, keysIn); } /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = safeGet(object, key), srcValue = safeGet(source, key), stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || isFunction(objValue)) { newValue = initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } assignMergeValue(object, key, newValue); } /** * The base implementation of `_.nth` which doesn't coerce arguments. * * @private * @param {Array} array The array to query. * @param {number} n The index of the element to return. * @returns {*} Returns the nth element of `array`. */ function baseNth(array, n) { var length = array.length; if (!length) { return; } n += n < 0 ? length : 0; return isIndex(n, length) ? array[n] : undefined; } /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { if (iteratees.length) { iteratees = arrayMap(iteratees, function(iteratee) { if (isArray(iteratee)) { return function(value) { return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); } } return iteratee; }); } else { iteratees = [identity]; } var index = -1; iteratees = arrayMap(iteratees, baseUnary(getIteratee())); var result = baseMap(collection, function(value, key, collection) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders); }); } /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return basePickBy(object, paths, function(value, path) { return hasIn(object, path); }); } /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = baseGet(object, path); if (predicate(value, path)) { baseSet(result, castPath(path, object), value); } } return result; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } /** * The base implementation of `_.pullAllBy` without support for iteratee * shorthands. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. */ function basePullAll(array, values, iteratee, comparator) { var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array; if (array === values) { values = copyArray(values); } if (iteratee) { seen = arrayMap(array, baseUnary(iteratee)); } while (++index < length) { var fromIndex = 0, value = values[index], computed = iteratee ? iteratee(value) : value; while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { if (seen !== array) { splice.call(seen, fromIndex, 1); } splice.call(array, fromIndex, 1); } } return array; } /** * The base implementation of `_.pullAt` without support for individual * indexes or capturing the removed elements. * * @private * @param {Array} array The array to modify. * @param {number[]} indexes The indexes of elements to remove. * @returns {Array} Returns `array`. */ function basePullAt(array, indexes) { var length = array ? indexes.length : 0, lastIndex = length - 1; while (length--) { var index = indexes[length]; if (length == lastIndex || index !== previous) { var previous = index; if (isIndex(index)) { splice.call(array, index, 1); } else { baseUnset(array, index); } } } return array; } /** * The base implementation of `_.random` without support for returning * floating-point numbers. * * @private * @param {number} lower The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the random number. */ function baseRandom(lower, upper) { return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); } /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } /** * The base implementation of `_.repeat` which doesn't coerce arguments. * * @private * @param {string} string The string to repeat. * @param {number} n The number of times to repeat the string. * @returns {string} Returns the repeated string. */ function baseRepeat(string, n) { var result = ''; if (!string || n < 1 || n > MAX_SAFE_INTEGER) { return result; } // Leverage the exponentiation by squaring algorithm for a faster repeat. // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. do { if (n % 2) { result += string; } n = nativeFloor(n / 2); if (n) { string += string; } } while (n); return result; } /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ''); } /** * The base implementation of `_.sample`. * * @private * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. */ function baseSample(collection) { return arraySample(values(collection)); } /** * The base implementation of `_.sampleSize` without param guards. * * @private * @param {Array|Object} collection The collection to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function baseSampleSize(collection, n) { var array = values(collection); return shuffleSelf(array, baseClamp(n, 0, array.length)); } /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object; } path = castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey(path[index]), newValue = value; if (key === '__proto__' || key === 'constructor' || key === 'prototype') { return object; } if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject(objValue) ? objValue : (isIndex(path[index + 1]) ? [] : {}); } } assignValue(nested, key, newValue); nested = nested[key]; } return object; } /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; /** * The base implementation of `_.shuffle`. * * @private * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. */ function baseShuffle(collection) { return shuffleSelf(values(collection)); } /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * The base implementation of `_.some` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function baseSome(collection, predicate) { var result; baseEach(collection, function(value, index, collection) { result = predicate(value, index, collection); return !result; }); return !!result; } /** * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which * performs a binary search of `array` to determine the index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndex(array, value, retHighest) { var low = 0, high = array == null ? low : array.length; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if (computed !== null && !isSymbol(computed) && (retHighest ? (computed <= value) : (computed < value))) { low = mid + 1; } else { high = mid; } } return high; } return baseSortedIndexBy(array, value, identity, retHighest); } /** * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` * which invokes `iteratee` for `value` and each element of `array` to compute * their sort ranking. The iteratee is invoked with one argument; (value). * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} iteratee The iteratee invoked per element. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndexBy(array, value, iteratee, retHighest) { var low = 0, high = array == null ? 0 : array.length; if (high === 0) { return 0; } value = iteratee(value); var valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined; while (low < high) { var mid = nativeFloor((low + high) / 2), computed = iteratee(array[mid]), othIsDefined = computed !== undefined, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed); if (valIsNaN) { var setLow = retHighest || othIsReflexive; } else if (valIsUndefined) { setLow = othIsReflexive && (retHighest || othIsDefined); } else if (valIsNull) { setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); } else if (valIsSymbol) { setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); } else if (othIsNull || othIsSymbol) { setLow = false; } else { setLow = retHighest ? (computed <= value) : (computed < value); } if (setLow) { low = mid + 1; } else { high = mid; } } return nativeMin(high, MAX_ARRAY_INDEX); } /** * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseSortedUniq(array, iteratee) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; if (!index || !eq(computed, seen)) { var seen = computed; result[resIndex++] = value === 0 ? 0 : value; } } return result; } /** * The base implementation of `_.toNumber` which doesn't ensure correct * conversions of binary, hexadecimal, or octal string values. * * @private * @param {*} value The value to process. * @returns {number} Returns the number. */ function baseToNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } return +value; } /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); } isCommon = false; includes = cacheHas; seen = new SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = castPath(path, object); object = parent(object, path); return object == null || delete object[toKey(last(path))]; } /** * The base implementation of `_.update`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to update. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseUpdate(object, path, updater, customizer) { return baseSet(object, path, updater(baseGet(object, path)), customizer); } /** * The base implementation of methods like `_.dropWhile` and `_.takeWhile` * without support for iteratee shorthands. * * @private * @param {Array} array The array to query. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [isDrop] Specify dropping elements instead of taking them. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the slice of `array`. */ function baseWhile(array, predicate, isDrop, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} return isDrop ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); } /** * The base implementation of `wrapperValue` which returns the result of * performing a sequence of actions on the unwrapped `value`, where each * successive action is supplied the return value of the previous. * * @private * @param {*} value The unwrapped value. * @param {Array} actions Actions to perform to resolve the unwrapped value. * @returns {*} Returns the resolved value. */ function baseWrapperValue(value, actions) { var result = value; if (result instanceof LazyWrapper) { result = result.value(); } return arrayReduce(actions, function(result, action) { return action.func.apply(action.thisArg, arrayPush([result], action.args)); }, result); } /** * The base implementation of methods like `_.xor`, without support for * iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of values. */ function baseXor(arrays, iteratee, comparator) { var length = arrays.length; if (length < 2) { return length ? baseUniq(arrays[0]) : []; } var index = -1, result = Array(length); while (++index < length) { var array = arrays[index], othIndex = -1; while (++othIndex < length) { if (othIndex != index) { result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); } } } return baseUniq(baseFlatten(result, 1), iteratee, comparator); } /** * This base implementation of `_.zipObject` which assigns values using `assignFunc`. * * @private * @param {Array} props The property identifiers. * @param {Array} values The property values. * @param {Function} assignFunc The function to assign values. * @returns {Object} Returns the new object. */ function baseZipObject(props, values, assignFunc) { var index = -1, length = props.length, valsLength = values.length, result = {}; while (++index < length) { var value = index < valsLength ? values[index] : undefined; assignFunc(result, props[index], value); } return result; } /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity; } /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } /** * A `baseRest` alias which can be replaced with `identity` by module * replacement plugins. * * @private * @type {Function} * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ var castRest = baseRest; /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); } /** * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). * * @private * @param {number|Object} id The timer id or timeout object of the timer to clear. */ var clearTimeout = ctxClearTimeout || function(id) { return root.clearTimeout(id); }; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } /** * Creates a function like `_.groupBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} [initializer] The accumulator object initializer. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { return function(collection, iteratee) { var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, getIteratee(iteratee, 2), accumulator); }; } /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } /** * Creates a function like `_.lowerFirst`. * * @private * @param {string} methodName The name of the `String` case method to use. * @returns {Function} Returns the new case function. */ function createCaseFirst(methodName) { return function(string) { string = toString(string); var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined; var chr = strSymbols ? strSymbols[0] : string.charAt(0); var trailing = strSymbols ? castSlice(strSymbols, 1).join('') : string.slice(1); return chr[methodName]() + trailing; }; } /** * Creates a function like `_.camelCase`. * * @private * @param {Function} callback The function to combine each word. * @returns {Function} Returns the new compounder function. */ function createCompounder(callback) { return function(string) { return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); }; } /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; } /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = getIteratee(predicate, 3); collection = keys(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } /** * Creates a `_.flow` or `_.flowRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new flow function. */ function createFlow(fromRight) { return flatRest(function(funcs) { var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; if (fromRight) { funcs.reverse(); } while (index--) { var func = funcs[index]; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (prereq && !wrapper && getFuncName(func) == 'wrapper') { var wrapper = new LodashWrapper([], true); } } index = wrapper ? index : length; while (++index < length) { func = funcs[index]; var funcName = getFuncName(func), data = funcName == 'wrapper' ? getData(func) : undefined; if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1 ) { wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); } else { wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func); } } return function() { var args = arguments, value = args[0]; if (wrapper && args.length == 1 && isArray(value)) { return wrapper.plant(value).value(); } var index = 0, result = length ? funcs[index].apply(this, args) : value; while (++index < length) { result = funcs[index].call(this, result); } return result; }; }); } /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); } if (partials) { args = composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } /** * Creates a function that performs a mathematical operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @param {number} [defaultValue] The value used for `undefined` arguments. * @returns {Function} Returns the new mathematical operation function. */ function createMathOperation(operator, defaultValue) { return function(value, other) { var result; if (value === undefined && other === undefined) { return defaultValue; } if (value !== undefined) { result = value; } if (other !== undefined) { if (result === undefined) { return other; } if (typeof value == 'string' || typeof other == 'string') { value = baseToString(value); other = baseToString(other); } else { value = baseToNumber(value); other = baseToNumber(other); } result = operator(value, other); } return result; }; } /** * Creates a function like `_.over`. * * @private * @param {Function} arrayFunc The function to iterate over iteratees. * @returns {Function} Returns the new over function. */ function createOver(arrayFunc) { return flatRest(function(iteratees) { iteratees = arrayMap(iteratees, baseUnary(getIteratee())); return baseRest(function(args) { var thisArg = this; return arrayFunc(iteratees, function(iteratee) { return apply(iteratee, thisArg, args); }); }); }); } /** * Creates the padding for `string` based on `length`. The `chars` string * is truncated if the number of characters exceeds `length`. * * @private * @param {number} length The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padding for `string`. */ function createPadding(length, chars) { chars = chars === undefined ? ' ' : baseToString(chars); var charsLength = chars.length; if (charsLength < 2) { return charsLength ? baseRepeat(chars, length) : chars; } var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); return hasUnicode(chars) ? castSlice(stringToArray(result), 0, length).join('') : result.slice(0, length); } /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; } /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { end = step = undefined; } // Ensure the sign of `-0` is preserved. start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); return baseRange(start, end, step, fromRight); }; } /** * Creates a function that performs a relational operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @returns {Function} Returns the new relational operation function. */ function createRelationalOperation(operator) { return function(value, other) { if (!(typeof value == 'string' && typeof other == 'string')) { value = toNumber(value); other = toNumber(other); } return operator(value, other); }; } /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); } /** * Creates a function like `_.round`. * * @private * @param {string} methodName The name of the `Math` method to use when rounding. * @returns {Function} Returns the new round function. */ function createRound(methodName) { var func = Math[methodName]; return function(number, precision) { number = toNumber(number); precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); if (precision && nativeIsFinite(number)) { // Shift with exponential notation to avoid floating-point issues. // See [MDN](https://mdn.io/round#Examples) for more details. var pair = (toString(number) + 'e').split('e'), value = func(pair[0] + 'e' + (+pair[1] + precision)); pair = (toString(value) + 'e').split('e'); return +(pair[0] + 'e' + (+pair[1] - precision)); } return func(number); }; } /** * Creates a set object of `values`. * * @private * @param {Array} values The values to add to the set. * @returns {Object} Returns the new set. */ var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { return new Set(values); }; /** * Creates a `_.toPairs` or `_.toPairsIn` function. * * @private * @param {Function} keysFunc The function to get the keys of a given object. * @returns {Function} Returns the new pairs function. */ function createToPairs(keysFunc) { return function(object) { var tag = getTag(object); if (tag == mapTag) { return mapToArray(object); } if (tag == setTag) { return setToPairs(object); } return baseToPairs(object, keysFunc(object)); }; } /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == WRAP_BIND_FLAG) { var result = createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { result = createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { result = createPartial(func, bitmask, thisArg, partials); } else { result = createHybrid.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask); } /** * Used by `_.defaults` to customize its `_.assignIn` use to assign properties * of source objects to the destination object for all destination properties * that resolve to `undefined`. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function customDefaultsAssignIn(objValue, srcValue, key, object) { if (objValue === undefined || (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { return srcValue; } return objValue; } /** * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source * objects into destination objects that are passed thru. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to merge. * @param {Object} object The parent object of `objValue`. * @param {Object} source The parent object of `srcValue`. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. * @returns {*} Returns the value to assign. */ function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { if (isObject(objValue) && isObject(srcValue)) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, objValue); baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); stack['delete'](srcValue); } return objValue; } /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject(value) ? undefined : value; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Check that cyclic values are equal. var arrStacked = stack.get(array); var othStacked = stack.get(other); if (arrStacked && othStacked) { return arrStacked == other && othStacked == array; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Check that cyclic values are equal. var objStacked = stack.get(object); var othStacked = stack.get(other); if (objStacked && othStacked) { return objStacked == other && othStacked == object; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return setToString(overRest(func, undefined, flatten), func + ''); } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; return object.placeholder; } /** * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, * this function returns the custom method, otherwise it returns `baseIteratee`. * If arguments are provided, the chosen function is invoked with them and * its result is returned. * * @private * @param {*} [value] The value to convert to an iteratee. * @param {number} [arity] The arity of the created iteratee. * @returns {Function} Returns the chosen function or its result. */ function getIteratee() { var result = lodash.iteratee || iteratee; result = result === iteratee ? baseIteratee : result; return arguments.length ? result(arguments[0], arguments[1]) : result; } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Gets the view, applying any `transforms` to the `start` and `end` positions. * * @private * @param {number} start The start of the view. * @param {number} end The end of the view. * @param {Array} transforms The transformations to apply to the view. * @returns {Object} Returns an object containing the `start` and `end` * positions of the view. */ function getView(start, end, transforms) { var index = -1, length = transforms.length; while (++index < length) { var data = transforms[index], size = data.size; switch (data.type) { case 'drop': start += size; break; case 'dropRight': end -= size; break; case 'take': end = nativeMin(end, start + size); break; case 'takeRight': start = nativeMax(start, end - size); break; } } return { 'start': start, 'end': end }; } /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return new Ctor; case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return new Ctor; case symbolTag: return cloneSymbol(object); } } /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `func` is capable of being masked. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `func` is maskable, else `false`. */ var isMaskable = coreJsData ? isFunction : stubFalse; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); var isCombo = ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } /** * Gets the value at `key`, unless `key` is "__proto__" or "constructor". * * @private * @param {Object} object The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function safeGet(object, key) { if (key === 'constructor' && typeof object[key] === 'function') { return; } if (key == '__proto__') { return; } return object[key]; } /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = shortOut(baseSetData); /** * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @returns {number|Object} Returns the timer id or timeout object. */ var setTimeout = ctxSetTimeout || function(func, wait) { return root.setTimeout(func, wait); }; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } /** * A specialized version of `_.shuffle` which mutates and sets the size of `array`. * * @private * @param {Array} array The array to shuffle. * @param {number} [size=array.length] The size of `array`. * @returns {Array} Returns `array`. */ function shuffleSelf(array, size) { var index = -1, length = array.length, lastIndex = length - 1; size = size === undefined ? length : size; while (++index < size) { var rand = baseRandom(index, lastIndex), value = array[rand]; array[rand] = array[index]; array[index] = value; } array.length = size; return array; } /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (string.charCodeAt(0) === 46 /* . */) { result.push(''); } string.replace(rePropName, function(match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } /*------------------------------------------------------------------------*/ /** * Creates an array of elements split into groups the length of `size`. * If `array` can't be split evenly, the final chunk will be the remaining * elements. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the new array of chunks. * @example * * _.chunk(['a', 'b', 'c', 'd'], 2); * // => [['a', 'b'], ['c', 'd']] * * _.chunk(['a', 'b', 'c', 'd'], 3); * // => [['a', 'b', 'c'], ['d']] */ function chunk(array, size, guard) { if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { size = 1; } else { size = nativeMax(toInteger(size), 0); } var length = array == null ? 0 : array.length; if (!length || size < 1) { return []; } var index = 0, resIndex = 0, result = Array(nativeCeil(length / size)); while (index < length) { result[resIndex++] = baseSlice(array, index, (index += size)); } return result; } /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } /** * Creates a new array concatenating `array` with any additional arrays * and/or values. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to concatenate. * @param {...*} [values] The values to concatenate. * @returns {Array} Returns the new concatenated array. * @example * * var array = [1]; * var other = _.concat(array, 2, [3], [[4]]); * * console.log(other); * // => [1, 2, 3, [4]] * * console.log(array); * // => [1] */ function concat() { var length = arguments.length; if (!length) { return []; } var args = Array(length - 1), array = arguments[0], index = length; while (index--) { args[index - 1] = arguments[index]; } return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); } /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; }); /** * This method is like `_.difference` except that it accepts `iteratee` which * is invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * **Note:** Unlike `_.pullAllBy`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2] * * // The `_.property` iteratee shorthand. * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var differenceBy = baseRest(function(array, values) { var iteratee = last(values); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.difference` except that it accepts `comparator` * which is invoked to compare elements of `array` to `values`. The order and * references of result values are determined by the first array. The comparator * is invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.pullAllWith`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); * // => [{ 'x': 2, 'y': 1 }] */ var differenceWith = baseRest(function(array, values) { var comparator = last(values); if (isArrayLikeObject(comparator)) { comparator = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) : []; }); /** * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ * @since 0.5.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.drop([1, 2, 3]); * // => [2, 3] * * _.drop([1, 2, 3], 2); * // => [3] * * _.drop([1, 2, 3], 5); * // => [] * * _.drop([1, 2, 3], 0); * // => [1, 2, 3] */ function drop(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropRight([1, 2, 3]); * // => [1, 2] * * _.dropRight([1, 2, 3], 2); * // => [1] * * _.dropRight([1, 2, 3], 5); * // => [] * * _.dropRight([1, 2, 3], 0); * // => [1, 2, 3] */ function dropRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` excluding elements dropped from the end. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.dropRightWhile(users, function(o) { return !o.active; }); * // => objects for ['barney'] * * // The `_.matches` iteratee shorthand. * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['barney', 'fred'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropRightWhile(users, ['active', false]); * // => objects for ['barney'] * * // The `_.property` iteratee shorthand. * _.dropRightWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; } /** * Creates a slice of `array` excluding elements dropped from the beginning. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.dropWhile(users, function(o) { return !o.active; }); * // => objects for ['pebbles'] * * // The `_.matches` iteratee shorthand. * _.dropWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['fred', 'pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropWhile(users, ['active', false]); * // => objects for ['pebbles'] * * // The `_.property` iteratee shorthand. * _.dropWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true) : []; } /** * Fills elements of `array` with `value` from `start` up to, but not * including, `end`. * * **Note:** This method mutates `array`. * * @static * @memberOf _ * @since 3.2.0 * @category Array * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.fill(array, 'a'); * console.log(array); * // => ['a', 'a', 'a'] * * _.fill(Array(3), 2); * // => [2, 2, 2] * * _.fill([4, 6, 8, 10], '*', 1, 3); * // => [4, '*', '*', 10] */ function fill(array, value, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { start = 0; end = length; } return baseFill(array, value, start, end); } /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseFindIndex(array, getIteratee(predicate, 3), index); } /** * This method is like `_.findIndex` except that it iterates over elements * of `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); * // => 2 * * // The `_.matches` iteratee shorthand. * _.findLastIndex(users, { 'user': 'barney', 'active': true }); * // => 0 * * // The `_.matchesProperty` iteratee shorthand. * _.findLastIndex(users, ['active', false]); * // => 2 * * // The `_.property` iteratee shorthand. * _.findLastIndex(users, 'active'); * // => 0 */ function findLastIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length - 1; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return baseFindIndex(array, getIteratee(predicate, 3), index, true); } /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, 1) : []; } /** * Recursively flattens `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flattenDeep([1, [2, [3, [4]], 5]]); * // => [1, 2, 3, 4, 5] */ function flattenDeep(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, INFINITY) : []; } /** * Recursively flatten `array` up to `depth` times. * * @static * @memberOf _ * @since 4.4.0 * @category Array * @param {Array} array The array to flatten. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * var array = [1, [2, [3, [4]], 5]]; * * _.flattenDepth(array, 1); * // => [1, 2, [3, [4]], 5] * * _.flattenDepth(array, 2); * // => [1, 2, 3, [4], 5] */ function flattenDepth(array, depth) { var length = array == null ? 0 : array.length; if (!length) { return []; } depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(array, depth); } /** * The inverse of `_.toPairs`; this method returns an object composed * from key-value `pairs`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} pairs The key-value pairs. * @returns {Object} Returns the new object. * @example * * _.fromPairs([['a', 1], ['b', 2]]); * // => { 'a': 1, 'b': 2 } */ function fromPairs(pairs) { var index = -1, length = pairs == null ? 0 : pairs.length, result = {}; while (++index < length) { var pair = pairs[index]; result[pair[0]] = pair[1]; } return result; } /** * Gets the first element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @alias first * @category Array * @param {Array} array The array to query. * @returns {*} Returns the first element of `array`. * @example * * _.head([1, 2, 3]); * // => 1 * * _.head([]); * // => undefined */ function head(array) { return (array && array.length) ? array[0] : undefined; } /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseIndexOf(array, value, index); } /** * Gets all but the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] */ function initial(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 0, -1) : []; } /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = baseRest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) : []; }); /** * This method is like `_.intersection` except that it accepts `iteratee` * which is invoked for each element of each `arrays` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [2.1] * * // The `_.property` iteratee shorthand. * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }] */ var intersectionBy = baseRest(function(arrays) { var iteratee = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); if (iteratee === last(mapped)) { iteratee = undefined; } else { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.intersection` except that it accepts `comparator` * which is invoked to compare elements of `arrays`. The order and references * of result values are determined by the first array. The comparator is * invoked with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.intersectionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }] */ var intersectionWith = baseRest(function(arrays) { var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); comparator = typeof comparator == 'function' ? comparator : undefined; if (comparator) { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, undefined, comparator) : []; }); /** * Converts all elements in `array` into a string separated by `separator`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to convert. * @param {string} [separator=','] The element separator. * @returns {string} Returns the joined string. * @example * * _.join(['a', 'b', 'c'], '~'); * // => 'a~b~c' */ function join(array, separator) { return array == null ? '' : nativeJoin.call(array, separator); } /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } /** * This method is like `_.indexOf` except that it iterates over elements of * `array` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.lastIndexOf([1, 2, 1, 2], 2); * // => 3 * * // Search from the `fromIndex`. * _.lastIndexOf([1, 2, 1, 2], 2, 2); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return value === value ? strictLastIndexOf(array, value, index) : baseFindIndex(array, baseIsNaN, index, true); } /** * Gets the element at index `n` of `array`. If `n` is negative, the nth * element from the end is returned. * * @static * @memberOf _ * @since 4.11.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=0] The index of the element to return. * @returns {*} Returns the nth element of `array`. * @example * * var array = ['a', 'b', 'c', 'd']; * * _.nth(array, 1); * // => 'b' * * _.nth(array, -2); * // => 'c'; */ function nth(array, n) { return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; } /** * Removes all given values from `array` using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` * to remove elements from an array by predicate. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {...*} [values] The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pull(array, 'a', 'c'); * console.log(array); * // => ['b', 'b'] */ var pull = baseRest(pullAll); /** * This method is like `_.pull` except that it accepts an array of values to remove. * * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pullAll(array, ['a', 'c']); * console.log(array); * // => ['b', 'b'] */ function pullAll(array, values) { return (array && array.length && values && values.length) ? basePullAll(array, values) : array; } /** * This method is like `_.pullAll` except that it accepts `iteratee` which is * invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The iteratee is invoked with one argument: (value). * * **Note:** Unlike `_.differenceBy`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); * console.log(array); * // => [{ 'x': 2 }] */ function pullAllBy(array, values, iteratee) { return (array && array.length && values && values.length) ? basePullAll(array, values, getIteratee(iteratee, 2)) : array; } /** * This method is like `_.pullAll` except that it accepts `comparator` which * is invoked to compare elements of `array` to `values`. The comparator is * invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.differenceWith`, this method mutates `array`. * * @static * @memberOf _ * @since 4.6.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); * console.log(array); * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ function pullAllWith(array, values, comparator) { return (array && array.length && values && values.length) ? basePullAll(array, values, undefined, comparator) : array; } /** * Removes elements from `array` corresponding to `indexes` and returns an * array of removed elements. * * **Note:** Unlike `_.at`, this method mutates `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to modify. * @param {...(number|number[])} [indexes] The indexes of elements to remove. * @returns {Array} Returns the new array of removed elements. * @example * * var array = ['a', 'b', 'c', 'd']; * var pulled = _.pullAt(array, [1, 3]); * * console.log(array); * // => ['a', 'c'] * * console.log(pulled); * // => ['b', 'd'] */ var pullAt = flatRest(function(array, indexes) { var length = array == null ? 0 : array.length, result = baseAt(array, indexes); basePullAt(array, arrayMap(indexes, function(index) { return isIndex(index, length) ? +index : index; }).sort(compareAscending)); return result; }); /** * Removes all elements from `array` that `predicate` returns truthy for * and returns an array of the removed elements. The predicate is invoked * with three arguments: (value, index, array). * * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` * to pull elements from an array by value. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [1, 2, 3, 4]; * var evens = _.remove(array, function(n) { * return n % 2 == 0; * }); * * console.log(array); * // => [1, 3] * * console.log(evens); * // => [2, 4] */ function remove(array, predicate) { var result = []; if (!(array && array.length)) { return result; } var index = -1, indexes = [], length = array.length; predicate = getIteratee(predicate, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); indexes.push(index); } } basePullAt(array, indexes); return result; } /** * Reverses `array` so that the first element becomes the last, the second * element becomes the second to last, and so on. * * **Note:** This method mutates `array` and is based on * [`Array#reverse`](https://mdn.io/Array/reverse). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.reverse(array); * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function reverse(array) { return array == null ? array : nativeReverse.call(array); } /** * Creates a slice of `array` from `start` up to, but not including, `end`. * * **Note:** This method is used instead of * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are * returned. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function slice(array, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { start = 0; end = length; } else { start = start == null ? 0 : toInteger(start); end = end === undefined ? length : toInteger(end); } return baseSlice(array, start, end); } /** * Uses a binary search to determine the lowest index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([30, 50], 40); * // => 1 */ function sortedIndex(array, value) { return baseSortedIndex(array, value); } /** * This method is like `_.sortedIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 0 * * // The `_.property` iteratee shorthand. * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); * // => 0 */ function sortedIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); } /** * This method is like `_.indexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedIndexOf([4, 5, 5, 5, 6], 5); * // => 1 */ function sortedIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value); if (index < length && eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedLastIndex([4, 5, 5, 5, 6], 5); * // => 4 */ function sortedLastIndex(array, value) { return baseSortedIndex(array, value, true); } /** * This method is like `_.sortedLastIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 1 * * // The `_.property` iteratee shorthand. * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); * // => 1 */ function sortedLastIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); } /** * This method is like `_.lastIndexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); * // => 3 */ function sortedLastIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value, true) - 1; if (eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.uniq` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniq([1, 1, 2]); * // => [1, 2] */ function sortedUniq(array) { return (array && array.length) ? baseSortedUniq(array) : []; } /** * This method is like `_.uniqBy` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); * // => [1.1, 2.3] */ function sortedUniqBy(array, iteratee) { return (array && array.length) ? baseSortedUniq(array, getIteratee(iteratee, 2)) : []; } /** * Gets all but the first element of `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.tail([1, 2, 3]); * // => [2, 3] */ function tail(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 1, length) : []; } /** * Creates a slice of `array` with `n` elements taken from the beginning. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.take([1, 2, 3]); * // => [1] * * _.take([1, 2, 3], 2); * // => [1, 2] * * _.take([1, 2, 3], 5); * // => [1, 2, 3] * * _.take([1, 2, 3], 0); * // => [] */ function take(array, n, guard) { if (!(array && array.length)) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` with `n` elements taken from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeRight([1, 2, 3]); * // => [3] * * _.takeRight([1, 2, 3], 2); * // => [2, 3] * * _.takeRight([1, 2, 3], 5); * // => [1, 2, 3] * * _.takeRight([1, 2, 3], 0); * // => [] */ function takeRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with elements taken from the end. Elements are * taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.takeRightWhile(users, function(o) { return !o.active; }); * // => objects for ['fred', 'pebbles'] * * // The `_.matches` iteratee shorthand. * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeRightWhile(users, ['active', false]); * // => objects for ['fred', 'pebbles'] * * // The `_.property` iteratee shorthand. * _.takeRightWhile(users, 'active'); * // => [] */ function takeRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; } /** * Creates a slice of `array` with elements taken from the beginning. Elements * are taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.takeWhile(users, function(o) { return !o.active; }); * // => objects for ['barney', 'fred'] * * // The `_.matches` iteratee shorthand. * _.takeWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeWhile(users, ['active', false]); * // => objects for ['barney', 'fred'] * * // The `_.property` iteratee shorthand. * _.takeWhile(users, 'active'); * // => [] */ function takeWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3)) : []; } /** * Creates an array of unique values, in order, from all given arrays using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([2], [1, 2]); * // => [2, 1] */ var union = baseRest(function(arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); /** * This method is like `_.union` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which uniqueness is computed. Result values are chosen from the first * array in which the value occurs. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * _.unionBy([2.1], [1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ var unionBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); }); /** * This method is like `_.union` except that it accepts `comparator` which * is invoked to compare elements of `arrays`. Result values are chosen from * the first array in which the value occurs. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.unionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var unionWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); }); /** * Creates a duplicate-free version of an array, using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons, in which only the first occurrence of each element * is kept. The order of result values is determined by the order they occur * in the array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniq([2, 1, 2]); * // => [2, 1] */ function uniq(array) { return (array && array.length) ? baseUniq(array) : []; } /** * This method is like `_.uniq` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * uniqueness is computed. The order of result values is determined by the * order they occur in the array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniqBy([2.1, 1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniqBy(array, iteratee) { return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; } /** * This method is like `_.uniq` except that it accepts `comparator` which * is invoked to compare elements of `array`. The order of result values is * determined by the order they occur in the array.The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.uniqWith(objects, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ function uniqWith(array, comparator) { comparator = typeof comparator == 'function' ? comparator : undefined; return (array && array.length) ? baseUniq(array, undefined, comparator) : []; } /** * This method is like `_.zip` except that it accepts an array of grouped * elements and creates an array regrouping the elements to their pre-zip * configuration. * * @static * @memberOf _ * @since 1.2.0 * @category Array * @param {Array} array The array of grouped elements to process. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] * * _.unzip(zipped); * // => [['a', 'b'], [1, 2], [true, false]] */ function unzip(array) { if (!(array && array.length)) { return []; } var length = 0; array = arrayFilter(array, function(group) { if (isArrayLikeObject(group)) { length = nativeMax(group.length, length); return true; } }); return baseTimes(length, function(index) { return arrayMap(array, baseProperty(index)); }); } /** * This method is like `_.unzip` except that it accepts `iteratee` to specify * how regrouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {Array} array The array of grouped elements to process. * @param {Function} [iteratee=_.identity] The function to combine * regrouped values. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip([1, 2], [10, 20], [100, 200]); * // => [[1, 10, 100], [2, 20, 200]] * * _.unzipWith(zipped, _.add); * // => [3, 30, 300] */ function unzipWith(array, iteratee) { if (!(array && array.length)) { return []; } var result = unzip(array); if (iteratee == null) { return result; } return arrayMap(result, function(group) { return apply(iteratee, undefined, group); }); } /** * Creates an array excluding all given values using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.pull`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...*} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.xor * @example * * _.without([2, 1, 2, 3], 1, 2); * // => [3] */ var without = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, values) : []; }); /** * Creates an array of unique values that is the * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) * of the given arrays. The order of result values is determined by the order * they occur in the arrays. * * @static * @memberOf _ * @since 2.4.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.without * @example * * _.xor([2, 1], [2, 3]); * // => [1, 3] */ var xor = baseRest(function(arrays) { return baseXor(arrayFilter(arrays, isArrayLikeObject)); }); /** * This method is like `_.xor` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which by which they're compared. The order of result values is determined * by the order they occur in the arrays. The iteratee is invoked with one * argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2, 3.4] * * // The `_.property` iteratee shorthand. * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var xorBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); }); /** * This method is like `_.xor` except that it accepts `comparator` which is * invoked to compare elements of `arrays`. The order of result values is * determined by the order they occur in the arrays. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.xorWith(objects, others, _.isEqual); * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var xorWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); }); /** * Creates an array of grouped elements, the first of which contains the * first elements of the given arrays, the second of which contains the * second elements of the given arrays, and so on. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] */ var zip = baseRest(unzip); /** * This method is like `_.fromPairs` except that it accepts two arrays, * one of property identifiers and one of corresponding values. * * @static * @memberOf _ * @since 0.4.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObject(['a', 'b'], [1, 2]); * // => { 'a': 1, 'b': 2 } */ function zipObject(props, values) { return baseZipObject(props || [], values || [], assignValue); } /** * This method is like `_.zipObject` except that it supports property paths. * * @static * @memberOf _ * @since 4.1.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } */ function zipObjectDeep(props, values) { return baseZipObject(props || [], values || [], baseSet); } /** * This method is like `_.zip` except that it accepts `iteratee` to specify * how grouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @param {Function} [iteratee=_.identity] The function to combine * grouped values. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { * return a + b + c; * }); * // => [111, 222] */ var zipWith = baseRest(function(arrays) { var length = arrays.length, iteratee = length > 1 ? arrays[length - 1] : undefined; iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; return unzipWith(arrays, iteratee); }); /*------------------------------------------------------------------------*/ /** * Creates a `lodash` wrapper instance that wraps `value` with explicit method * chain sequences enabled. The result of such sequences must be unwrapped * with `_#value`. * * @static * @memberOf _ * @since 1.3.0 * @category Seq * @param {*} value The value to wrap. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'pebbles', 'age': 1 } * ]; * * var youngest = _ * .chain(users) * .sortBy('age') * .map(function(o) { * return o.user + ' is ' + o.age; * }) * .head() * .value(); * // => 'pebbles is 1' */ function chain(value) { var result = lodash(value); result.__chain__ = true; return result; } /** * This method invokes `interceptor` and returns `value`. The interceptor * is invoked with one argument; (value). The purpose of this method is to * "tap into" a method chain sequence in order to modify intermediate results. * * @static * @memberOf _ * @since 0.1.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns `value`. * @example * * _([1, 2, 3]) * .tap(function(array) { * // Mutate input array. * array.pop(); * }) * .reverse() * .value(); * // => [2, 1] */ function tap(value, interceptor) { interceptor(value); return value; } /** * This method is like `_.tap` except that it returns the result of `interceptor`. * The purpose of this method is to "pass thru" values replacing intermediate * results in a method chain sequence. * * @static * @memberOf _ * @since 3.0.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns the result of `interceptor`. * @example * * _(' abc ') * .chain() * .trim() * .thru(function(value) { * return [value]; * }) * .value(); * // => ['abc'] */ function thru(value, interceptor) { return interceptor(value); } /** * This method is the wrapper version of `_.at`. * * @name at * @memberOf _ * @since 1.0.0 * @category Seq * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _(object).at(['a[0].b.c', 'a[1]']).value(); * // => [3, 4] */ var wrapperAt = flatRest(function(paths) { var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { return baseAt(object, paths); }; if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) { return this.thru(interceptor); } value = value.slice(start, +start + (length ? 1 : 0)); value.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(value, this.__chain__).thru(function(array) { if (length && !array.length) { array.push(undefined); } return array; }); }); /** * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. * * @name chain * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // A sequence without explicit chaining. * _(users).head(); * // => { 'user': 'barney', 'age': 36 } * * // A sequence with explicit chaining. * _(users) * .chain() * .head() * .pick('user') * .value(); * // => { 'user': 'barney' } */ function wrapperChain() { return chain(this); } /** * Executes the chain sequence and returns the wrapped result. * * @name commit * @memberOf _ * @since 3.2.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2]; * var wrapped = _(array).push(3); * * console.log(array); * // => [1, 2] * * wrapped = wrapped.commit(); * console.log(array); * // => [1, 2, 3] * * wrapped.last(); * // => 3 * * console.log(array); * // => [1, 2, 3] */ function wrapperCommit() { return new LodashWrapper(this.value(), this.__chain__); } /** * Gets the next value on a wrapped object following the * [iterator protocol](https://mdn.io/iteration_protocols#iterator). * * @name next * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the next iterator value. * @example * * var wrapped = _([1, 2]); * * wrapped.next(); * // => { 'done': false, 'value': 1 } * * wrapped.next(); * // => { 'done': false, 'value': 2 } * * wrapped.next(); * // => { 'done': true, 'value': undefined } */ function wrapperNext() { if (this.__values__ === undefined) { this.__values__ = toArray(this.value()); } var done = this.__index__ >= this.__values__.length, value = done ? undefined : this.__values__[this.__index__++]; return { 'done': done, 'value': value }; } /** * Enables the wrapper to be iterable. * * @name Symbol.iterator * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the wrapper object. * @example * * var wrapped = _([1, 2]); * * wrapped[Symbol.iterator]() === wrapped; * // => true * * Array.from(wrapped); * // => [1, 2] */ function wrapperToIterator() { return this; } /** * Creates a clone of the chain sequence planting `value` as the wrapped value. * * @name plant * @memberOf _ * @since 3.2.0 * @category Seq * @param {*} value The value to plant. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2]).map(square); * var other = wrapped.plant([3, 4]); * * other.value(); * // => [9, 16] * * wrapped.value(); * // => [1, 4] */ function wrapperPlant(value) { var result, parent = this; while (parent instanceof baseLodash) { var clone = wrapperClone(parent); clone.__index__ = 0; clone.__values__ = undefined; if (result) { previous.__wrapped__ = clone; } else { result = clone; } var previous = clone; parent = parent.__wrapped__; } previous.__wrapped__ = value; return result; } /** * This method is the wrapper version of `_.reverse`. * * **Note:** This method mutates the wrapped array. * * @name reverse * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2, 3]; * * _(array).reverse().value() * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function wrapperReverse() { var value = this.__wrapped__; if (value instanceof LazyWrapper) { var wrapped = value; if (this.__actions__.length) { wrapped = new LazyWrapper(this); } wrapped = wrapped.reverse(); wrapped.__actions__.push({ 'func': thru, 'args': [reverse], 'thisArg': undefined }); return new LodashWrapper(wrapped, this.__chain__); } return this.thru(reverse); } /** * Executes the chain sequence to resolve the unwrapped value. * * @name value * @memberOf _ * @since 0.1.0 * @alias toJSON, valueOf * @category Seq * @returns {*} Returns the resolved unwrapped value. * @example * * _([1, 2, 3]).value(); * // => [1, 2, 3] */ function wrapperValue() { return baseWrapperValue(this.__wrapped__, this.__actions__); } /*------------------------------------------------------------------------*/ /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the number of times the key was returned by `iteratee`. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.5.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': 1, '6': 2 } * * // The `_.property` iteratee shorthand. * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { ++result[key]; } else { baseAssignValue(result, key, 1); } }); /** * Checks if `predicate` returns truthy for **all** elements of `collection`. * Iteration is stopped once `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index|key, collection). * * **Note:** This method returns `true` for * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of * elements of empty collections. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. * @example * * _.every([true, 1, null, 'yes'], Boolean); * // => false * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.every(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.every(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.every(users, 'active'); * // => false */ function every(collection, predicate, guard) { var func = isArray(collection) ? arrayEvery : baseEvery; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] * * // Combining several predicates using `_.overEvery` or `_.overSome`. * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); * // => objects for ['fred', 'barney'] */ function filter(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = createFind(findIndex); /** * This method is like `_.find` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=collection.length-1] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * _.findLast([1, 2, 3, 4], function(n) { * return n % 2 == 1; * }); * // => 3 */ var findLast = createFind(findLastIndex); /** * Creates a flattened array of values by running each element in `collection` * thru `iteratee` and flattening the mapped results. The iteratee is invoked * with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [n, n]; * } * * _.flatMap([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMap(collection, iteratee) { return baseFlatten(map(collection, iteratee), 1); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDeep([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMapDeep(collection, iteratee) { return baseFlatten(map(collection, iteratee), INFINITY); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results up to `depth` times. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDepth([1, 2], duplicate, 2); * // => [[1, 1], [2, 2]] */ function flatMapDepth(collection, iteratee, depth) { depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(map(collection, iteratee), depth); } /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.forEach` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @alias eachRight * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEach * @example * * _.forEachRight([1, 2], function(value) { * console.log(value); * }); * // => Logs `2` then `1`. */ function forEachRight(collection, iteratee) { var func = isArray(collection) ? arrayEachRight : baseEachRight; return func(collection, getIteratee(iteratee, 3)); } /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The order of grouped values * is determined by the order they occur in `collection`. The corresponding * value of each key is an array of elements responsible for generating the * key. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': [4.2], '6': [6.1, 6.3] } * * // The `_.property` iteratee shorthand. * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); } else { baseAssignValue(result, key, [value]); } }); /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } /** * Invokes the method at `path` of each element in `collection`, returning * an array of the results of each invoked method. Any additional arguments * are provided to each invoked method. If `path` is a function, it's invoked * for, and `this` bound to, each element in `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|string} path The path of the method to invoke or * the function invoked per iteration. * @param {...*} [args] The arguments to invoke each method with. * @returns {Array} Returns the array of results. * @example * * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invokeMap([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ var invokeMap = baseRest(function(collection, path, args) { var index = -1, isFunc = typeof path == 'function', result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value) { result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); }); return result; }); /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the last element responsible for generating the key. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * var array = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.keyBy(array, function(o) { * return String.fromCharCode(o.code); * }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.keyBy(array, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } */ var keyBy = createAggregator(function(result, value, key) { baseAssignValue(result, key, value); }); /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } return baseOrderBy(collection, iteratees, orders); } /** * Creates an array of elements split into two groups, the first of which * contains elements `predicate` returns truthy for, the second of which * contains elements `predicate` returns falsey for. The predicate is * invoked with one argument: (value). * * @static * @memberOf _ * @since 3.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of grouped elements. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true }, * { 'user': 'pebbles', 'age': 1, 'active': false } * ]; * * _.partition(users, function(o) { return o.active; }); * // => objects for [['fred'], ['barney', 'pebbles']] * * // The `_.matches` iteratee shorthand. * _.partition(users, { 'age': 1, 'active': false }); * // => objects for [['pebbles'], ['barney', 'fred']] * * // The `_.matchesProperty` iteratee shorthand. * _.partition(users, ['active', false]); * // => objects for [['barney', 'pebbles'], ['fred']] * * // The `_.property` iteratee shorthand. * _.partition(users, 'active'); * // => objects for [['fred'], ['barney', 'pebbles']] */ var partition = createAggregator(function(result, value, key) { result[key ? 0 : 1].push(value); }, function() { return [[], []]; }); /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); } /** * This method is like `_.reduce` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduce * @example * * var array = [[0, 1], [2, 3], [4, 5]]; * * _.reduceRight(array, function(flattened, other) { * return flattened.concat(other); * }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); } /** * The opposite of `_.filter`; this method returns the elements of `collection` * that `predicate` does **not** return truthy for. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.filter * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true } * ]; * * _.reject(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.reject(users, { 'age': 40, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.reject(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.reject(users, 'active'); * // => objects for ['barney'] */ function reject(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, negate(getIteratee(predicate, 3))); } /** * Gets a random element from `collection`. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. * @example * * _.sample([1, 2, 3, 4]); * // => 2 */ function sample(collection) { var func = isArray(collection) ? arraySample : baseSample; return func(collection); } /** * Gets `n` random elements at unique keys from `collection` up to the * size of `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @param {number} [n=1] The number of elements to sample. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the random elements. * @example * * _.sampleSize([1, 2, 3], 2); * // => [3, 1] * * _.sampleSize([1, 2, 3], 4); * // => [2, 3, 1] */ function sampleSize(collection, n, guard) { if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } var func = isArray(collection) ? arraySampleSize : baseSampleSize; return func(collection, n); } /** * Creates an array of shuffled values, using a version of the * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. * @example * * _.shuffle([1, 2, 3, 4]); * // => [4, 1, 3, 2] */ function shuffle(collection) { var func = isArray(collection) ? arrayShuffle : baseShuffle; return func(collection); } /** * Gets the size of `collection` by returning its length for array-like * values or the number of own enumerable string keyed properties for objects. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns the collection size. * @example * * _.size([1, 2, 3]); * // => 3 * * _.size({ 'a': 1, 'b': 2 }); * // => 2 * * _.size('pebbles'); * // => 7 */ function size(collection) { if (collection == null) { return 0; } if (isArrayLike(collection)) { return isString(collection) ? stringSize(collection) : collection.length; } var tag = getTag(collection); if (tag == mapTag || tag == setTag) { return collection.size; } return baseKeys(collection).length; } /** * Checks if `predicate` returns truthy for **any** element of `collection`. * Iteration is stopped once `predicate` returns truthy. The predicate is * invoked with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.some(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.some(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.some(users, 'active'); * // => true */ function some(collection, predicate, guard) { var func = isArray(collection) ? arraySome : baseSome; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection thru each iteratee. This method * performs a stable sort, that is, it preserves the original sort order of * equal elements. The iteratees are invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to sort by. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 30 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.sortBy(users, [function(o) { return o.user; }]); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] * * _.sortBy(users, ['user', 'age']); * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] */ var sortBy = baseRest(function(collection, iteratees) { if (collection == null) { return []; } var length = iteratees.length; if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { iteratees = []; } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { iteratees = [iteratees[0]]; } return baseOrderBy(collection, baseFlatten(iteratees, 1), []); }); /*------------------------------------------------------------------------*/ /** * Gets the timestamp of the number of milliseconds that have elapsed since * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @since 2.4.0 * @category Date * @returns {number} Returns the timestamp. * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => Logs the number of milliseconds it took for the deferred invocation. */ var now = ctxNow || function() { return root.Date.now(); }; /*------------------------------------------------------------------------*/ /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it's called `n` or more times. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => Logs 'done saving!' after the two async saves have completed. */ function after(n, func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that invokes `func`, with up to `n` arguments, * ignoring any additional arguments. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @param {number} [n=func.length] The arity cap. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.ary(parseInt, 1)); * // => [6, 8, 10] */ function ary(func, n, guard) { n = guard ? undefined : n; n = (func && n == null) ? func.length : n; return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); } /** * Creates a function that invokes `func`, with the `this` binding and arguments * of the created function, while it's called less than `n` times. Subsequent * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {number} n The number of calls at which `func` is no longer invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * jQuery(element).on('click', _.before(5, addContactToList)); * // => Allows adding up to 4 contacts to the list. */ function before(n, func) { var result; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n > 0) { result = func.apply(this, arguments); } if (n <= 1) { func = undefined; } return result; }; } /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(func, bitmask, thisArg, partials, holders); }); /** * Creates a function that invokes the method at `object[key]` with `partials` * prepended to the arguments it receives. * * This method differs from `_.bind` by allowing bound functions to reference * methods that may be redefined or don't yet exist. See * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) * for more details. * * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * @static * @memberOf _ * @since 0.10.0 * @category Function * @param {Object} object The object to invoke the method on. * @param {string} key The key of the method. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'user': 'fred', * 'greet': function(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * }; * * var bound = _.bindKey(object, 'greet', 'hi'); * bound('!'); * // => 'hi fred!' * * object.greet = function(greeting, punctuation) { * return greeting + 'ya ' + this.user + punctuation; * }; * * bound('!'); * // => 'hiya fred!' * * // Bound with placeholders. * var bound = _.bindKey(object, 'greet', _, '!'); * bound('hi'); * // => 'hiya fred!' */ var bindKey = baseRest(function(object, key, partials) { var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bindKey)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(key, bitmask, object, partials, holders); }); /** * Creates a function that accepts arguments of `func` and either invokes * `func` returning its result, if at least `arity` number of arguments have * been provided, or returns a function that accepts the remaining `func` * arguments, and so on. The arity of `func` may be specified if `func.length` * is not sufficient. * * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 2.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curry(abc); * * curried(1)(2)(3); * // => [1, 2, 3] * * curried(1, 2)(3); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(1)(_, 3)(2); * // => [1, 2, 3] */ function curry(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curry.placeholder; return result; } /** * This method is like `_.curry` except that arguments are applied to `func` * in the manner of `_.partialRight` instead of `_.partial`. * * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curryRight(abc); * * curried(3)(2)(1); * // => [1, 2, 3] * * curried(2, 3)(1); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(3)(1, _)(2); * // => [1, 2, 3] */ function curryRight(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curryRight.placeholder; return result; } /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed `func` invocations and a `flush` method to immediately invoke them. * Provide `options` to indicate whether `func` should be invoked on the * leading and/or trailing edge of the `wait` timeout. The `func` is invoked * with the last arguments provided to the debounced function. Subsequent * calls to the debounced function return the result of the last `func` * invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the debounced function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=false] * Specify invoking on the leading edge of the timeout. * @param {number} [options.maxWait] * The maximum time `func` is allowed to be delayed before it's invoked. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // Avoid costly calculations while the window size is in flux. * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // Invoke `sendMail` when clicked, debouncing subsequent calls. * jQuery(element).on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // Ensure `batchLog` is invoked once after 1 second of debounced calls. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); * var source = new EventSource('/stream'); * jQuery(source).on('message', debounced); * * // Cancel the trailing debounced invocation. * jQuery(window).on('popstate', debounced.cancel); */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = 'maxWait' in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = 'trailing' in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { // Reset any `maxWait` timer. lastInvokeTime = time; // Start the timer for the trailing edge. timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall; return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the // trailing edge, the system time has gone backwards and we're treating // it as the trailing edge, or we've hit the `maxWait` limit. return (lastCallTime === undefined || (timeSinceLastCall >= wait) || (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } // Restart the timer. timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been // debounced at least once. if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = undefined; return result; } function cancel() { if (timerId !== undefined) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = undefined; } function flush() { return timerId === undefined ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === undefined) { return leadingEdge(lastCallTime); } if (maxing) { // Handle invocations in a tight loop. clearTimeout(timerId); timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } /** * Defers invoking the `func` until the current call stack has cleared. Any * additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to defer. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.defer(function(text) { * console.log(text); * }, 'deferred'); * // => Logs 'deferred' after one millisecond. */ var defer = baseRest(function(func, args) { return baseDelay(func, 1, args); }); /** * Invokes `func` after `wait` milliseconds. Any additional arguments are * provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.delay(function(text) { * console.log(text); * }, 1000, 'later'); * // => Logs 'later' after one second. */ var delay = baseRest(function(func, wait, args) { return baseDelay(func, toNumber(wait) || 0, args); }); /** * Creates a function that invokes `func` with arguments reversed. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to flip arguments for. * @returns {Function} Returns the new flipped function. * @example * * var flipped = _.flip(function() { * return _.toArray(arguments); * }); * * flipped('a', 'b', 'c', 'd'); * // => ['d', 'c', 'b', 'a'] */ function flip(func) { return createWrap(func, WRAP_FLIP_FLAG); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; /** * Creates a function that negates the result of the predicate `func`. The * `func` predicate is invoked with the `this` binding and arguments of the * created function. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} predicate The predicate to negate. * @returns {Function} Returns the new negated function. * @example * * function isEven(n) { * return n % 2 == 0; * } * * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); * // => [1, 3, 5] */ function negate(predicate) { if (typeof predicate != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return function() { var args = arguments; switch (args.length) { case 0: return !predicate.call(this); case 1: return !predicate.call(this, args[0]); case 2: return !predicate.call(this, args[0], args[1]); case 3: return !predicate.call(this, args[0], args[1], args[2]); } return !predicate.apply(this, args); }; } /** * Creates a function that is restricted to invoking `func` once. Repeat calls * to the function return the value of the first invocation. The `func` is * invoked with the `this` binding and arguments of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // => `createApplication` is invoked once */ function once(func) { return before(2, func); } /** * Creates a function that invokes `func` with its arguments transformed. * * @static * @since 4.0.0 * @memberOf _ * @category Function * @param {Function} func The function to wrap. * @param {...(Function|Function[])} [transforms=[_.identity]] * The argument transforms. * @returns {Function} Returns the new function. * @example * * function doubled(n) { * return n * 2; * } * * function square(n) { * return n * n; * } * * var func = _.overArgs(function(x, y) { * return [x, y]; * }, [square, doubled]); * * func(9, 3); * // => [81, 6] * * func(10, 5); * // => [100, 10] */ var overArgs = castRest(function(func, transforms) { transforms = (transforms.length == 1 && isArray(transforms[0])) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); var funcsLength = transforms.length; return baseRest(function(args) { var index = -1, length = nativeMin(args.length, funcsLength); while (++index < length) { args[index] = transforms[index].call(this, args[index]); } return apply(func, this, args); }); }); /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partial)); return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); }); /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partialRight)); return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); }); /** * Creates a function that invokes `func` with arguments arranged according * to the specified `indexes` where the argument value at the first index is * provided as the first argument, the argument value at the second index is * provided as the second argument, and so on. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to rearrange arguments for. * @param {...(number|number[])} indexes The arranged argument indexes. * @returns {Function} Returns the new function. * @example * * var rearged = _.rearg(function(a, b, c) { * return [a, b, c]; * }, [2, 0, 1]); * * rearged('b', 'c', 'a') * // => ['a', 'b', 'c'] */ var rearg = flatRest(function(func, indexes) { return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); }); /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as * an array. * * **Note:** This method is based on the * [rest parameter](https://mdn.io/rest_parameters). * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.rest(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function rest(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start === undefined ? start : toInteger(start); return baseRest(func, start); } /** * Creates a function that invokes `func` with the `this` binding of the * create function and an array of arguments much like * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). * * **Note:** This method is based on the * [spread operator](https://mdn.io/spread_operator). * * @static * @memberOf _ * @since 3.2.0 * @category Function * @param {Function} func The function to spread arguments over. * @param {number} [start=0] The start position of the spread. * @returns {Function} Returns the new function. * @example * * var say = _.spread(function(who, what) { * return who + ' says ' + what; * }); * * say(['fred', 'hello']); * // => 'fred says hello' * * var numbers = Promise.all([ * Promise.resolve(40), * Promise.resolve(36) * ]); * * numbers.then(_.spread(function(x, y) { * return x + y; * })); * // => a Promise of 76 */ function spread(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start == null ? 0 : nativeMax(toInteger(start), 0); return baseRest(function(args) { var array = args[start], otherArgs = castSlice(args, 0, start); if (array) { arrayPush(otherArgs, array); } return apply(func, this, otherArgs); }); } /** * Creates a throttled function that only invokes `func` at most once per * every `wait` milliseconds. The throttled function comes with a `cancel` * method to cancel delayed `func` invocations and a `flush` method to * immediately invoke them. Provide `options` to indicate whether `func` * should be invoked on the leading and/or trailing edge of the `wait` * timeout. The `func` is invoked with the last arguments provided to the * throttled function. Subsequent calls to the throttled function return the * result of the last `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the throttled function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to throttle. * @param {number} [wait=0] The number of milliseconds to throttle invocations to. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=true] * Specify invoking on the leading edge of the timeout. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // Avoid excessively updating the position while scrolling. * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); * jQuery(element).on('click', throttled); * * // Cancel the trailing throttled invocation. * jQuery(window).on('popstate', throttled.cancel); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (isObject(options)) { leading = 'leading' in options ? !!options.leading : leading; trailing = 'trailing' in options ? !!options.trailing : trailing; } return debounce(func, wait, { 'leading': leading, 'maxWait': wait, 'trailing': trailing }); } /** * Creates a function that accepts up to one argument, ignoring any * additional arguments. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.unary(parseInt)); * // => [6, 8, 10] */ function unary(func) { return ary(func, 1); } /** * Creates a function that provides `value` to `wrapper` as its first * argument. Any additional arguments provided to the function are appended * to those provided to the `wrapper`. The wrapper is invoked with the `this` * binding of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {*} value The value to wrap. * @param {Function} [wrapper=identity] The wrapper function. * @returns {Function} Returns the new function. * @example * * var p = _.wrap(_.escape, function(func, text) { * return '

    ' + func(text) + '

    '; * }); * * p('fred, barney, & pebbles'); * // => '

    fred, barney, & pebbles

    ' */ function wrap(value, wrapper) { return partial(castFunction(wrapper), value); } /*------------------------------------------------------------------------*/ /** * Casts `value` as an array if it's not one. * * @static * @memberOf _ * @since 4.4.0 * @category Lang * @param {*} value The value to inspect. * @returns {Array} Returns the cast array. * @example * * _.castArray(1); * // => [1] * * _.castArray({ 'a': 1 }); * // => [{ 'a': 1 }] * * _.castArray('abc'); * // => ['abc'] * * _.castArray(null); * // => [null] * * _.castArray(undefined); * // => [undefined] * * _.castArray(); * // => [] * * var array = [1, 2, 3]; * console.log(_.castArray(array) === array); * // => true */ function castArray() { if (!arguments.length) { return []; } var value = arguments[0]; return isArray(value) ? value : [value]; } /** * Creates a shallow clone of `value`. * * **Note:** This method is loosely based on the * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) * and supports cloning arrays, array buffers, booleans, date objects, maps, * numbers, `Object` objects, regexes, sets, strings, symbols, and typed * arrays. The own enumerable properties of `arguments` objects are cloned * as plain objects. An empty object is returned for uncloneable values such * as error objects, functions, DOM nodes, and WeakMaps. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to clone. * @returns {*} Returns the cloned value. * @see _.cloneDeep * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var shallow = _.clone(objects); * console.log(shallow[0] === objects[0]); * // => true */ function clone(value) { return baseClone(value, CLONE_SYMBOLS_FLAG); } /** * This method is like `_.clone` except that it accepts `customizer` which * is invoked to produce the cloned value. If `customizer` returns `undefined`, * cloning is handled by the method instead. The `customizer` is invoked with * up to four arguments; (value [, index|key, object, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the cloned value. * @see _.cloneDeepWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(false); * } * } * * var el = _.cloneWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 0 */ function cloneWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); } /** * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ * @since 1.0.0 * @category Lang * @param {*} value The value to recursively clone. * @returns {*} Returns the deep cloned value. * @see _.clone * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var deep = _.cloneDeep(objects); * console.log(deep[0] === objects[0]); * // => false */ function cloneDeep(value) { return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); } /** * This method is like `_.cloneWith` except that it recursively clones `value`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to recursively clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the deep cloned value. * @see _.cloneWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(true); * } * } * * var el = _.cloneDeepWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 20 */ function cloneDeepWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); } /** * Checks if `object` conforms to `source` by invoking the predicate * properties of `source` with the corresponding property values of `object`. * * **Note:** This method is equivalent to `_.conforms` when `source` is * partially applied. * * @static * @memberOf _ * @since 4.14.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); * // => true * * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); * // => false */ function conformsTo(object, source) { return source == null || baseConformsTo(object, source, keys(source)); } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is greater than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. * @see _.lt * @example * * _.gt(3, 1); * // => true * * _.gt(3, 3); * // => false * * _.gt(1, 3); * // => false */ var gt = createRelationalOperation(baseGt); /** * Checks if `value` is greater than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than or equal to * `other`, else `false`. * @see _.lte * @example * * _.gte(3, 1); * // => true * * _.gte(3, 3); * // => true * * _.gte(1, 3); * // => false */ var gte = createRelationalOperation(function(value, other) { return value >= other; }); /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is classified as an `ArrayBuffer` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. * @example * * _.isArrayBuffer(new ArrayBuffer(2)); * // => true * * _.isArrayBuffer(new Array(2)); * // => false */ var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. * @example * * _.isBoolean(false); * // => true * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || (isObjectLike(value) && baseGetTag(value) == boolTag); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Checks if `value` is classified as a `Date` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. * @example * * _.isDate(new Date); * // => true * * _.isDate('Mon April 23 2012'); * // => false */ var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; /** * Checks if `value` is likely a DOM element. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true * * _.isElement(''); * // => false */ function isElement(value) { return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); } /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) { return !value.length; } var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size; } if (isPrototype(value)) { return !baseKeys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } /** * This method is like `_.isEqual` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with up to * six arguments: (objValue, othValue [, index|key, object, other, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, othValue) { * if (isGreeting(objValue) && isGreeting(othValue)) { * return true; * } * } * * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqualWith(array, other, customizer); * // => true */ function isEqualWith(value, other, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; var result = customizer ? customizer(value, other) : undefined; return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; } /** * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, * `SyntaxError`, `TypeError`, or `URIError` object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an error object, else `false`. * @example * * _.isError(new Error); * // => true * * _.isError(Error); * // => false */ function isError(value) { if (!isObjectLike(value)) { return false; } var tag = baseGetTag(value); return tag == errorTag || tag == domExcTag || (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); } /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite(value) { return typeof value == 'number' && nativeIsFinite(value); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** * Checks if `value` is an integer. * * **Note:** This method is based on * [`Number.isInteger`](https://mdn.io/Number/isInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an integer, else `false`. * @example * * _.isInteger(3); * // => true * * _.isInteger(Number.MIN_VALUE); * // => false * * _.isInteger(Infinity); * // => false * * _.isInteger('3'); * // => false */ function isInteger(value) { return typeof value == 'number' && value == toInteger(value); } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; /** * Performs a partial deep comparison between `object` and `source` to * determine if `object` contains equivalent property values. * * **Note:** This method is equivalent to `_.matches` when `source` is * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.isMatch(object, { 'b': 2 }); * // => true * * _.isMatch(object, { 'b': 1 }); * // => false */ function isMatch(object, source) { return object === source || baseIsMatch(object, source, getMatchData(source)); } /** * This method is like `_.isMatch` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with five * arguments: (objValue, srcValue, index|key, object, source). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, srcValue) { * if (isGreeting(objValue) && isGreeting(srcValue)) { * return true; * } * } * * var object = { 'greeting': 'hello' }; * var source = { 'greeting': 'hi' }; * * _.isMatchWith(object, source, customizer); * // => true */ function isMatchWith(object, source, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseIsMatch(object, source, getMatchData(source), customizer); } /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber(value) && value != +value; } /** * Checks if `value` is a pristine native function. * * **Note:** This method can't reliably detect native functions in the presence * of the core-js package because core-js circumvents this kind of detection. * Despite multiple requests, the core-js maintainer has made it clear: any * attempt to fix the detection will be obstructed. As a result, we're left * with little choice but to throw an error. Unfortunately, this also affects * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), * which rely on core-js. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (isMaskable(value)) { throw new Error(CORE_ERROR_TEXT); } return baseIsNative(value); } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(void 0); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is `null` or `undefined`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * * _.isNil(null); * // => true * * _.isNil(void 0); * // => true * * _.isNil(NaN); * // => false */ function isNil(value) { return value == null; } /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && baseGetTag(value) == numberTag); } /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } /** * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. * @example * * _.isRegExp(/abc/); * // => true * * _.isRegExp('/abc/'); * // => false */ var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; /** * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 * double precision number which isn't the result of a rounded unsafe integer. * * **Note:** This method is based on * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. * @example * * _.isSafeInteger(3); * // => true * * _.isSafeInteger(Number.MIN_VALUE); * // => false * * _.isSafeInteger(Infinity); * // => false * * _.isSafeInteger('3'); * // => false */ function isSafeInteger(value) { return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } /** * Checks if `value` is classified as a `WeakMap` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. * @example * * _.isWeakMap(new WeakMap); * // => true * * _.isWeakMap(new Map); * // => false */ function isWeakMap(value) { return isObjectLike(value) && getTag(value) == weakMapTag; } /** * Checks if `value` is classified as a `WeakSet` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. * @example * * _.isWeakSet(new WeakSet); * // => true * * _.isWeakSet(new Set); * // => false */ function isWeakSet(value) { return isObjectLike(value) && baseGetTag(value) == weakSetTag; } /** * Checks if `value` is less than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. * @see _.gt * @example * * _.lt(1, 3); * // => true * * _.lt(3, 3); * // => false * * _.lt(3, 1); * // => false */ var lt = createRelationalOperation(baseLt); /** * Checks if `value` is less than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than or equal to * `other`, else `false`. * @see _.gte * @example * * _.lte(1, 3); * // => true * * _.lte(3, 3); * // => true * * _.lte(3, 1); * // => false */ var lte = createRelationalOperation(function(value, other) { return value <= other; }); /** * Converts `value` to an array. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Array} Returns the converted array. * @example * * _.toArray({ 'a': 1, 'b': 2 }); * // => [1, 2] * * _.toArray('abc'); * // => ['a', 'b', 'c'] * * _.toArray(1); * // => [] * * _.toArray(null); * // => [] */ function toArray(value) { if (!value) { return []; } if (isArrayLike(value)) { return isString(value) ? stringToArray(value) : copyArray(value); } if (symIterator && value[symIterator]) { return iteratorToArray(value[symIterator]()); } var tag = getTag(value), func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); return func(value); } /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } /** * Converts `value` to an integer suitable for use as the length of an * array-like object. * * **Note:** This method is based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toLength(3.2); * // => 3 * * _.toLength(Number.MIN_VALUE); * // => 0 * * _.toLength(Infinity); * // => 4294967295 * * _.toLength('3.2'); * // => 3 */ function toLength(value) { return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; } /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = baseTrim(value); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } /** * Converts `value` to a safe integer. A safe integer can be compared and * represented correctly. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toSafeInteger(3.2); * // => 3 * * _.toSafeInteger(Number.MIN_VALUE); * // => 0 * * _.toSafeInteger(Infinity); * // => 9007199254740991 * * _.toSafeInteger('3.2'); * // => 3 */ function toSafeInteger(value) { return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) : (value === 0 ? value : 0); } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /*------------------------------------------------------------------------*/ /** * Assigns own enumerable string keyed properties of source objects to the * destination object. Source objects are applied from left to right. * Subsequent sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object` and is loosely based on * [`Object.assign`](https://mdn.io/Object/assign). * * @static * @memberOf _ * @since 0.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assignIn * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assign({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'c': 3 } */ var assign = createAssigner(function(object, source) { if (isPrototype(source) || isArrayLike(source)) { copyObject(source, keys(source), object); return; } for (var key in source) { if (hasOwnProperty.call(source, key)) { assignValue(object, key, source[key]); } } }); /** * This method is like `_.assign` except that it iterates over own and * inherited source properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assign * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assignIn({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } */ var assignIn = createAssigner(function(object, source) { copyObject(source, keysIn(source), object); }); /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); /** * This method is like `_.assign` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignInWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keys(source), object, customizer); }); /** * Creates an array of values corresponding to `paths` of `object`. * * @static * @memberOf _ * @since 1.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Array} Returns the picked values. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _.at(object, ['a[0].b.c', 'a[1]']); * // => [3, 4] */ var at = flatRest(baseAt); /** * Creates an object that inherits from the `prototype` object. If a * `properties` object is given, its own enumerable string keyed properties * are assigned to the created object. * * @static * @memberOf _ * @since 2.3.0 * @category Object * @param {Object} prototype The object to inherit from. * @param {Object} [properties] The properties to assign to the object. * @returns {Object} Returns the new object. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * function Circle() { * Shape.call(this); * } * * Circle.prototype = _.create(Shape.prototype, { * 'constructor': Circle * }); * * var circle = new Circle; * circle instanceof Circle; * // => true * * circle instanceof Shape; * // => true */ function create(prototype, properties) { var result = baseCreate(prototype); return properties == null ? result : baseAssign(result, properties); } /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = baseRest(function(object, sources) { object = Object(object); var index = -1; var length = sources.length; var guard = length > 2 ? sources[2] : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { length = 1; } while (++index < length) { var source = sources[index]; var props = keysIn(source); var propsIndex = -1; var propsLength = props.length; while (++propsIndex < propsLength) { var key = props[propsIndex]; var value = object[key]; if (value === undefined || (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { object[key] = source[key]; } } } return object; }); /** * This method is like `_.defaults` except that it recursively assigns * default properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaults * @example * * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); * // => { 'a': { 'b': 2, 'c': 3 } } */ var defaultsDeep = baseRest(function(args) { args.push(undefined, customDefaultsMerge); return apply(mergeWith, undefined, args); }); /** * This method is like `_.find` except that it returns the key of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findKey(users, function(o) { return o.age < 40; }); * // => 'barney' (iteration order is not guaranteed) * * // The `_.matches` iteratee shorthand. * _.findKey(users, { 'age': 1, 'active': true }); * // => 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.findKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findKey(users, 'active'); * // => 'barney' */ function findKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); } /** * This method is like `_.findKey` except that it iterates over elements of * a collection in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findLastKey(users, function(o) { return o.age < 40; }); * // => returns 'pebbles' assuming `_.findKey` returns 'barney' * * // The `_.matches` iteratee shorthand. * _.findLastKey(users, { 'age': 36, 'active': true }); * // => 'barney' * * // The `_.matchesProperty` iteratee shorthand. * _.findLastKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findLastKey(users, 'active'); * // => 'pebbles' */ function findLastKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); } /** * Iterates over own and inherited enumerable string keyed properties of an * object and invokes `iteratee` for each property. The iteratee is invoked * with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forInRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forIn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). */ function forIn(object, iteratee) { return object == null ? object : baseFor(object, getIteratee(iteratee, 3), keysIn); } /** * This method is like `_.forIn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forIn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forInRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. */ function forInRight(object, iteratee) { return object == null ? object : baseForRight(object, getIteratee(iteratee, 3), keysIn); } /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && baseForOwn(object, getIteratee(iteratee, 3)); } /** * This method is like `_.forOwn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwnRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. */ function forOwnRight(object, iteratee) { return object && baseForOwnRight(object, getIteratee(iteratee, 3)); } /** * Creates an array of function property names from own enumerable properties * of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functionsIn * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functions(new Foo); * // => ['a', 'b'] */ function functions(object) { return object == null ? [] : baseFunctions(object, keys(object)); } /** * Creates an array of function property names from own and inherited * enumerable properties of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functions * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functionsIn(new Foo); * // => ['a', 'b', 'c'] */ function functionsIn(object) { return object == null ? [] : baseFunctions(object, keysIn(object)); } /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && hasPath(object, path, baseHas); } /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } result[value] = key; }, constant(identity)); /** * This method is like `_.invert` except that the inverted object is generated * from the results of running each element of `object` thru `iteratee`. The * corresponding inverted value of each inverted key is an array of keys * responsible for generating the inverted value. The iteratee is invoked * with one argument: (value). * * @static * @memberOf _ * @since 4.1.0 * @category Object * @param {Object} object The object to invert. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invertBy(object); * // => { '1': ['a', 'c'], '2': ['b'] } * * _.invertBy(object, function(value) { * return 'group' + value; * }); * // => { 'group1': ['a', 'c'], 'group2': ['b'] } */ var invertBy = createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } }, getIteratee); /** * Invokes the method at `path` of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. * @example * * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; * * _.invoke(object, 'a[0].b.c.slice', 1, 3); * // => [2, 3] */ var invoke = baseRest(baseInvoke); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, iteratee(value, key, object), value); }); return result; } /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex); }); /** * This method is like `_.merge` except that it accepts `customizer` which * is invoked to produce the merged values of the destination and source * properties. If `customizer` returns `undefined`, merging is handled by the * method instead. The `customizer` is invoked with six arguments: * (objValue, srcValue, key, object, source, stack). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} customizer The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * function customizer(objValue, srcValue) { * if (_.isArray(objValue)) { * return objValue.concat(srcValue); * } * } * * var object = { 'a': [1], 'b': [2] }; * var other = { 'a': [3], 'b': [4] }; * * _.mergeWith(object, other, customizer); * // => { 'a': [1, 3], 'b': [2, 4] } */ var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { baseMerge(object, source, srcIndex, customizer); }); /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = arrayMap(paths, function(path) { path = castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); copyObject(object, getAllKeysIn(object), result); if (isDeep) { result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); } var length = paths.length; while (length--) { baseUnset(result, paths[length]); } return result; }); /** * The opposite of `_.pickBy`; this method creates an object composed of * the own and inherited enumerable string keyed properties of `object` that * `predicate` doesn't return truthy for. The predicate is invoked with two * arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omitBy(object, _.isNumber); * // => { 'b': '2' } */ function omitBy(object, predicate) { return pickBy(object, negate(getIteratee(predicate))); } /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = flatRest(function(object, paths) { return object == null ? {} : basePick(object, paths); }); /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = arrayMap(getAllKeysIn(object), function(prop) { return [prop]; }); predicate = getIteratee(predicate); return basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } /** * This method is like `_.get` except that if the resolved value is a * function it's invoked with the `this` binding of its parent object and * its result is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to resolve. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * * _.result(object, 'a[0].b.c1'); * // => 3 * * _.result(object, 'a[0].b.c2'); * // => 4 * * _.result(object, 'a[0].b.c3', 'default'); * // => 'default' * * _.result(object, 'a[0].b.c3', _.constant('default')); * // => 'default' */ function result(object, path, defaultValue) { path = castPath(path, object); var index = -1, length = path.length; // Ensure the loop is entered when path is empty. if (!length) { length = 1; object = undefined; } while (++index < length) { var value = object == null ? undefined : object[toKey(path[index])]; if (value === undefined) { index = length; value = defaultValue; } object = isFunction(value) ? value.call(object) : value; } return object; } /** * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, * it's created. Arrays are created for missing index properties while objects * are created for all other missing properties. Use `_.setWith` to customize * `path` creation. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.set(object, 'a[0].b.c', 4); * console.log(object.a[0].b.c); * // => 4 * * _.set(object, ['x', '0', 'y', 'z'], 5); * console.log(object.x[0].y.z); * // => 5 */ function set(object, path, value) { return object == null ? object : baseSet(object, path, value); } /** * This method is like `_.set` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.setWith(object, '[0][1]', 'a', Object); * // => { '0': { '1': 'a' } } */ function setWith(object, path, value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseSet(object, path, value, customizer); } /** * Creates an array of own enumerable string keyed-value pairs for `object` * which can be consumed by `_.fromPairs`. If `object` is a map or set, its * entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entries * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairs(new Foo); * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) */ var toPairs = createToPairs(keys); /** * Creates an array of own and inherited enumerable string keyed-value pairs * for `object` which can be consumed by `_.fromPairs`. If `object` is a map * or set, its entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entriesIn * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairsIn(new Foo); * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) */ var toPairsIn = createToPairs(keysIn); /** * An alternative to `_.reduce`; this method transforms `object` to a new * `accumulator` object which is the result of running each of its own * enumerable string keyed properties thru `iteratee`, with each invocation * potentially mutating the `accumulator` object. If `accumulator` is not * provided, a new object with the same `[[Prototype]]` will be used. The * iteratee is invoked with four arguments: (accumulator, value, key, object). * Iteratee functions may exit iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 1.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The custom accumulator value. * @returns {*} Returns the accumulated value. * @example * * _.transform([2, 3, 4], function(result, n) { * result.push(n *= n); * return n % 2 == 0; * }, []); * // => [4, 9] * * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } */ function transform(object, iteratee, accumulator) { var isArr = isArray(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); iteratee = getIteratee(iteratee, 4); if (accumulator == null) { var Ctor = object && object.constructor; if (isArrLike) { accumulator = isArr ? new Ctor : []; } else if (isObject(object)) { accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; } else { accumulator = {}; } } (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { return iteratee(accumulator, value, index, object); }); return accumulator; } /** * Removes the property at `path` of `object`. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. * @example * * var object = { 'a': [{ 'b': { 'c': 7 } }] }; * _.unset(object, 'a[0].b.c'); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; * * _.unset(object, ['a', '0', 'b', 'c']); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; */ function unset(object, path) { return object == null ? true : baseUnset(object, path); } /** * This method is like `_.set` except that accepts `updater` to produce the * value to set. Use `_.updateWith` to customize `path` creation. The `updater` * is invoked with one argument: (value). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.update(object, 'a[0].b.c', function(n) { return n * n; }); * console.log(object.a[0].b.c); * // => 9 * * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); * console.log(object.x[0].y.z); * // => 0 */ function update(object, path, updater) { return object == null ? object : baseUpdate(object, path, castFunction(updater)); } /** * This method is like `_.update` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.updateWith(object, '[0][1]', _.constant('a'), Object); * // => { '0': { '1': 'a' } } */ function updateWith(object, path, updater, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); } /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : baseValues(object, keys(object)); } /** * Creates an array of the own and inherited enumerable string keyed property * values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.valuesIn(new Foo); * // => [1, 2, 3] (iteration order is not guaranteed) */ function valuesIn(object) { return object == null ? [] : baseValues(object, keysIn(object)); } /*------------------------------------------------------------------------*/ /** * Clamps `number` within the inclusive `lower` and `upper` bounds. * * @static * @memberOf _ * @since 4.0.0 * @category Number * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. * @example * * _.clamp(-10, -5, 5); * // => -5 * * _.clamp(10, -5, 5); * // => 5 */ function clamp(number, lower, upper) { if (upper === undefined) { upper = lower; lower = undefined; } if (upper !== undefined) { upper = toNumber(upper); upper = upper === upper ? upper : 0; } if (lower !== undefined) { lower = toNumber(lower); lower = lower === lower ? lower : 0; } return baseClamp(toNumber(number), lower, upper); } /** * Checks if `n` is between `start` and up to, but not including, `end`. If * `end` is not specified, it's set to `start` with `start` then set to `0`. * If `start` is greater than `end` the params are swapped to support * negative ranges. * * @static * @memberOf _ * @since 3.3.0 * @category Number * @param {number} number The number to check. * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. * @see _.range, _.rangeRight * @example * * _.inRange(3, 2, 4); * // => true * * _.inRange(4, 8); * // => true * * _.inRange(4, 2); * // => false * * _.inRange(2, 2); * // => false * * _.inRange(1.2, 2); * // => true * * _.inRange(5.2, 4); * // => false * * _.inRange(-3, -2, -6); * // => true */ function inRange(number, start, end) { start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } number = toNumber(number); return baseInRange(number, start, end); } /** * Produces a random number between the inclusive `lower` and `upper` bounds. * If only one argument is provided a number between `0` and the given number * is returned. If `floating` is `true`, or either `lower` or `upper` are * floats, a floating-point number is returned instead of an integer. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @memberOf _ * @since 0.7.0 * @category Number * @param {number} [lower=0] The lower bound. * @param {number} [upper=1] The upper bound. * @param {boolean} [floating] Specify returning a floating-point number. * @returns {number} Returns the random number. * @example * * _.random(0, 5); * // => an integer between 0 and 5 * * _.random(5); * // => also an integer between 0 and 5 * * _.random(5, true); * // => a floating-point number between 0 and 5 * * _.random(1.2, 5.2); * // => a floating-point number between 1.2 and 5.2 */ function random(lower, upper, floating) { if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { upper = floating = undefined; } if (floating === undefined) { if (typeof upper == 'boolean') { floating = upper; upper = undefined; } else if (typeof lower == 'boolean') { floating = lower; lower = undefined; } } if (lower === undefined && upper === undefined) { lower = 0; upper = 1; } else { lower = toFinite(lower); if (upper === undefined) { upper = lower; lower = 0; } else { upper = toFinite(upper); } } if (lower > upper) { var temp = lower; lower = upper; upper = temp; } if (floating || lower % 1 || upper % 1) { var rand = nativeRandom(); return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); } return baseRandom(lower, upper); } /*------------------------------------------------------------------------*/ /** * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the camel cased string. * @example * * _.camelCase('Foo Bar'); * // => 'fooBar' * * _.camelCase('--foo-bar--'); * // => 'fooBar' * * _.camelCase('__FOO_BAR__'); * // => 'fooBar' */ var camelCase = createCompounder(function(result, word, index) { word = word.toLowerCase(); return result + (index ? capitalize(word) : word); }); /** * Converts the first character of `string` to upper case and the remaining * to lower case. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to capitalize. * @returns {string} Returns the capitalized string. * @example * * _.capitalize('FRED'); * // => 'Fred' */ function capitalize(string) { return upperFirst(toString(string).toLowerCase()); } /** * Deburrs `string` by converting * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) * letters to basic Latin letters and removing * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to deburr. * @returns {string} Returns the deburred string. * @example * * _.deburr('déjà vu'); * // => 'deja vu' */ function deburr(string) { string = toString(string); return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); } /** * Checks if `string` ends with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=string.length] The position to search up to. * @returns {boolean} Returns `true` if `string` ends with `target`, * else `false`. * @example * * _.endsWith('abc', 'c'); * // => true * * _.endsWith('abc', 'b'); * // => false * * _.endsWith('abc', 'b', 2); * // => true */ function endsWith(string, target, position) { string = toString(string); target = baseToString(target); var length = string.length; position = position === undefined ? length : baseClamp(toInteger(position), 0, length); var end = position; position -= target.length; return position >= 0 && string.slice(position, end) == target; } /** * Converts the characters "&", "<", ">", '"', and "'" in `string` to their * corresponding HTML entities. * * **Note:** No other characters are escaped. To escape additional * characters use a third-party library like [_he_](https://mths.be/he). * * Though the ">" character is escaped for symmetry, characters like * ">" and "/" don't need escaping in HTML and have no special meaning * unless they're part of a tag or unquoted attribute value. See * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) * (under "semi-related fun fact") for more details. * * When working with HTML you should always * [quote attribute values](http://wonko.com/post/html-escaping) to reduce * XSS vectors. * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('fred, barney, & pebbles'); * // => 'fred, barney, & pebbles' */ function escape(string) { string = toString(string); return (string && reHasUnescapedHtml.test(string)) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; } /** * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https://lodash\.com/\)' */ function escapeRegExp(string) { string = toString(string); return (string && reHasRegExpChar.test(string)) ? string.replace(reRegExpChar, '\\$&') : string; } /** * Converts `string` to * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the kebab cased string. * @example * * _.kebabCase('Foo Bar'); * // => 'foo-bar' * * _.kebabCase('fooBar'); * // => 'foo-bar' * * _.kebabCase('__FOO_BAR__'); * // => 'foo-bar' */ var kebabCase = createCompounder(function(result, word, index) { return result + (index ? '-' : '') + word.toLowerCase(); }); /** * Converts `string`, as space separated words, to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.lowerCase('--Foo-Bar--'); * // => 'foo bar' * * _.lowerCase('fooBar'); * // => 'foo bar' * * _.lowerCase('__FOO_BAR__'); * // => 'foo bar' */ var lowerCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toLowerCase(); }); /** * Converts the first character of `string` to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.lowerFirst('Fred'); * // => 'fred' * * _.lowerFirst('FRED'); * // => 'fRED' */ var lowerFirst = createCaseFirst('toLowerCase'); /** * Pads `string` on the left and right sides if it's shorter than `length`. * Padding characters are truncated if they can't be evenly divided by `length`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.pad('abc', 8); * // => ' abc ' * * _.pad('abc', 8, '_-'); * // => '_-abc_-_' * * _.pad('abc', 3); * // => 'abc' */ function pad(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; if (!length || strLength >= length) { return string; } var mid = (length - strLength) / 2; return ( createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars) ); } /** * Pads `string` on the right side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padEnd('abc', 6); * // => 'abc ' * * _.padEnd('abc', 6, '_-'); * // => 'abc_-_' * * _.padEnd('abc', 3); * // => 'abc' */ function padEnd(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (string + createPadding(length - strLength, chars)) : string; } /** * Pads `string` on the left side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padStart('abc', 6); * // => ' abc' * * _.padStart('abc', 6, '_-'); * // => '_-_abc' * * _.padStart('abc', 3); * // => 'abc' */ function padStart(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (createPadding(length - strLength, chars) + string) : string; } /** * Converts `string` to an integer of the specified radix. If `radix` is * `undefined` or `0`, a `radix` of `10` is used unless `value` is a * hexadecimal, in which case a `radix` of `16` is used. * * **Note:** This method aligns with the * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. * * @static * @memberOf _ * @since 1.1.0 * @category String * @param {string} string The string to convert. * @param {number} [radix=10] The radix to interpret `value` by. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {number} Returns the converted integer. * @example * * _.parseInt('08'); * // => 8 * * _.map(['6', '08', '10'], _.parseInt); * // => [6, 8, 10] */ function parseInt(string, radix, guard) { if (guard || radix == null) { radix = 0; } else if (radix) { radix = +radix; } return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); } /** * Repeats the given string `n` times. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to repeat. * @param {number} [n=1] The number of times to repeat the string. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the repeated string. * @example * * _.repeat('*', 3); * // => '***' * * _.repeat('abc', 2); * // => 'abcabc' * * _.repeat('abc', 0); * // => '' */ function repeat(string, n, guard) { if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } return baseRepeat(toString(string), n); } /** * Replaces matches for `pattern` in `string` with `replacement`. * * **Note:** This method is based on * [`String#replace`](https://mdn.io/String/replace). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to modify. * @param {RegExp|string} pattern The pattern to replace. * @param {Function|string} replacement The match replacement. * @returns {string} Returns the modified string. * @example * * _.replace('Hi Fred', 'Fred', 'Barney'); * // => 'Hi Barney' */ function replace() { var args = arguments, string = toString(args[0]); return args.length < 3 ? string : string.replace(args[1], args[2]); } /** * Converts `string` to * [snake case](https://en.wikipedia.org/wiki/Snake_case). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the snake cased string. * @example * * _.snakeCase('Foo Bar'); * // => 'foo_bar' * * _.snakeCase('fooBar'); * // => 'foo_bar' * * _.snakeCase('--FOO-BAR--'); * // => 'foo_bar' */ var snakeCase = createCompounder(function(result, word, index) { return result + (index ? '_' : '') + word.toLowerCase(); }); /** * Splits `string` by `separator`. * * **Note:** This method is based on * [`String#split`](https://mdn.io/String/split). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to split. * @param {RegExp|string} separator The separator pattern to split by. * @param {number} [limit] The length to truncate results to. * @returns {Array} Returns the string segments. * @example * * _.split('a-b-c', '-', 2); * // => ['a', 'b'] */ function split(string, separator, limit) { if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { separator = limit = undefined; } limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; if (!limit) { return []; } string = toString(string); if (string && ( typeof separator == 'string' || (separator != null && !isRegExp(separator)) )) { separator = baseToString(separator); if (!separator && hasUnicode(string)) { return castSlice(stringToArray(string), 0, limit); } } return string.split(separator, limit); } /** * Converts `string` to * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). * * @static * @memberOf _ * @since 3.1.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the start cased string. * @example * * _.startCase('--foo-bar--'); * // => 'Foo Bar' * * _.startCase('fooBar'); * // => 'Foo Bar' * * _.startCase('__FOO_BAR__'); * // => 'FOO BAR' */ var startCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + upperFirst(word); }); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; } /** * Creates a compiled template function that can interpolate data properties * in "interpolate" delimiters, HTML-escape interpolated data properties in * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data * properties may be accessed as free variables in the template. If a setting * object is given, it takes precedence over `_.templateSettings` values. * * **Note:** In the development build `_.template` utilizes * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) * for easier debugging. * * For more information on precompiling templates see * [lodash's custom builds documentation](https://lodash.com/custom-builds). * * For more information on Chrome extension sandboxes see * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The template string. * @param {Object} [options={}] The options object. * @param {RegExp} [options.escape=_.templateSettings.escape] * The HTML "escape" delimiter. * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] * The "evaluate" delimiter. * @param {Object} [options.imports=_.templateSettings.imports] * An object to import into the template as free variables. * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] * The "interpolate" delimiter. * @param {string} [options.sourceURL='lodash.templateSources[n]'] * The sourceURL of the compiled template. * @param {string} [options.variable='obj'] * The data object variable name. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the compiled template function. * @example * * // Use the "interpolate" delimiter to create a compiled template. * var compiled = _.template('hello <%= user %>!'); * compiled({ 'user': 'fred' }); * // => 'hello fred!' * * // Use the HTML "escape" delimiter to escape data property values. * var compiled = _.template('<%- value %>'); * compiled({ 'value': '