Socket
Socket
Sign inDemoInstall

@salesforce/core

Package Overview
Dependencies
Maintainers
26
Versions
499
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@salesforce/core - npm Package Compare versions

Comparing version 0.24.8 to 0.26.1

docs/enums/configaggregator.location.html

138

lib/authInfo.d.ts

@@ -1,50 +0,1 @@

/**
* Options for OAuth2.
* @typedef OAuth2Options
* @property {string} authzServiceUrl
* @property {string} tokenServiceUrl
* @property {string} clientId
* @property {string} clientSecret
* @property {string} httpProxy
* @property {string} loginUrl
* @property {string} proxyUrl
* @property {string} redirectUri
* @property {string} refreshToken
* @property {string} revokeServiceUrl
* @property {string} authCode
* @property {string} privateKeyFile
* @see https://jsforce.github.io/jsforce/doc/OAuth2.html
*/
/**
* Fields for authorization, organization, and local information.
* @typedef AuthFields
* @property {string} accessToken
* @property {string} alias
* @property {string} authCode
* @property {string} clientId
* @property {string} clientSecret
* @property {string} created
* @property {string} createdOrgInstance
* @property {string} devHubUsername
* @property {string} instanceUrl
* @property {string} isDevHub
* @property {string} loginUrl
* @property {string} orgId
* @property {string} password
* @property {string} privateKey
* @property {string} refreshToken
* @property {string} scratchAdminUsername
* @property {string} snapshot
* @property {string} userId
* @property {string} username
* @property {string} usernames
* @property {string} userProfileName
*/
/**
* Options for access token flow.
* @typedef AccessTokenOptions
* @property {string} accessToken
* @property {string} loginUrl
* @property {string} instanceUrl
*/
import { AsyncCreatable } from '@salesforce/kit';

@@ -54,2 +5,5 @@ import { Nullable, Optional } from '@salesforce/ts-types';

import { Connection } from './connection';
/**
* Fields for authorization, org, and local information.
*/
export interface AuthFields {

@@ -78,2 +32,5 @@ accessToken?: string;

}
/**
* Options for access token flow.
*/
export interface AccessTokenOptions {

@@ -84,7 +41,22 @@ accessToken?: string;

}
/**
* A function to update a refresh token when the access token is expired.
*/
export declare type RefreshFn = (conn: Connection, callback: (err: Nullable<Error>, accessToken?: string, res?: object) => Promise<void>) => Promise<void>;
/**
* Options for {@link Connection}.
*/
export declare type ConnectionOptions = AuthFields & {
/**
* OAuth options.
*/
oauth2?: Partial<OAuth2Options>;
/**
* Refresh token callback.
*/
refreshFn?: RefreshFn;
};
/**
* Salesforce URLs.
*/
export declare enum SfdcUrl {

@@ -100,3 +72,7 @@ SANDBOX = "https://test.salesforce.com",

*
* @example
* **See** [Authorization](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_auth.htm)
*
* **See** [Salesforce DX Usernames and Orgs](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_usernames_orgs.htm)
*
* ```
* // Creating a new authentication file.

@@ -116,5 +92,3 @@ * const authInfo = await AuthInfo.create(myAdminUsername, {

* const connection = await Connection.create(authInfo);
*
* @see https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_auth.htm
* @see https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_usernames_orgs.htm
* ```
*/

@@ -129,3 +103,2 @@ export declare class AuthInfo extends AsyncCreatable<AuthInfo.Options> {

* Returns true if one or more authentications are persisted.
* @returns {Promise<boolean>}
*/

@@ -135,10 +108,8 @@ static hasAuthentications(): Promise<boolean>;

* Get the authorization URL.
* @param {OAuth2Options} options The options to generate the URL.
* @returns {string}
* @param options The options to generate the URL.
*/
static getAuthorizationUrl(options: OAuth2Options): string;
/**
* Forces the auth file to be re-read from disk for a given user.
* @param {string} username The username for the auth info to re-read.
* @returns {boolean} True if a value was removed.
* Forces the auth file to be re-read from disk for a given user. Returns `true` if a value was removed.
* @param username The username for the auth info to re-read.
*/

@@ -154,3 +125,5 @@ static clearCache(username: string): boolean;

/**
* @ignore
* Constructor
* **Do not directly construct instances of this class -- use {@link AuthInfo.create} instead.**
* @param options The options for the class instance
*/

@@ -160,3 +133,2 @@ constructor(options: AuthInfo.Options);

* Get the username.
* @returns {string}
*/

@@ -166,3 +138,2 @@ getUsername(): Optional<string>;

* Returns true if `this` is using the JWT flow.
* @returns {boolean}
*/

@@ -172,3 +143,2 @@ isJwt(): boolean;

* Returns true if `this` is using an access token flow.
* @returns {boolean}
*/

@@ -178,3 +148,2 @@ isAccessTokenFlow(): boolean;

* Returns true if `this` is using the oauth flow.
* @returns {boolean}
*/

@@ -184,3 +153,2 @@ isOauth(): boolean;

* Returns true if `this` is using the refresh token flow.
* @returns {boolean}
*/

@@ -190,4 +158,3 @@ isRefreshTokenFlow(): boolean;

* Updates the cache and persists the authentication fields (encrypted).
* @param {AuthFields} [authData] New data to save.
* @returns {Promise<AuthInfo>}
* @param authData New data to save.
*/

@@ -197,6 +164,6 @@ save(authData?: AuthFields): Promise<AuthInfo>;

* Update the authorization fields, encrypting sensitive fields, but do not persist.
* For convenience `this` object is returned.
*
* @param {AuthFields} authData Authorization fields to update.
* @param {boolean} encrypt Encrypt the fields.
* @returns {AuthInfo} For convenience `this` object is returned.
* @param authData Authorization fields to update.
* @param encrypt Encrypt the fields.
*/

@@ -206,4 +173,2 @@ update(authData?: AuthFields, encrypt?: boolean): AuthInfo;

* Get the auth fields (decrypted) needed to make a connection.
*
* @returns {AuthFields}
*/

@@ -213,3 +178,2 @@ getConnectionOptions(): ConnectionOptions;

* Get the authorization fields.
* @returns {AuthFields}
*/

@@ -219,3 +183,2 @@ getFields(): AuthFields;

* Returns true if this org is using access token auth.
* @returns {boolean}
*/

@@ -225,4 +188,4 @@ isUsingAccessToken(): boolean;

* Get the SFDX Auth URL.
* @see https://developer.salesforce.com/docs/atlas.en-us.sfdx_cli_reference.meta/sfdx_cli_reference/cli_reference_force_auth.htm#cli_reference_force_auth
* @returns {string}
*
* **See** [SFDX Authorization](https://developer.salesforce.com/docs/atlas.en-us.sfdx_cli_reference.meta/sfdx_cli_reference/cli_reference_force_auth.htm#cli_reference_force_auth)
*/

@@ -235,8 +198,8 @@ getSfdxAuthUrl(): string;

/**
* Initialize this AuthInfo instance with the specified options. If options are not provided
* initialize from cache or by reading from persistence store.
* @param {OAuth2Options} [options] Options to be used for creating an OAuth2 instance.
* @throws {SfdxError}
* **`{name: 'NamedOrgNotFound'}`:** Org information does not exist.
* @returns {Promise<AuthInfo>} For convenience `this` object is returned.
* Initialize this AuthInfo instance with the specified options. If options are not provided, initialize it from cache
* or by reading from the persistence store. For convenience `this` object is returned.
* @param options Options to be used for creating an OAuth2 instance.
*
* **Throws** *{@link SfdxError}{ name: 'NamedOrgNotFound' }* Org information does not exist.
* @returns {Promise<AuthInfo>}
*/

@@ -253,9 +216,18 @@ private initAuthOptions;

/**
* Constrcutor options for AuthInfo
* Constructor options for AuthInfo.
*/
interface Options {
/**
* Org signup username.
*/
username?: string;
/**
* OAuth options.
*/
oauth2Options?: OAuth2Options;
/**
* Options for the access token auth.
*/
accessTokenOptions?: AccessTokenOptions;
}
}

@@ -8,52 +8,3 @@ "use strict";

*/
/**
* Options for OAuth2.
* @typedef OAuth2Options
* @property {string} authzServiceUrl
* @property {string} tokenServiceUrl
* @property {string} clientId
* @property {string} clientSecret
* @property {string} httpProxy
* @property {string} loginUrl
* @property {string} proxyUrl
* @property {string} redirectUri
* @property {string} refreshToken
* @property {string} revokeServiceUrl
* @property {string} authCode
* @property {string} privateKeyFile
* @see https://jsforce.github.io/jsforce/doc/OAuth2.html
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Fields for authorization, organization, and local information.
* @typedef AuthFields
* @property {string} accessToken
* @property {string} alias
* @property {string} authCode
* @property {string} clientId
* @property {string} clientSecret
* @property {string} created
* @property {string} createdOrgInstance
* @property {string} devHubUsername
* @property {string} instanceUrl
* @property {string} isDevHub
* @property {string} loginUrl
* @property {string} orgId
* @property {string} password
* @property {string} privateKey
* @property {string} refreshToken
* @property {string} scratchAdminUsername
* @property {string} snapshot
* @property {string} userId
* @property {string} username
* @property {string} usernames
* @property {string} userProfileName
*/
/**
* Options for access token flow.
* @typedef AccessTokenOptions
* @property {string} accessToken
* @property {string} loginUrl
* @property {string} instanceUrl
*/
const kit_1 = require("@salesforce/kit");

@@ -75,3 +26,3 @@ const ts_types_1 = require("@salesforce/ts-types");

const sfdxError_1 = require("./sfdxError");
const fs = require("./util/fs");
const fs_1 = require("./util/fs");
// Extend OAuth2 to add JWT Bearer Token Flow support.

@@ -130,2 +81,5 @@ class JwtOAuth2 extends jsforce_1.OAuth2 {

}
/**
* Salesforce URLs.
*/
var SfdcUrl;

@@ -229,3 +183,7 @@ (function (SfdcUrl) {

*
* @example
* **See** [Authorization](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_auth.htm)
*
* **See** [Salesforce DX Usernames and Orgs](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_usernames_orgs.htm)
*
* ```
* // Creating a new authentication file.

@@ -245,9 +203,9 @@ * const authInfo = await AuthInfo.create(myAdminUsername, {

* const connection = await Connection.create(authInfo);
*
* @see https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_auth.htm
* @see https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_usernames_orgs.htm
* ```
*/
class AuthInfo extends kit_1.AsyncCreatable {
/**
* @ignore
* Constructor
* **Do not directly construct instances of this class -- use {@link AuthInfo.create} instead.**
* @param options The options for the class instance
*/

@@ -267,3 +225,3 @@ constructor(options) {

static async listAllAuthFiles() {
const globalFiles = await fs.readdir(global_1.Global.DIR);
const globalFiles = await fs_1.fs.readdir(global_1.Global.DIR);
const authFiles = globalFiles.filter(file => file.match(AuthInfo.authFilenameFilterRegEx));

@@ -280,3 +238,2 @@ // Want to throw a clean error if no files are found.

* Returns true if one or more authentications are persisted.
* @returns {Promise<boolean>}
*/

@@ -297,4 +254,3 @@ static async hasAuthentications() {

* Get the authorization URL.
* @param {OAuth2Options} options The options to generate the URL.
* @returns {string}
* @param options The options to generate the URL.
*/

@@ -313,5 +269,4 @@ static getAuthorizationUrl(options) {

/**
* Forces the auth file to be re-read from disk for a given user.
* @param {string} username The username for the auth info to re-read.
* @returns {boolean} True if a value was removed.
* Forces the auth file to be re-read from disk for a given user. Returns `true` if a value was removed.
* @param username The username for the auth info to re-read.
*/

@@ -326,3 +281,2 @@ static clearCache(username) {

* Get the username.
* @returns {string}
*/

@@ -334,3 +288,2 @@ getUsername() {

* Returns true if `this` is using the JWT flow.
* @returns {boolean}
*/

@@ -343,3 +296,2 @@ isJwt() {

* Returns true if `this` is using an access token flow.
* @returns {boolean}
*/

@@ -352,3 +304,2 @@ isAccessTokenFlow() {

* Returns true if `this` is using the oauth flow.
* @returns {boolean}
*/

@@ -360,3 +311,2 @@ isOauth() {

* Returns true if `this` is using the refresh token flow.
* @returns {boolean}
*/

@@ -369,4 +319,3 @@ isRefreshTokenFlow() {

* Updates the cache and persists the authentication fields (encrypted).
* @param {AuthFields} [authData] New data to save.
* @returns {Promise<AuthInfo>}
* @param authData New data to save.
*/

@@ -392,6 +341,6 @@ async save(authData) {

* Update the authorization fields, encrypting sensitive fields, but do not persist.
* For convenience `this` object is returned.
*
* @param {AuthFields} authData Authorization fields to update.
* @param {boolean} encrypt Encrypt the fields.
* @returns {AuthInfo} For convenience `this` object is returned.
* @param authData Authorization fields to update.
* @param encrypt Encrypt the fields.
*/

@@ -411,4 +360,2 @@ update(authData, encrypt = true) {

* Get the auth fields (decrypted) needed to make a connection.
*
* @returns {AuthFields}
*/

@@ -454,3 +401,2 @@ getConnectionOptions() {

* Get the authorization fields.
* @returns {AuthFields}
*/

@@ -462,3 +408,2 @@ getFields() {

* Returns true if this org is using access token auth.
* @returns {boolean}
*/

@@ -470,4 +415,4 @@ isUsingAccessToken() {

* Get the SFDX Auth URL.
* @see https://developer.salesforce.com/docs/atlas.en-us.sfdx_cli_reference.meta/sfdx_cli_reference/cli_reference_force_auth.htm#cli_reference_force_auth
* @returns {string}
*
* **See** [SFDX Authorization](https://developer.salesforce.com/docs/atlas.en-us.sfdx_cli_reference.meta/sfdx_cli_reference/cli_reference_force_auth.htm#cli_reference_force_auth)
*/

@@ -516,8 +461,8 @@ getSfdxAuthUrl() {

/**
* Initialize this AuthInfo instance with the specified options. If options are not provided
* initialize from cache or by reading from persistence store.
* @param {OAuth2Options} [options] Options to be used for creating an OAuth2 instance.
* @throws {SfdxError}
* **`{name: 'NamedOrgNotFound'}`:** Org information does not exist.
* @returns {Promise<AuthInfo>} For convenience `this` object is returned.
* Initialize this AuthInfo instance with the specified options. If options are not provided, initialize it from cache
* or by reading from the persistence store. For convenience `this` object is returned.
* @param options Options to be used for creating an OAuth2 instance.
*
* **Throws** *{@link SfdxError}{ name: 'NamedOrgNotFound' }* Org information does not exist.
* @returns {Promise<AuthInfo>}
*/

@@ -564,3 +509,2 @@ async initAuthOptions(options) {

const config = await authInfoConfig_1.AuthInfoConfig.create(authInfoConfig_1.AuthInfoConfig.getOptions(username));
await config.read(true);
authConfig = config.toObject();

@@ -618,3 +562,3 @@ }

async buildJwtConfig(options) {
const privateKeyContents = await fs.readFile(ts_types_1.ensure(options.privateKey), 'utf8');
const privateKeyContents = await fs_1.fs.readFile(ts_types_1.ensure(options.privateKey), 'utf8');
const audienceUrl = getJwtAudienceUrl(options);

@@ -621,0 +565,0 @@ const jwtToken = await jwt.sign({

@@ -1,7 +0,5 @@

import { ConfigFile } from './configFile';
import { JsonMap, Optional } from '@salesforce/ts-types';
import { ConfigGroup } from './configGroup';
/**
* Different groups of aliases. Currently only support orgs.
* @typedef AliasGroup
* @property {string} ORGS
*/

@@ -18,6 +16,4 @@ export declare enum AliasGroup {

*
* @extends ConfigGroup
*
* @example
* const aliases = await Aliases.retrieve<Aliases>();
* ```
* const aliases = await Aliases.create();
* aliases.set('myAlias', 'username@company.org');

@@ -27,3 +23,4 @@ * await aliases.write();

* const username: string = await Aliases.fetch('myAlias');
* @see https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_usernames_orgs.htm
* ```
* https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_usernames_orgs.htm
*/

@@ -33,4 +30,2 @@ export declare class Aliases extends ConfigGroup<ConfigGroup.Options> {

* The aliases state file filename.
* @override
* @returns {string}
*/

@@ -40,24 +35,28 @@ static getFileName(): string;

* Get Aliases specific options.
* @returns {ConfigGroupOptions}
*/
static getDefaultOptions(): ConfigGroup.Options;
static retrieve<T extends ConfigFile<ConfigFile.Options>>(options?: ConfigFile.Options): Promise<T>;
/**
* Updates a group of aliases in a bulk save.
* @param {array} aliasKeyAndValues An array of strings in the format `<alias>=<value>`.
* Updates a group of aliases in a bulk save and returns the new aliases that were saved.
*
* ```
* const aliases = await Aliases.parseAndUpdate(['foo=bar', 'bar=baz'])
* ```
* @param aliasKeyAndValues An array of strings in the format `<alias>=<value>`.
* Each element will be saved in the Aliases state file under the group.
* @param {AliasGroup} [group = AliasGroup.ORGS] The group the alias belongs to. Defaults to ORGS.
* @returns {Promise<object>} The new aliases that were saved.
* @example
* const aliases = await Aliases.parseAndUpdate(['foo=bar', 'bar=baz'])
* @param group The group the alias belongs to. Defaults to ORGS.
*/
static parseAndUpdate(aliasKeyAndValues: string[], group?: AliasGroup): Promise<object>;
static parseAndUpdate(aliasKeyAndValues: string[], group?: AliasGroup): Promise<JsonMap>;
/**
* Get an alias from a key and group. Shorthand for `Alias.retrieve().get(key)`.
* @param {string} key The value of the alias to match
* @param {string} [group=AliasGroup.Orgs] The group the alias belongs to. Defaults to Orgs
* @returns {Promise<string>} The promise resolved when the alias is retrieved
* Get an alias from a key and group. Shorthand for `Alias.create().get(key)`. Returns the promise resolved when the
* alias is created.
* @param key The value of the alias to match.
* @param group The group the alias belongs to. Defaults to Orgs.
*/
static fetch(key: string, group?: AliasGroup): Promise<string>;
static fetch(key: string, group?: AliasGroup): Promise<Optional<string>>;
/**
* Constructor
* **Do not directly construct instances of this class -- use {@link Aliases.create} instead.**
* @param options The options for the class instance
*/
constructor(options: ConfigGroup.Options);
}
"use strict";
/*
* Copyright (c) 2018, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
Object.defineProperty(exports, "__esModule", { value: true });
const ts_types_1 = require("@salesforce/ts-types");
const sfdxError_1 = require("../sfdxError");

@@ -8,4 +15,2 @@ const configGroup_1 = require("./configGroup");

* Different groups of aliases. Currently only support orgs.
* @typedef AliasGroup
* @property {string} ORGS
*/

@@ -23,6 +28,4 @@ var AliasGroup;

*
* @extends ConfigGroup
*
* @example
* const aliases = await Aliases.retrieve<Aliases>();
* ```
* const aliases = await Aliases.create();
* aliases.set('myAlias', 'username@company.org');

@@ -32,3 +35,4 @@ * await aliases.write();

* const username: string = await Aliases.fetch('myAlias');
* @see https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_usernames_orgs.htm
* ```
* https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_usernames_orgs.htm
*/

@@ -38,4 +42,2 @@ class Aliases extends configGroup_1.ConfigGroup {

* The aliases state file filename.
* @override
* @returns {string}
*/

@@ -47,3 +49,2 @@ static getFileName() {

* Get Aliases specific options.
* @returns {ConfigGroupOptions}
*/

@@ -53,15 +54,11 @@ static getDefaultOptions() {

}
static async retrieve(options) {
const aliases = await Aliases.create(options || Aliases.getDefaultOptions());
await aliases.read();
return aliases;
}
/**
* Updates a group of aliases in a bulk save.
* @param {array} aliasKeyAndValues An array of strings in the format `<alias>=<value>`.
* Updates a group of aliases in a bulk save and returns the new aliases that were saved.
*
* ```
* const aliases = await Aliases.parseAndUpdate(['foo=bar', 'bar=baz'])
* ```
* @param aliasKeyAndValues An array of strings in the format `<alias>=<value>`.
* Each element will be saved in the Aliases state file under the group.
* @param {AliasGroup} [group = AliasGroup.ORGS] The group the alias belongs to. Defaults to ORGS.
* @returns {Promise<object>} The new aliases that were saved.
* @example
* const aliases = await Aliases.parseAndUpdate(['foo=bar', 'bar=baz'])
* @param group The group the alias belongs to. Defaults to ORGS.
*/

@@ -81,15 +78,20 @@ static async parseAndUpdate(aliasKeyAndValues, group = AliasGroup.ORGS) {

}
const aliases = await Aliases.retrieve();
const aliases = await Aliases.create(Aliases.getDefaultOptions());
return await aliases.updateValues(newAliases, group);
}
/**
* Get an alias from a key and group. Shorthand for `Alias.retrieve().get(key)`.
* @param {string} key The value of the alias to match
* @param {string} [group=AliasGroup.Orgs] The group the alias belongs to. Defaults to Orgs
* @returns {Promise<string>} The promise resolved when the alias is retrieved
* Get an alias from a key and group. Shorthand for `Alias.create().get(key)`. Returns the promise resolved when the
* alias is created.
* @param key The value of the alias to match.
* @param group The group the alias belongs to. Defaults to Orgs.
*/
static async fetch(key, group = AliasGroup.ORGS) {
const aliases = (await Aliases.retrieve(Aliases.getDefaultOptions()));
return aliases.getInGroup(key, group);
const aliases = await Aliases.create(Aliases.getDefaultOptions());
return ts_types_1.asString(aliases.getInGroup(key, group));
}
/**
* Constructor
* **Do not directly construct instances of this class -- use {@link Aliases.create} instead.**
* @param options The options for the class instance
*/
constructor(options) {

@@ -96,0 +98,0 @@ super(options);

@@ -6,6 +6,5 @@ import { ConfigFile } from './configFile';

*
* @extends ConfigFile
*
* @example
* const authInfo = await AuthInfoConfig.retrieve<AuthInfoConfig>(AuthInfoConfig.getOptions(username));
* ```
* const authInfo = await AuthInfoConfig.create(AuthInfoConfig.getOptions(username));
* ```
*/

@@ -12,0 +11,0 @@ export declare class AuthInfoConfig extends ConfigFile<ConfigFile.Options> {

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -9,2 +8,3 @@ * Copyright (c) 2018, salesforce.com, inc.

*/
Object.defineProperty(exports, "__esModule", { value: true });
const configFile_1 = require("./configFile");

@@ -15,6 +15,5 @@ /**

*
* @extends ConfigFile
*
* @example
* const authInfo = await AuthInfoConfig.retrieve<AuthInfoConfig>(AuthInfoConfig.getOptions(username));
* ```
* const authInfo = await AuthInfoConfig.create(AuthInfoConfig.getOptions(username));
* ```
*/

@@ -21,0 +20,0 @@ class AuthInfoConfig extends configFile_1.ConfigFile {

@@ -1,22 +0,1 @@

/**
* Contains meta information about sfdx config properties.
* @typedef {object} ConfigPropertyMeta
* @property {string} key The config property name.
* @property {input} value Reference to the config data input validation.
* @property {boolean} hidden True if the property should be indirectly hidden from the user.
* @property {boolean} encrypted True if the property values should be stored encrypted.
*/
/**
* Contains meta information about sfdx config properties.
* @typedef {object} ConfigPropertyMetaInput
* @property {function} validator Test if the input value is valid.
* @property {string} failedMessage The message to return in the error if the validation fails.
*/
/**
* Supported Org Default Types.
* @typedef {object} ORG_DEFAULT
* @property {string} DEVHUB Default developer hub username.
* @property {string} USERNAME Default username.
* @property {function} list `() => string[]` List the Org defaults.
*/
import { ConfigFile } from './configFile';

@@ -50,5 +29,4 @@ import { ConfigContents, ConfigValue } from './configStore';

/**
* Test if the input value is valid.
* Tests if the input value is valid and returns true if the input data is valid.
* @param value The input value.
* @returns {boolean} Returns true if the input data is valid.
*/

@@ -67,10 +45,8 @@ validator: (value: ConfigValue) => boolean;

*
* @extends ConfigFile
*
* @example
* const localConfig = await Config.retrieve<Config>();
* ```
* const localConfig = await Config.create();
* localConfig.set('defaultusername', 'username@company.org');
* await localConfig.write();
*
* @see https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_config_values.htm
* ```
* https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_config_values.htm
*/

@@ -80,3 +56,2 @@ export declare class Config extends ConfigFile<ConfigFile.Options> {

* Username associated with the default dev hub org.
* @type {string}
*/

@@ -86,3 +61,2 @@ static readonly DEFAULT_DEV_HUB_USERNAME: string;

* Username associate with the default org.
* @type {string}
*/

@@ -92,3 +66,2 @@ static readonly DEFAULT_USERNAME: string;

* The sid for the debugger configuration.
* @type {string}
*/

@@ -98,32 +71,33 @@ static readonly ISV_DEBUGGER_SID: string;

* The url for the debugger configuration.
* @type {string}
*/
static readonly ISV_DEBUGGER_URL: string;
/**
* true if polling should be used over streaming when creating scratch orgs.
* @type {string}
* The api version
*/
static readonly USE_BACKUP_POLLING_ORG_CREATE = "useBackupPolling.org:create";
static readonly API_VERSION = "apiVersion";
/**
* The api version
* @type {string}
* Returns the default file name for a config file.
*
* **See** {@link SFDX_CONFIG_FILE_NAME}
*/
static readonly API_VERSION = "apiVersion";
static getFileName(): string;
/**
* @returns {ConfigPropertyMeta[]} Returns an object representing the supported allowed properties.
* Returns an object representing the supported allowed properties.
*/
static getAllowedProperties(): ConfigPropertyMeta[];
/**
* Gets default options.
* @param isGlobal Make the config global.
* @param filename Override the default file. {@link Config.getFileName}
*/
static getDefaultOptions(isGlobal?: boolean, filename?: string): ConfigFile.Options;
/**
* The value of a supported config property.
* @param {boolean} isGlobal True for a global config. False for a local config.
* @param {string} propertyName The name of the property to set.
* @param {ConfigValue} [value] The property value.
* @returns {Promise<object>}
* @param isGlobal True for a global config. False for a local config.
* @param propertyName The name of the property to set.
* @param value The property value.
*/
static update(isGlobal: boolean, propertyName: string, value?: ConfigValue): Promise<object>;
static update(isGlobal: boolean, propertyName: string, value?: ConfigValue): Promise<ConfigContents>;
/**
* Clear all the configured properties both local and global.
* @returns {Promise<void>}
*/

@@ -137,3 +111,3 @@ static clear(): Promise<void>;

/**
* @returns {Promise<object>} Read, assign, and return the config contents.
* Read, assign, and return the config contents.
*/

@@ -143,4 +117,3 @@ read(): Promise<ConfigContents>;

* Writes Config properties taking into account encrypted properties.
* @param {ConfigContents} newContents The new Config value to persist.
* @return {Promise<ConfigContents>}
* @param newContents The new Config value to persist.
*/

@@ -150,12 +123,14 @@ write(newContents?: ConfigContents): Promise<ConfigContents>;

* Sets a value for a property.
* @param {string} propertyName The property to set.
* @param {ConfigValue} value The value of the property.
* @returns {Promise<void>}
* @throws {SfdxError} **`{name: 'InvalidConfigValue'}`** Invalid configuration value.
*
* **Throws** *{@link SfdxError}{ name: 'InvalidConfigValue' }* If the input validator fails.
* @param key The property to set.
* @param value The value of the property.
*/
set(key: string, value: ConfigValue): ConfigContents;
/**
* Initializer for supported config types.
*/
protected init(): Promise<void>;
/**
* Initialize the crypto dependency.
* @return {Promise<void>}
*/

@@ -165,3 +140,2 @@ private initCrypto;

* Closes the crypto dependency. Crypto should be close after it's used and no longer needed.
* @return {Promise<void>}
*/

@@ -171,4 +145,3 @@ private clearCrypto;

* Get an individual property config.
* @param {string} propertyName The name of the property.
* @return {ConfigPropertyMeta} The meta config.
* @param propertyName The name of the property.
*/

@@ -178,11 +151,5 @@ private getPropertyConfig;

* Encrypts and content properties that have a encryption attribute.
* @param {boolean} encrypt `true` to encrypt.
* @return {Promise<void>}
* @param encrypt `true` to encrypt.
*/
private cryptProperties;
}
export declare const ORG_DEFAULT: {
DEVHUB: string;
USERNAME: string;
list(): string[];
};

@@ -8,23 +8,2 @@ "use strict";

*/
/**
* Contains meta information about sfdx config properties.
* @typedef {object} ConfigPropertyMeta
* @property {string} key The config property name.
* @property {input} value Reference to the config data input validation.
* @property {boolean} hidden True if the property should be indirectly hidden from the user.
* @property {boolean} encrypted True if the property values should be stored encrypted.
*/
/**
* Contains meta information about sfdx config properties.
* @typedef {object} ConfigPropertyMetaInput
* @property {function} validator Test if the input value is valid.
* @property {string} failedMessage The message to return in the error if the validation fails.
*/
/**
* Supported Org Default Types.
* @typedef {object} ORG_DEFAULT
* @property {string} DEVHUB Default developer hub username.
* @property {string} USERNAME Default username.
* @property {function} list `() => string[]` List the Org defaults.
*/
Object.defineProperty(exports, "__esModule", { value: true });

@@ -45,10 +24,8 @@ const kit_1 = require("@salesforce/kit");

*
* @extends ConfigFile
*
* @example
* const localConfig = await Config.retrieve<Config>();
* ```
* const localConfig = await Config.create();
* localConfig.set('defaultusername', 'username@company.org');
* await localConfig.write();
*
* @see https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_config_values.htm
* ```
* https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_config_values.htm
*/

@@ -59,2 +36,7 @@ class Config extends configFile_1.ConfigFile {

}
/**
* Returns the default file name for a config file.
*
* **See** {@link SFDX_CONFIG_FILE_NAME}
*/
static getFileName() {

@@ -64,3 +46,3 @@ return SFDX_CONFIG_FILE_NAME;

/**
* @returns {ConfigPropertyMeta[]} Returns an object representing the supported allowed properties.
* Returns an object representing the supported allowed properties.
*/

@@ -73,2 +55,7 @@ static getAllowedProperties() {

}
/**
* Gets default options.
* @param isGlobal Make the config global.
* @param filename Override the default file. {@link Config.getFileName}
*/
static getDefaultOptions(isGlobal = false, filename) {

@@ -83,6 +70,5 @@ return {

* The value of a supported config property.
* @param {boolean} isGlobal True for a global config. False for a local config.
* @param {string} propertyName The name of the property to set.
* @param {ConfigValue} [value] The property value.
* @returns {Promise<object>}
* @param isGlobal True for a global config. False for a local config.
* @param propertyName The name of the property to set.
* @param value The property value.
*/

@@ -102,3 +88,2 @@ static async update(isGlobal, propertyName, value) {

* Clear all the configured properties both local and global.
* @returns {Promise<void>}
*/

@@ -114,3 +99,3 @@ static async clear() {

/**
* @returns {Promise<object>} Read, assign, and return the config contents.
* Read, assign, and return the config contents.
*/

@@ -129,4 +114,3 @@ async read() {

* Writes Config properties taking into account encrypted properties.
* @param {ConfigContents} newContents The new Config value to persist.
* @return {Promise<ConfigContents>}
* @param newContents The new Config value to persist.
*/

@@ -144,6 +128,6 @@ async write(newContents) {

* Sets a value for a property.
* @param {string} propertyName The property to set.
* @param {ConfigValue} value The value of the property.
* @returns {Promise<void>}
* @throws {SfdxError} **`{name: 'InvalidConfigValue'}`** Invalid configuration value.
*
* **Throws** *{@link SfdxError}{ name: 'InvalidConfigValue' }* If the input validator fails.
* @param key The property to set.
* @param value The value of the property.
*/

@@ -168,2 +152,5 @@ set(key, value) {

}
/**
* Initializer for supported config types.
*/
async init() {

@@ -180,3 +167,3 @@ await super.init();

// If a value is provided validate it otherwise no value is unset.
validator: value => value == null || (ts_types_1.isString(value) && sfdc_1.isSalesforceDomain(value)),
validator: value => value == null || (ts_types_1.isString(value) && sfdc_1.sfdc.isSalesforceDomain(value)),
failedMessage: Config.messages.getMessage('InvalidInstanceUrl')

@@ -190,3 +177,3 @@ }

// If a value is provided validate it otherwise no value is unset.
validator: value => ts_types_1.isString(value) && sfdc_1.validateApiVersion(value),
validator: value => ts_types_1.isString(value) && sfdc_1.sfdc.validateApiVersion(value),
failedMessage: Config.messages.getMessage('InvalidApiVersion')

@@ -207,9 +194,2 @@ }

}
},
{
key: Config.USE_BACKUP_POLLING_ORG_CREATE,
input: {
validator: value => value == null || value === 'true' || value === 'false',
failedMessage: `${Config.USE_BACKUP_POLLING_ORG_CREATE} must be a boolean value. true/false.`
}
}

@@ -222,3 +202,2 @@ ];

* Initialize the crypto dependency.
* @return {Promise<void>}
*/

@@ -232,3 +211,2 @@ async initCrypto() {

* Closes the crypto dependency. Crypto should be close after it's used and no longer needed.
* @return {Promise<void>}
*/

@@ -243,4 +221,3 @@ async clearCrypto() {

* Get an individual property config.
* @param {string} propertyName The name of the property.
* @return {ConfigPropertyMeta} The meta config.
* @param propertyName The name of the property.
*/

@@ -256,4 +233,3 @@ getPropertyConfig(propertyName) {

* Encrypts and content properties that have a encryption attribute.
* @param {boolean} encrypt `true` to encrypt.
* @return {Promise<void>}
* @param encrypt `true` to encrypt.
*/

@@ -277,3 +253,2 @@ async cryptProperties(encrypt) {

* Username associated with the default dev hub org.
* @type {string}
*/

@@ -283,3 +258,2 @@ Config.DEFAULT_DEV_HUB_USERNAME = 'defaultdevhubusername';

* Username associate with the default org.
* @type {string}
*/

@@ -289,3 +263,2 @@ Config.DEFAULT_USERNAME = 'defaultusername';

* The sid for the debugger configuration.
* @type {string}
*/

@@ -295,23 +268,9 @@ Config.ISV_DEBUGGER_SID = 'isvDebuggerSid';

* The url for the debugger configuration.
* @type {string}
*/
Config.ISV_DEBUGGER_URL = 'isvDebuggerUrl';
/**
* true if polling should be used over streaming when creating scratch orgs.
* @type {string}
*/
Config.USE_BACKUP_POLLING_ORG_CREATE = 'useBackupPolling.org:create';
/**
* The api version
* @type {string}
*/
Config.API_VERSION = 'apiVersion';
exports.Config = Config;
exports.ORG_DEFAULT = {
DEVHUB: Config.DEFAULT_DEV_HUB_USERNAME,
USERNAME: Config.DEFAULT_USERNAME,
list() {
return [exports.ORG_DEFAULT.DEVHUB, exports.ORG_DEFAULT.USERNAME];
}
};
//# sourceMappingURL=config.js.map

@@ -1,27 +0,4 @@

/**
* An enum of all possible locations for a config value.
* @typedef Location
* @property {string} GLOBAL Represents the global config.
* @property {string} LOCAL Represents the local project config.
* @property {string} ENVIRONMENT Represents environment variables.
*/
/**
* Information about a config property.
* @typedef ConfigInfo
* @property {string} key The config key.
* @property {string | boolean} value The config value.
* @property {Location} location The location of the config property.
* @property {string} path The path of the config value.
* @property {function} isLocal `() => boolean` Location is `Location.LOCAL`.
* @property {function} isGlobal `() => boolean` Location is `Location.GLOBAL`.
* @property {function} isEnvVar `() => boolean` Location is `Location.ENVIRONMENT`.
*/
import { AsyncOptionalCreatable } from '@salesforce/kit';
import { JsonMap, Optional } from '@salesforce/ts-types';
import { AnyJson, JsonMap, Optional } from '@salesforce/ts-types';
import { Config } from './config';
export declare const enum Location {
GLOBAL = "Global",
LOCAL = "Local",
ENVIRONMENT = "Environment"
}
/**

@@ -31,16 +8,28 @@ * Information about a config property.

export interface ConfigInfo {
/**
* key The config key.
*/
key: string;
location?: Location;
value: string | boolean;
/**
* The location of the config property.
*/
location?: ConfigAggregator.Location;
/**
* The config value.
*/
value?: AnyJson;
/**
* The path of the config value.
*/
path?: string;
/**
* @returns true if the config property is in the local project
* `true` if the config property is in the local project.
*/
isLocal: () => boolean;
/**
* @returns true if the config property is in the global space
* `true` if the config property is in the global space.
*/
isGlobal: () => boolean;
/**
* @returns true if the config property is an environment variable.
* `true` if the config property is an environment variable.
*/

@@ -59,7 +48,6 @@ isEnvVar: () => boolean;

*
* @example
* ```
* const aggregator = await ConfigAggregator.create();
* console.log(aggregator.getPropertyValue('defaultusername'));
*
* @hideconstructor
* ```
*/

@@ -73,29 +61,22 @@ export declare class ConfigAggregator extends AsyncOptionalCreatable<JsonMap> {

/**
* **Do not directly construct instances of this class -- use {@link ConfigAggregator.resolve} instead.**
*
* @private
* @constructor
* **Do not directly construct instances of this class -- use {@link ConfigAggregator.create} instead.**
* @ignore
*/
constructor(options?: JsonMap);
init(): Promise<void>;
/**
* Retrieve the path to the config file.
* @callback retrieverFunction
* @param {boolean} isGlobal Is it the global or local project config file?
* @returns {Promise<string>} The path of the config file.
* Initialize this instances async dependencies.
*/
init(): Promise<void>;
/**
* Get a resolved config property.
*
* @param {string} key The key of the property.
* @returns {string | boolean}
* @throws {SfdxError}
* **`{name: 'UnknownConfigKey'}`:** An attempt to get a property that's not supported.
* **Throws** *{@link SfdxError}{ name: 'UnknownConfigKey' }* An attempt to get a property that's not supported.
*
* @param key The key of the property.
*/
getPropertyValue(key: string): string | boolean;
getPropertyValue(key: string): Optional<AnyJson>;
/**
* Get a resolved config property.
*
* @param {string} key The key of the property.
* @returns {ConfigInfo}
* @param key The key of the property.
*/

@@ -111,6 +92,5 @@ getInfo(key: string): ConfigInfo;

*
* @param {string} key The key of the property.
* @returns {Optional<Location>}
* @param key The key of the property.
*/
getLocation(key: string): Optional<Location>;
getLocation(key: string): Optional<ConfigAggregator.Location>;
/**

@@ -128,4 +108,3 @@ * Get a resolved file path or environment variable name of the property.

*
* @param {string} key The key of the property.
* @returns {Optional<string>}
* @param key The key of the property.
*/

@@ -136,3 +115,3 @@ getPath(key: string): Optional<string>;

*
* @example
* ```
* > console.log(aggregator.getConfigInfo());

@@ -143,4 +122,3 @@ * [

* ]
*
* @returns {ConfigInfo[]}
* ```
*/

@@ -150,4 +128,2 @@ getConfigInfo(): ConfigInfo[];

* Get the local project config instance.
*
* @returns {Config}
*/

@@ -157,4 +133,2 @@ getLocalConfig(): Config;

* Get the global config instance.
*
* @returns {Config}
*/

@@ -164,8 +138,6 @@ getGlobalConfig(): Config;

* Get the resolved config object from the local, global and environment config instances.
* @returns {object}
*/
getConfig(): object;
getConfig(): JsonMap;
/**
* Get the config properties that are environment variables.
* @returns {Map<string, string>}
*/

@@ -175,3 +147,2 @@ getEnvVars(): Map<string, string>;

* Re-read all property configurations from disk.
* @returns {Promise<void>}
*/

@@ -181,4 +152,2 @@ reload(): Promise<ConfigAggregator>;

* Loads all the properties and aggregates them according to location.
* @returns {Promise<void>}
* @private
*/

@@ -189,3 +158,2 @@ private loadProperties;

* @param config The config object to set.
* @private
*/

@@ -195,4 +163,3 @@ private setConfig;

* Set the local config object.
* @param {Config} config The config object value to set.
* @private
* @param config The config object value to set.
*/

@@ -202,4 +169,3 @@ private setLocalConfig;

* Set the global config object.
* @param {Config} config The config object value to set.
* @private
* @param config The config object value to set.
*/

@@ -209,4 +175,2 @@ private setGlobalConfig;

* Get the allowed properties.
* @returns {ConfigPropertyMeta[]}
* @private
*/

@@ -216,4 +180,3 @@ private getAllowedProperties;

* Set the allowed properties.
* @param {ConfigPropertyMeta[]} properties The properties to set.
* @private
* @param properties The properties to set.
*/

@@ -223,6 +186,24 @@ private setAllowedProperties;

* Sets the env variables.
* @param {Dictionary<string>} envVars The env variables to set.
* @private
* @param envVars The env variables to set.
*/
private setEnvVars;
}
export declare namespace ConfigAggregator {
/**
* An enum of all possible locations for a config value.
*/
const enum Location {
/**
* Represents the global config.
*/
GLOBAL = "Global",
/**
* Represents the local project config.
*/
LOCAL = "Local",
/**
* Represents environment variables.
*/
ENVIRONMENT = "Environment"
}
}

@@ -8,20 +8,2 @@ "use strict";

*/
/**
* An enum of all possible locations for a config value.
* @typedef Location
* @property {string} GLOBAL Represents the global config.
* @property {string} LOCAL Represents the local project config.
* @property {string} ENVIRONMENT Represents environment variables.
*/
/**
* Information about a config property.
* @typedef ConfigInfo
* @property {string} key The config key.
* @property {string | boolean} value The config value.
* @property {Location} location The location of the config property.
* @property {string} path The path of the config value.
* @property {function} isLocal `() => boolean` Location is `Location.LOCAL`.
* @property {function} isGlobal `() => boolean` Location is `Location.GLOBAL`.
* @property {function} isEnvVar `() => boolean` Location is `Location.ENVIRONMENT`.
*/
Object.defineProperty(exports, "__esModule", { value: true });

@@ -43,14 +25,11 @@ const kit_1 = require("@salesforce/kit");

*
* @example
* ```
* const aggregator = await ConfigAggregator.create();
* console.log(aggregator.getPropertyValue('defaultusername'));
*
* @hideconstructor
* ```
*/
class ConfigAggregator extends kit_1.AsyncOptionalCreatable {
/**
* **Do not directly construct instances of this class -- use {@link ConfigAggregator.resolve} instead.**
*
* @private
* @constructor
* **Do not directly construct instances of this class -- use {@link ConfigAggregator.create} instead.**
* @ignore
*/

@@ -60,2 +39,5 @@ constructor(options) {

}
/**
* Initialize this instances async dependencies.
*/
async init() {

@@ -65,18 +47,10 @@ await this.loadProperties();

/**
* Retrieve the path to the config file.
* @callback retrieverFunction
* @param {boolean} isGlobal Is it the global or local project config file?
* @returns {Promise<string>} The path of the config file.
*/
/**
* Get a resolved config property.
*
* @param {string} key The key of the property.
* @returns {string | boolean}
* @throws {SfdxError}
* **`{name: 'UnknownConfigKey'}`:** An attempt to get a property that's not supported.
* **Throws** *{@link SfdxError}{ name: 'UnknownConfigKey' }* An attempt to get a property that's not supported.
*
* @param key The key of the property.
*/
getPropertyValue(key) {
if (this.getAllowedProperties().some(element => key === element.key)) {
// @ts-ignore TODO: Need to sort out object types on config stuff
return this.getConfig()[key];

@@ -91,4 +65,3 @@ }

*
* @param {string} key The key of the property.
* @returns {ConfigInfo}
* @param key The key of the property.
*/

@@ -115,4 +88,3 @@ getInfo(key) {

*
* @param {string} key The key of the property.
* @returns {Optional<Location>}
* @param key The key of the property.
*/

@@ -142,4 +114,3 @@ getLocation(key) {

*
* @param {string} key The key of the property.
* @returns {Optional<string>}
* @param key The key of the property.
*/

@@ -160,3 +131,3 @@ getPath(key) {

*
* @example
* ```
* > console.log(aggregator.getConfigInfo());

@@ -167,4 +138,3 @@ * [

* ]
*
* @returns {ConfigInfo[]}
* ```
*/

@@ -179,4 +149,2 @@ getConfigInfo() {

* Get the local project config instance.
*
* @returns {Config}
*/

@@ -188,4 +156,2 @@ getLocalConfig() {

* Get the global config instance.
*
* @returns {Config}
*/

@@ -197,3 +163,2 @@ getGlobalConfig() {

* Get the resolved config object from the local, global and environment config instances.
* @returns {object}
*/

@@ -205,3 +170,2 @@ getConfig() {

* Get the config properties that are environment variables.
* @returns {Map<string, string>}
*/

@@ -213,3 +177,2 @@ getEnvVars() {

* Re-read all property configurations from disk.
* @returns {Promise<void>}
*/

@@ -222,4 +185,2 @@ async reload() {

* Loads all the properties and aggregates them according to location.
* @returns {Promise<void>}
* @private
*/

@@ -257,3 +218,4 @@ async loadProperties() {

configs.push(this.envVars);
const reduced = configs.filter(ts_types_1.isObject).reduce((result, configElement) => kit_1.merge(result, configElement), {});
const json = {};
const reduced = configs.filter(ts_types_1.isJsonMap).reduce((acc, el) => kit_1.merge(acc, el), json);
this.setConfig(reduced);

@@ -264,3 +226,2 @@ }

* @param config The config object to set.
* @private
*/

@@ -272,4 +233,3 @@ setConfig(config) {

* Set the local config object.
* @param {Config} config The config object value to set.
* @private
* @param config The config object value to set.
*/

@@ -281,4 +241,3 @@ setLocalConfig(config) {

* Set the global config object.
* @param {Config} config The config object value to set.
* @private
* @param config The config object value to set.
*/

@@ -290,4 +249,2 @@ setGlobalConfig(config) {

* Get the allowed properties.
* @returns {ConfigPropertyMeta[]}
* @private
*/

@@ -299,4 +256,3 @@ getAllowedProperties() {

* Set the allowed properties.
* @param {ConfigPropertyMeta[]} properties The properties to set.
* @private
* @param properties The properties to set.
*/

@@ -308,4 +264,3 @@ setAllowedProperties(properties) {

* Sets the env variables.
* @param {Dictionary<string>} envVars The env variables to set.
* @private
* @param envVars The env variables to set.
*/

@@ -312,0 +267,0 @@ setEnvVars(envVars) {

@@ -1,10 +0,1 @@

/**
* Options when creating the config file.
* @typedef {object} ConfigOptions
* @property {string} rootFolder The root folder where the config file is stored.
* @property {string} filename The file name.
* @property {boolean} isGlobal If the file is in the global or project directory.
* @property {boolean} isState If the file is in the state folder or no (.sfdx).
* @property {string} filePath The full file path where the config file is stored.
*/
/// <reference types="node" />

@@ -19,13 +10,14 @@ import { Stats as fsStats } from 'fs';

*
* @extends BaseConfigStore
*
* @example
* class MyConfig extents ConfigFile {
* public static getFileName(): string {
* return 'myConfigFilename.json';
* }
* ```
* class MyConfig extends ConfigFile {
* public static getFileName(): string {
* return 'myConfigFilename.json';
* }
* }
* const myConfig = await MyConfig.create<MyConfig>();
* const myConfig = await MyConfig.create({
* isGlobal: true
* });
* myConfig.set('mykey', 'myvalue');
* await myconfig.write();
* await myConfig.write();
* ```
*/

@@ -44,67 +36,50 @@ export declare class ConfigFile<T extends ConfigFile.Options> extends BaseConfigStore<T> {

/**
* Helper used to determined what the local and global folder point to.
* Helper used to determined what the local and global folder point to. Returns the file path of the root folder.
*
* @param isGlobal True if the config should be global. False for local.
* @returns The file path of the root folder.
*/
static resolveRootFolder(isGlobal: boolean): Promise<string>;
private path;
/**
* Creates the config instance and reads the contents of the existing file, if there is one.
*
* This is the same as
* ```
* const myConfig = await MyConfig.create<MyConfig>();
* await myConfig.read();
* ```
*
* **Note:** Cast to the extended class. e.g. `await MyConfig.retrieve<MyConfig>();`
*
* @param {ConfigOptions} [options] The options used to create the file. Will use {@link ConfigFile.getDefaultOptions} by default.
* {@link ConfigFile.getDefaultOptions} with no parameters by default.
* Constructor
* **Do not directly construct instances of this class -- use {@link ConfigFile.create} instead.**
* @param options The options for the class instance
* @ignore
*/
static retrieve<T extends ConfigFile<ConfigFile.Options>>(options: ConfigFile.Options): Promise<T>;
private path;
constructor(options: T);
/**
* Determines if the config file is read/write accessible.
* Determines if the config file is read/write accessible. Returns `true` if the user has capabilities specified
* by perm.
* @param {number} perm The permission.
* @returns {Promise<boolean>} `true` if the user has capabilities specified by perm.
* @see {@link https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callback|fs.access}
*
* **See** {@link https://nodejs.org/dist/latest/docs/api/fs.html#fs_fs_access_path_mode_callback}
*/
access(perm: number): Promise<boolean>;
/**
* Read the config file and set the config contents.
* Read the config file and set the config contents. Returns the config contents of the config file.
* **Throws** *{@link SfdxError}{ name: 'UnexpectedJsonFileFormat' }* There was a problem reading or parsing the file.
* @param [throwOnNotFound = false] Optionally indicate if a throw should occur on file read.
* @returns The config contents of the config file.
* @throws {SfdxError}
* **`{name: 'UnexpectedJsonFileFormat'}`:** There was a problem reading or parsing the file.
*/
read(throwOnNotFound?: boolean): Promise<ConfigContents>;
/**
* Write the config file with new contents. If no new contents are passed in
* it will write the existing config contents that were set from {@link ConfigFile.read}, or an
* empty file if {@link ConfigFile.read} was not called.
* Write the config file with new contents. If no new contents are provided it will write the existing config
* contents that were set from {@link ConfigFile.read}, or an empty file if {@link ConfigFile.read} was not called.
*
* @param [newContents] The new contents of the file.
* @returns The written contents.
* @param newContents The new contents of the file.
*/
write(newContents?: ConfigContents): Promise<object>;
write(newContents?: ConfigContents): Promise<ConfigContents>;
/**
* Check to see if the config file exists.
*
* @returns True if the config file exists and has access, false otherwise.
* Check to see if the config file exists. Returns `true` if the config file exists and has access, false otherwise.
*/
exists(): Promise<boolean>;
/**
* Get the stats of the file.
* Get the stats of the file. Returns the stats of the file.
*
* @returns The stats of the file.
* @see {@link https://nodejs.org/api/fs.html#fs_fs_fstat_fd_callback|fs.stat}
* {@link fs.stat}
*/
stat(): Promise<fsStats>;
/**
* Delete the config file if it exists.
* Delete the config file if it exists. Returns `true` if the file was deleted, `false` otherwise.
*
* @returns True if the file was deleted, false otherwise.
* @see {@link https://nodejs.org/api/fs.html#fs_fs_unlink_path_callback|fs.unlink}
* {@link fs.unlink}
*/

@@ -117,3 +92,3 @@ unlink(): Promise<void>;

/**
* Returns true if this config is using the global path, false otherwise.
* Returns `true` if this config is using the global path, `false` otherwise.
*/

@@ -129,12 +104,25 @@ isGlobal(): boolean;

* The interface for Config options.
* *NOTE:* And changes to this interface must also change the jsdoc typedef header above.
* @interface
*/
interface Options extends BaseConfigStore.Options {
/**
* The root folder where the config file is stored.
*/
rootFolder?: string;
/**
* The file name.
*/
filename?: string;
/**
* If the file is in the global or project directory.
*/
isGlobal?: boolean;
/**
* If the file is in the state folder or no (.sfdx).
*/
isState?: boolean;
/**
* The full file path where the config file is stored.
*/
filePath?: string;
}
}

@@ -8,11 +8,2 @@ "use strict";

*/
/**
* Options when creating the config file.
* @typedef {object} ConfigOptions
* @property {string} rootFolder The root folder where the config file is stored.
* @property {string} filename The file name.
* @property {boolean} isGlobal If the file is in the global or project directory.
* @property {boolean} isState If the file is in the state folder or no (.sfdx).
* @property {string} filePath The full file path where the config file is stored.
*/
Object.defineProperty(exports, "__esModule", { value: true });

@@ -34,15 +25,22 @@ const ts_types_1 = require("@salesforce/ts-types");

*
* @extends BaseConfigStore
*
* @example
* class MyConfig extents ConfigFile {
* public static getFileName(): string {
* return 'myConfigFilename.json';
* }
* ```
* class MyConfig extends ConfigFile {
* public static getFileName(): string {
* return 'myConfigFilename.json';
* }
* }
* const myConfig = await MyConfig.create<MyConfig>();
* const myConfig = await MyConfig.create({
* isGlobal: true
* });
* myConfig.set('mykey', 'myvalue');
* await myconfig.write();
* await myConfig.write();
* ```
*/
class ConfigFile extends configStore_1.BaseConfigStore {
/**
* Constructor
* **Do not directly construct instances of this class -- use {@link ConfigFile.create} instead.**
* @param options The options for the class instance
* @ignore
*/
constructor(options) {

@@ -71,6 +69,5 @@ super(options);

/**
* Helper used to determined what the local and global folder point to.
* Helper used to determined what the local and global folder point to. Returns the file path of the root folder.
*
* @param isGlobal True if the config should be global. False for local.
* @returns The file path of the root folder.
*/

@@ -84,29 +81,11 @@ static async resolveRootFolder(isGlobal) {

/**
* Creates the config instance and reads the contents of the existing file, if there is one.
* Determines if the config file is read/write accessible. Returns `true` if the user has capabilities specified
* by perm.
* @param {number} perm The permission.
*
* This is the same as
* ```
* const myConfig = await MyConfig.create<MyConfig>();
* await myConfig.read();
* ```
*
* **Note:** Cast to the extended class. e.g. `await MyConfig.retrieve<MyConfig>();`
*
* @param {ConfigOptions} [options] The options used to create the file. Will use {@link ConfigFile.getDefaultOptions} by default.
* {@link ConfigFile.getDefaultOptions} with no parameters by default.
* **See** {@link https://nodejs.org/dist/latest/docs/api/fs.html#fs_fs_access_path_mode_callback}
*/
static async retrieve(options) {
const configFile = await ConfigFile.create(options);
await configFile.read();
return configFile;
}
/**
* Determines if the config file is read/write accessible.
* @param {number} perm The permission.
* @returns {Promise<boolean>} `true` if the user has capabilities specified by perm.
* @see {@link https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callback|fs.access}
*/
async access(perm) {
try {
await fs_2.access(this.getPath(), perm);
await fs_2.fs.access(this.getPath(), perm);
return true;

@@ -119,11 +98,9 @@ }

/**
* Read the config file and set the config contents.
* Read the config file and set the config contents. Returns the config contents of the config file.
* **Throws** *{@link SfdxError}{ name: 'UnexpectedJsonFileFormat' }* There was a problem reading or parsing the file.
* @param [throwOnNotFound = false] Optionally indicate if a throw should occur on file read.
* @returns The config contents of the config file.
* @throws {SfdxError}
* **`{name: 'UnexpectedJsonFileFormat'}`:** There was a problem reading or parsing the file.
*/
async read(throwOnNotFound = false) {
try {
const obj = await fs_2.readJsonMap(this.getPath());
const obj = await fs_2.fs.readJsonMap(this.getPath());
this.setContentsFromObject(obj);

@@ -143,8 +120,6 @@ return this.getContents();

/**
* Write the config file with new contents. If no new contents are passed in
* it will write the existing config contents that were set from {@link ConfigFile.read}, or an
* empty file if {@link ConfigFile.read} was not called.
* Write the config file with new contents. If no new contents are provided it will write the existing config
* contents that were set from {@link ConfigFile.read}, or an empty file if {@link ConfigFile.read} was not called.
*
* @param [newContents] The new contents of the file.
* @returns The written contents.
* @param newContents The new contents of the file.
*/

@@ -155,10 +130,8 @@ async write(newContents) {

}
await fs_2.mkdirp(path_1.dirname(this.getPath()));
await fs_2.writeJson(this.getPath(), this.toObject());
await fs_2.fs.mkdirp(path_1.dirname(this.getPath()));
await fs_2.fs.writeJson(this.getPath(), this.toObject());
return this.getContents();
}
/**
* Check to see if the config file exists.
*
* @returns True if the config file exists and has access, false otherwise.
* Check to see if the config file exists. Returns `true` if the config file exists and has access, false otherwise.
*/

@@ -169,15 +142,13 @@ async exists() {

/**
* Get the stats of the file.
* Get the stats of the file. Returns the stats of the file.
*
* @returns The stats of the file.
* @see {@link https://nodejs.org/api/fs.html#fs_fs_fstat_fd_callback|fs.stat}
* {@link fs.stat}
*/
async stat() {
return fs_2.stat(this.getPath());
return fs_2.fs.stat(this.getPath());
}
/**
* Delete the config file if it exists.
* Delete the config file if it exists. Returns `true` if the file was deleted, `false` otherwise.
*
* @returns True if the file was deleted, false otherwise.
* @see {@link https://nodejs.org/api/fs.html#fs_fs_unlink_path_callback|fs.unlink}
* {@link fs.unlink}
*/

@@ -187,3 +158,3 @@ async unlink() {

if (exists) {
return await fs_2.unlink(this.getPath());
return await fs_2.fs.unlink(this.getPath());
}

@@ -199,3 +170,3 @@ throw new sfdxError_1.SfdxError(`Target file doesn't exist. path: ${this.getPath()}`, 'TargetFileNotFound');

/**
* Returns true if this config is using the global path, false otherwise.
* Returns `true` if this config is using the global path, `false` otherwise.
*/

@@ -232,2 +203,3 @@ isGlobal() {

this.path = path_1.join(configRootFolder, this.options.filePath ? this.options.filePath : '', this.options.filename);
await this.read();
}

@@ -234,0 +206,0 @@ }

@@ -1,8 +0,2 @@

/**
* Options when creating the config file. Extends {@link ConfigOptions}.
* @typedef {object} ConfigGroupOptions
* @extends ConfigOptions
* @property {string} defaultGroup The default group for properties to go into.
*/
import { JsonMap, Optional } from '@salesforce/ts-types';
import { Dictionary, JsonMap, Optional } from '@salesforce/ts-types';
import { ConfigFile } from './configFile';

@@ -16,16 +10,14 @@ import { ConfigContents, ConfigEntry, ConfigValue } from './configStore';

*
* @extends ConfigFile
*
* @example
* class MyPluginConfig extents ConfigGroup {
* class MyConfig extents ConfigFile {
* public static getFileName(): string {
* return 'myPluginConfigFilename.json';
* }
* ```
* class MyPluginConfig extends ConfigGroup<ConfigGroup.Options> {
* public static getFileName(): string {
* return 'myPluginConfigFilename.json';
* }
* }
* const myConfig = await MyPluginConfig.retrieve<MyPluginConfig>(ConfigGroup.getOptions('all'));
* myconfig.setDefaultGroup('myCommand'); // Can be set in your command's init.
* const myConfig = await MyPluginConfig.create(ConfigGroup.getOptions('all'));
* myConfig.setDefaultGroup('myCommand'); // Can be set in your command's init.
* myConfig.set('mykey', 'myvalue'); // Sets 'myKey' for the 'myCommand' group.
* myConfig.setInGroup('myKey', 'myvalue', 'all'); // Manually set in another group.
* await myconfig.write();
* await myConfig.write();
* ```
*/

@@ -35,27 +27,24 @@ export declare class ConfigGroup<T extends ConfigGroup.Options> extends ConfigFile<T> {

* Get ConfigGroup specific options, such as the default group.
* @param {string} defaultGroup The default group to use when creating the config.
* @param {string} [filename] The filename of the config file. Uses the static {@link getFileName} by default.
* @param defaultGroup The default group to use when creating the config.
* @param filename The filename of the config file. Uses the static {@link getFileName} by default.
*/
static getOptions(defaultGroup: string, filename?: string): ConfigGroup.Options;
static retrieve<T extends ConfigFile<ConfigFile.Options>>(options?: ConfigFile.Options): Promise<T>;
private defaultGroup;
/**
* Sets the default group for all {@link BaseConfigStore} methods to use.
* @param {String} group The group.
* @throws {SfdxError} **`{name: 'MissingGroupName'}`:** The group parameter is null or undefined.
* **Throws** *{@link SfdxError}{ name: 'MissingGroupName' }* The group parameter is null or undefined.
* @param group The group.
*/
setDefaultGroup(group: string): void;
/**
* Set a group of entries in a bulk save.
* @param {object} newEntries An object representing the aliases to set.
* @param {string} [group = 'default'] The group the property belongs to.
* @returns {Promise<object>} The new property that was saved.
* Set a group of entries in a bulk save. Returns The new properties that were saved.
* @param newEntries An object representing the aliases to set.
* @param group The group the property belongs to.
*/
updateValues(newEntries: object, group?: string): Promise<object>;
updateValues(newEntries: Dictionary<ConfigValue>, group?: string): Promise<Dictionary<ConfigValue>>;
/**
* Set a value on a group.
* @param {string} key The key.
* @param {string} value The value.
* @param {string} [group = 'default'] The group.
* @returns {Promise<void>} The promise resolved when the value is set.
* Set a value on a group. Returns the promise resolved when the value is set.
* @param key The key.
* @param value The value.
* @param group The group.
*/

@@ -65,11 +54,7 @@ updateValue(key: string, value: ConfigValue, group?: string): Promise<void>;

* Gets an array of key value pairs.
* @returns {ConfigEntry[]}
* @override
*/
entries(): ConfigEntry[];
/**
* Returns a specified element from ConfigGroup.
* @param {string} key The key.
* @returns {Optional<ConfigValue>} The associated value.
* @override
* Returns a specified element from ConfigGroup. Returns the associated value.
* @param key The key.
*/

@@ -80,4 +65,2 @@ get(key: string): Optional<ConfigValue>;

* @param {string} key The key.
* @returns {boolean}
* @override
*/

@@ -87,4 +70,2 @@ has(key: string): boolean;

* Returns an array of the keys from the default group.
* @returns {string[]}
* @override
*/

@@ -94,4 +75,2 @@ keys(): string[];

* Returns an array of the values from the default group.
* @returns {ConfigValue[]}
* @override
*/

@@ -101,13 +80,9 @@ values(): ConfigValue[];

* Add or updates an element with the specified key in the default group.
* @param {string} key The key.
* @param {ConfigValue} value The value.
* @returns {ConfigContents}
* @override
* @param key The key.
* @param value The value.
*/
set(key: string, value: ConfigValue): ConfigContents;
/**
* Removes an element with the specified key from the default group.
* @param {string} key The key.
* @returns {boolean} True if the item was deleted.
* @override
* Removes an element with the specified key from the default group. Returns `true` if the item was deleted.
* @param key The key.
*/

@@ -117,9 +92,7 @@ unset(key: string): boolean;

* Remove all key value pairs from the default group.
* @override
*/
clear(): void;
/**
* Get all config content for a group.
* Get all config contents for a group.
* @param {string} [group = 'default'] The group.
* @returns {ConfigContents} The contents.
*/

@@ -129,5 +102,4 @@ getGroup(group?: string): Optional<ConfigContents>;

* Returns the value associated to the key and group, or undefined if there is none.
* @param {string} key The key.
* @param {string} [group = 'default'] The group. Defaults to the default group.
* @returns {Optional<ConfigValue>}
* @param key The key.
* @param group The group. Defaults to the default group.
*/

@@ -137,4 +109,2 @@ getInGroup(key: string, group?: string): Optional<ConfigValue>;

* Convert the config object to a json object.
* @returns {JsonMap}
* @override
*/

@@ -150,7 +120,9 @@ toObject(): JsonMap;

* @param key The key.
* @param [value] The value.
* @param [group = 'default'] The group. Defaults to the default group.
* @returns {ConfigContents} The contents.
* @param value The value.
* @param group The group. Uses the default group if not specified.
*/
setInGroup(key: string, value?: ConfigValue, group?: string): ConfigContents;
/**
* Initialize the asynchronous dependencies.
*/
init(): Promise<void>;

@@ -160,9 +132,10 @@ }

/**
* The interface for Config options.
* *NOTE:* And changes to this interface must also change the jsdoc typedef header above.
* @interface
* Options when creating the config file.
*/
interface Options extends ConfigFile.Options {
/**
* The default group for properties to go into.
*/
defaultGroup: string;
}
}

@@ -8,8 +8,2 @@ "use strict";

*/
/**
* Options when creating the config file. Extends {@link ConfigOptions}.
* @typedef {object} ConfigGroupOptions
* @extends ConfigOptions
* @property {string} defaultGroup The default group for properties to go into.
*/
Object.defineProperty(exports, "__esModule", { value: true });

@@ -26,16 +20,14 @@ const kit_1 = require("@salesforce/kit");

*
* @extends ConfigFile
*
* @example
* class MyPluginConfig extents ConfigGroup {
* class MyConfig extents ConfigFile {
* public static getFileName(): string {
* return 'myPluginConfigFilename.json';
* }
* ```
* class MyPluginConfig extends ConfigGroup<ConfigGroup.Options> {
* public static getFileName(): string {
* return 'myPluginConfigFilename.json';
* }
* }
* const myConfig = await MyPluginConfig.retrieve<MyPluginConfig>(ConfigGroup.getOptions('all'));
* myconfig.setDefaultGroup('myCommand'); // Can be set in your command's init.
* const myConfig = await MyPluginConfig.create(ConfigGroup.getOptions('all'));
* myConfig.setDefaultGroup('myCommand'); // Can be set in your command's init.
* myConfig.set('mykey', 'myvalue'); // Sets 'myKey' for the 'myCommand' group.
* myConfig.setInGroup('myKey', 'myvalue', 'all'); // Manually set in another group.
* await myconfig.write();
* await myConfig.write();
* ```
*/

@@ -49,4 +41,4 @@ class ConfigGroup extends configFile_1.ConfigFile {

* Get ConfigGroup specific options, such as the default group.
* @param {string} defaultGroup The default group to use when creating the config.
* @param {string} [filename] The filename of the config file. Uses the static {@link getFileName} by default.
* @param defaultGroup The default group to use when creating the config.
* @param filename The filename of the config file. Uses the static {@link getFileName} by default.
*/

@@ -59,11 +51,6 @@ static getOptions(defaultGroup, filename) {

}
static async retrieve(options) {
const aliases = await ConfigGroup.create(options || ConfigGroup.getDefaultOptions());
await aliases.read();
return aliases;
}
/**
* Sets the default group for all {@link BaseConfigStore} methods to use.
* @param {String} group The group.
* @throws {SfdxError} **`{name: 'MissingGroupName'}`:** The group parameter is null or undefined.
* **Throws** *{@link SfdxError}{ name: 'MissingGroupName' }* The group parameter is null or undefined.
* @param group The group.
*/

@@ -77,6 +64,5 @@ setDefaultGroup(group) {

/**
* Set a group of entries in a bulk save.
* @param {object} newEntries An object representing the aliases to set.
* @param {string} [group = 'default'] The group the property belongs to.
* @returns {Promise<object>} The new property that was saved.
* Set a group of entries in a bulk save. Returns The new properties that were saved.
* @param newEntries An object representing the aliases to set.
* @param group The group the property belongs to.
*/

@@ -91,7 +77,6 @@ async updateValues(newEntries, group) {

/**
* Set a value on a group.
* @param {string} key The key.
* @param {string} value The value.
* @param {string} [group = 'default'] The group.
* @returns {Promise<void>} The promise resolved when the value is set.
* Set a value on a group. Returns the promise resolved when the value is set.
* @param key The key.
* @param value The value.
* @param group The group.
*/

@@ -107,4 +92,2 @@ async updateValue(key, value, group) {

* Gets an array of key value pairs.
* @returns {ConfigEntry[]}
* @override
*/

@@ -119,6 +102,4 @@ entries() {

/**
* Returns a specified element from ConfigGroup.
* @param {string} key The key.
* @returns {Optional<ConfigValue>} The associated value.
* @override
* Returns a specified element from ConfigGroup. Returns the associated value.
* @param key The key.
*/

@@ -131,4 +112,2 @@ get(key) {

* @param {string} key The key.
* @returns {boolean}
* @override
*/

@@ -141,4 +120,2 @@ has(key) {

* Returns an array of the keys from the default group.
* @returns {string[]}
* @override
*/

@@ -150,4 +127,2 @@ keys() {

* Returns an array of the values from the default group.
* @returns {ConfigValue[]}
* @override
*/

@@ -159,6 +134,4 @@ values() {

* Add or updates an element with the specified key in the default group.
* @param {string} key The key.
* @param {ConfigValue} value The value.
* @returns {ConfigContents}
* @override
* @param key The key.
* @param value The value.
*/

@@ -169,6 +142,4 @@ set(key, value) {

/**
* Removes an element with the specified key from the default group.
* @param {string} key The key.
* @returns {boolean} True if the item was deleted.
* @override
* Removes an element with the specified key from the default group. Returns `true` if the item was deleted.
* @param key The key.
*/

@@ -185,3 +156,2 @@ unset(key) {

* Remove all key value pairs from the default group.
* @override
*/

@@ -192,5 +162,4 @@ clear() {

/**
* Get all config content for a group.
* Get all config contents for a group.
* @param {string} [group = 'default'] The group.
* @returns {ConfigContents} The contents.
*/

@@ -202,5 +171,4 @@ getGroup(group = this.defaultGroup) {

* Returns the value associated to the key and group, or undefined if there is none.
* @param {string} key The key.
* @param {string} [group = 'default'] The group. Defaults to the default group.
* @returns {Optional<ConfigValue>}
* @param key The key.
* @param group The group. Defaults to the default group.
*/

@@ -215,4 +183,2 @@ getInGroup(key, group) {

* Convert the config object to a json object.
* @returns {JsonMap}
* @override
*/

@@ -239,5 +205,4 @@ toObject() {

* @param key The key.
* @param [value] The value.
* @param [group = 'default'] The group. Defaults to the default group.
* @returns {ConfigContents} The contents.
* @param value The value.
* @param group The group. Uses the default group if not specified.
*/

@@ -254,2 +219,5 @@ setInGroup(key, value, group) {

}
/**
* Initialize the asynchronous dependencies.
*/
async init() {

@@ -256,0 +224,0 @@ await super.init();

@@ -1,15 +0,1 @@

/**
* The allowed types stored in a config store.
* @typedef {(string | boolean | object)} ConfigValue
*/
/**
* The type of entries in a config store defined by the key and value type of {@link ConfigContents}.
* @typedef {object} ConfigEntry
* @property {string} key
* @property {ConfigValue} value
*/
/**
* The type of content a config stores.
* @typedef {Map<string, ConfigValue>} ConfigContents
*/
import { AsyncCreatable } from '@salesforce/kit';

@@ -33,3 +19,2 @@ import { AnyJson, JsonMap, Optional } from '@salesforce/ts-types';

* An interface for a config object with a persistent store.
* @interface
*/

@@ -57,3 +42,2 @@ export interface ConfigStore {

* **Note:** To see the interface, look in typescripts autocomplete help or the npm package's ConfigStore.d.ts file.
* @implements {ConfigStore}
*/

@@ -63,6 +47,10 @@ export declare abstract class BaseConfigStore<T extends BaseConfigStore.Options> extends AsyncCreatable<T> implements ConfigStore {

private contents;
/**
* Constructor.
* @param options The options for the class instance.
* @ignore
*/
constructor(options: T);
/**
* Returns an array of {@link ConfigEntry} for each element in the config.
* @returns {ConfigEntry}
*/

@@ -72,4 +60,3 @@ entries(): ConfigEntry[];

* Returns the value associated to the key, or undefined if there is none.
* @param {string} key The key.
* @return {Optional<ConfigValue>}
* @param key The key.
*/

@@ -79,4 +66,3 @@ get(key: string): Optional<ConfigValue>;

* Returns the list of keys that contain a value.
* @param {ConfigValue} value The value to filter keys on.
* @returns {string[]}
* @param value The value to filter keys on.
*/

@@ -86,3 +72,3 @@ getKeysByValue(value: ConfigValue): string[];

* Returns a boolean asserting whether a value has been associated to the key in the config object or not.
* @param {string} key The key.
* @param key The key.
*/

@@ -92,3 +78,2 @@ has(key: string): boolean;

* Returns an array that contains the keys for each element in the config object.
* @returns {string[]}
*/

@@ -98,17 +83,16 @@ keys(): string[];

* Sets the value for the key in the config object.
* @param {string} key The Key.
* @param {ConfigValue} value The value.
* @returns {ConfigContents} Returns the config object.
* @param key The Key.
* @param value The value.
*/
set(key: string, value: ConfigValue): ConfigContents;
/**
* Returns true if an element in the config object existed and has been removed, or false if the element does not exist. {@link BaseConfigStore.has(key)} will return false afterwards.
* @param {string} key The key.
* @returns {boolean}
* Returns `true` if an element in the config object existed and has been removed, or `false` if the element does not
* exist. {@link BaseConfigStore.has} will return false afterwards.
* @param key The key.
*/
unset(key: string): boolean;
/**
* Returns true if all elements in the config object existed and have been removed, or false if all the elements do not exist (some may have been removed). {@link BaseConfigStore.has(key)} will return false afterwards.
* @param {string[]} keys The keys.
* @returns {boolean}
* Returns `true` if all elements in the config object existed and have been removed, or `false` if all the elements
* do not exist (some may have been removed). {@link BaseConfigStore.has(key)} will return false afterwards.
* @param keys The keys.
*/

@@ -122,3 +106,2 @@ unsetAll(keys: string[]): boolean;

* Returns an array that contains the values for each element in the config object.
* @returns {ConfigValue[]}
*/

@@ -128,3 +111,2 @@ values(): ConfigValue[];

* Returns the entire config contents.
* @returns {ConfigContents}
*/

@@ -134,3 +116,3 @@ getContents(): ConfigContents;

* Sets the entire config contents.
* @param {ConfigContents} contents The contents.
* @param contents The contents.
*/

@@ -145,3 +127,4 @@ setContents(contents?: ConfigContents): void;

* Asynchronously invokes `actionFn` once for each key-value pair present in the config object.
* @param {function} actionFn The function `(key: string, value: ConfigValue) => Promise<void>` to be called for each element.
* @param {function} actionFn The function `(key: string, value: ConfigValue) => Promise<void>` to be called for
* each element.
* @returns {Promise<void>}

@@ -151,4 +134,4 @@ */

/**
* Convert the config object to a JSON object.
* @returns {JsonMap} Returns the config contents. Same as calling ConfigStore.getContents
* Convert the config object to a JSON object. Returns the config contents.
* Same as calling {@link ConfigStore.getContents}
*/

@@ -158,10 +141,19 @@ toObject(): JsonMap;

* Convert an object to a {@link ConfigContents} and set it as the config contents.
* @param {object} obj The object.
* @param obj The object.
*/
setContentsFromObject<U extends object>(obj: U): void;
}
/**
* @ignore
*/
export declare namespace BaseConfigStore {
/**
* Options for the config store.
*/
interface Options {
/**
* Intial contents for the config.
*/
contents?: ConfigContents;
}
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -9,16 +8,3 @@ * Copyright (c) 2018, salesforce.com, inc.

*/
/**
* The allowed types stored in a config store.
* @typedef {(string | boolean | object)} ConfigValue
*/
/**
* The type of entries in a config store defined by the key and value type of {@link ConfigContents}.
* @typedef {object} ConfigEntry
* @property {string} key
* @property {ConfigValue} value
*/
/**
* The type of content a config stores.
* @typedef {Map<string, ConfigValue>} ConfigContents
*/
Object.defineProperty(exports, "__esModule", { value: true });
const kit_1 = require("@salesforce/kit");

@@ -31,5 +17,9 @@ const ts_types_1 = require("@salesforce/ts-types");

* **Note:** To see the interface, look in typescripts autocomplete help or the npm package's ConfigStore.d.ts file.
* @implements {ConfigStore}
*/
class BaseConfigStore extends kit_1.AsyncCreatable {
/**
* Constructor.
* @param options The options for the class instance.
* @ignore
*/
constructor(options) {

@@ -42,3 +32,2 @@ super(options);

* Returns an array of {@link ConfigEntry} for each element in the config.
* @returns {ConfigEntry}
*/

@@ -50,4 +39,3 @@ entries() {

* Returns the value associated to the key, or undefined if there is none.
* @param {string} key The key.
* @return {Optional<ConfigValue>}
* @param key The key.
*/

@@ -59,4 +47,3 @@ get(key) {

* Returns the list of keys that contain a value.
* @param {ConfigValue} value The value to filter keys on.
* @returns {string[]}
* @param value The value to filter keys on.
*/

@@ -70,3 +57,3 @@ getKeysByValue(value) {

* Returns a boolean asserting whether a value has been associated to the key in the config object or not.
* @param {string} key The key.
* @param key The key.
*/

@@ -78,3 +65,2 @@ has(key) {

* Returns an array that contains the keys for each element in the config object.
* @returns {string[]}
*/

@@ -86,5 +72,4 @@ keys() {

* Sets the value for the key in the config object.
* @param {string} key The Key.
* @param {ConfigValue} value The value.
* @returns {ConfigContents} Returns the config object.
* @param key The Key.
* @param value The value.
*/

@@ -96,5 +81,5 @@ set(key, value) {

/**
* Returns true if an element in the config object existed and has been removed, or false if the element does not exist. {@link BaseConfigStore.has(key)} will return false afterwards.
* @param {string} key The key.
* @returns {boolean}
* Returns `true` if an element in the config object existed and has been removed, or `false` if the element does not
* exist. {@link BaseConfigStore.has} will return false afterwards.
* @param key The key.
*/

@@ -105,5 +90,5 @@ unset(key) {

/**
* Returns true if all elements in the config object existed and have been removed, or false if all the elements do not exist (some may have been removed). {@link BaseConfigStore.has(key)} will return false afterwards.
* @param {string[]} keys The keys.
* @returns {boolean}
* Returns `true` if all elements in the config object existed and have been removed, or `false` if all the elements
* do not exist (some may have been removed). {@link BaseConfigStore.has(key)} will return false afterwards.
* @param keys The keys.
*/

@@ -121,3 +106,2 @@ unsetAll(keys) {

* Returns an array that contains the values for each element in the config object.
* @returns {ConfigValue[]}
*/

@@ -129,3 +113,2 @@ values() {

* Returns the entire config contents.
* @returns {ConfigContents}
*/

@@ -140,3 +123,3 @@ getContents() {

* Sets the entire config contents.
* @param {ConfigContents} contents The contents.
* @param contents The contents.
*/

@@ -158,3 +141,4 @@ setContents(contents) {

* Asynchronously invokes `actionFn` once for each key-value pair present in the config object.
* @param {function} actionFn The function `(key: string, value: ConfigValue) => Promise<void>` to be called for each element.
* @param {function} actionFn The function `(key: string, value: ConfigValue) => Promise<void>` to be called for
* each element.
* @returns {Promise<void>}

@@ -169,4 +153,4 @@ */

/**
* Convert the config object to a JSON object.
* @returns {JsonMap} Returns the config contents. Same as calling ConfigStore.getContents
* Convert the config object to a JSON object. Returns the config contents.
* Same as calling {@link ConfigStore.getContents}
*/

@@ -178,3 +162,3 @@ toObject() {

* Convert an object to a {@link ConfigContents} and set it as the config contents.
* @param {object} obj The object.
* @param obj The object.
*/

@@ -181,0 +165,0 @@ setContentsFromObject(obj) {

@@ -5,3 +5,2 @@ import { ConfigFile } from './configFile';

* Represent a key chain config backed by a json file.
* @private
*/

@@ -15,14 +14,8 @@ export declare class KeychainConfig extends ConfigFile<ConfigFile.Options> {

/**
* Retrieves the global config state of the keychain
* @param options Option override otherwise the default options are used.
*/
static retrieve<T extends ConfigFile<ConfigFile.Options>>(options?: ConfigFile.Options): Promise<T>;
/**
* Write the config file with new contents. If no new contents are passed in
* it will write this.contents that was set from read().
* it will write this.contents that was set from read(). Returns the written contents.
*
* @param {ConfigContents} newContents the new contents of the file
* @returns {Promise<ConfigContents>} the written contents
* @param newContents the new contents of the file
*/
write(newContents?: ConfigContents): Promise<ConfigContents>;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -9,8 +8,8 @@ * Copyright (c) 2018, salesforce.com, inc.

*/
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = require("path");
const fs = require("../util/fs");
const fs_1 = require("../util/fs");
const configFile_1 = require("./configFile");
/**
* Represent a key chain config backed by a json file.
* @private
*/

@@ -29,16 +28,6 @@ // istanbul ignore next - getPassword/setPassword is always mocked out

/**
* Retrieves the global config state of the keychain
* @param options Option override otherwise the default options are used.
*/
static async retrieve(options) {
const keychainConfig = await KeychainConfig.create(options || KeychainConfig.getDefaultOptions());
await keychainConfig.read();
return keychainConfig;
}
/**
* Write the config file with new contents. If no new contents are passed in
* it will write this.contents that was set from read().
* it will write this.contents that was set from read(). Returns the written contents.
*
* @param {ConfigContents} newContents the new contents of the file
* @returns {Promise<ConfigContents>} the written contents
* @param newContents the new contents of the file
*/

@@ -49,4 +38,4 @@ async write(newContents) {

}
await fs.mkdirp(path_1.dirname(this.getPath()));
await fs.writeFile(this.getPath(), JSON.stringify(this.getContents(), null, 4), { mode: '600' });
await fs_1.fs.mkdirp(path_1.dirname(this.getPath()));
await fs_1.fs.writeFile(this.getPath(), JSON.stringify(this.getContents(), null, 4), { mode: '600' });
return this.getContents();

@@ -53,0 +42,0 @@ }

import { ConfigFile } from './configFile';
/**
* A config file that stores usernames for an org.
*
* @extends ConfigFile
*/

@@ -10,12 +8,23 @@ export declare class OrgUsersConfig extends ConfigFile<OrgUsersConfig.Options> {

* Gets the config options for a given org ID.
* @param {string} orgId The orgId. Generally this org would have multiple users configured.
* @return {ConfigOptions} The ConfigOptions.
* @param orgId The orgId. Generally this org would have multiple users configured.
*/
static getOptions(orgId: string): OrgUsersConfig.Options;
/**
* Constructor.
* **Do not directly construct instances of this class -- use {@link OrgUsersConfig.create} instead.**
* @param options The options for the class instance
* @ignore
*/
constructor(options: OrgUsersConfig.Options);
}
export declare namespace OrgUsersConfig {
/**
* The config file options.
*/
interface Options extends ConfigFile.Options {
/**
* The org id associated with this user.
*/
orgId: string;
}
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -9,7 +8,6 @@ * Copyright (c) 2018, salesforce.com, inc.

*/
Object.defineProperty(exports, "__esModule", { value: true });
const configFile_1 = require("./configFile");
/**
* A config file that stores usernames for an org.
*
* @extends ConfigFile
*/

@@ -19,4 +17,3 @@ class OrgUsersConfig extends configFile_1.ConfigFile {

* Gets the config options for a given org ID.
* @param {string} orgId The orgId. Generally this org would have multiple users configured.
* @return {ConfigOptions} The ConfigOptions.
* @param orgId The orgId. Generally this org would have multiple users configured.
*/

@@ -31,2 +28,8 @@ static getOptions(orgId) {

}
/**
* Constructor.
* **Do not directly construct instances of this class -- use {@link OrgUsersConfig.create} instead.**
* @param options The options for the class instance
* @ignore
*/
constructor(options) {

@@ -33,0 +36,0 @@ super(options);

@@ -19,5 +19,4 @@ import { JsonCollection, JsonMap, Optional } from '@salesforce/ts-types';

* fetch size is 10,000 records. Modify this via the options argument.
* @param {string} soql The SOQL string.
* @param {ExecuteOptions} options The query options. NOTE: the autoFetch option will always be true.
* @returns {Promise.<QueryResult<T>>}
* @param soql The SOQL string.
* @param options The query options. NOTE: the autoFetch option will always be true.
*/

@@ -28,5 +27,4 @@ autoFetchQuery<T>(soql: string, options?: ExecuteOptions): Promise<QueryResult<T>>;

* Handles connections and requests to Salesforce Orgs.
* @extends jsforce.Connection
*
* @example
* ```
* // Uses latest API version

@@ -41,7 +39,15 @@ * const connection = await Connection.create({

* connection.query('SELECT Name from Account');
* ```
*/
export declare class Connection extends JSForceConnection {
/**
* Creates an instance of a Connection. Performs additional async initializations.
* @param options Constructor options.
*/
static create(this: {
new (options: Connection.Options): Connection;
}, options: Connection.Options): Promise<Connection>;
/**
* Tooling api reference.
*/
tooling: Tooling;

@@ -53,3 +59,12 @@ private logger;

private options;
/**
* Constructor
* **Do not directly construct instances of this class -- use {@link Connection.create} instead.**
* @param options The options for the class instance.
* @ignore
*/
constructor(options: Connection.Options);
/**
* Async initializer.
*/
init(): Promise<void>;

@@ -60,4 +75,2 @@ /**

*
* @override
*
* @param request HTTP request object or URL to GET request.

@@ -71,10 +84,7 @@ * @param options HTTP API request options.

*
* @override
*
* @param {RequestInfo | string} request HTTP request object or URL to GET request.
* @returns {Promise<JsonMap>} The request Promise.
* @param request HTTP request object or URL to GET request.
*/
requestRaw(request: RequestInfo): Promise<JsonMap>;
/**
* @returns {string} The Force API base url for the instance.
* The Force API base url for the instance.
*/

@@ -84,3 +94,2 @@ baseUrl(): string;

* Retrieves the highest api version that is supported by the target server instance.
* @returns {Promise<string>} The max API version number. i.e 46.0
*/

@@ -94,3 +103,2 @@ retrieveMaxApiVersion(): Promise<string>;

* Get the API version used for all connection requests.
* @returns {string}
*/

@@ -100,15 +108,17 @@ getApiVersion(): string;

* Set the API version for all connection requests.
* @param {string} version The API version.
* @throws {SfdxError} **`{name: 'IncorrectAPIVersion'}`:** Incorrect API version.
*
* **Throws** *{@link SfdxError}{ name: 'IncorrectAPIVersion' }* Incorrect API version.
* @param version The API version.
*/
setApiVersion(version: string): void;
/**
* Getter for the AuthInfo
* @returns {AuthInfo} A cloned authInfo.
* Getter for the AuthInfo.
*/
getAuthInfoFields(): AuthFields;
/**
* Getter for the auth fields.
*/
getConnectionOptions(): AuthFields;
/**
* Getter for the username of the Salesforce Org
* @returns {Optional<string>}
* Getter for the username of the Salesforce Org.
*/

@@ -118,3 +128,2 @@ getUsername(): Optional<string>;

* Returns true if this connection is using access token auth.
* @returns {boolean}
*/

@@ -124,3 +133,3 @@ isUsingAccessToken(): boolean;

* Normalize a Salesforce url to include a instance information.
* @param url {string} partial url.
* @param url Partial url.
*/

@@ -131,6 +140,5 @@ normalizeUrl(url: string): string;

* useful with large query result sizes, such as over 2000 records. The default maximum
* fetch size is 10,000 records. Modify this via the options argument.
* @param {string} soql The SOQL string.
* @param {ExecuteOptions} options The query options. NOTE: the autoFetch option will always be true.
* @returns {Promise<QueryResult<T>>}
* fetch size is 10,000 records. Modify this via the options argument.
* @param soql The SOQL string.
* @param options The query options. NOTE: the autoFetch option will always be true.
*/

@@ -141,9 +149,18 @@ autoFetchQuery<T>(soql: string, options?: ExecuteOptions): Promise<QueryResult<T>>;

/**
* Connection Options
* Connection Options.
*/
interface Options {
/**
* AuthInfo instance.
*/
authInfo: AuthInfo;
/**
* ConfigAggregator for getting defaults.
*/
configAggregator?: ConfigAggregator;
/**
* Additional connection parameters.
*/
connectionOptions?: ConnectionOptions;
}
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -9,2 +8,3 @@ * Copyright (c) 2018, salesforce.com, inc.

*/
Object.defineProperty(exports, "__esModule", { value: true });
const kit_1 = require("@salesforce/kit");

@@ -31,5 +31,4 @@ const ts_types_1 = require("@salesforce/ts-types");

* Handles connections and requests to Salesforce Orgs.
* @extends jsforce.Connection
*
* @example
* ```
* // Uses latest API version

@@ -44,4 +43,9 @@ * const connection = await Connection.create({

* connection.query('SELECT Name from Account');
* ```
*/
class Connection extends jsforce_1.Connection {
/**
* Creates an instance of a Connection. Performs additional async initializations.
* @param options Constructor options.
*/
static async create(options) {

@@ -67,2 +71,8 @@ const _aggregator = options.configAggregator || (await configAggregator_1.ConfigAggregator.create());

}
/**
* Constructor
* **Do not directly construct instances of this class -- use {@link Connection.create} instead.**
* @param options The options for the class instance.
* @ignore
*/
constructor(options) {

@@ -73,2 +83,5 @@ super(options.connectionOptions || {});

}
/**
* Async initializer.
*/
async init() {

@@ -81,4 +94,2 @@ this.logger = this._logger = this.tooling._logger = await logger_1.Logger.child('connection');

*
* @override
*
* @param request HTTP request object or URL to GET request.

@@ -98,6 +109,3 @@ * @param options HTTP API request options.

*
* @override
*
* @param {RequestInfo | string} request HTTP request object or URL to GET request.
* @returns {Promise<JsonMap>} The request Promise.
* @param request HTTP request object or URL to GET request.
*/

@@ -115,3 +123,3 @@ async requestRaw(request) {

/**
* @returns {string} The Force API base url for the instance.
* The Force API base url for the instance.
*/

@@ -124,3 +132,2 @@ baseUrl() {

* Retrieves the highest api version that is supported by the target server instance.
* @returns {Promise<string>} The max API version number. i.e 46.0
*/

@@ -147,3 +154,2 @@ async retrieveMaxApiVersion() {

* Get the API version used for all connection requests.
* @returns {string}
*/

@@ -155,7 +161,8 @@ getApiVersion() {

* Set the API version for all connection requests.
* @param {string} version The API version.
* @throws {SfdxError} **`{name: 'IncorrectAPIVersion'}`:** Incorrect API version.
*
* **Throws** *{@link SfdxError}{ name: 'IncorrectAPIVersion' }* Incorrect API version.
* @param version The API version.
*/
setApiVersion(version) {
if (!sfdc_1.validateApiVersion(version)) {
if (!sfdc_1.sfdc.validateApiVersion(version)) {
throw new sfdxError_1.SfdxError(`Invalid API version ${version}. Expecting format "[1-9][0-9].0", i.e. 42.0`, 'IncorrectAPIVersion');

@@ -166,4 +173,3 @@ }

/**
* Getter for the AuthInfo
* @returns {AuthInfo} A cloned authInfo.
* Getter for the AuthInfo.
*/

@@ -173,2 +179,5 @@ getAuthInfoFields() {

}
/**
* Getter for the auth fields.
*/
getConnectionOptions() {

@@ -178,4 +187,3 @@ return this.options.authInfo.getConnectionOptions();

/**
* Getter for the username of the Salesforce Org
* @returns {Optional<string>}
* Getter for the username of the Salesforce Org.
*/

@@ -187,3 +195,2 @@ getUsername() {

* Returns true if this connection is using access token auth.
* @returns {boolean}
*/

@@ -195,3 +202,3 @@ isUsingAccessToken() {

* Normalize a Salesforce url to include a instance information.
* @param url {string} partial url.
* @param url Partial url.
*/

@@ -204,6 +211,5 @@ normalizeUrl(url) {

* useful with large query result sizes, such as over 2000 records. The default maximum
* fetch size is 10,000 records. Modify this via the options argument.
* @param {string} soql The SOQL string.
* @param {ExecuteOptions} options The query options. NOTE: the autoFetch option will always be true.
* @returns {Promise<QueryResult<T>>}
* fetch size is 10,000 records. Modify this via the options argument.
* @param soql The SOQL string.
* @param options The query options. NOTE: the autoFetch option will always be true.
*/

@@ -210,0 +216,0 @@ async autoFetchQuery(soql, options = {}) {

@@ -10,2 +10,5 @@ import { AsyncOptionalCreatable } from '@salesforce/kit';

}
/**
* Class for managing encrypting and decrypting private auth information.
*/
export declare class Crypto extends AsyncOptionalCreatable<CryptoOptions> {

@@ -17,2 +20,5 @@ private _key;

/**
* Constructor
* **Do not directly construct instances of this class -- use {@link Crypto.create} instead.**
* @param options The options for the class instance.
* @ignore

@@ -22,6 +28,4 @@ */

/**
* Encrypts text.
*
* @param {string} [text] The text to encrypt.
* @returns {Optional<string>} The encrypted string or undefined if no string was passed.
* Encrypts text. Returns the encrypted string or undefined if no string was passed.
* @param text The text to encrypt.
*/

@@ -31,8 +35,12 @@ encrypt(text?: string): Optional<string>;

* Decrypts text.
* @param {string} [text] The text to decrypt.
* @returns {Optional<string>} If enableTokenEncryption is set to false or not defined in package.json then the text
* is simply returned. The text is then assumed to be unencrypted.
* @param text The text to decrypt.
*/
decrypt(text?: string): Optional<string>;
/**
* Clears the crypto state. This should be called in a finally block.
*/
close(): void;
/**
* Initialize async components.
*/
protected init(): Promise<void>;

@@ -39,0 +47,0 @@ private getKeyChain;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -9,2 +8,3 @@ * Copyright (c) 2018, salesforce.com, inc.

*/
Object.defineProperty(exports, "__esModule", { value: true });
const kit_1 = require("@salesforce/kit");

@@ -28,4 +28,2 @@ const ts_types_1 = require("@salesforce/ts-types");

* osxKeyChain promise wrapper.
* @type {{get: KeychainPromises.get, set: KeychainPromises.set}}
* @private
*/

@@ -59,4 +57,10 @@ const keychainPromises = {

};
/**
* Class for managing encrypting and decrypting private auth information.
*/
class Crypto extends kit_1.AsyncOptionalCreatable {
/**
* Constructor
* **Do not directly construct instances of this class -- use {@link Crypto.create} instead.**
* @param options The options for the class instance.
* @ignore

@@ -70,6 +74,4 @@ */

/**
* Encrypts text.
*
* @param {string} [text] The text to encrypt.
* @returns {Optional<string>} The encrypted string or undefined if no string was passed.
* Encrypts text. Returns the encrypted string or undefined if no string was passed.
* @param text The text to encrypt.
*/

@@ -95,5 +97,3 @@ encrypt(text) {

* Decrypts text.
* @param {string} [text] The text to decrypt.
* @returns {Optional<string>} If enableTokenEncryption is set to false or not defined in package.json then the text
* is simply returned. The text is then assumed to be unencrypted.
* @param text The text to decrypt.
*/

@@ -128,2 +128,5 @@ decrypt(text) {

}
/**
* Clears the crypto state. This should be called in a finally block.
*/
close() {

@@ -134,2 +137,5 @@ if (!this.noResetOnClose) {

}
/**
* Initialize async components.
*/
async init() {

@@ -136,0 +142,0 @@ const logger = await logger_1.Logger.child('crypto');

@@ -7,4 +7,4 @@ export { Aliases, AliasGroup } from './config/aliases';

export { OrgUsersConfig } from './config/orgUsersConfig';
export { ConfigPropertyMeta, ConfigPropertyMetaInput, ORG_DEFAULT, Config } from './config/config';
export { ConfigInfo, Location, ConfigAggregator } from './config/configAggregator';
export { ConfigPropertyMeta, ConfigPropertyMetaInput, Config } from './config/config';
export { ConfigInfo, ConfigAggregator } from './config/configAggregator';
export { AuthFields, AuthInfo, SfdcUrl } from './authInfo';

@@ -15,6 +15,6 @@ export { Connection, SFDX_HTTP_HEADERS } from './connection';

export { Messages } from './messages';
export { Org, OrgFields } from './org';
export { Org } from './org';
export { SfdxProject, SfdxProjectJson } from './sfdxProject';
export { SchemaPrinter } from './schemaPrinter';
export { SchemaValidator } from './schemaValidator';
export { SchemaPrinter } from './schema/printer';
export { SchemaValidator } from './schema/validator';
export { SfdxError, SfdxErrorConfig } from './sfdxError';

@@ -26,5 +26,3 @@ export { StatusResult } from './status/client';

export { DefaultUserFields, REQUIRED_FIELDS, User, UserFields } from './user';
import * as fs from './util/fs';
export { fs };
import * as sfdc from './util/sfdc';
export { sfdc };
export * from './util/fs';
export * from './util/sfdc';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -9,2 +8,6 @@ * Copyright (c) 2018, salesforce.com, inc.

*/
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const messages_1 = require("./messages");

@@ -26,3 +29,2 @@ messages_1.Messages.importMessagesDirectory(__dirname);

var config_1 = require("./config/config");
exports.ORG_DEFAULT = config_1.ORG_DEFAULT;
exports.Config = config_1.Config;

@@ -47,10 +49,9 @@ var configAggregator_1 = require("./config/configAggregator");

exports.Org = org_1.Org;
exports.OrgFields = org_1.OrgFields;
var sfdxProject_1 = require("./sfdxProject");
exports.SfdxProject = sfdxProject_1.SfdxProject;
exports.SfdxProjectJson = sfdxProject_1.SfdxProjectJson;
var schemaPrinter_1 = require("./schemaPrinter");
exports.SchemaPrinter = schemaPrinter_1.SchemaPrinter;
var schemaValidator_1 = require("./schemaValidator");
exports.SchemaValidator = schemaValidator_1.SchemaValidator;
var printer_1 = require("./schema/printer");
exports.SchemaPrinter = printer_1.SchemaPrinter;
var validator_1 = require("./schema/validator");
exports.SchemaValidator = validator_1.SchemaValidator;
var sfdxError_1 = require("./sfdxError");

@@ -71,6 +72,4 @@ exports.SfdxError = sfdxError_1.SfdxError;

// Utility sub-modules
const fs = require("./util/fs");
exports.fs = fs;
const sfdc = require("./util/sfdc");
exports.sfdc = sfdc;
__export(require("./util/fs"));
__export(require("./util/sfdc"));
//# sourceMappingURL=exported.js.map

@@ -6,7 +6,2 @@ /**

* To set the mode, `export SFDX_ENV=<mode>` in your current environment.
* @typedef Mode
* @property {string} PRODUCTION
* @property {string} DEVELOPMENT
* @property {string} DEMO
* @property {string} TEST
*/

@@ -30,3 +25,3 @@ export declare enum Mode {

*
* @see Global.STATE_FOLDER
* **See** {@link Global.STATE_FOLDER}
*/

@@ -41,6 +36,5 @@ static readonly DIR: string;

*
* @example
* ```
* console.log(Global.getEnvironmentMode() === Mode.PRODUCTION);
*
* @returns {Mode}
* ```
*/

@@ -50,8 +44,7 @@ static getEnvironmentMode(): Mode;

* Creates a directory within {@link Global.DIR}, or {@link Global.DIR} itself if the `dirPath` param
* is not provided.
* is not provided. This is resolved or rejected when the directory creation operation has completed.
*
* @param {string} [dirPath] The directory path to be created within {@link Global.DIR}.
* @returns {Promise<void>} Resolved or rejected when the directory creation operation has completed.
* @param dirPath The directory path to be created within {@link Global.DIR}.
*/
static createDir(dirPath?: string): Promise<void>;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -9,6 +8,7 @@ * Copyright (c) 2018, salesforce.com, inc.

*/
Object.defineProperty(exports, "__esModule", { value: true });
const kit_1 = require("@salesforce/kit");
const os = require("os");
const path = require("path");
const fs = require("./util/fs");
const fs_1 = require("./util/fs");
/**

@@ -19,7 +19,2 @@ * Represents an environment mode. Supports `production`, `development`, `demo`, and `test`

* To set the mode, `export SFDX_ENV=<mode>` in your current environment.
* @typedef Mode
* @property {string} PRODUCTION
* @property {string} DEVELOPMENT
* @property {string} DEMO
* @property {string} TEST
*/

@@ -40,6 +35,5 @@ var Mode;

*
* @example
* ```
* console.log(Global.getEnvironmentMode() === Mode.PRODUCTION);
*
* @returns {Mode}
* ```
*/

@@ -51,10 +45,9 @@ static getEnvironmentMode() {

* Creates a directory within {@link Global.DIR}, or {@link Global.DIR} itself if the `dirPath` param
* is not provided.
* is not provided. This is resolved or rejected when the directory creation operation has completed.
*
* @param {string} [dirPath] The directory path to be created within {@link Global.DIR}.
* @returns {Promise<void>} Resolved or rejected when the directory creation operation has completed.
* @param dirPath The directory path to be created within {@link Global.DIR}.
*/
static async createDir(dirPath) {
dirPath = dirPath ? path.join(Global.DIR, dirPath) : Global.DIR;
await fs.mkdirp(dirPath, fs.DEFAULT_USER_DIR_MODE);
await fs_1.fs.mkdirp(dirPath, fs_1.fs.DEFAULT_USER_DIR_MODE);
}

@@ -69,3 +62,3 @@ }

*
* @see Global.STATE_FOLDER
* **See** {@link Global.STATE_FOLDER}
*/

@@ -72,0 +65,0 @@ Global.DIR = path.join(os.homedir(), Global.STATE_FOLDER);

@@ -5,5 +5,4 @@ import { KeyChain } from './keyChainImpl';

* @param platform The os platform.
* @returns {Promise<any>} The keychain impl.
* @private
* @ignore
*/
export declare const retrieveKeychain: (platform: string) => Promise<KeyChain>;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -9,2 +8,3 @@ * Copyright (c) 2018, salesforce.com, inc.

*/
Object.defineProperty(exports, "__esModule", { value: true });
const kit_1 = require("@salesforce/kit");

@@ -17,4 +17,3 @@ const keyChainImpl_1 = require("./keyChainImpl");

* @param platform The os platform.
* @returns {Promise<any>} The keychain impl.
* @private
* @ignore
*/

@@ -21,0 +20,0 @@ exports.retrieveKeychain = async (platform) => {

@@ -6,4 +6,18 @@ /// <reference types="node" />

export declare type FsIfc = Pick<typeof nodeFs, 'statSync'>;
/**
* Basic keychain interface.
*/
export interface PasswordStore {
/**
* Gets a password
* @param opts cli level password options.
* @param fn function callback for password.
* @param retryCount number of reties to get the password.
*/
getPassword(opts: ProgramOpts, fn: (error: Nullable<Error>, password?: string) => void, retryCount?: number): Promise<void>;
/**
* Sets a password.
* @param opts cli level password options.
* @param fn function callback for password.
*/
setPassword(opts: ProgramOpts, fn: (error: Nullable<Error>, password?: string) => void): Promise<void>;

@@ -19,7 +33,9 @@ }

* Abstract prototype for general cross platform keychain interaction.
* @param osImpl The platform impl for (linux, darwin, windows)
* @param fsIfc The file system interface
* @constructor
* @param osImpl The platform impl for (linux, darwin, windows).
* @param fsIfc The file system interface.
*/
constructor(osImpl: OsImpl, fsIfc: FsIfc);
/**
* Validates the os level program is executable.
*/
validateProgram(): Promise<void>;

@@ -55,3 +71,3 @@ /**

/**
* @private
* @@ignore
*/

@@ -64,3 +80,3 @@ export declare class GenericKeychainAccess implements PasswordStore {

/**
* @private
* @ignore
*/

@@ -71,3 +87,3 @@ export declare class GenericUnixKeychainAccess extends GenericKeychainAccess {

/**
* @private
* @ignore
*/

@@ -77,3 +93,3 @@ export declare class GenericWindowsKeychainAccess extends GenericKeychainAccess {

/**
* @private
* @ignore
*/

@@ -80,0 +96,0 @@ export declare const keyChainImpl: {

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -9,2 +8,3 @@ * Copyright (c) 2018, salesforce.com, inc.

*/
Object.defineProperty(exports, "__esModule", { value: true });
const ts_types_1 = require("@salesforce/ts-types");

@@ -19,3 +19,3 @@ const childProcess = require("child_process");

const sfdxError_1 = require("./sfdxError");
const fs = require("./util/fs");
const fs_1 = require("./util/fs");
/* tslint:disable: no-bitwise */

@@ -26,3 +26,2 @@ const GET_PASSWORD_RETRY_COUNT = 3;

* @param optionsArray CLI command args.
* @private
*/

@@ -33,8 +32,7 @@ function _optionsToString(optionsArray) {

/**
* Helper to determine if a program is executable
* Helper to determine if a program is executable. Returns `true` if the program is executable for the user. For
* Windows true is always returned.
* @param mode Stats mode.
* @param gid Unix group id.
* @param uid Unix user id.
* @returns {boolean} `true` if the program is executable for the user. For Windows true is always returned.
* @private
*/

@@ -46,5 +44,3 @@ const _isExe = (mode, gid, uid) => {

return Boolean(mode & parseInt('0001', 8) ||
(mode & parseInt('0010', 8) &&
process.getgid &&
gid === process.getgid()) ||
(mode & parseInt('0010', 8) && process.getgid && gid === process.getgid()) ||
(mode & parseInt('0100', 8) && process.getuid && uid === process.getuid()));

@@ -54,6 +50,10 @@ };

* Private helper to validate that a program exists on the file system and is executable.
*
* **Throws** *{@link SfdxError}{ name: 'MissingCredentialProgramError' }* When the OS credential program isn't found.
*
* **Throws** *{@link SfdxError}{ name: 'CredentialProgramAccessError' }* When the OS credential program isn't accessible.
*
* @param programPath The absolute path of the program.
* @param fsIfc The file system interface.
* @param isExeIfc Executable validation function.
* @private
*/

@@ -79,5 +79,4 @@ const _validateProgram = async (programPath, fsIfc, isExeIfc) => {

* Abstract prototype for general cross platform keychain interaction.
* @param osImpl The platform impl for (linux, darwin, windows)
* @param fsIfc The file system interface
* @constructor
* @param osImpl The platform impl for (linux, darwin, windows).
* @param fsIfc The file system interface.
*/

@@ -88,2 +87,5 @@ constructor(osImpl, fsIfc) {

}
/**
* Validates the os level program is executable.
*/
async validateProgram() {

@@ -173,9 +175,6 @@ await _validateProgram(this.osImpl.getProgram(), this.fsIfc, _isExe);

* Uses libsecret.
*
* @private
*/
const _linuxImpl = {
getProgram() {
return (process.env.SFDX_SECRET_TOOL_PATH ||
path.join(path.sep, 'usr', 'bin', 'secret-tool'));
return process.env.SFDX_SECRET_TOOL_PATH || path.join(path.sep, 'usr', 'bin', 'secret-tool');
},

@@ -195,4 +194,3 @@ getProgramOptions(opts) {

// Calling secret-tool too fast can cause it to return an unexpected error. (below)
if (stderr != null &&
stderr.includes('invalid or unencryptable secret')) {
if (stderr != null && stderr.includes('invalid or unencryptable secret')) {
// @ts-ignore TODO: make an error subclass with this field

@@ -211,10 +209,3 @@ error.retry = true;

setProgramOptions(opts) {
return [
'store',
"--label='salesforce.com'",
'user',
opts.account,
'domain',
opts.service
];
return ['store', "--label='salesforce.com'", 'user', opts.account, 'domain', opts.service];
},

@@ -241,4 +232,2 @@ setCommandFunc(opts, fn) {

* /usr/bin/security is a cli front end for OSX keychain.
*
* @private
*/

@@ -250,10 +239,3 @@ const _darwinImpl = {

getProgramOptions(opts) {
return [
'find-generic-password',
'-a',
opts.account,
'-s',
opts.service,
'-g'
];
return ['find-generic-password', '-a', opts.account, '-s', opts.service, '-g'];
},

@@ -297,9 +279,3 @@ getCommandFunc(opts, fn) {

setProgramOptions(opts) {
const result = [
'add-generic-password',
'-a',
opts.account,
'-s',
opts.service
];
const result = ['add-generic-password', '-a', opts.account, '-s', opts.service];
if (opts.password) {

@@ -343,6 +319,6 @@ result.push('-w', opts.password);

})(SecretField || (SecretField = {}));
// istanbul ignore next - getPassword/setPassword is always mocked out
/**
* @private
* @@ignore
*/
// istanbul ignore next - getPassword/setPassword is always mocked out
class GenericKeychainAccess {

@@ -355,9 +331,7 @@ async getPassword(opts, fn) {

// read it's contents
return keychainConfig_1.KeychainConfig.retrieve()
return keychainConfig_1.KeychainConfig.create(keychainConfig_1.KeychainConfig.getDefaultOptions())
.then((config) => {
// validate service name and account just because
if (opts.service === config.get(SecretField.SERVICE) &&
opts.account === config.get(SecretField.ACCOUNT)) {
if (opts.service === config.get(SecretField.SERVICE) && opts.account === config.get(SecretField.ACCOUNT)) {
const key = config.get(SecretField.KEY);
// @ts-ignore TODO: Remove this ignore if we ever factor out `object` from `ConfigValue`
fn(null, ts_types_1.asString(key));

@@ -410,3 +384,3 @@ }

const root = await configFile_1.ConfigFile.resolveRootFolder(true);
await fs.access(path.join(root, global_1.Global.STATE_FOLDER), fs.constants.R_OK | fs.constants.X_OK | fs.constants.W_OK);
await fs_1.fs.access(path.join(root, global_1.Global.STATE_FOLDER), fs_1.fs.constants.R_OK | fs_1.fs.constants.X_OK | fs_1.fs.constants.W_OK);
await cb(null);

@@ -421,3 +395,3 @@ }

/**
* @private
* @ignore
*/

@@ -450,3 +424,3 @@ // istanbul ignore next - getPassword/setPassword is always mocked out

/**
* @private
* @ignore
*/

@@ -457,3 +431,3 @@ class GenericWindowsKeychainAccess extends GenericKeychainAccess {

/**
* @private
* @ignore
*/

@@ -460,0 +434,0 @@ exports.keyChainImpl = {

@@ -0,86 +1,51 @@

/// <reference types="node" />
import { Writable } from 'stream';
/**
* A Bunyan `Serializer` function.
*
* @callback Serializer
* @param {any} input The input to be serialized.
* @returns {any} The serialized input.
*
* @see {@link https://github.com/cwallsfdc/node-bunyan#serializers|Bunyan Serializers API}
* @param input The input to be serialized.
* **See** {@link https://github.com/cwallsfdc/node-bunyan#serializers|Bunyan Serializers API}
*/
export declare type Serializer = (input: any) => any;
/**
* A collection of named `Serializer`s.
*
* @typedef {Object<string, Serializer>} Serializers
*
* @see {@link https://github.com/cwallsfdc/node-bunyan#serializers|Bunyan Serializers API}
* **See** {@link https://github.com/cwallsfdc/node-bunyan#serializers|Bunyan Serializers API}
*/
export interface Serializers {
[key: string]: Serializer;
}
/**
* The common set of `Logger` options.
*
* @typedef LoggerOptions
* @property {string} name The logger name.
* @property {Serializers} [serializers] The logger's serializers.
* @property {boolean} [src] Whether or not to log source file, line, and function information.
* @property {LoggerLevelValue} [level] The desired log level.
* @property {Writable} [stream] A stream to write to.
* @property {LoggerStream} [streams] An array of streams to write to.
*
* @see {@link https://github.com/cwallsfdc/node-bunyan#constructor-api|Bunyan Constructor API}
*/
/**
* Standard `Logger` levels.
*
* @typedef {number} LoggerLevel
* @property TRACE
* @property DEBUG
* @property INFO
* @property WARN
* @property ERROR
* @property FATAL
*
* @see {@link https://github.com/cwallsfdc/node-bunyan#levels|Bunyan Levels}
*/
/**
* A Bunyan stream configuration.
*
* @typedef LoggerStream
* @property {type} [type] The type of stream -- may be inferred from other properties.
* @property {level} [level] The desired log level for the stream.
* @property {stream} [stream] The stream to write to. Mutually exclusive with `path`.
* @property {path} [path] A log file path to write to. Mutually exclusive with `stream`.
* @property {name} [name] The name of the stream.
* @property {any} [extras] Additional type-specific configuration parameters.
*
* @see {@link https://github.com/cwallsfdc/node-bunyan#streams|Bunyan Streams}
*/
/**
* Any numeric `Logger` level.
*
* @typedef {LoggerLevel|number} LoggerLevelValue
*/
/**
* A collection of named `FieldValue`s.
*
* @typedef {Object<string, FieldValue>} Fields
* @see {@link https://github.com/cwallsfdc/node-bunyan#log-record-fields|Bunyan Log Record Fields}
*/
/**
* All possible field value types.
*
* @typedef {string|number|boolean} FieldValue
*/
/// <reference types="node" />
import { Writable } from 'stream';
export declare type Serializer = (input: any) => any;
export interface Serializers {
[key: string]: Serializer;
}
export interface LoggerOptions {
/**
* The logger name.
*/
name: string;
/**
* The logger's serializers.
*/
serializers?: Serializers;
/**
* Whether or not to log source file, line, and function information.
*/
src?: boolean;
/**
* The desired log level.
*/
level?: LoggerLevelValue;
/**
* A stream to write to.
*/
stream?: Writable;
/**
* An array of streams to write to.
*/
streams?: LoggerStream[];
}
/**
* Standard `Logger` levels.
*
* **See** {@link https://github.com/cwallsfdc/node-bunyan#levels|Bunyan Levels}
*/
export declare enum LoggerLevel {

@@ -94,15 +59,49 @@ TRACE = 10,

}
/**
* A Bunyan stream configuration.
*
* @see {@link https://github.com/cwallsfdc/node-bunyan#streams|Bunyan Streams}
*/
export interface LoggerStream {
/**
* The type of stream -- may be inferred from other properties.
*/
type?: string;
/**
* The desired log level for the stream.
*/
level?: LoggerLevelValue;
/**
* The stream to write to. Mutually exclusive with `path`.
*/
stream?: Writable;
/**
* The name of the stream.
*/
name?: string;
/**
* A log file path to write to. Mutually exclusive with `stream`.
*/
path?: string;
[key: string]: any;
}
/**
* Any numeric `Logger` level.
*/
export declare type LoggerLevelValue = LoggerLevel | number;
/**
* A collection of named `FieldValue`s.
*
* **See** {@link https://github.com/cwallsfdc/node-bunyan#log-record-fields|Bunyan Log Record Fields}
*/
export interface Fields {
[key: string]: FieldValue;
}
/**
* All possible field value types.
*/
export declare type FieldValue = string | number | boolean;
/**
* Log line interface
*/
export interface LogLine {

@@ -122,17 +121,18 @@ name: string;

*
* @example
* ```
* // Gets the root sfdx logger
* const logger = await Logger.root();
* @example
*
* // Creates a child logger of the root sfdx logger with custom fields applied
* const childLogger = await Logger.child('myRootChild', {tag: 'value'});
* @example
*
* // Creates a custom logger unaffiliated with the root logger
* const myCustomLogger = new Logger('myCustomLogger');
* @example
*
* // Creates a child of a custom logger unaffiliated with the root logger with custom fields applied
* const myCustomChildLogger = myCustomLogger.child('myCustomChild', {tag: 'value'});
* ```
* **See** https://github.com/cwallsfdc/node-bunyan
*
* @see https://github.com/cwallsfdc/node-bunyan
* @see https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_log_messages.htm
* **See** https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_log_messages.htm
*/

@@ -142,5 +142,2 @@ export declare class Logger {

* The name of the root sfdx `Logger`.
*
* @type {string}
* @see Logger.root
*/

@@ -150,4 +147,2 @@ static readonly ROOT_NAME = "sfdx";

* The default `LoggerLevel` when constructing new `Logger` instances.
*
* @type {LoggerLevel}
*/

@@ -158,4 +153,3 @@ static readonly DEFAULT_LEVEL = LoggerLevel.WARN;

*
* @type {string[]}
* @see LoggerLevel
* **See** {@link LoggerLevel}
*/

@@ -165,4 +159,2 @@ static readonly LEVEL_NAMES: string[];

* Gets the root logger with the default level and file stream.
*
* @returns {Promise<Logger>}
*/

@@ -179,5 +171,4 @@ static root(): Promise<Logger>;

*
* @param {string} name The name of the child logger.
* @param {Fields} [fields] Additional fields included in all log lines.
* @returns {Promise<Logger>}
* @param name The name of the child logger.
* @param fields Additional fields included in all log lines.
*/

@@ -189,5 +180,5 @@ static child(name: string, fields?: Fields): Promise<Logger>;

* @param {string} levelName The level name to convert to a `LoggerLevel` enum value.
* @throws {SfdxError}
* **`{name: 'UnrecognizedLoggerLevelName'}`:** The level name was not case-insensitively recognized as a valid `LoggerLevel` value.
* @see LoggerLevel
*
* **Throws** *{@link SfdxError}{ name: 'UnrecognizedLoggerLevelName' }* The level name was not case-insensitively recognized as a valid `LoggerLevel` value.
* @see {@Link LoggerLevel}
*/

@@ -201,5 +192,6 @@ static getLevelByName(levelName: string): LoggerLevelValue;

*
* @param {LoggerOptions|string} optionsOrName A set of `LoggerOptions` or name to use with the default options.
* @throws {SfdxError}
* **`{name: 'RedundantRootLogger'}`:** More than one attempt is made to construct the root `Logger`.
* @param optionsOrName A set of `LoggerOptions` or name to use with the default options.
*
* **Throws** *{@link SfdxError}{ name: 'RedundantRootLogger' }* More than one attempt is made to construct the root
* `Logger`.
*/

@@ -210,11 +202,10 @@ constructor(optionsOrName: LoggerOptions | string);

*
* @param {LoggerStream} stream The stream configuration to add.
* @param {LoggerLevelValue} [defaultLevel] The default level of the stream.
* @param stream The stream configuration to add.
* @param defaultLevel The default level of the stream.
*/
addStream(stream: LoggerStream, defaultLevel?: LoggerLevelValue): void;
/**
* Adds a file stream to this logger.
* Adds a file stream to this logger. Resolved or rejected upon completion of the addition.
*
* @param {string} logFile The path to the log file. If it doesn't exist it will be created.
* @returns {Promise<void>} Resolved or rejected upon completion of the addition.
* @param logFile The path to the log file. If it doesn't exist it will be created.
*/

@@ -224,4 +215,2 @@ addLogFileStream(logFile: string): Promise<void>;

* Gets the name of this logger.
*
* @returns {string}
*/

@@ -231,4 +220,2 @@ getName(): string;

* Gets the current level of this logger.
*
* @returns {LoggerLevelValue}
*/

@@ -239,18 +226,19 @@ getLevel(): LoggerLevelValue;

* attempt to read it from the environment variable `SFDX_LOG_LEVEL`, and if not found,
* {@link Logger.DEFAULT_LOG_LEVEL} will be used instead.
* {@link Logger.DEFAULT_LOG_LEVEL} will be used instead. For convenience `this` object is returned.
*
* @example
* @param {LoggerLevelValue} [level] The logger level.
*
* **Throws** *{@link SfdxError}{ name: 'UnrecognizedLoggerLevelName' }* A value of `level` read from `SFDX_LOG_LEVEL`
* was invalid.
*
* ```
* // Sets the level from the environment or default value
* logger.setLevel()
* @example
*
* // Set the level from the INFO enum
* logger.setLevel(LoggerLevel.INFO)
* @example
*
* // Sets the level case-insensitively from a string value
* logger.setLevel(Logger.getLevelByName('info'))
*
* @param {LoggerLevelValue} [level] The logger level.
* @returns {Logger} For convenience `this` object is returned.
* @throws {SfdxError}
* **`{name: 'UnrecognizedLoggerLevelName'}`:** A value of `level` read from `SFDX_LOG_LEVEL` was invalid.
* ```
*/

@@ -260,4 +248,2 @@ setLevel(level?: LoggerLevelValue): Logger;

* Gets the underlying Bunyan logger.
*
* @returns {any} The low-level Bunyan logger.
*/

@@ -269,4 +255,3 @@ getBunyanLogger(): any;

*
* @param {LoggerLevelValue} level The requested log level to compare against the currently set log level.
* @returns {boolean}
* @param level The requested log level to compare against the currently set log level.
*/

@@ -276,6 +261,5 @@ shouldLog(level: LoggerLevelValue): boolean;

* Use in-memory logging for this logger instance instead of any parent streams. Useful for testing.
* For convenience this object is returned.
*
* **WARNING: This cannot be undone for this logger instance.**
*
* @returns {Logger} For convenience this object is returned.
*/

@@ -285,4 +269,2 @@ useMemoryLogging(): Logger;

* Gets an array of log line objects. Each element is an object that corresponds to a log line.
*
* @returns {Array<string>}
*/

@@ -292,4 +274,2 @@ getBufferedRecords(): LogLine[];

* Reads a text blob of all the log lines contained in memory or the log file.
*
* @returns {string}
*/

@@ -300,3 +280,3 @@ readLogContentsAsText(): string;

*
* @param {function} filter A function with signature `(...args: any[]) => any[]` that transforms log message arguments.
* @param filter A function with signature `(...args: any[]) => any[]` that transforms log message arguments.
*/

@@ -307,3 +287,3 @@ addFilter(filter: (...args: Array<unknown>) => unknown): void;

*
* @param {function} [fn] A function with signature `(stream: LoggerStream) => void` to call for each stream with
* @param fn A function with signature `(stream: LoggerStream) => void` to call for each stream with
* the stream as an arg.

@@ -313,57 +293,49 @@ */

/**
* Create a child logger, typically to add a few log record fields.
* Create a child logger, typically to add a few log record fields. For convenience this object is returned.
*
* @param {string} name The name of the child logger that is emitted w/ log line as `log:<name>`.
* @param {Fields} [fields] Additional fields included in all log lines for the child logger.
* @returns {Logger} For convenience this object is returned.
* @param name The name of the child logger that is emitted w/ log line as `log:<name>`.
* @param fields Additional fields included in all log lines for the child logger.
*/
child(name: string, fields?: Fields): Logger;
/**
* Add a field to all log lines for this logger.
* Add a field to all log lines for this logger. For convenience `this` object is returned.
*
* @param {string} name The name of the field to add.
* @param {FieldValue} value The value of the field to be logged.
* @returns {Logger} For convenience `this` object is returned.
* @param name The name of the field to add.
* @param value The value of the field to be logged.
*/
addField(name: string, value: FieldValue): Logger;
/**
* Logs at `trace` level with filtering applied.
* Logs at `trace` level with filtering applied. For convenience `this` object is returned.
*
* @param {...any} args Any number of arguments to be logged.
* @returns {Logger} For convenience `this` object is returned.
* @param args Any number of arguments to be logged.
*/
trace(...args: any[]): Logger;
/**
* Logs at `debug` level with filtering applied.
* Logs at `debug` level with filtering applied. For convenience `this` object is returned.
*
* @param {...any} args Any number of arguments to be logged.
* @returns {Logger} For convenience `this` object is returned.
* @param args Any number of arguments to be logged.
*/
debug(...args: Array<unknown>): Logger;
/**
* Logs at `info` level with filtering applied.
* Logs at `info` level with filtering applied. For convenience `this` object is returned.
*
* @param {...any} args Any number of arguments to be logged.
* @returns {Logger} For convenience `this` object is returned.
* @param args Any number of arguments to be logged.
*/
info(...args: Array<unknown>): Logger;
/**
* Logs at `warn` level with filtering applied.
* Logs at `warn` level with filtering applied. For convenience `this` object is returned.
*
* @param {...any} args Any number of arguments to be logged.
* @returns {Logger} For convenience `this` object is returned.
* @param args Any number of arguments to be logged.
*/
warn(...args: Array<unknown>): Logger;
/**
* Logs at `error` level with filtering applied.
* Logs at `error` level with filtering applied. For convenience `this` object is returned.
*
* @param {...any} args Any number of arguments to be logged.
* @returns {Logger} For convenience `this` object is returned.
* @param args Any number of arguments to be logged.
*/
error(...args: Array<unknown>): Logger;
/**
* Logs at `fatal` level with filtering applied.
* Logs at `fatal` level with filtering applied. For convenience `this` object is returned.
*
* @param {...any} args Any number of arguments to be logged.
* @returns {Logger} For convenience `this` object is returned.
* @param args Any number of arguments to be logged.
*/

@@ -370,0 +342,0 @@ fatal(...args: Array<unknown>): Logger;

@@ -8,73 +8,2 @@ "use strict";

*/
/**
* A Bunyan `Serializer` function.
*
* @callback Serializer
* @param {any} input The input to be serialized.
* @returns {any} The serialized input.
*
* @see {@link https://github.com/cwallsfdc/node-bunyan#serializers|Bunyan Serializers API}
*/
/**
* A collection of named `Serializer`s.
*
* @typedef {Object<string, Serializer>} Serializers
*
* @see {@link https://github.com/cwallsfdc/node-bunyan#serializers|Bunyan Serializers API}
*/
/**
* The common set of `Logger` options.
*
* @typedef LoggerOptions
* @property {string} name The logger name.
* @property {Serializers} [serializers] The logger's serializers.
* @property {boolean} [src] Whether or not to log source file, line, and function information.
* @property {LoggerLevelValue} [level] The desired log level.
* @property {Writable} [stream] A stream to write to.
* @property {LoggerStream} [streams] An array of streams to write to.
*
* @see {@link https://github.com/cwallsfdc/node-bunyan#constructor-api|Bunyan Constructor API}
*/
/**
* Standard `Logger` levels.
*
* @typedef {number} LoggerLevel
* @property TRACE
* @property DEBUG
* @property INFO
* @property WARN
* @property ERROR
* @property FATAL
*
* @see {@link https://github.com/cwallsfdc/node-bunyan#levels|Bunyan Levels}
*/
/**
* A Bunyan stream configuration.
*
* @typedef LoggerStream
* @property {type} [type] The type of stream -- may be inferred from other properties.
* @property {level} [level] The desired log level for the stream.
* @property {stream} [stream] The stream to write to. Mutually exclusive with `path`.
* @property {path} [path] A log file path to write to. Mutually exclusive with `stream`.
* @property {name} [name] The name of the stream.
* @property {any} [extras] Additional type-specific configuration parameters.
*
* @see {@link https://github.com/cwallsfdc/node-bunyan#streams|Bunyan Streams}
*/
/**
* Any numeric `Logger` level.
*
* @typedef {LoggerLevel|number} LoggerLevelValue
*/
/**
* A collection of named `FieldValue`s.
*
* @typedef {Object<string, FieldValue>} Fields
* @see {@link https://github.com/cwallsfdc/node-bunyan#log-record-fields|Bunyan Log Record Fields}
*/
/**
* All possible field value types.
*
* @typedef {string|number|boolean} FieldValue
*/
Object.defineProperty(exports, "__esModule", { value: true });

@@ -93,3 +22,8 @@ // tslint:disable-next-line:ordered-imports

const sfdxError_1 = require("./sfdxError");
const fs = require("./util/fs");
const fs_1 = require("./util/fs");
/**
* Standard `Logger` levels.
*
* **See** {@link https://github.com/cwallsfdc/node-bunyan#levels|Bunyan Levels}
*/
var LoggerLevel;

@@ -108,17 +42,18 @@ (function (LoggerLevel) {

*
* @example
* ```
* // Gets the root sfdx logger
* const logger = await Logger.root();
* @example
*
* // Creates a child logger of the root sfdx logger with custom fields applied
* const childLogger = await Logger.child('myRootChild', {tag: 'value'});
* @example
*
* // Creates a custom logger unaffiliated with the root logger
* const myCustomLogger = new Logger('myCustomLogger');
* @example
*
* // Creates a child of a custom logger unaffiliated with the root logger with custom fields applied
* const myCustomChildLogger = myCustomLogger.child('myCustomChild', {tag: 'value'});
* ```
* **See** https://github.com/cwallsfdc/node-bunyan
*
* @see https://github.com/cwallsfdc/node-bunyan
* @see https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_log_messages.htm
* **See** https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_log_messages.htm
*/

@@ -129,5 +64,6 @@ class Logger {

*
* @param {LoggerOptions|string} optionsOrName A set of `LoggerOptions` or name to use with the default options.
* @throws {SfdxError}
* **`{name: 'RedundantRootLogger'}`:** More than one attempt is made to construct the root `Logger`.
* @param optionsOrName A set of `LoggerOptions` or name to use with the default options.
*
* **Throws** *{@link SfdxError}{ name: 'RedundantRootLogger' }* More than one attempt is made to construct the root
* `Logger`.
*/

@@ -173,4 +109,2 @@ constructor(optionsOrName) {

* Gets the root logger with the default level and file stream.
*
* @returns {Promise<Logger>}
*/

@@ -227,5 +161,4 @@ static async root() {

*
* @param {string} name The name of the child logger.
* @param {Fields} [fields] Additional fields included in all log lines.
* @returns {Promise<Logger>}
* @param name The name of the child logger.
* @param fields Additional fields included in all log lines.
*/

@@ -239,5 +172,5 @@ static async child(name, fields) {

* @param {string} levelName The level name to convert to a `LoggerLevel` enum value.
* @throws {SfdxError}
* **`{name: 'UnrecognizedLoggerLevelName'}`:** The level name was not case-insensitively recognized as a valid `LoggerLevel` value.
* @see LoggerLevel
*
* **Throws** *{@link SfdxError}{ name: 'UnrecognizedLoggerLevelName' }* The level name was not case-insensitively recognized as a valid `LoggerLevel` value.
* @see {@Link LoggerLevel}
*/

@@ -254,4 +187,4 @@ static getLevelByName(levelName) {

*
* @param {LoggerStream} stream The stream configuration to add.
* @param {LoggerLevelValue} [defaultLevel] The default level of the stream.
* @param stream The stream configuration to add.
* @param defaultLevel The default level of the stream.
*/

@@ -262,6 +195,5 @@ addStream(stream, defaultLevel) {

/**
* Adds a file stream to this logger.
* Adds a file stream to this logger. Resolved or rejected upon completion of the addition.
*
* @param {string} logFile The path to the log file. If it doesn't exist it will be created.
* @returns {Promise<void>} Resolved or rejected upon completion of the addition.
* @param logFile The path to the log file. If it doesn't exist it will be created.
*/

@@ -271,8 +203,8 @@ async addLogFileStream(logFile) {

// Check if we have write access to the log file (i.e., we created it already)
await fs.access(logFile, fs.constants.W_OK);
await fs_1.fs.access(logFile, fs_1.fs.constants.W_OK);
}
catch (err1) {
try {
await fs.mkdirp(path.dirname(logFile), {
mode: fs.DEFAULT_USER_DIR_MODE
await fs_1.fs.mkdirp(path.dirname(logFile), {
mode: fs_1.fs.DEFAULT_USER_DIR_MODE
});

@@ -284,3 +216,3 @@ }

try {
await fs.writeFile(logFile, '', { mode: fs.DEFAULT_USER_FILE_MODE });
await fs_1.fs.writeFile(logFile, '', { mode: fs_1.fs.DEFAULT_USER_FILE_MODE });
}

@@ -306,4 +238,2 @@ catch (err3) {

* Gets the name of this logger.
*
* @returns {string}
*/

@@ -315,4 +245,2 @@ getName() {

* Gets the current level of this logger.
*
* @returns {LoggerLevelValue}
*/

@@ -325,18 +253,19 @@ getLevel() {

* attempt to read it from the environment variable `SFDX_LOG_LEVEL`, and if not found,
* {@link Logger.DEFAULT_LOG_LEVEL} will be used instead.
* {@link Logger.DEFAULT_LOG_LEVEL} will be used instead. For convenience `this` object is returned.
*
* @example
* @param {LoggerLevelValue} [level] The logger level.
*
* **Throws** *{@link SfdxError}{ name: 'UnrecognizedLoggerLevelName' }* A value of `level` read from `SFDX_LOG_LEVEL`
* was invalid.
*
* ```
* // Sets the level from the environment or default value
* logger.setLevel()
* @example
*
* // Set the level from the INFO enum
* logger.setLevel(LoggerLevel.INFO)
* @example
*
* // Sets the level case-insensitively from a string value
* logger.setLevel(Logger.getLevelByName('info'))
*
* @param {LoggerLevelValue} [level] The logger level.
* @returns {Logger} For convenience `this` object is returned.
* @throws {SfdxError}
* **`{name: 'UnrecognizedLoggerLevelName'}`:** A value of `level` read from `SFDX_LOG_LEVEL` was invalid.
* ```
*/

@@ -352,4 +281,2 @@ setLevel(level) {

* Gets the underlying Bunyan logger.
*
* @returns {any} The low-level Bunyan logger.
*/

@@ -364,4 +291,3 @@ // tslint:disable-next-line:no-any

*
* @param {LoggerLevelValue} level The requested log level to compare against the currently set log level.
* @returns {boolean}
* @param level The requested log level to compare against the currently set log level.
*/

@@ -376,6 +302,5 @@ shouldLog(level) {

* Use in-memory logging for this logger instance instead of any parent streams. Useful for testing.
* For convenience this object is returned.
*
* **WARNING: This cannot be undone for this logger instance.**
*
* @returns {Logger} For convenience this object is returned.
*/

@@ -394,4 +319,2 @@ useMemoryLogging() {

* Gets an array of log line objects. Each element is an object that corresponds to a log line.
*
* @returns {Array<string>}
*/

@@ -406,4 +329,2 @@ getBufferedRecords() {

* Reads a text blob of all the log lines contained in memory or the log file.
*
* @returns {string}
*/

@@ -422,3 +343,3 @@ readLogContentsAsText() {

if (stream.type === 'file') {
content += await fs.readFile(stream.path, 'utf8');
content += await fs_1.fs.readFile(stream.path, 'utf8');
}

@@ -432,3 +353,3 @@ });

*
* @param {function} filter A function with signature `(...args: any[]) => any[]` that transforms log message arguments.
* @param filter A function with signature `(...args: any[]) => any[]` that transforms log message arguments.
*/

@@ -445,3 +366,3 @@ addFilter(filter) {

*
* @param {function} [fn] A function with signature `(stream: LoggerStream) => void` to call for each stream with
* @param fn A function with signature `(stream: LoggerStream) => void` to call for each stream with
* the stream as an arg.

@@ -469,7 +390,6 @@ */

/**
* Create a child logger, typically to add a few log record fields.
* Create a child logger, typically to add a few log record fields. For convenience this object is returned.
*
* @param {string} name The name of the child logger that is emitted w/ log line as `log:<name>`.
* @param {Fields} [fields] Additional fields included in all log lines for the child logger.
* @returns {Logger} For convenience this object is returned.
* @param name The name of the child logger that is emitted w/ log line as `log:<name>`.
* @param fields Additional fields included in all log lines for the child logger.
*/

@@ -490,7 +410,6 @@ child(name, fields = {}) {

/**
* Add a field to all log lines for this logger.
* Add a field to all log lines for this logger. For convenience `this` object is returned.
*
* @param {string} name The name of the field to add.
* @param {FieldValue} value The value of the field to be logged.
* @returns {Logger} For convenience `this` object is returned.
* @param name The name of the field to add.
* @param value The value of the field to be logged.
*/

@@ -502,6 +421,5 @@ addField(name, value) {

/**
* Logs at `trace` level with filtering applied.
* Logs at `trace` level with filtering applied. For convenience `this` object is returned.
*
* @param {...any} args Any number of arguments to be logged.
* @returns {Logger} For convenience `this` object is returned.
* @param args Any number of arguments to be logged.
*/

@@ -514,6 +432,5 @@ // tslint:disable-next-line:no-any

/**
* Logs at `debug` level with filtering applied.
* Logs at `debug` level with filtering applied. For convenience `this` object is returned.
*
* @param {...any} args Any number of arguments to be logged.
* @returns {Logger} For convenience `this` object is returned.
* @param args Any number of arguments to be logged.
*/

@@ -525,6 +442,5 @@ debug(...args) {

/**
* Logs at `info` level with filtering applied.
* Logs at `info` level with filtering applied. For convenience `this` object is returned.
*
* @param {...any} args Any number of arguments to be logged.
* @returns {Logger} For convenience `this` object is returned.
* @param args Any number of arguments to be logged.
*/

@@ -536,6 +452,5 @@ info(...args) {

/**
* Logs at `warn` level with filtering applied.
* Logs at `warn` level with filtering applied. For convenience `this` object is returned.
*
* @param {...any} args Any number of arguments to be logged.
* @returns {Logger} For convenience `this` object is returned.
* @param args Any number of arguments to be logged.
*/

@@ -547,6 +462,5 @@ warn(...args) {

/**
* Logs at `error` level with filtering applied.
* Logs at `error` level with filtering applied. For convenience `this` object is returned.
*
* @param {...any} args Any number of arguments to be logged.
* @returns {Logger} For convenience `this` object is returned.
* @param args Any number of arguments to be logged.
*/

@@ -558,6 +472,5 @@ error(...args) {

/**
* Logs at `fatal` level with filtering applied.
* Logs at `fatal` level with filtering applied. For convenience `this` object is returned.
*
* @param {...any} args Any number of arguments to be logged.
* @returns {Logger} For convenience `this` object is returned.
* @param args Any number of arguments to be logged.
*/

@@ -580,5 +493,2 @@ fatal(...args) {

* The name of the root sfdx `Logger`.
*
* @type {string}
* @see Logger.root
*/

@@ -588,4 +498,2 @@ Logger.ROOT_NAME = 'sfdx';

* The default `LoggerLevel` when constructing new `Logger` instances.
*
* @type {LoggerLevel}
*/

@@ -596,4 +504,3 @@ Logger.DEFAULT_LEVEL = LoggerLevel.WARN;

*
* @type {string[]}
* @see LoggerLevel
* **See** {@link LoggerLevel}
*/

@@ -600,0 +507,0 @@ Logger.LEVEL_NAMES = Object.values(LoggerLevel)

import { AnyJson } from '@salesforce/ts-types';
export declare type Tokens = Array<string | boolean | number | null | undefined>;
/**
* A loader function to return messages.
* @param locale The local set by the framework.
*/
export declare type LoaderFunction = (locale: string) => Messages;
/**
* The core message framework manages messages and allows them to be accessible by

@@ -33,3 +38,3 @@ * all plugins and consumers of sfdx-core. It is set up to handle localization down

*
* @example
* ```
* // Create loader functions for all files in the messages directory

@@ -44,7 +49,12 @@ * Messages.importMessagesDirectory(__dirname);

* messages.getMessage('JsonParseError');
*
* @hideconstructor
* ```
*/
export declare class Messages {
private messages;
/**
* Internal readFile. Exposed for unit testing. Do not use util/fs.readFile as messages.js
* should have no internal dependencies.
* @param filePath read file target.
* @ignore
*/
static _readFile: (filePath: string) => AnyJson;

@@ -54,18 +64,11 @@ /**

* machine's locale in the future.
* @returns {string}
*/
static getLocale(): string;
/**
* A loader function.
* @callback loaderFunction
* @param {string} locale The local set by the framework.
* @returns {Message} The messages.
*/
/**
* Set a custom loader function for a package and bundle that will be called on {@link Messages.loadMessages}.
* @param {string} packageName The npm package name.
* @param {string} bundle The name of the bundle.
* @param {loaderFunction} loader The loader function.
* @param packageName The npm package name.
* @param bundle The name of the bundle.
* @param loader The loader function.
*/
static setLoaderFunction(packageName: string, bundle: string, loader: (locale: string) => Messages): void;
static setLoaderFunction(packageName: string, bundle: string, loader: LoaderFunction): void;
/**

@@ -76,7 +79,6 @@ * Generate a file loading function. Use {@link Messages.importMessageFile} unless

*
* @param {string} bundle The name of the bundle.
* @param {string} filePath The messages file path.
* @returns {loaderFunction}
* @param bundleName The name of the bundle.
* @param filePath The messages file path.
*/
static generateFileLoaderFunction(bundleName: string, filePath: string): (locale: string) => Messages;
static generateFileLoaderFunction(bundleName: string, filePath: string): LoaderFunction;
/**

@@ -86,4 +88,4 @@ * Add a single message file to the list of loading functions using the file name as the bundle name.

*
* @param {string} packageName The npm package name.
* @param {string} filePath The path of the file.
* @param packageName The npm package name.
* @param filePath The path of the file.
*/

@@ -97,10 +99,11 @@ static importMessageFile(packageName: string, filePath: string): void;

*
* @example
* ```
* // e.g. If your message directory is in the project root, you would do:
* Messages.importMessagesDirectory(__dirname);
* ```
*
* @param {string} moduleDirectoryPath The path to load the messages folder.
* @param {boolean} [truncateToProjectPath=true] Will look for the messages directory in the project root (where the package.json file is located).
* @param moduleDirectoryPath The path to load the messages folder.
* @param truncateToProjectPath Will look for the messages directory in the project root (where the package.json file is located).
* i.e., the module is typescript and the messages folder is in the top level of the module directory.
* @param {string} [packageName] The npm package name. Figured out from the root directory's package.json.
* @param packageName The npm package name. Figured out from the root directory's package.json.
*/

@@ -112,5 +115,4 @@ static importMessagesDirectory(moduleDirectoryPath: string, truncateToProjectPath?: boolean, packageName?: string): void;

*
* @param {string} packageName The name of the npm package.
* @param {string} bundleName The name of the bundle to load.
* @returns {Messages}
* @param packageName The name of the npm package.
* @param bundleName The name of the bundle to load.
*/

@@ -120,4 +122,4 @@ static loadMessages(packageName: string, bundleName: string): Messages;

* Check if a bundle already been loaded.
* @param {string} packageName The npm package name.
* @param {string} bundleName The bundle name.
* @param packageName The npm package name.
* @param bundleName The bundle name.
*/

@@ -139,5 +141,5 @@ static isCached(packageName: string, bundleName: string): boolean;

* **Note:** Use {Messages.loadMessages} unless you are writing your own loader function.
* @param {string} bundleName The bundle name.
* @param {string} locale The locale.
* @param {Map<string, AnyJson>} messages The messages. Can not be modified once created.
* @param bundleName The bundle name.
* @param locale The locale.
* @param messages The messages. Can not be modified once created.
*/

@@ -147,6 +149,6 @@ constructor(bundleName: string, locale: string, messages: Map<string, AnyJson>);

* Get a message using a message key and use the tokens as values for tokenization.
* @param {string} key The key of the message.
* @param {Tokens} tokens The values to substitute in the message.
* @returns {string}
* @see https://nodejs.org/api/util.html#util_util_format_format_args
* @param key The key of the message.
* @param tokens The values to substitute in the message.
*
* **See** https://nodejs.org/api/util.html#util_util_format_format_args
*/

@@ -153,0 +155,0 @@ getMessage(key: string, tokens?: Tokens): string;

@@ -58,3 +58,3 @@ "use strict";

*
* @example
* ```
* // Create loader functions for all files in the messages directory

@@ -69,4 +69,3 @@ * Messages.importMessagesDirectory(__dirname);

* messages.getMessage('JsonParseError');
*
* @hideconstructor
* ```
*/

@@ -78,5 +77,5 @@ class Messages {

* **Note:** Use {Messages.loadMessages} unless you are writing your own loader function.
* @param {string} bundleName The bundle name.
* @param {string} locale The locale.
* @param {Map<string, AnyJson>} messages The messages. Can not be modified once created.
* @param bundleName The bundle name.
* @param locale The locale.
* @param messages The messages. Can not be modified once created.
*/

@@ -91,3 +90,2 @@ constructor(bundleName, locale, messages) {

* machine's locale in the future.
* @returns {string}
*/

@@ -98,12 +96,6 @@ static getLocale() {

/**
* A loader function.
* @callback loaderFunction
* @param {string} locale The local set by the framework.
* @returns {Message} The messages.
*/
/**
* Set a custom loader function for a package and bundle that will be called on {@link Messages.loadMessages}.
* @param {string} packageName The npm package name.
* @param {string} bundle The name of the bundle.
* @param {loaderFunction} loader The loader function.
* @param packageName The npm package name.
* @param bundle The name of the bundle.
* @param loader The loader function.
*/

@@ -118,5 +110,4 @@ static setLoaderFunction(packageName, bundle, loader) {

*
* @param {string} bundle The name of the bundle.
* @param {string} filePath The messages file path.
* @returns {loaderFunction}
* @param bundleName The name of the bundle.
* @param filePath The messages file path.
*/

@@ -126,3 +117,3 @@ static generateFileLoaderFunction(bundleName, filePath) {

// Anything can be returned by a js file, so stringify the results to ensure valid json is returned.
const fileContents = JSON.stringify(this._readFile(filePath));
const fileContents = JSON.stringify(Messages._readFile(filePath));
// If the file is empty, JSON.stringify will turn it into "" which will validate on parse, so throw.

@@ -159,4 +150,4 @@ if (!fileContents || fileContents === 'null' || fileContents === '""') {

*
* @param {string} packageName The npm package name.
* @param {string} filePath The path of the file.
* @param packageName The npm package name.
* @param filePath The path of the file.
*/

@@ -168,3 +159,3 @@ static importMessageFile(packageName, filePath) {

const bundleName = path.basename(filePath, path.extname(filePath));
if (!this.isCached(packageName, bundleName)) {
if (!Messages.isCached(packageName, bundleName)) {
this.setLoaderFunction(packageName, bundleName, Messages.generateFileLoaderFunction(bundleName, filePath));

@@ -179,10 +170,11 @@ }

*
* @example
* ```
* // e.g. If your message directory is in the project root, you would do:
* Messages.importMessagesDirectory(__dirname);
* ```
*
* @param {string} moduleDirectoryPath The path to load the messages folder.
* @param {boolean} [truncateToProjectPath=true] Will look for the messages directory in the project root (where the package.json file is located).
* @param moduleDirectoryPath The path to load the messages folder.
* @param truncateToProjectPath Will look for the messages directory in the project root (where the package.json file is located).
* i.e., the module is typescript and the messages folder is in the top level of the module directory.
* @param {string} [packageName] The npm package name. Figured out from the root directory's package.json.
* @param packageName The npm package name. Figured out from the root directory's package.json.
*/

@@ -212,3 +204,3 @@ static importMessagesDirectory(moduleDirectoryPath, truncateToProjectPath = true, packageName) {

try {
packageName = ts_types_1.asString(ts_types_1.ensureJsonMap(this._readFile(path.join(moduleMessagesDirPath, 'package.json'))).name);
packageName = ts_types_1.asString(ts_types_1.ensureJsonMap(Messages._readFile(path.join(moduleMessagesDirPath, 'package.json'))).name);
if (!packageName) {

@@ -241,5 +233,4 @@ throw new kit_1.NamedError('MissingPackageName', errMessage);

*
* @param {string} packageName The name of the npm package.
* @param {string} bundleName The name of the bundle to load.
* @returns {Messages}
* @param packageName The name of the npm package.
* @param bundleName The name of the bundle to load.
*/

@@ -268,4 +259,4 @@ static loadMessages(packageName, bundleName) {

* Check if a bundle already been loaded.
* @param {string} packageName The npm package name.
* @param {string} bundleName The bundle name.
* @param packageName The npm package name.
* @param bundleName The bundle name.
*/

@@ -277,6 +268,6 @@ static isCached(packageName, bundleName) {

* Get a message using a message key and use the tokens as values for tokenization.
* @param {string} key The key of the message.
* @param {Tokens} tokens The values to substitute in the message.
* @returns {string}
* @see https://nodejs.org/api/util.html#util_util_format_format_args
* @param key The key of the message.
* @param tokens The values to substitute in the message.
*
* **See** https://nodejs.org/api/util.html#util_util_format_format_args
*/

@@ -306,4 +297,8 @@ getMessage(key, tokens = []) {

}
// Internal readFile. Exposed for unit testing. Do not use util/fs.readFile as messages.js
// should have no internal dependencies.
/**
* Internal readFile. Exposed for unit testing. Do not use util/fs.readFile as messages.js
* should have no internal dependencies.
* @param filePath read file target.
* @ignore
*/
Messages._readFile = (filePath) => {

@@ -310,0 +305,0 @@ return require(filePath);

@@ -1,22 +0,1 @@

/**
* Org Fields.
* @typedef OrgFields
* @property {string} ALIAS The org alias.
* @property {string} CREATED_ORG_INSTANCE The Salesforce instance the org was created on. e.g. `cs42`.
* @property {string} DEV_HUB_USERNAME The username of the dev hub org that created this org. Only populated for scratch orgs.
* @property {string} INSTANCE_URL The full url of the instance the org lives on.
* @property {string} IS_DEV_HUB Is the current org a dev hub org. e.g. They have access to the `ScratchOrgInfo` object.
* @property {string} LOGIN_URL The login url of the org. e.g. `https://login.salesforce.com` or `https://test.salesforce.com`.
* @property {string} ORG_ID The org ID.
* @property {string} STATUS The `OrgStatus` of the org.
* @property {string} SNAPSHOT The snapshot used to create the scratch org.
*/
/**
* Scratch Org status.
* @typedef OrgStatus
* @property {string} ACTIVE The scratch org is active.
* @property {string} EXPIRED The scratch org has expired.
* @property {string} UNKNOWN The org is a scratch Org but no dev hub is indicated.
* @property {string} MISSING The dev hub configuration is reporting an active Scratch org but the AuthInfo cannot be found.
*/
import { AsyncCreatable } from '@salesforce/kit';

@@ -28,29 +7,14 @@ import { AnyJson, JsonMap, Optional } from '@salesforce/ts-types';

import { Connection } from './connection';
export declare enum OrgStatus {
ACTIVE = "ACTIVE",
EXPIRED = "EXPIRED",
UNKNOWN = "UNKNOWN",
MISSING = "MISSING"
}
export declare enum OrgFields {
ALIAS = "alias",
CREATED = "created",
CREATED_ORG_INSTANCE = "createdOrgInstance",
DEV_HUB_USERNAME = "devHubUsername",
INSTANCE_URL = "instanceUrl",
IS_DEV_HUB = "isDevHub",
LOGIN_URL = "loginUrl",
ORG_ID = "orgId",
STATUS = "status",
SNAPSHOT = "snapshot"
}
/**
* Provides a way to manage a locally authenticated Org.
*
* @see {@link AuthInfo}
* @see {@link Connection}
* @see {@link Aliases}
* @see {@link Config}
* **See** {@link AuthInfo}
*
* @example
* **See** {@link Connection}
*
* **See** {@link Aliases}
*
* **See** {@link Config}
*
* ```
* // Email username

@@ -64,4 +28,5 @@ * const org1: Org = await Org.create({ aliasOrUsername: 'foo@example.com' });//tslint:disable-line:no-unused-variable

* });
* ```
*
* @see https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_usernames_orgs.htm
* **See** https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_usernames_orgs.htm
*/

@@ -80,7 +45,9 @@ export declare class Org extends AsyncCreatable<Org.Options> {

* Clean all data files in the org's data path. Usually <workspace>/.sfdx/orgs/<username>.
* @param {string} [orgDataPath] A relative path other than "orgs/".
* @param orgDataPath A relative path other than "orgs/".
* @param throwWhenRemoveFails Should the remove org operations throw an error on failure?
* @returns {Promise<void>}
*/
cleanLocalOrgData(orgDataPath?: string, throwWhenRemoveFails?: boolean): Promise<void>;
/**
* @ignore
*/
retrieveOrgUsersConfig(): Promise<OrgUsersConfig>;

@@ -91,4 +58,3 @@ /**

* matching aliases.
* @param {boolean} [throwWhenRemoveFails = false] Determines if the call should throw an error or fail silently.
* @returns {Promise<void>}
* @param throwWhenRemoveFails Determines if the call should throw an error or fail silently.
*/

@@ -98,6 +64,8 @@ remove(throwWhenRemoveFails?: boolean): Promise<void>;

* Check that this org is a scratch org by asking the dev hub if it knows about it.
* @param {string} [devHubUsername] The username of the dev hub org.
* @returns {Promise<Config>}
* @throws {SfdxError} **`{name: 'NotADevHub'}`** Not a Dev Hub.
* @throws {SfdxError} **`{name: 'NoResults'}`** No results.
*
* **Throws** *{@link SfdxError}{ name: 'NotADevHub' }* Not a Dev Hub.
*
* **Throws** *{@link SfdxError}{ name: 'NoResults' }* No results.
*
* @param devHubUsername The username of the dev hub org.
*/

@@ -107,3 +75,2 @@ checkScratchOrg(devHubUsername?: string): Promise<Partial<AuthFields>>;

* Returns the Org object or null if this org is not affiliated with a Dev Hub (according to the local config).
* @returns {Promise<Org>}
*/

@@ -113,3 +80,2 @@ getDevHubOrg(): Promise<Optional<Org>>;

* Returns `true` if the org is a Dev Hub.
* @returns {Boolean}
*/

@@ -119,3 +85,2 @@ isDevHubOrg(): boolean;

* Refreshes the auth for this org's instance by calling HTTP GET on the baseUrl of the connection object.
* @returns {Promise<void>}
*/

@@ -125,20 +90,22 @@ refreshAuth(): Promise<void>;

* Reads and returns the content of all user auth files for this org as an array.
* @returns {Promise<AuthInfo[]>}
*/
readUserAuthFiles(): Promise<AuthInfo[]>;
/**
* Adds a username to the user config for this org.
* @param {AuthInfo | string} auth The AuthInfo for the username to add.
* @returns {Promise<Org>} For convenience `this` object is returned.
* @example
* Adds a username to the user config for this org. For convenience `this` object is returned.
*
* ```
* const org: Org = await Org.create(await Connection.create(await AuthInfo.create('foo@example.com')));
* const userAuth: AuthInfo = await AuthInfo.create('bar@example.com');
* await org.addUsername(userAuth);
* ```
*
* @param {AuthInfo | string} auth The AuthInfo for the username to add.
*/
addUsername(auth: AuthInfo | string): Promise<Org>;
/**
* Removes a username from the user config for this object.
* Removes a username from the user config for this object. For convenience `this` object is returned.
*
* **Throws** *{@link SfdxError}{ name: 'MissingAuthInfo' }* Auth info is missing.
*
* @param {AuthInfo | string} auth The AuthInfo containing the username to remove.
* @returns {Promise<Org>} For convenience `this` object is returned.
* @throws {SfdxError} **`{name: 'MissingAuthInfo'}`** Auth info is missing.
*/

@@ -150,3 +117,2 @@ removeUsername(auth: AuthInfo | string): Promise<Org>;

* results in a warning.
* @returns {Promise<string>} The max api version number, i.e `46.0`.
*/

@@ -156,3 +122,2 @@ retrieveMaxApiVersion(): Promise<string>;

* Returns the admin username used to create the org.
* @return {Optional<string>}
*/

@@ -162,3 +127,2 @@ getUsername(): Optional<string>;

* Returns the orgId for this org.
* @return {string}
*/

@@ -168,3 +132,2 @@ getOrgId(): string;

* Returns for the config aggregator.
* @returns {ConfigAggregator}
*/

@@ -174,16 +137,19 @@ getConfigAggregator(): ConfigAggregator;

* Returns an org field. Returns undefined if the field is not set or invalid.
* @returns {AnyJson}
*/
getField(key: OrgFields): AnyJson;
getField(key: Org.Fields): AnyJson;
/**
* Returns a map of requested fields.
* @returns {JsonMap}
*/
getFields(keys: OrgFields[]): JsonMap;
getFields(keys: Org.Fields[]): JsonMap;
/**
* Returns the JSForce connection for the org.
* @returns {Connection}
*/
getConnection(): Connection;
/**
* Initialize async components.
*/
protected init(): Promise<void>;
/**
* **Throws** *{@link SfdxError} Throws and unsupported error.
*/
protected getDefaultOptions(): Org.Options;

@@ -194,3 +160,3 @@ private manageDelete;

/**
* Constructor Options for and Org
* Constructor Options for and Org.
*/

@@ -203,2 +169,65 @@ interface Options {

}
/**
* Scratch Org status.
*/
enum Status {
/**
* The scratch org is active.
*/
ACTIVE = "ACTIVE",
/**
* The scratch org has expired.
*/
EXPIRED = "EXPIRED",
/**
* The org is a scratch Org but no dev hub is indicated.
*/
UNKNOWN = "UNKNOWN",
/**
* The dev hub configuration is reporting an active Scratch org but the AuthInfo cannot be found.
*/
MISSING = "MISSING"
}
/**
* Org Fields.
*/
enum Fields {
/**
* The org alias.
*/
ALIAS = "alias",
CREATED = "created",
/**
* The Salesforce instance the org was created on. e.g. `cs42`.
*/
CREATED_ORG_INSTANCE = "createdOrgInstance",
/**
* The username of the dev hub org that created this org. Only populated for scratch orgs.
*/
DEV_HUB_USERNAME = "devHubUsername",
/**
* The full url of the instance the org lives on.
*/
INSTANCE_URL = "instanceUrl",
/**
* Is the current org a dev hub org. e.g. They have access to the `ScratchOrgInfo` object.
*/
IS_DEV_HUB = "isDevHub",
/**
* The login url of the org. e.g. `https://login.salesforce.com` or `https://test.salesforce.com`.
*/
LOGIN_URL = "loginUrl",
/**
* The org ID.
*/
ORG_ID = "orgId",
/**
* The `OrgStatus` of the org.
*/
STATUS = "status",
/**
* The snapshot used to create the scratch org.
*/
SNAPSHOT = "snapshot"
}
}

@@ -8,24 +8,3 @@ "use strict";

*/
/**
* Org Fields.
* @typedef OrgFields
* @property {string} ALIAS The org alias.
* @property {string} CREATED_ORG_INSTANCE The Salesforce instance the org was created on. e.g. `cs42`.
* @property {string} DEV_HUB_USERNAME The username of the dev hub org that created this org. Only populated for scratch orgs.
* @property {string} INSTANCE_URL The full url of the instance the org lives on.
* @property {string} IS_DEV_HUB Is the current org a dev hub org. e.g. They have access to the `ScratchOrgInfo` object.
* @property {string} LOGIN_URL The login url of the org. e.g. `https://login.salesforce.com` or `https://test.salesforce.com`.
* @property {string} ORG_ID The org ID.
* @property {string} STATUS The `OrgStatus` of the org.
* @property {string} SNAPSHOT The snapshot used to create the scratch org.
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Scratch Org status.
* @typedef OrgStatus
* @property {string} ACTIVE The scratch org is active.
* @property {string} EXPIRED The scratch org has expired.
* @property {string} UNKNOWN The org is a scratch Org but no dev hub is indicated.
* @property {string} MISSING The dev hub configuration is reporting an active Scratch org but the AuthInfo cannot be found.
*/
const kit_1 = require("@salesforce/kit");

@@ -43,48 +22,16 @@ const ts_types_1 = require("@salesforce/ts-types");

const sfdxError_1 = require("./sfdxError");
const fs = require("./util/fs");
const fs_1 = require("./util/fs");
const sfdc_1 = require("./util/sfdc");
var OrgStatus;
(function (OrgStatus) {
OrgStatus["ACTIVE"] = "ACTIVE";
OrgStatus["EXPIRED"] = "EXPIRED";
OrgStatus["UNKNOWN"] = "UNKNOWN";
OrgStatus["MISSING"] = "MISSING";
})(OrgStatus = exports.OrgStatus || (exports.OrgStatus = {}));
// A subset of fields from AuthInfoFields and properties that are specific to Org,
// and properties that are defined on Org itself.
var OrgFields;
(function (OrgFields) {
// From AuthInfo
OrgFields["ALIAS"] = "alias";
OrgFields["CREATED"] = "created";
OrgFields["CREATED_ORG_INSTANCE"] = "createdOrgInstance";
OrgFields["DEV_HUB_USERNAME"] = "devHubUsername";
OrgFields["INSTANCE_URL"] = "instanceUrl";
OrgFields["IS_DEV_HUB"] = "isDevHub";
OrgFields["LOGIN_URL"] = "loginUrl";
OrgFields["ORG_ID"] = "orgId";
// From Org
OrgFields["STATUS"] = "status";
OrgFields["SNAPSHOT"] = "snapshot";
// Should it be on org? Leave it off for now, as it might
// be confusing to the consumer what this actually is.
// USERNAMES = 'usernames',
// Keep separation of concerns. I think these should be on a "user" that belongs to the org.
// Org can have a list of user objects that belong to it? Should connection be on user and org.getConnection()
// gets the orgs current user for the process? Maybe we just want to keep with the Org only model for
// the end of time?
// USER_ID = 'userId',
// USERNAME = 'username',
// PASSWORD = 'password',
// USER_PROFILE_NAME = 'userProfileName'
})(OrgFields = exports.OrgFields || (exports.OrgFields = {}));
/**
* Provides a way to manage a locally authenticated Org.
*
* @see {@link AuthInfo}
* @see {@link Connection}
* @see {@link Aliases}
* @see {@link Config}
* **See** {@link AuthInfo}
*
* @example
* **See** {@link Connection}
*
* **See** {@link Aliases}
*
* **See** {@link Config}
*
* ```
* // Email username

@@ -98,4 +45,5 @@ * const org1: Org = await Org.create({ aliasOrUsername: 'foo@example.com' });//tslint:disable-line:no-unused-variable

* });
* ```
*
* @see https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_usernames_orgs.htm
* **See** https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_usernames_orgs.htm
*/

@@ -109,3 +57,3 @@ class Org extends kit_1.AsyncCreatable {

// tslint:disable-next-line:no-unused-variable
this.status = OrgStatus.UNKNOWN;
this.status = Org.Status.UNKNOWN;
this.options = options;

@@ -115,5 +63,4 @@ }

* Clean all data files in the org's data path. Usually <workspace>/.sfdx/orgs/<username>.
* @param {string} [orgDataPath] A relative path other than "orgs/".
* @param orgDataPath A relative path other than "orgs/".
* @param throwWhenRemoveFails Should the remove org operations throw an error on failure?
* @returns {Promise<void>}
*/

@@ -136,4 +83,7 @@ async cleanLocalOrgData(orgDataPath, throwWhenRemoveFails = false) {

}
return this.manageDelete(async () => await fs.remove(dataPath), dataPath, throwWhenRemoveFails);
return this.manageDelete(async () => await fs_1.fs.remove(dataPath), dataPath, throwWhenRemoveFails);
}
/**
* @ignore
*/
async retrieveOrgUsersConfig() {

@@ -146,4 +96,3 @@ return await orgUsersConfig_1.OrgUsersConfig.create(orgUsersConfig_1.OrgUsersConfig.getOptions(this.getOrgId()));

* matching aliases.
* @param {boolean} [throwWhenRemoveFails = false] Determines if the call should throw an error or fail silently.
* @returns {Promise<void>}
* @param throwWhenRemoveFails Determines if the call should throw an error or fail silently.
*/

@@ -157,3 +106,3 @@ async remove(throwWhenRemoveFails = false) {

const auths = await this.readUserAuthFiles();
const aliases = await aliases_1.Aliases.retrieve();
const aliases = await aliases_1.Aliases.create(aliases_1.Aliases.getDefaultOptions());
this.logger.info(`Cleaning up usernames in org: ${this.getOrgId()}`);

@@ -186,6 +135,8 @@ for (const auth of auths) {

* Check that this org is a scratch org by asking the dev hub if it knows about it.
* @param {string} [devHubUsername] The username of the dev hub org.
* @returns {Promise<Config>}
* @throws {SfdxError} **`{name: 'NotADevHub'}`** Not a Dev Hub.
* @throws {SfdxError} **`{name: 'NoResults'}`** No results.
*
* **Throws** *{@link SfdxError}{ name: 'NotADevHub' }* Not a Dev Hub.
*
* **Throws** *{@link SfdxError}{ name: 'NoResults' }* No results.
*
* @param devHubUsername The username of the dev hub org.
*/

@@ -201,3 +152,3 @@ async checkScratchOrg(devHubUsername) {

const thisOrgAuthConfig = this.getConnection().getAuthInfoFields();
const trimmedId = sfdc_1.trimTo15(thisOrgAuthConfig.orgId);
const trimmedId = sfdc_1.sfdc.trimTo15(thisOrgAuthConfig.orgId);
const DEV_HUB_SOQL = `SELECT CreatedDate,Edition,ExpirationDate FROM ActiveScratchOrg WHERE ScratchOrg=\'${trimmedId}\'`;

@@ -221,3 +172,2 @@ let results;

* Returns the Org object or null if this org is not affiliated with a Dev Hub (according to the local config).
* @returns {Promise<Org>}
*/

@@ -228,4 +178,4 @@ async getDevHubOrg() {

}
else if (this.getField(OrgFields.DEV_HUB_USERNAME)) {
const devHubUsername = ts_types_1.ensureString(this.getField(OrgFields.DEV_HUB_USERNAME));
else if (this.getField(Org.Fields.DEV_HUB_USERNAME)) {
const devHubUsername = ts_types_1.ensureString(this.getField(Org.Fields.DEV_HUB_USERNAME));
return Org.create({

@@ -240,10 +190,8 @@ connection: await connection_1.Connection.create({

* Returns `true` if the org is a Dev Hub.
* @returns {Boolean}
*/
isDevHubOrg() {
return this.getField(OrgFields.IS_DEV_HUB);
return this.getField(Org.Fields.IS_DEV_HUB);
}
/**
* Refreshes the auth for this org's instance by calling HTTP GET on the baseUrl of the connection object.
* @returns {Promise<void>}
*/

@@ -261,3 +209,2 @@ async refreshAuth() {

* Reads and returns the content of all user auth files for this org as an array.
* @returns {Promise<AuthInfo[]>}
*/

@@ -281,9 +228,11 @@ async readUserAuthFiles() {

/**
* Adds a username to the user config for this org.
* @param {AuthInfo | string} auth The AuthInfo for the username to add.
* @returns {Promise<Org>} For convenience `this` object is returned.
* @example
* Adds a username to the user config for this org. For convenience `this` object is returned.
*
* ```
* const org: Org = await Org.create(await Connection.create(await AuthInfo.create('foo@example.com')));
* const userAuth: AuthInfo = await AuthInfo.create('bar@example.com');
* await org.addUsername(userAuth);
* ```
*
* @param {AuthInfo | string} auth The AuthInfo for the username to add.
*/

@@ -322,6 +271,7 @@ async addUsername(auth) {

/**
* Removes a username from the user config for this object.
* Removes a username from the user config for this object. For convenience `this` object is returned.
*
* **Throws** *{@link SfdxError}{ name: 'MissingAuthInfo' }* Auth info is missing.
*
* @param {AuthInfo | string} auth The AuthInfo containing the username to remove.
* @returns {Promise<Org>} For convenience `this` object is returned.
* @throws {SfdxError} **`{name: 'MissingAuthInfo'}`** Auth info is missing.
*/

@@ -346,3 +296,2 @@ async removeUsername(auth) {

* results in a warning.
* @returns {Promise<string>} The max api version number, i.e `46.0`.
*/

@@ -354,3 +303,2 @@ async retrieveMaxApiVersion() {

* Returns the admin username used to create the org.
* @return {Optional<string>}
*/

@@ -362,10 +310,8 @@ getUsername() {

* Returns the orgId for this org.
* @return {string}
*/
getOrgId() {
return this.getField(OrgFields.ORG_ID);
return this.getField(Org.Fields.ORG_ID);
}
/**
* Returns for the config aggregator.
* @returns {ConfigAggregator}
*/

@@ -377,3 +323,2 @@ getConfigAggregator() {

* Returns an org field. Returns undefined if the field is not set or invalid.
* @returns {AnyJson}
*/

@@ -386,13 +331,12 @@ getField(key) {

* Returns a map of requested fields.
* @returns {JsonMap}
*/
getFields(keys) {
const json = {};
return keys.reduce((map, key) => {
map[key] = this.getField(key);
return map;
}, {});
}, json);
}
/**
* Returns the JSForce connection for the org.
* @returns {Connection}
*/

@@ -402,2 +346,5 @@ getConnection() {

}
/**
* Initialize async components.
*/
async init() {

@@ -423,2 +370,5 @@ this.logger = await logger_1.Logger.child('Org');

}
/**
* **Throws** *{@link SfdxError} Throws and unsupported error.
*/
getDefaultOptions() {

@@ -440,2 +390,83 @@ throw new sfdxError_1.SfdxError('Not Supported');

exports.Org = Org;
(function (Org) {
/**
* Scratch Org status.
*/
let Status;
(function (Status) {
/**
* The scratch org is active.
*/
Status["ACTIVE"] = "ACTIVE";
/**
* The scratch org has expired.
*/
Status["EXPIRED"] = "EXPIRED";
/**
* The org is a scratch Org but no dev hub is indicated.
*/
Status["UNKNOWN"] = "UNKNOWN";
/**
* The dev hub configuration is reporting an active Scratch org but the AuthInfo cannot be found.
*/
Status["MISSING"] = "MISSING";
})(Status = Org.Status || (Org.Status = {}));
/**
* Org Fields.
*/
// A subset of fields from AuthInfoFields and properties that are specific to Org,
// and properties that are defined on Org itself.
let Fields;
(function (Fields) {
/**
* The org alias.
*/
// From AuthInfo
Fields["ALIAS"] = "alias";
Fields["CREATED"] = "created";
/**
* The Salesforce instance the org was created on. e.g. `cs42`.
*/
Fields["CREATED_ORG_INSTANCE"] = "createdOrgInstance";
/**
* The username of the dev hub org that created this org. Only populated for scratch orgs.
*/
Fields["DEV_HUB_USERNAME"] = "devHubUsername";
/**
* The full url of the instance the org lives on.
*/
Fields["INSTANCE_URL"] = "instanceUrl";
/**
* Is the current org a dev hub org. e.g. They have access to the `ScratchOrgInfo` object.
*/
Fields["IS_DEV_HUB"] = "isDevHub";
/**
* The login url of the org. e.g. `https://login.salesforce.com` or `https://test.salesforce.com`.
*/
Fields["LOGIN_URL"] = "loginUrl";
/**
* The org ID.
*/
Fields["ORG_ID"] = "orgId";
/**
* The `OrgStatus` of the org.
*/
Fields["STATUS"] = "status";
/**
* The snapshot used to create the scratch org.
*/
Fields["SNAPSHOT"] = "snapshot";
// Should it be on org? Leave it off for now, as it might
// be confusing to the consumer what this actually is.
// USERNAMES = 'usernames',
// Keep separation of concerns. I think these should be on a "user" that belongs to the org.
// Org can have a list of user objects that belong to it? Should connection be on user and org.getConnection()
// gets the orgs current user for the process? Maybe we just want to keep with the Org only model for
// the end of time?
// USER_ID = 'userId',
// USERNAME = 'username',
// PASSWORD = 'password',
// USER_PROFILE_NAME = 'userProfileName'
})(Fields = Org.Fields || (Org.Fields = {}));
})(Org = exports.Org || (exports.Org = {}));
//# sourceMappingURL=org.js.map

@@ -14,4 +14,4 @@ import { Org } from './org';

/**
* Creates a new instance of PermissionSetAssignment
* @param org {PermissionSetAssignment} new instance of PermissionSetAssignment
* Creates a new instance of PermissionSetAssignment.
* @param org The target org for the assignment.
*/

@@ -21,12 +21,7 @@ static init(org: Org): Promise<PermissionSetAssignment>;

private org;
/**
* constructor
* @param org {Org} The org containing the user and permission set.
* @param logger {Logger} A Logger instance.
*/
private constructor();
/**
* Assigns a user to one or more permission sets.
* @param id {string} A user id
* @param permSetString {string[]} An array of permission set names.
* @param id A user id
* @param permSetString An array of permission set names.
*/

@@ -36,5 +31,5 @@ create(id: string, permSetString: string): Promise<PermissionSetAssignmentFields>;

* Parses a permission set name based on if it has a namespace or not.
* @param permSetString {string} The permission set string.
* @param permSetString The permission set string.
*/
private parsePermissionSetString;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -9,2 +8,3 @@ * Copyright (c) 2018, salesforce.com, inc.

*/
Object.defineProperty(exports, "__esModule", { value: true });
const kit_1 = require("@salesforce/kit");

@@ -21,4 +21,4 @@ const ts_types_1 = require("@salesforce/ts-types");

/**
* Creates a new instance of PermissionSetAssignment
* @param org {PermissionSetAssignment} new instance of PermissionSetAssignment
* Creates a new instance of PermissionSetAssignment.
* @param org The target org for the assignment.
*/

@@ -31,7 +31,2 @@ static async init(org) {

}
/**
* constructor
* @param org {Org} The org containing the user and permission set.
* @param logger {Logger} A Logger instance.
*/
constructor(org, logger) {

@@ -43,4 +38,4 @@ this.logger = logger;

* Assigns a user to one or more permission sets.
* @param id {string} A user id
* @param permSetString {string[]} An array of permission set names.
* @param id A user id
* @param permSetString An array of permission set names.
*/

@@ -104,3 +99,3 @@ async create(id, permSetString) {

* Parses a permission set name based on if it has a namespace or not.
* @param permSetString {string} The permission set string.
* @param permSetString The permission set string.
*/

@@ -107,0 +102,0 @@ parsePermissionSetString(permSetString) {

/// <reference types="node" />
import { Optional } from '@salesforce/ts-types';
/**
* Returns the intended type of the object to return. This is implementation specific.
* @param buffer A buffer containing the decrypted secret.
*/
export declare type DecipherCallback<T> = (buffer: Buffer) => T;
/**
* Used to store and retrieve a sensitive information in memory. This is not meant for at rest encryption.
* @example
*
* ```
* const sString: SecureBuffer<string> = new SecureBuffer();

@@ -15,3 +20,3 @@ * sString.consume(secretTextBuffer);

* });
*
* ```
*/

@@ -24,14 +29,8 @@ export declare class SecureBuffer<T> {

* Invokes a callback with a decrypted version of the buffer.
* @param {DecipherCallback} cb - The callback containing the decrypted buffer parameter that returns a desired
* @param cb The callback containing the decrypted buffer parameter that returns a desired.
* typed object. It's important to understand that once the callback goes out of scope the buffer parameters is
* overwritten with random data. Do not make a copy of this buffer and persist it!
* @return T - The value of the callback of type T
*/
value(cb: (buffer: Buffer) => T): Optional<T>;
value(cb: DecipherCallback<T>): Optional<T>;
/**
* @callback DecipherCallback
* @param {Buffer} buffer - A buffer containing the decrypted secret.
* @returns T - The intended type of the object to return. This is implementation specific.
*/
/**
* Overwrites the value of the encrypted secret with random data.

@@ -42,3 +41,3 @@ */

* Consumes a buffer of data that's intended to be secret.
* @param {Buffer} buffer - Data to encrypt. The input buffer is overwritten with random data after it's encrypted
* @param buffer Data to encrypt. The input buffer is overwritten with random data after it's encrypted
* and assigned internally.

@@ -45,0 +44,0 @@ */

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -9,2 +8,3 @@ * Copyright (c) 2018, salesforce.com, inc.

*/
Object.defineProperty(exports, "__esModule", { value: true });
const ts_types_1 = require("@salesforce/ts-types");

@@ -16,4 +16,4 @@ const crypto = require("crypto");

* Used to store and retrieve a sensitive information in memory. This is not meant for at rest encryption.
* @example
*
* ```
* const sString: SecureBuffer<string> = new SecureBuffer();

@@ -27,3 +27,3 @@ * sString.consume(secretTextBuffer);

* });
*
* ```
*/

@@ -37,6 +37,5 @@ class SecureBuffer {

* Invokes a callback with a decrypted version of the buffer.
* @param {DecipherCallback} cb - The callback containing the decrypted buffer parameter that returns a desired
* @param cb The callback containing the decrypted buffer parameter that returns a desired.
* typed object. It's important to understand that once the callback goes out of scope the buffer parameters is
* overwritten with random data. Do not make a copy of this buffer and persist it!
* @return T - The value of the callback of type T
*/

@@ -60,7 +59,2 @@ value(cb) {

/**
* @callback DecipherCallback
* @param {Buffer} buffer - A buffer containing the decrypted secret.
* @returns T - The intended type of the object to return. This is implementation specific.
*/
/**
* Overwrites the value of the encrypted secret with random data.

@@ -77,3 +71,3 @@ */

* Consumes a buffer of data that's intended to be secret.
* @param {Buffer} buffer - Data to encrypt. The input buffer is overwritten with random data after it's encrypted
* @param buffer Data to encrypt. The input buffer is overwritten with random data after it's encrypted
* and assigned internally.

@@ -80,0 +74,0 @@ */

import { NamedError } from '@salesforce/kit';
import { Optional } from '@salesforce/ts-types';
import { JsonMap, Optional } from '@salesforce/ts-types';
import { Messages, Tokens } from './messages';

@@ -7,4 +7,5 @@ /**

*
* @example
* ```
* SfdxError.create(new SfdxErrorConfig('MyPackage', 'apex', 'runTest').addAction('apexErrorAction1', [className]));
* ```
*/

@@ -29,8 +30,8 @@ export declare class SfdxErrorConfig {

* Create a new SfdxErrorConfig.
* @param {string} packageName The name of the package.
* @param {string} bundleName The message bundle.
* @param {string} errorKey The error message key.
* @param {Tokens} errorTokens The tokens to use when getting the error message.
* @param {string} [actionKey] The action message key.
* @param {Tokens} [actionTokens] The tokens to use when getting the action message(s).
* @param packageName The name of the package.
* @param bundleName The message bundle.
* @param errorKey The error message key.
* @param errorTokens The tokens to use when getting the error message.
* @param actionKey The action message key.
* @param actionTokens The tokens to use when getting the action message(s).
*/

@@ -40,3 +41,3 @@ constructor(packageName: string, bundleName: string, errorKey: string, errorTokens?: Tokens, actionKey?: string, actionTokens?: Tokens);

* Set the error key.
* @param {string} key The key to set.
* @param key The key to set.
* @returns {SfdxErrorConfig} For convenience `this` object is returned.

@@ -47,16 +48,13 @@ */

* Set the error tokens.
* @param {Tokens} tokens The tokens to set.
* @returns {SfdxErrorConfig} For convenience `this` object is returned.
* @param tokens The tokens to set. For convenience `this` object is returned.
*/
setErrorTokens(tokens: Tokens): SfdxErrorConfig;
/**
* Add an error action to assist the user with a resolution.
* @param {string} actionKey The action key in the message bundle.
* @param {Tokens} [actionTokens] The action tokens for the string.
* @returns {SfdxErrorConfig} For convenience `this` object is returned.
* Add an error action to assist the user with a resolution. For convenience `this` object is returned.
* @param actionKey The action key in the message bundle.
* @param actionTokens The action tokens for the string.
*/
addAction(actionKey: string, actionTokens?: Tokens): SfdxErrorConfig;
/**
* Load the messages using Messages.loadMessages.
* @returns {Messages} Returns the loaded messages.
* Load the messages using `Messages.loadMessages`. Returns the loaded messages.
*/

@@ -66,4 +64,3 @@ load(): Messages;

* Get the error message using messages.getMessage.
* @returns {string}
* @throws {SfdxError} If errorMessages.load was not called first.
* **Throws** If `errorMessages.load` was not called first.
*/

@@ -73,10 +70,8 @@ getError(): string;

* Get the action messages using messages.getMessage.
* @returns {Optional<string[]>} List of action messages.
* @throws {SfdxError} If errorMessages.load was not called first.
* **@throws** If `errorMessages.load` was not called first.
*/
getActions(): Optional<string[]>;
/**
* Remove all actions from this error config. Useful when reusing SfdxErrorConfig.
* for other error messages within the same bundle.
* @returns {SfdxErrorConfig} For convenience `this` object is returned.
* Remove all actions from this error config. Useful when reusing SfdxErrorConfig for other error messages within
* the same bundle. For convenience `this` object is returned.
*/

@@ -92,3 +87,3 @@ removeActions(): SfdxErrorConfig;

*
* @example
* ```
* // To load a message bundle:

@@ -104,11 +99,11 @@ * Messages.importMessagesDirectory(__dirname);

* throw new SfdxError(myErrMsg, 'MyErrorName');
*
* ```
*/
export declare class SfdxError extends NamedError {
/**
* Create a new SfdxError.
* @param {string} packageName The message package name used to create the SfdxError.
* @param {string} bundleName The message bundle name used to create the SfdxError.
* @param {string} key The key within the bundle for the message.
* @param {Tokens} [tokens] The values to use for message tokenization.
* Create a new `SfdxError`.
* @param packageName The message package name used to create the `SfdxError`.
* @param bundleName The message bundle name used to create the `SfdxError`.
* @param key The key within the bundle for the message.
* @param tokens The values to use for message tokenization.
*/

@@ -118,3 +113,3 @@ static create(packageName: string, bundleName: string, key: string, tokens?: Tokens): SfdxError;

* Create a new SfdxError.
* @param {SfdxErrorConfig} errorConfig The SfdxErrorConfig object used to create the SfdxError.
* @param errorConfig The `SfdxErrorConfig` object used to create the SfdxError.
*/

@@ -124,4 +119,3 @@ static create(errorConfig: SfdxErrorConfig): SfdxError;

* Convert an Error to an SfdxError.
* @param {Error} err The error to convert.
* @returns {SfdxError}
* @param err The error to convert.
*/

@@ -148,26 +142,23 @@ static wrap(err: Error): SfdxError;

* Create an SfdxError.
* @param {string} message The error message.
* @param {string} [name] The error name. Defaults to 'SfdxError'.
* @param {string[]} [actions] The action message(s).
* @param {number} [exitCode] The exit code which will be used by SfdxCommand.
* @param {Error} [cause] The underlying error that caused this error to be raised.
* @param message The error message.
* @param name The error name. Defaults to 'SfdxError'.
* @param actions The action message(s).
* @param exitCode The exit code which will be used by SfdxCommand.
* @param cause The underlying error that caused this error to be raised.
*/
constructor(message: string, name?: string, actions?: string[], exitCode?: number, cause?: Error);
/**
* Sets the name of the command.
* @param {string} commandName The command name.
* @returns {SfdxError} For convenience `this` object is returned.
* Sets the name of the command. For convenience `this` object is returned.
* @param commandName The command name.
*/
setCommandName(commandName: string): SfdxError;
/**
* An additional payload for the error.
* @param {any} data The payload data.
* @returns {SfdxError} For convenience `this` object is returned.
* An additional payload for the error. For convenience `this` object is returned.
* @param data The payload data.
*/
setData(data: unknown): SfdxError;
/**
* Convert an SfdxError's state to an object.
* @returns {object} A plain object representing the state of this error.
* Convert an {@link SfdxError} state to an object. Returns a plain object representing the state of this error.
*/
toObject(): object;
toObject(): JsonMap;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -9,2 +8,3 @@ * Copyright (c) 2018, salesforce.com, inc.

*/
Object.defineProperty(exports, "__esModule", { value: true });
const kit_1 = require("@salesforce/kit");

@@ -16,4 +16,5 @@ const ts_types_1 = require("@salesforce/ts-types");

*
* @example
* ```
* SfdxError.create(new SfdxErrorConfig('MyPackage', 'apex', 'runTest').addAction('apexErrorAction1', [className]));
* ```
*/

@@ -23,8 +24,8 @@ class SfdxErrorConfig {

* Create a new SfdxErrorConfig.
* @param {string} packageName The name of the package.
* @param {string} bundleName The message bundle.
* @param {string} errorKey The error message key.
* @param {Tokens} errorTokens The tokens to use when getting the error message.
* @param {string} [actionKey] The action message key.
* @param {Tokens} [actionTokens] The tokens to use when getting the action message(s).
* @param packageName The name of the package.
* @param bundleName The message bundle.
* @param errorKey The error message key.
* @param errorTokens The tokens to use when getting the error message.
* @param actionKey The action message key.
* @param actionTokens The tokens to use when getting the action message(s).
*/

@@ -42,3 +43,3 @@ constructor(packageName, bundleName, errorKey, errorTokens = [], actionKey, actionTokens) {

* Set the error key.
* @param {string} key The key to set.
* @param key The key to set.
* @returns {SfdxErrorConfig} For convenience `this` object is returned.

@@ -52,4 +53,3 @@ */

* Set the error tokens.
* @param {Tokens} tokens The tokens to set.
* @returns {SfdxErrorConfig} For convenience `this` object is returned.
* @param tokens The tokens to set. For convenience `this` object is returned.
*/

@@ -61,6 +61,5 @@ setErrorTokens(tokens) {

/**
* Add an error action to assist the user with a resolution.
* @param {string} actionKey The action key in the message bundle.
* @param {Tokens} [actionTokens] The action tokens for the string.
* @returns {SfdxErrorConfig} For convenience `this` object is returned.
* Add an error action to assist the user with a resolution. For convenience `this` object is returned.
* @param actionKey The action key in the message bundle.
* @param actionTokens The action tokens for the string.
*/

@@ -72,4 +71,3 @@ addAction(actionKey, actionTokens = []) {

/**
* Load the messages using Messages.loadMessages.
* @returns {Messages} Returns the loaded messages.
* Load the messages using `Messages.loadMessages`. Returns the loaded messages.
*/

@@ -82,4 +80,3 @@ load() {

* Get the error message using messages.getMessage.
* @returns {string}
* @throws {SfdxError} If errorMessages.load was not called first.
* **Throws** If `errorMessages.load` was not called first.
*/

@@ -94,4 +91,3 @@ getError() {

* Get the action messages using messages.getMessage.
* @returns {Optional<string[]>} List of action messages.
* @throws {SfdxError} If errorMessages.load was not called first.
* **@throws** If `errorMessages.load` was not called first.
*/

@@ -114,5 +110,4 @@ getActions() {

/**
* Remove all actions from this error config. Useful when reusing SfdxErrorConfig.
* for other error messages within the same bundle.
* @returns {SfdxErrorConfig} For convenience `this` object is returned.
* Remove all actions from this error config. Useful when reusing SfdxErrorConfig for other error messages within
* the same bundle. For convenience `this` object is returned.
*/

@@ -132,3 +127,3 @@ removeActions() {

*
* @example
* ```
* // To load a message bundle:

@@ -144,3 +139,3 @@ * Messages.importMessagesDirectory(__dirname);

* throw new SfdxError(myErrMsg, 'MyErrorName');
*
* ```
*/

@@ -162,4 +157,3 @@ class SfdxError extends kit_1.NamedError {

* Convert an Error to an SfdxError.
* @param {Error} err The error to convert.
* @returns {SfdxError}
* @param err The error to convert.
*/

@@ -176,7 +170,7 @@ static wrap(err) {

* Create an SfdxError.
* @param {string} message The error message.
* @param {string} [name] The error name. Defaults to 'SfdxError'.
* @param {string[]} [actions] The action message(s).
* @param {number} [exitCode] The exit code which will be used by SfdxCommand.
* @param {Error} [cause] The underlying error that caused this error to be raised.
* @param message The error message.
* @param name The error name. Defaults to 'SfdxError'.
* @param actions The action message(s).
* @param exitCode The exit code which will be used by SfdxCommand.
* @param cause The underlying error that caused this error to be raised.
*/

@@ -189,5 +183,4 @@ constructor(message, name, actions, exitCode, cause) {

/**
* Sets the name of the command.
* @param {string} commandName The command name.
* @returns {SfdxError} For convenience `this` object is returned.
* Sets the name of the command. For convenience `this` object is returned.
* @param commandName The command name.
*/

@@ -199,5 +192,4 @@ setCommandName(commandName) {

/**
* An additional payload for the error.
* @param {any} data The payload data.
* @returns {SfdxError} For convenience `this` object is returned.
* An additional payload for the error. For convenience `this` object is returned.
* @param data The payload data.
*/

@@ -209,4 +201,3 @@ setData(data) {

/**
* Convert an SfdxError's state to an object.
* @returns {object} A plain object representing the state of this error.
* Convert an {@link SfdxError} state to an object. Returns a plain object representing the state of this error.
*/

@@ -213,0 +204,0 @@ toObject() {

@@ -10,6 +10,4 @@ import { ConfigFile } from './config/configFile';

*
* @extends ConfigFile
*
* @example
* const project = await SfdxProjectJson.retrieve<SfdxProjectJson>();
* ```
* const project = await SfdxProjectJson.retrieve();
* const myPluginProperties = project.get('myplugin') || {};

@@ -19,4 +17,5 @@ * myPluginProperties.myprop = 'someValue';

* await project.write();
* ```
*
* @see https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_ws_create_new.htm
* **See** [force:project:create](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_ws_create_new.htm)
*/

@@ -34,6 +33,7 @@ export declare class SfdxProjectJson extends ConfigFile<ConfigFile.Options> {

*
* @example
* ```
* const project = await SfdxProject.resolve();
* const projectJson = await project.resolveProjectConfig();
* console.log(projectJson.sfdcLoginUrl);
* ```
*/

@@ -44,15 +44,17 @@ export declare class SfdxProject {

* Get a Project from a given path or from the working directory.
* @param {string} path The path of the project.
* @throws InvalidProjectWorkspace If the current folder is not located in a workspace.
* @returns {Promise<SfdxProject>} The resolved project.
* @param path The path of the project.
*
* **Throws** *{@link SfdxError}{ name: 'InvalidProjectWorkspace' }* If the current folder is not located in a workspace.
*/
static resolve(path?: string): Promise<SfdxProject>;
/**
* Performs an upward directory search for an sfdx project file.
* Performs an upward directory search for an sfdx project file. Returns the absolute path to the project.
*
* @param {string} [dir=process.cwd()] The directory path to start traversing from.
* @returns {Promise<string>} The absolute path to the project.
* @throws {SfdxError} **`{name: 'InvalidProjectWorkspace'}`** If the current folder is not located in a workspace.
* @see fs.traverseForFile
* @see {@link https://nodejs.org/api/process.html#process_process_cwd|process.cwd()}
* @param dir The directory path to start traversing from.
*
* **Throws** *{@link SfdxError}{ name: 'InvalidProjectWorkspace' }* If the current folder is not located in a workspace.
*
* **See** {@link traverseForFile}
*
* **See** [process.cwd()](https://nodejs.org/api/process.html#process_process_cwd)
*/

@@ -64,6 +66,5 @@ static resolveProjectPath(dir?: string): Promise<string>;

/**
* Do not directly construct instances of this class -- use {@link Project.resolve} instead.
* Do not directly construct instances of this class -- use {@link SfdxProject.resolve} instead.
*
* @private
* @constructor
* @ignore
*/

@@ -73,3 +74,2 @@ private constructor();

* Returns the project path.
* @returns {string}
*/

@@ -82,5 +82,5 @@ getPath(): string;

* *Note:* When reading values from {@link SfdxProjectJson}, it is recommended to use
* {@link Project.resolveProjectConfig} instead.
* {@link SfdxProject.resolveProjectConfig} instead.
*
* @param {boolean} isGlobal True to get the global project file, otherwise the local project config.
* @param isGlobal True to get the global project file, otherwise the local project config.
*/

@@ -92,3 +92,3 @@ retrieveSfdxProjectJson(isGlobal?: boolean): Promise<SfdxProjectJson>;

* this when reading values from SfdxProjectJson.
* @returns {object} A resolved config object that contains a bunch of different
* @returns A resolved config object that contains a bunch of different
* properties, including some 3rd party custom properties.

@@ -95,0 +95,0 @@ */

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -9,2 +8,3 @@ * Copyright (c) 2018, salesforce.com, inc.

*/
Object.defineProperty(exports, "__esModule", { value: true });
const kit_1 = require("@salesforce/kit");

@@ -22,6 +22,4 @@ const configAggregator_1 = require("./config/configAggregator");

*
* @extends ConfigFile
*
* @example
* const project = await SfdxProjectJson.retrieve<SfdxProjectJson>();
* ```
* const project = await SfdxProjectJson.retrieve();
* const myPluginProperties = project.get('myplugin') || {};

@@ -31,4 +29,5 @@ * myPluginProperties.myprop = 'someValue';

* await project.write();
* ```
*
* @see https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_ws_create_new.htm
* **See** [force:project:create](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_ws_create_new.htm)
*/

@@ -50,3 +49,3 @@ class SfdxProjectJson extends configFile_1.ConfigFile {

// Verify that the configObject does not have upper case keys; throw if it does. Must be heads down camel case.
const upperCaseKey = sfdc_1.findUpperCaseKeys(this.toObject());
const upperCaseKey = sfdc_1.sfdc.findUpperCaseKeys(this.toObject());
if (upperCaseKey) {

@@ -70,13 +69,13 @@ throw sfdxError_1.SfdxError.create('@salesforce/core', 'core', 'InvalidJsonCasing', [upperCaseKey, this.getPath()]);

*
* @example
* ```
* const project = await SfdxProject.resolve();
* const projectJson = await project.resolveProjectConfig();
* console.log(projectJson.sfdcLoginUrl);
* ```
*/
class SfdxProject {
/**
* Do not directly construct instances of this class -- use {@link Project.resolve} instead.
* Do not directly construct instances of this class -- use {@link SfdxProject.resolve} instead.
*
* @private
* @constructor
* @ignore
*/

@@ -88,5 +87,5 @@ constructor(path) {

* Get a Project from a given path or from the working directory.
* @param {string} path The path of the project.
* @throws InvalidProjectWorkspace If the current folder is not located in a workspace.
* @returns {Promise<SfdxProject>} The resolved project.
* @param path The path of the project.
*
* **Throws** *{@link SfdxError}{ name: 'InvalidProjectWorkspace' }* If the current folder is not located in a workspace.
*/

@@ -97,9 +96,11 @@ static async resolve(path) {

/**
* Performs an upward directory search for an sfdx project file.
* Performs an upward directory search for an sfdx project file. Returns the absolute path to the project.
*
* @param {string} [dir=process.cwd()] The directory path to start traversing from.
* @returns {Promise<string>} The absolute path to the project.
* @throws {SfdxError} **`{name: 'InvalidProjectWorkspace'}`** If the current folder is not located in a workspace.
* @see fs.traverseForFile
* @see {@link https://nodejs.org/api/process.html#process_process_cwd|process.cwd()}
* @param dir The directory path to start traversing from.
*
* **Throws** *{@link SfdxError}{ name: 'InvalidProjectWorkspace' }* If the current folder is not located in a workspace.
*
* **See** {@link traverseForFile}
*
* **See** [process.cwd()](https://nodejs.org/api/process.html#process_process_cwd)
*/

@@ -111,3 +112,2 @@ static async resolveProjectPath(dir) {

* Returns the project path.
* @returns {string}
*/

@@ -122,5 +122,5 @@ getPath() {

* *Note:* When reading values from {@link SfdxProjectJson}, it is recommended to use
* {@link Project.resolveProjectConfig} instead.
* {@link SfdxProject.resolveProjectConfig} instead.
*
* @param {boolean} isGlobal True to get the global project file, otherwise the local project config.
* @param isGlobal True to get the global project file, otherwise the local project config.
*/

@@ -147,3 +147,3 @@ async retrieveSfdxProjectJson(isGlobal = false) {

* this when reading values from SfdxProjectJson.
* @returns {object} A resolved config object that contains a bunch of different
* @returns A resolved config object that contains a bunch of different
* properties, including some 3rd party custom properties.

@@ -150,0 +150,0 @@ */

import { AnyJson } from '@salesforce/ts-types';
/**
* Return type for the Streaming and Polling client.
* @interface
*/
export interface StatusResult {
/**
* If the result of the streaming or polling client is expected to return a result
*/
payload?: AnyJson;
/**
* Indicates to the streaming or polling client that the subscriber has what its needs. If `true` the client will end
* the messaging exchanges with the endpoint.
*/
completed: boolean;
}
"use strict";
/*
* Copyright (c) 2018, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=client.js.map

@@ -8,15 +8,14 @@ /// <reference types="node" />

*
* @example
*
* ```
* (async () => {
* const options: MyDomainResolver.Options = {
* url: new URL('http://mydomain.salesforce.com'),
* timeout: Duration.minutes(5),
* frequency: Duration.seconds(10)
* };
*
* const resolver: MyDomainResolver = await MyDomainResolver.create(options);
* const ipAddress: AnyJson = await resolver.resolve();
* console.log(`Successfully resolved host: ${options.url} to address: ${ipAddress}`);
* const options: MyDomainResolver.Options = {
* url: new URL('http://mydomain.salesforce.com'),
* timeout: Duration.minutes(5),
* frequency: Duration.seconds(10)
* };
* const resolver: MyDomainResolver = await MyDomainResolver.create(options);
* const ipAddress: AnyJson = await resolver.resolve();
* console.log(`Successfully resolved host: ${options.url} to address: ${ipAddress}`);
* })();
* ```
*/

@@ -30,4 +29,3 @@ export declare class MyDomainResolver extends AsyncOptionalCreatable<MyDomainResolver.Options> {

* Method that performs the dns lookup of the host. If the lookup fails the internal polling client will try again
* given the optional interval.
* @returns {Promise<AnyJson>} The resolved ip address.
* given the optional interval. Returns the resolved ip address.
*/

@@ -42,15 +40,15 @@ resolve(): Promise<string>;

/**
* Options for the MyDomain DNS resolver
* Options for the MyDomain DNS resolver.
*/
interface Options {
/**
* The host to resolve
* The host to resolve.
*/
url: URL;
/**
* The retry interval
* The retry interval.
*/
timeout?: Duration;
/**
* The retry timeout
* The retry timeout.
*/

@@ -57,0 +55,0 @@ frequency?: Duration;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -9,2 +8,3 @@ * Copyright (c) 2018, salesforce.com, inc.

*/
Object.defineProperty(exports, "__esModule", { value: true });
const dns_1 = require("dns");

@@ -21,15 +21,14 @@ const url_1 = require("url");

*
* @example
*
* ```
* (async () => {
* const options: MyDomainResolver.Options = {
* url: new URL('http://mydomain.salesforce.com'),
* timeout: Duration.minutes(5),
* frequency: Duration.seconds(10)
* };
*
* const resolver: MyDomainResolver = await MyDomainResolver.create(options);
* const ipAddress: AnyJson = await resolver.resolve();
* console.log(`Successfully resolved host: ${options.url} to address: ${ipAddress}`);
* const options: MyDomainResolver.Options = {
* url: new URL('http://mydomain.salesforce.com'),
* timeout: Duration.minutes(5),
* frequency: Duration.seconds(10)
* };
* const resolver: MyDomainResolver = await MyDomainResolver.create(options);
* const ipAddress: AnyJson = await resolver.resolve();
* console.log(`Successfully resolved host: ${options.url} to address: ${ipAddress}`);
* })();
* ```
*/

@@ -43,4 +42,3 @@ class MyDomainResolver extends kit_1.AsyncOptionalCreatable {

* Method that performs the dns lookup of the host. If the lookup fails the internal polling client will try again
* given the optional interval.
* @returns {Promise<AnyJson>} The resolved ip address.
* given the optional interval. Returns the resolved ip address.
*/

@@ -47,0 +45,0 @@ async resolve() {

@@ -10,3 +10,3 @@ import { AsyncOptionalCreatable, Duration } from '@salesforce/kit';

*
* @example
* ```
* const options: PollingClient.Options = {

@@ -22,2 +22,3 @@ * async poll(): Promise<StatusResult> {

* console.log(`pollResult: ${pollResult}`);
* ```
*/

@@ -32,4 +33,3 @@ export declare class PollingClient extends AsyncOptionalCreatable<PollingClient.Options> {

* @param options Polling client options
* @see {@link AsyncCreatable.create}
* @throws if options is undefined
* @ignore
*/

@@ -39,3 +39,2 @@ constructor(options?: PollingClient.Options);

* Asynchronous initializer.
* @async
*/

@@ -46,5 +45,2 @@ init(): Promise<void>;

* in the polling options.
* @returns A promise to call the specified polling function using the interval and timeout specified
* in the polling options.
* @async
*/

@@ -58,8 +54,23 @@ subscribe(): Promise<AnyJson>;

* Options for the polling client.
* @interface
*/
interface Options {
/**
* Polling function.
*/
poll: () => Promise<StatusResult>;
/**
* How frequent should the polling function be called.
*/
frequency: Duration;
/**
* Hard timeout for polling.
*/
timeout: Duration;
/**
* Change the name of the timeout error.
*
* ```
* if (err.name === 'MyChangedName) ...
* ```
*/
timeoutErrorName?: string;

@@ -77,4 +88,4 @@ }

* constructor
* @param {function} poll The function used for polling status.
* @see StatusResult
* @param poll The function used for polling status.
* {@link StatusResult}
*/

@@ -81,0 +92,0 @@ constructor(poll: () => Promise<StatusResult>);

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -9,2 +8,3 @@ * Copyright (c) 2018, salesforce.com, inc.

*/
Object.defineProperty(exports, "__esModule", { value: true });
const timers_1 = require("timers");

@@ -20,3 +20,3 @@ const kit_1 = require("@salesforce/kit");

*
* @example
* ```
* const options: PollingClient.Options = {

@@ -32,2 +32,3 @@ * async poll(): Promise<StatusResult> {

* console.log(`pollResult: ${pollResult}`);
* ```
*/

@@ -38,4 +39,3 @@ class PollingClient extends kit_1.AsyncOptionalCreatable {

* @param options Polling client options
* @see {@link AsyncCreatable.create}
* @throws if options is undefined
* @ignore
*/

@@ -48,3 +48,2 @@ constructor(options) {

* Asynchronous initializer.
* @async
*/

@@ -57,5 +56,2 @@ async init() {

* in the polling options.
* @returns A promise to call the specified polling function using the interval and timeout specified
* in the polling options.
* @async
*/

@@ -134,4 +130,4 @@ subscribe() {

* constructor
* @param {function} poll The function used for polling status.
* @see StatusResult
* @param poll The function used for polling status.
* {@link StatusResult}
*/

@@ -138,0 +134,0 @@ constructor(poll) {

@@ -9,6 +9,15 @@ /// <reference types="node" />

* Types for defining extensions.
* @interface
*/
export interface StreamingExtension {
/**
* Extension for outgoing message.
* @param message The message.
* @param callback The callback to invoke after the message is processed.
*/
outgoing?: (message: JsonMap, callback: AnyFunction) => void;
/**
* Extension for the incoming message.
* @param message The message.
* @param callback The callback to invoke after the message is processed.
*/
incoming?: (message: JsonMap, callback: AnyFunction) => void;

@@ -23,3 +32,2 @@ }

* The Faye implementation is used by default but it could be used to adapt another Cometd impl.
* @abstract
*/

@@ -29,4 +37,3 @@ export declare abstract class CometClient extends EventEmitter {

* Disable polling features.
* @param {string} label Polling feature label.
* @abstract
* @param label Polling feature label.
*/

@@ -37,3 +44,2 @@ abstract disable(label: string): void;

* @param extension The json function for the extension.
* @abstract
*/

@@ -45,3 +51,2 @@ abstract addExtension(extension: StreamingExtension): void;

* @param value The header value.
* @abstract
*/

@@ -53,3 +58,2 @@ abstract setHeader(name: string, value: string): void;

* errors when errors are encountered.
* @abstract
*/

@@ -63,2 +67,5 @@ abstract handshake(callback: () => void): void;

abstract subscribe(channel: string, callback: (message: JsonMap) => void): CometSubscription;
/**
* Method to call to disconnect the client from the server.
*/
abstract disconnect(): void;

@@ -69,3 +76,2 @@ }

* Also allows for mocking the functional behavior.
* @interface
*/

@@ -115,4 +121,3 @@ export interface StreamingClientIfc {

*
* @example
*
* ```
* const streamProcessor = (message: JsonMap): StatusResult => {

@@ -153,3 +158,3 @@ * const payload = ensureJsonMap(message.payload);

* });
*
* ```
*/

@@ -164,4 +169,3 @@ export declare class StreamingClient extends AsyncOptionalCreatable<StreamingClient.Options> {

* @param options Streaming client options
* @see {@link AsyncCreatable.create}
* @throws if options is undefined
* {@link AsyncCreatable.create}
*/

@@ -171,3 +175,2 @@ constructor(options?: StreamingClient.Options);

* Asynchronous initializer.
* @async
*/

@@ -182,12 +185,11 @@ init(): Promise<void>;

* Provides a convenient way to handshake with the server endpoint before trying to subscribe.
* @async
*/
handshake(): Promise<StreamingClient.ConnectionState>;
/**
* Subscribe to streaming events.
* @param {function} [streamInit] - This function should call the platform apis that result in streaming updates on push topics.
* @returns {Promise} - When the streaming processor that's set in the options completes, it returns a payload in
* the StatusResult object. The payload is just echoed here for convenience.
* @async
* @see {@link StatusResult}
* Subscribe to streaming events. When the streaming processor that's set in the options completes execution it
* returns a payload in the StatusResult object. The payload is just echoed here for convenience.
*
* **Throws** *{@link SfdxError}{ name: '{@link StreamingClient.TimeoutErrorType.SUBSCRIBE}'}* When the subscribe timeout occurs.
* @param streamInit This function should call the platform apis that result in streaming updates on push topics.
* {@link StatusResult}
*/

@@ -205,4 +207,3 @@ subscribe(streamInit?: () => Promise<void>): Promise<AnyJson>;

* Simple inner log wrapper
* @param {any} message The message to log
* @private
* @param message The message to log
*/

@@ -217,8 +218,29 @@ private log;

interface Options {
/**
* The org streaming target.
*/
org: Org;
/**
* The hard timeout that happens with subscribe
*/
subscribeTimeout: Duration;
/**
* The hard timeout that happens with a handshake.
*/
handshakeTimeout: Duration;
/**
* The streaming channel aka topic
*/
channel: string;
/**
* The salesforce api version
*/
apiVersion: string;
/**
* The function for processing streaming messages
*/
streamProcessor: StreamProcessor;
/**
* The function for build the inner client impl. Allows for mocking.
*/
streamingImpl: StreamingClientIfc;

@@ -253,4 +275,6 @@ }

* Setter for the subscribe timeout.
*
* **Throws** An error if the newTime is less than the default time.
* @param newTime The new subscribe timeout.
* @throws An error if the newTime is less than the default time.
* {@link DefaultOptions.DEFAULT_SUBSCRIBE_TIMEOUT}
*/

@@ -260,4 +284,6 @@ setSubscribeTimeout(newTime: Duration): void;

* Setter for the handshake timeout.
*
* **Throws** An error if the newTime is less than the default time.
* @param newTime The new handshake timeout
* @throws An error if the newTime is less than the default time.
* {@link DefaultOptions.DEFAULT_HANDSHAKE_TIMEOUT}
*/

@@ -268,7 +294,8 @@ setHandshakeTimeout(newTime: Duration): void;

* Connection state
* @typedef StreamingConnectionState
* @property CONNECTED Used to indicated that the streaming client is connected.
* @see {@link StreamingClient.handshake}
*/
enum ConnectionState {
/**
* Used to indicated that the streaming client is connected.
*/
CONNECTED = 0

@@ -278,10 +305,13 @@ }

* Indicators to test error names for StreamingTimeouts
* @typedef StreamingConnectionState
* @property HANDSHAKE - To indicate the error occurred on handshake
* @property SUBSCRIBE - To indicate the error occurred on subscribe
*/
enum TimeoutErrorType {
/**
* To indicate the error occurred on handshake
*/
HANDSHAKE = "genericHandshakeTimeoutMessage",
/**
* To indicate the error occurred on subscribe
*/
SUBSCRIBE = "genericTimeoutMessage"
}
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -9,2 +8,3 @@ * Copyright (c) 2018, salesforce.com, inc.

*/
Object.defineProperty(exports, "__esModule", { value: true });
const kit_1 = require("@salesforce/kit");

@@ -21,3 +21,2 @@ const ts_types_1 = require("@salesforce/ts-types");

* The Faye implementation is used by default but it could be used to adapt another Cometd impl.
* @abstract
*/

@@ -62,4 +61,3 @@ class CometClient extends events_1.EventEmitter {

*
* @example
*
* ```
* const streamProcessor = (message: JsonMap): StatusResult => {

@@ -100,3 +98,3 @@ * const payload = ensureJsonMap(message.payload);

* });
*
* ```
*/

@@ -107,4 +105,3 @@ class StreamingClient extends kit_1.AsyncOptionalCreatable {

* @param options Streaming client options
* @see {@link AsyncCreatable.create}
* @throws if options is undefined
* {@link AsyncCreatable.create}
*/

@@ -143,3 +140,2 @@ constructor(options) {

* Asynchronous initializer.
* @async
*/

@@ -186,3 +182,2 @@ async init() {

* Provides a convenient way to handshake with the server endpoint before trying to subscribe.
* @async
*/

@@ -206,8 +201,8 @@ handshake() {

/**
* Subscribe to streaming events.
* @param {function} [streamInit] - This function should call the platform apis that result in streaming updates on push topics.
* @returns {Promise} - When the streaming processor that's set in the options completes, it returns a payload in
* the StatusResult object. The payload is just echoed here for convenience.
* @async
* @see {@link StatusResult}
* Subscribe to streaming events. When the streaming processor that's set in the options completes execution it
* returns a payload in the StatusResult object. The payload is just echoed here for convenience.
*
* **Throws** *{@link SfdxError}{ name: '{@link StreamingClient.TimeoutErrorType.SUBSCRIBE}'}* When the subscribe timeout occurs.
* @param streamInit This function should call the platform apis that result in streaming updates on push topics.
* {@link StatusResult}
*/

@@ -312,4 +307,3 @@ subscribe(streamInit) {

* Simple inner log wrapper
* @param {any} message The message to log
* @private
* @param message The message to log
*/

@@ -384,4 +378,6 @@ log(message) {

* Setter for the subscribe timeout.
*
* **Throws** An error if the newTime is less than the default time.
* @param newTime The new subscribe timeout.
* @throws An error if the newTime is less than the default time.
* {@link DefaultOptions.DEFAULT_SUBSCRIBE_TIMEOUT}
*/

@@ -393,4 +389,6 @@ setSubscribeTimeout(newTime) {

* Setter for the handshake timeout.
*
* **Throws** An error if the newTime is less than the default time.
* @param newTime The new handshake timeout
* @throws An error if the newTime is less than the default time.
* {@link DefaultOptions.DEFAULT_HANDSHAKE_TIMEOUT}
*/

@@ -408,4 +406,2 @@ setHandshakeTimeout(newTime) {

* Connection state
* @typedef StreamingConnectionState
* @property CONNECTED Used to indicated that the streaming client is connected.
* @see {@link StreamingClient.handshake}

@@ -415,2 +411,5 @@ */

(function (ConnectionState) {
/**
* Used to indicated that the streaming client is connected.
*/
ConnectionState[ConnectionState["CONNECTED"] = 0] = "CONNECTED";

@@ -420,9 +419,12 @@ })(ConnectionState = StreamingClient.ConnectionState || (StreamingClient.ConnectionState = {}));

* Indicators to test error names for StreamingTimeouts
* @typedef StreamingConnectionState
* @property HANDSHAKE - To indicate the error occurred on handshake
* @property SUBSCRIBE - To indicate the error occurred on subscribe
*/
let TimeoutErrorType;
(function (TimeoutErrorType) {
/**
* To indicate the error occurred on handshake
*/
TimeoutErrorType["HANDSHAKE"] = "genericHandshakeTimeoutMessage";
/**
* To indicate the error occurred on subscribe
*/
TimeoutErrorType["SUBSCRIBE"] = "genericTimeoutMessage";

@@ -429,0 +431,0 @@ })(TimeoutErrorType = StreamingClient.TimeoutErrorType || (StreamingClient.TimeoutErrorType = {}));

@@ -8,3 +8,3 @@ /// <reference types="node" />

import { SfdxError } from './sfdxError';
import { CometClient, CometSubscription } from './status/streamingClient';
import { CometClient, CometSubscription, StreamingExtension } from './status/streamingClient';
/**

@@ -21,7 +21,30 @@ * Different parts of the system that are mocked out. They can be restored for

}
/**
* Different hooks into {@link ConfigFile} used for testing instead of doing file IO.
*/
export interface ConfigStub {
/**
* readFn A function that controls all aspect of {@link ConfigFile.read}. For example, it won't set the contents
* unless explicitly done. Only use this if you know what you are doing. Use retrieveContents
* instead.
*/
readFn?: () => Promise<ConfigContents>;
/**
* A function that controls all aspects of {@link ConfigFile.write}. For example, it won't read the contents unless
* explicitly done. Only use this if you know what you are doing. Use updateContents instead.
*/
writeFn?: () => Promise<void>;
/**
* The contents that are used when @{link ConfigFile.read} unless retrieveContents is set. This will also contain the
* new config when @{link ConfigFile.write} is called. This will persist through config instances,
* such as {@link Alias.update} and {@link Alias.fetch}.
*/
contents?: ConfigContents;
/**
* A function to conditionally read based on the config instance. The `this` value will be the config instance.
*/
retrieveContents?: () => Promise<JsonMap>;
/**
* A function to conditionally set based on the config instance. The `this` value will be the config instance.
*/
updateContents?: () => Promise<JsonMap>;

@@ -33,7 +56,28 @@ }

export interface TestContext {
/**
* The default sandbox is cleared out before each test run.
*
* **See** [sinon sandbox]{@link http://sinonjs.org/releases/v1.17.7/sandbox/}.
*/
SANDBOX: sinonType.SinonSandbox;
/**
* An object of different sandboxes. Used when
* needing to restore parts of the system for customized testing.
*/
SANDBOXES: SandboxTypes;
/**
* The test logger that is used when {@link Logger.child} is used anywhere. It uses memory logging.
*/
TEST_LOGGER: Logger;
/**
* id A unique id for the test run.
*/
id: string;
/**
* A function that returns unique strings.
*/
uniqid: () => string;
/**
* An object used in tests that interact with config files.
*/
configStubs: {

@@ -46,60 +90,45 @@ [configName: string]: Optional<ConfigStub>;

};
/**
* A function used when resolving the local path.
* @param uid Unique id.
*/
localPathRetriever: (uid: string) => Promise<string>;
/**
* A function used when resolving the global path.
* @param uid Unique id.
*/
globalPathRetriever: (uid: string) => Promise<string>;
/**
* A function used for resolving paths. Calls localPathRetriever and globalPathRetriever.
* @param isGlobal `true` if the config is global.
* @param uid user id.
*/
rootPathRetriever: (isGlobal: boolean, uid?: string) => Promise<string>;
/**
* Used to mock http request to Salesforce.
* @param request An HttpRequest.
* @param options Additional options.
*
* **See** {@link Connection.request}
*/
fakeConnectionRequest: (request: AnyJson, options?: AnyJson) => Promise<AnyJson>;
/**
* Gets a config stub contents by name.
* @param name The name of the config.
* @param group If the config supports groups.
*/
getConfigStubContents(name: string, group?: string): ConfigContents;
/**
* Sets a config stub contents by name
* @param name The name of the config stub.
* @param value The actual stub contents. The Mock data.
*/
setConfigStubContents(name: string, value: ConfigContents): void;
}
/**
* @module testSetup
*/
/**
* Different hooks into {@link ConfigFile} used for testing instead of doing file IO.
* @typedef {object} TestContext
* @property {function} readFn A function `() => Promise<ConfigContents>;` that controls
* all aspect of {@link ConfigFile.read}. For example, it won't set the contents unless
* explicitly done. Only use this if you know what you are doing. Use retrieveContents
* instead.
* @property {function} writeFn A function `() => Promise<void>;` that controls all aspects
* of {@link ConfigFile.write}. For example, it won't read the contents unless explicitly
* done. Only use this if you know what you are doing. Use updateContents instead.
* @property {object} contents The contents that are used when @{link ConfigFile.read} unless
* retrieveContents is set. This will also contain the new config when @{link ConfigFile.write}
* is called. This will persist through config instances, such as {@link Alias.update} and
* {@link Alias.fetch}.
* @property {function} retrieveContents A function `() => Promise<object>;` to conditionally
* read based on the config instance. The `this` value will be the config instance.
* @property {function} updateContents A function `() => Promise<object>;` to conditionally
* set based on the config instance. The `this` value will be the config instance.
*/
/**
* Different configuration options when running before each.
* @typedef {object} TestContext
* @property {sinon.sandbox} SANDBOX The default sandbox is cleared out before
* each test run. See [sinon sandbox]{@link http://sinonjs.org/releases/v1.17.7/sandbox/}.
* @property {SandboxTypes} SANDBOXES An object of different sandboxes. Used when
* needing to restore parts of the system for customized testing.
* @property {Logger} TEST_LOGGER The test logger that is used when {@link Logger.child}
* is used anywhere. It uses memory logging.
* @property {string} id A unique id for the test run.
* @property {function} uniqid A function `() => string` that returns unique strings.
* @property {object} configStubs An object of `[configName: string]: ConfigStub` used in test that interact with config files.
* names to {@link ConfigStubs} that contain properties used when reading and writing
* to config files.
* @property {function} localPathRetriever A function `(uid: string) => Promise<string>;`
* used when resolving the local path.
* @property {function} globalPathRetriever A function `(uid: string) => Promise<string>;`
* used when resolving the global path.
* @property {function} rootPathRetriever: A function `(isGlobal: boolean, uid?: string) => Promise<string>;`
* used then resolving paths. Calls localPathRetriever and globalPathRetriever.
*/
/**
* Use to mock out different pieces of sfdx-core to make testing easier. This will mock out
* logging to a file, config file reading and writing, local and global path resolution, and
* *http request using connection (soon)*.
* @function testSetup
* @returns {TestContext}
*
* @example
* ```
* // In a mocha tests

@@ -123,2 +152,3 @@ * import testSetup from '@salesforce/core/lib/testSetup';

* });
* ```
*/

@@ -128,4 +158,4 @@ export declare const testSetup: (sinon?: any) => TestContext;

* A pre-canned error for try/catch testing.
* @see shouldThrow
* @type {SfdxError}
*
* **See** {@link shouldThrow}
*/

@@ -135,3 +165,3 @@ export declare const unexpectedResult: SfdxError;

* Use for this testing pattern:
*
* ```
* try {

@@ -151,5 +181,4 @@ * await call()

* }
*
* @param {Promise<AnyJson>} f The async function that is expected to throw.
* @returns {Promise<void>}
* ```
* @param f The async function that is expected to throw.
*/

@@ -169,6 +198,21 @@ export declare function shouldThrow(f: Promise<unknown>): Promise<never>;

export interface StreamingMockCometSubscriptionOptions {
/**
* Target URL.
*/
url: string;
/**
* Simple id to associate with this instance.
*/
id: string;
/**
* What is the subscription outcome a successful callback or an error?.
*/
subscriptionCall: StreamingMockSubscriptionCall;
/**
* If it's an error that states what that error should be.
*/
subscriptionErrbackError?: SfdxError;
/**
* A list of messages to playback for the client. One message per process tick.
*/
messagePlaylist?: JsonMap[];

@@ -184,3 +228,11 @@ }

constructor(options: StreamingMockCometSubscriptionOptions);
/**
* Sets up a streaming subscription callback to occur after the setTimeout event loop phase.
* @param callback The function to invoke.
*/
callback(callback: () => void): void;
/**
* Sets up a streaming subscription errback to occur after the setTimeout event loop phase.
* @param callback The function to invoke.
*/
errback(callback: (error: Error) => void): void;

@@ -200,7 +252,28 @@ }

constructor(options: StreamingMockCometSubscriptionOptions);
addExtension(extension: JsonMap): void;
/**
* Fake addExtension. Does nothing.
*/
addExtension(extension: StreamingExtension): void;
/**
* Fake disable. Does nothing.
*/
disable(label: string): void;
/**
* Fake handshake that invoke callback after the setTimeout event phase.
* @param callback The function to invoke.
*/
handshake(callback: () => void): void;
/**
* Fake setHeader. Does nothing,
*/
setHeader(name: string, value: string): void;
/**
* Fake subscription that completed after the setTimout event phase.
* @param channel The streaming channel.
* @param callback The function to invoke after the subscription completes.
*/
subscribe(channel: string, callback: (message: JsonMap) => void): CometSubscription;
/**
* Fake disconnect. Does Nothing.
*/
disconnect(): Promise<void>;

@@ -207,0 +280,0 @@ }

"use strict";
/*
* Copyright (c) 2018, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
Object.defineProperty(exports, "__esModule", { value: true });
const kit_1 = require("@salesforce/kit");
const ts_sinon_1 = require("@salesforce/ts-sinon");
const ts_types_1 = require("@salesforce/ts-types");

@@ -28,77 +35,7 @@ const crypto_1 = require("crypto");

}
function defaultFakeConnectionRequest(request, options) {
return Promise.resolve({ records: [] });
function defaultFakeConnectionRequest() {
return Promise.resolve(ts_types_1.ensureAnyJson({ records: [] }));
}
/**
* @module testSetup
*/
/**
* Different hooks into {@link ConfigFile} used for testing instead of doing file IO.
* @typedef {object} TestContext
* @property {function} readFn A function `() => Promise<ConfigContents>;` that controls
* all aspect of {@link ConfigFile.read}. For example, it won't set the contents unless
* explicitly done. Only use this if you know what you are doing. Use retrieveContents
* instead.
* @property {function} writeFn A function `() => Promise<void>;` that controls all aspects
* of {@link ConfigFile.write}. For example, it won't read the contents unless explicitly
* done. Only use this if you know what you are doing. Use updateContents instead.
* @property {object} contents The contents that are used when @{link ConfigFile.read} unless
* retrieveContents is set. This will also contain the new config when @{link ConfigFile.write}
* is called. This will persist through config instances, such as {@link Alias.update} and
* {@link Alias.fetch}.
* @property {function} retrieveContents A function `() => Promise<object>;` to conditionally
* read based on the config instance. The `this` value will be the config instance.
* @property {function} updateContents A function `() => Promise<object>;` to conditionally
* set based on the config instance. The `this` value will be the config instance.
*/
/**
* Different configuration options when running before each.
* @typedef {object} TestContext
* @property {sinon.sandbox} SANDBOX The default sandbox is cleared out before
* each test run. See [sinon sandbox]{@link http://sinonjs.org/releases/v1.17.7/sandbox/}.
* @property {SandboxTypes} SANDBOXES An object of different sandboxes. Used when
* needing to restore parts of the system for customized testing.
* @property {Logger} TEST_LOGGER The test logger that is used when {@link Logger.child}
* is used anywhere. It uses memory logging.
* @property {string} id A unique id for the test run.
* @property {function} uniqid A function `() => string` that returns unique strings.
* @property {object} configStubs An object of `[configName: string]: ConfigStub` used in test that interact with config files.
* names to {@link ConfigStubs} that contain properties used when reading and writing
* to config files.
* @property {function} localPathRetriever A function `(uid: string) => Promise<string>;`
* used when resolving the local path.
* @property {function} globalPathRetriever A function `(uid: string) => Promise<string>;`
* used when resolving the global path.
* @property {function} rootPathRetriever: A function `(isGlobal: boolean, uid?: string) => Promise<string>;`
* used then resolving paths. Calls localPathRetriever and globalPathRetriever.
*/
/**
* Use to mock out different pieces of sfdx-core to make testing easier. This will mock out
* logging to a file, config file reading and writing, local and global path resolution, and
* *http request using connection (soon)*.
* @function testSetup
* @returns {TestContext}
*
* @example
* // In a mocha tests
* import testSetup from '@salesforce/core/lib/testSetup';
*
* const $$ = testSetup();
*
* describe(() => {
* it('test', () => {
* // Stub out your own method
* $$.SANDBOX.stub(MyClass.prototype, 'myMethod').returnsFake(() => {});
*
* // Set the contents that is used when aliases are read. Same for all config files.
* $$.configStubs.Aliases = { contents: { 'myTestAlias': 'user@company.com' } };
*
* // Will use the contents set above.
* const username = Aliases.fetch('myTestAlias');
* expect(username).to.equal('user@company.com');
* });
* });
*/
// tslint:disable-next-line:no-any
exports.testSetup = kit_1.once((sinon) => {
const _testSetup = (sinon) => {
if (!sinon) {

@@ -155,3 +92,3 @@ try {

// Most core files create a child logger so stub this to return our test logger.
testContext.SANDBOX.stub(logger_1.Logger, 'child').returns(Promise.resolve(testContext.TEST_LOGGER));
ts_sinon_1.stubMethod(testContext.SANDBOX, logger_1.Logger, 'child').returns(Promise.resolve(testContext.TEST_LOGGER));
testContext.SANDBOXES.CONFIG.stub(configFile_1.ConfigFile, 'resolveRootFolder').callsFake((isGlobal) => testContext.rootPathRetriever(isGlobal, testContext.id));

@@ -205,7 +142,34 @@ // Mock out all config file IO for all tests. They can restore individually if they need original functionality.

return testContext;
});
};
/**
* Use to mock out different pieces of sfdx-core to make testing easier. This will mock out
* logging to a file, config file reading and writing, local and global path resolution, and
* *http request using connection (soon)*.
*
* ```
* // In a mocha tests
* import testSetup from '@salesforce/core/lib/testSetup';
*
* const $$ = testSetup();
*
* describe(() => {
* it('test', () => {
* // Stub out your own method
* $$.SANDBOX.stub(MyClass.prototype, 'myMethod').returnsFake(() => {});
*
* // Set the contents that is used when aliases are read. Same for all config files.
* $$.configStubs.Aliases = { contents: { 'myTestAlias': 'user@company.com' } };
*
* // Will use the contents set above.
* const username = Aliases.fetch('myTestAlias');
* expect(username).to.equal('user@company.com');
* });
* });
* ```
*/
exports.testSetup = kit_1.once(_testSetup);
/**
* A pre-canned error for try/catch testing.
* @see shouldThrow
* @type {SfdxError}
*
* **See** {@link shouldThrow}
*/

@@ -215,3 +179,3 @@ exports.unexpectedResult = new sfdxError_1.SfdxError('This code was expected to failed', 'UnexpectedResult');

* Use for this testing pattern:
*
* ```
* try {

@@ -231,5 +195,4 @@ * await call()

* }
*
* @param {Promise<AnyJson>} f The async function that is expected to throw.
* @returns {Promise<void>}
* ```
* @param f The async function that is expected to throw.
*/

@@ -258,2 +221,6 @@ async function shouldThrow(f) {

}
/**
* Sets up a streaming subscription callback to occur after the setTimeout event loop phase.
* @param callback The function to invoke.
*/
callback(callback) {

@@ -267,2 +234,6 @@ if (this.options.subscriptionCall === StreamingMockSubscriptionCall.CALLBACK) {

}
/**
* Sets up a streaming subscription errback to occur after the setTimeout event loop phase.
* @param callback The function to invoke.
*/
errback(callback) {

@@ -300,4 +271,14 @@ if (this.options.subscriptionCall === StreamingMockSubscriptionCall.ERRORBACK) {

}
/**
* Fake addExtension. Does nothing.
*/
addExtension(extension) { }
/**
* Fake disable. Does nothing.
*/
disable(label) { }
/**
* Fake handshake that invoke callback after the setTimeout event phase.
* @param callback The function to invoke.
*/
handshake(callback) {

@@ -308,3 +289,11 @@ setTimeout(() => {

}
/**
* Fake setHeader. Does nothing,
*/
setHeader(name, value) { }
/**
* Fake subscription that completed after the setTimout event phase.
* @param channel The streaming channel.
* @param callback The function to invoke after the subscription completes.
*/
subscribe(channel, callback) {

@@ -323,2 +312,5 @@ const subscription = new StreamingMockCometSubscription(this.options);

}
/**
* Fake disconnect. Does Nothing.
*/
disconnect() {

@@ -325,0 +317,0 @@ return Promise.resolve();

@@ -22,3 +22,4 @@ import { AsyncCreatable } from '@salesforce/kit';

* Required fields type needed to represent a Salesforce User object.
* @see https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_user.htm
*
* **See** https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_user.htm
*/

@@ -32,3 +33,3 @@ export declare type UserFields = {

*
* @example
* ```
* const options: DefaultUserFieldsOptions = {

@@ -38,2 +39,3 @@ * templateUser: org.getUsername() || ''

* const fields = (await DefaultUserFields.create(options)).getFields();
* ```
*/

@@ -44,4 +46,13 @@ export declare class DefaultUserFields extends AsyncCreatable<User.Options> {

private options;
/**
* @ignore
*/
constructor(options: User.Options);
/**
* Get user fields.
*/
getFields(): UserFields;
/**
* Initialize asynchronous components.
*/
protected init(): Promise<void>;

@@ -55,10 +66,8 @@ }

/**
* Initialize a new instance of a user.
* @param {Org} org The org associated with the user.
* @returns {User} A user instance
* Initialize a new instance of a user and return it.
* @param org The org associated with the user.
*/
static init(org: Org): Promise<User>;
/**
* Generate default password for a user.
* @returns {SecureBuffer} An encrypted buffer containing a utf8 encoded password.
* Generate default password for a user. Returns An encrypted buffer containing a utf8 encoded password.
*/

@@ -71,5 +80,5 @@ static generatePasswordUtf8(): SecureBuffer<void>;

* Assigns a password to a user. For a user to have the ability to assign their own password, the org needs the
* following org preference: SelfSetPasswordInApi
* @param {AuthInfo} info The AuthInfo object for user to assign the password to.
* @param {SecureBuffer} password [throwWhenRemoveFails = User.generatePasswordUtf8()] A SecureBuffer containing the new password.
* following org preference: SelfSetPasswordInApi.
* @param info The AuthInfo object for user to assign the password to.
* @param password [throwWhenRemoveFails = User.generatePasswordUtf8()] A SecureBuffer containing the new password.
*/

@@ -79,6 +88,6 @@ assignPassword(info: AuthInfo, password?: SecureBuffer<void>): Promise<{}>;

* Methods to assign one or more permission set names to a user.
* @param {string} id The Salesforce id of the user to assign the permission set to.
* @param {string[]} permsetNames An array of permission set names.
* @param id The Salesforce id of the user to assign the permission set to.
* @param permsetNames An array of permission set names.
*
* @example
* ```
* const org = await Org.create(await Connection.create(await AuthInfo.create('standardUser')));

@@ -88,2 +97,3 @@ * const user: User = await User.init(org)

* await user.assignPermissionSets(fields.id, ['sfdx', 'approver']);
* ```
*/

@@ -101,6 +111,5 @@ assignPermissionSets(id: string, permsetNames: string[]): Promise<void>;

*
* @param {UserFields} fields The required fields for creating a user.
* @returns {Promise<AuthInfo>} An AuthInfo object for the new user.
* @param fields The required fields for creating a user.
*
* @example
* ```
* const org = await Org.create(await Connection.create(await AuthInfo.create('fooUser')));

@@ -110,2 +119,3 @@ * const fields: UserFields = await DefaultUserFields.init(org);

* const info: AuthInfo = await user.create(fields);
* ```
*/

@@ -115,8 +125,9 @@ create(fields: UserFields): Promise<AuthInfo>;

* Method to retrieve the UserFields for a user.
* @param {string} username The username of the user
* @param username The username of the user.
*
* @example
* ```
* const org = await Org.create(await Connection.create(await AuthInfo.create('fooUser')));
* const user: User = await User.init(org);
* const fields: UserFields = await user.retrieve('boris@thecat.com')
* ```
*/

@@ -126,3 +137,3 @@ retrieve(username: string): Promise<UserFields>;

* Helper method that verifies the server's User object is available and if so allows persisting the Auth information.
* @param {AuthInfo} newUserAuthInfo The AuthInfo for the new user.
* @param newUserAuthInfo The AuthInfo for the new user.
*/

@@ -132,3 +143,3 @@ private describeUserAndSave;

* Helper that makes a REST request to create the user, and update additional required fields.
* @param {UserFields} fields The configuration the new user should have.
* @param fields The configuration the new user should have.
*/

@@ -138,3 +149,3 @@ private createUserInternal;

* Update the remaining required fields for the user.
* @param {UserFields} fields The fields for the user.
* @param fields The fields for the user.
*/

@@ -141,0 +152,0 @@ private updateRequiredUserFields;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -9,2 +8,3 @@ * Copyright (c) 2018, salesforce.com, inc.

*/
Object.defineProperty(exports, "__esModule", { value: true });
const kit_1 = require("@salesforce/kit");

@@ -46,4 +46,4 @@ const ts_types_1 = require("@salesforce/ts-types");

/**
* Helper method to lookup UserFields
* @param {string} username The username
* Helper method to lookup UserFields.
* @param username The username.
*/

@@ -80,7 +80,7 @@ async function _retrieveUserFields(username) {

* Gets the profile id associated with a profile name.
* @param {string} name The name of the profile.
* @param {Connection} connection The connection for the query.
* @param name The name of the profile.
* @param connection The connection for the query.
*/
async function _retrieveProfileId(name, connection) {
if (!sfdc_1.validateSalesforceId(name)) {
if (!sfdc_1.sfdc.validateSalesforceId(name)) {
const profileQuery = `SELECT Id FROM Profile WHERE name='${name}'`;

@@ -98,3 +98,3 @@ const result = await connection.query(profileQuery);

*
* @example
* ```
* const options: DefaultUserFieldsOptions = {

@@ -104,4 +104,8 @@ * templateUser: org.getUsername() || ''

* const fields = (await DefaultUserFields.create(options)).getFields();
* ```
*/
class DefaultUserFields extends kit_1.AsyncCreatable {
/**
* @ignore
*/
constructor(options) {

@@ -111,5 +115,11 @@ super(options);

}
/**
* Get user fields.
*/
getFields() {
return this.userFields;
}
/**
* Initialize asynchronous components.
*/
async init() {

@@ -137,5 +147,4 @@ this.logger = await logger_1.Logger.child('DefaultUserFields');

/**
* Initialize a new instance of a user.
* @param {Org} org The org associated with the user.
* @returns {User} A user instance
* Initialize a new instance of a user and return it.
* @param org The org associated with the user.
*/

@@ -152,4 +161,3 @@ static async init(org) {

/**
* Generate default password for a user.
* @returns {SecureBuffer} An encrypted buffer containing a utf8 encoded password.
* Generate default password for a user. Returns An encrypted buffer containing a utf8 encoded password.
*/

@@ -174,5 +182,5 @@ static generatePasswordUtf8() {

* Assigns a password to a user. For a user to have the ability to assign their own password, the org needs the
* following org preference: SelfSetPasswordInApi
* @param {AuthInfo} info The AuthInfo object for user to assign the password to.
* @param {SecureBuffer} password [throwWhenRemoveFails = User.generatePasswordUtf8()] A SecureBuffer containing the new password.
* following org preference: SelfSetPasswordInApi.
* @param info The AuthInfo object for user to assign the password to.
* @param password [throwWhenRemoveFails = User.generatePasswordUtf8()] A SecureBuffer containing the new password.
*/

@@ -199,6 +207,6 @@ async assignPassword(info, password = User.generatePasswordUtf8()) {

* Methods to assign one or more permission set names to a user.
* @param {string} id The Salesforce id of the user to assign the permission set to.
* @param {string[]} permsetNames An array of permission set names.
* @param id The Salesforce id of the user to assign the permission set to.
* @param permsetNames An array of permission set names.
*
* @example
* ```
* const org = await Org.create(await Connection.create(await AuthInfo.create('standardUser')));

@@ -208,2 +216,3 @@ * const user: User = await User.init(org)

* await user.assignPermissionSets(fields.id, ['sfdx', 'approver']);
* ```
*/

@@ -232,6 +241,5 @@ async assignPermissionSets(id, permsetNames) {

*
* @param {UserFields} fields The required fields for creating a user.
* @returns {Promise<AuthInfo>} An AuthInfo object for the new user.
* @param fields The required fields for creating a user.
*
* @example
* ```
* const org = await Org.create(await Connection.create(await AuthInfo.create('fooUser')));

@@ -241,2 +249,3 @@ * const fields: UserFields = await DefaultUserFields.init(org);

* const info: AuthInfo = await user.create(fields);
* ```
*/

@@ -272,8 +281,9 @@ async create(fields) {

* Method to retrieve the UserFields for a user.
* @param {string} username The username of the user
* @param username The username of the user.
*
* @example
* ```
* const org = await Org.create(await Connection.create(await AuthInfo.create('fooUser')));
* const user: User = await User.init(org);
* const fields: UserFields = await user.retrieve('boris@thecat.com')
* ```
*/

@@ -285,3 +295,3 @@ async retrieve(username) {

* Helper method that verifies the server's User object is available and if so allows persisting the Auth information.
* @param {AuthInfo} newUserAuthInfo The AuthInfo for the new user.
* @param newUserAuthInfo The AuthInfo for the new user.
*/

@@ -302,3 +312,3 @@ async describeUserAndSave(newUserAuthInfo) {

* Helper that makes a REST request to create the user, and update additional required fields.
* @param {UserFields} fields The configuration the new user should have.
* @param fields The configuration the new user should have.
*/

@@ -365,3 +375,3 @@ async createUserInternal(fields) {

* Update the remaining required fields for the user.
* @param {UserFields} fields The fields for the user.
* @param fields The fields for the user.
*/

@@ -368,0 +378,0 @@ async updateRequiredUserFields(fields) {

@@ -1,127 +0,92 @@

/**
* @module fs
*/
/// <reference types="node" />
import { AnyJson, JsonMap, Optional } from '@salesforce/ts-types';
import * as fs from 'fs';
/**
* The default file system mode to use when creating directories.
*/
export declare const DEFAULT_USER_DIR_MODE = "700";
/**
* The default file system mode to use when creating files.
*/
export declare const DEFAULT_USER_FILE_MODE = "600";
/**
* A convenience reference to {@link https://nodejs.org/api/fs.html#fs_fs_constants}
* to reduce the need to import multiple `fs` modules.
*/
export declare const constants: typeof fs.constants;
/**
* Promisified version of {@link https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback|fs.readFile}.
*
* @function readFile
* @returns {Promise<string>|Promise<Buffer>|Promise<string|Buffer>}
*/
export declare const readFile: typeof fs.readFile.__promisify__;
/**
* Promisified version of {@link https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback|fs.readdir}.
*
* @function readdir
* @returns {Promise<Array<string>>|Promise<Array<Buffer>>|Promise<Array<string|Buffer>>}
*/
export declare const readdir: typeof fs.readdir.__promisify__;
/**
* Promisified version of {@link https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback|fs.writeFile}.
*
* @function writeFile
* @returns {Promise<void>}
*/
export declare const writeFile: typeof fs.writeFile.__promisify__;
/**
* Promisified version of {@link https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callback|fs.access}.
*
* @function access
* @returns {Promise<void>}
*/
export declare const access: typeof fs.access.__promisify__;
/**
* Promisified version of {@link https://nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback|fs.open}.
*
* @function open
* @returns {Promise<number>}
*/
export declare const open: typeof fs.open.__promisify__;
/**
* Promisified version of {@link https://nodejs.org/api/fs.html#fs_fs_unlink_path_callback|fs.unlink}.
*
* @function unlink
* @returns {Promise<void>}
*/
export declare const unlink: typeof fs.unlink.__promisify__;
/**
* Promisified version of {@link https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback|fs.rmdir}.
*
* @function rmdir
* @returns {Promise<void>}
*/
export declare const rmdir: typeof fs.rmdir.__promisify__;
/**
* Promisified version of {@link https://nodejs.org/api/fs.html#fs_fs_fstat_fd_callback|fs.stat}.
*
* @function stat
* @returns {Promise<fs.Stats>}
*/
export declare const stat: typeof fs.stat.__promisify__;
/**
* Promisified version of {@link https://npmjs.com/package/mkdirp|mkdirp}.
*
* @function mkdirp
* @returns {Promise<void>}
*/
export declare const mkdirp: (folderPath: string, mode?: string | object) => Promise<void>;
/**
* Deletes a folder recursively, removing all descending files and folders.
*
* @param {string} dirPath The path to remove.
* @returns {Promise<void>}
* @throws {SfdxError}
* **`{name: 'PathIsNullOrUndefined'}`** The path is not defined.
* @throws {SfdxError}
* **`{name: 'DirMissingOrNoAccess'}`** The folder or any sub-folder is missing or has no access.
*/
export declare function remove(dirPath: string): Promise<void>;
/**
* Searches a file path in an ascending manner (until reaching the filesystem root) for the first occurrence a
* specific file name. Resolves with the directory path containing the located file, or `null` if the file was
* not found.
*
* @param {string} dir The directory path in which to start the upward search.
* @param {string} file The file name to look for.
* @returns {Promise<Optional<string>>}
*/
export declare function traverseForFile(dir: string, file: string): Promise<Optional<string>>;
/**
* Read a file and convert it to JSON.
*
* @param {string} jsonPath The path of the file.
* @param {boolean} [throwOnEmpty] Whether to throw an error if the JSON file is empty.
* @return {Promise<AnyJson>} The contents of the file as a JSON object.
*/
export declare function readJson(jsonPath: string, throwOnEmpty?: boolean): Promise<AnyJson>;
/**
* Read a file and convert it to JSON, throwing an error if the parsed contents are not a `JsonMap`.
*
* @param {string} jsonPath The path of the file.
* @param {boolean} [throwOnEmpty] Whether to throw an error if the JSON file is empty.
* @return {Promise<JsonMap>} The contents of the file as a JSON object.
*/
export declare function readJsonMap(jsonPath: string, throwOnEmpty?: boolean): Promise<JsonMap>;
/**
* Convert a JSON-compatible object to a `string` and write it to a file.
*
* @param {string} jsonPath The path of the file to write.
* @param {object} data The JSON object to write.
* @return {Promise<void>}
*/
export declare function writeJson(jsonPath: string, data: AnyJson): Promise<void>;
import { AnyJson, JsonMap } from '@salesforce/ts-types';
import * as fsLib from 'fs';
export declare const fs: {
/**
* The default file system mode to use when creating directories.
*/
DEFAULT_USER_DIR_MODE: string;
/**
* The default file system mode to use when creating files.
*/
DEFAULT_USER_FILE_MODE: string;
/**
* A convenience reference to {@link https://nodejs.org/api/fsLib.html#fs_fs_constants}
* to reduce the need to import multiple `fs` modules.
*/
constants: typeof fsLib.constants;
/**
* Promisified version of {@link https://nodejs.org/api/fsLib.html#fs_fs_readfile_path_options_callback|fsLib.readFile}.
*/
readFile: typeof fsLib.readFile.__promisify__;
/**
* Promisified version of {@link https://nodejs.org/api/fsLib.html#fs_fs_readdir_path_options_callback|fsLib.readdir}.
*/
readdir: typeof fsLib.readdir.__promisify__;
/**
* Promisified version of {@link https://nodejs.org/api/fsLib.html#fs_fs_writefile_file_data_options_callback|fsLib.writeFile}.
*/
writeFile: typeof fsLib.writeFile.__promisify__;
/**
* Promisified version of {@link https://nodejs.org/api/fsLib.html#fs_fs_access_path_mode_callback|fsLib.access}.
*/
access: typeof fsLib.access.__promisify__;
/**
* Promisified version of {@link https://nodejs.org/api/fsLib.html#fs_fs_open_path_flags_mode_callback|fsLib.open}.
*/
open: typeof fsLib.open.__promisify__;
/**
* Promisified version of {@link https://nodejs.org/api/fsLib.html#fs_fs_unlink_path_callback|fsLib.unlink}.
*/
unlink: typeof fsLib.unlink.__promisify__;
/**
* Promisified version of {@link https://nodejs.org/api/fsLib.html#fs_fs_readdir_path_options_callback|fsLib.rmdir}.
*/
rmdir: typeof fsLib.rmdir.__promisify__;
/**
* Promisified version of {@link https://nodejs.org/api/fsLib.html#fs_fs_fstat_fd_callback|fsLib.stat}.
*/
stat: typeof fsLib.stat.__promisify__;
/**
* Promisified version of {@link https://npmjs.com/package/mkdirp|mkdirp}.
*/
mkdirp: (folderPath: string, mode?: string | object | undefined) => Promise<void>;
/**
* Deletes a folder recursively, removing all descending files and folders.
*
* **Throws** *PathIsNullOrUndefined* The path is not defined.
* **Throws** *DirMissingOrNoAccess* The folder or any sub-folder is missing or has no access.
* @param {string} dirPath The path to remove.
*/
remove: (dirPath: string) => Promise<void>;
/**
* Searches a file path in an ascending manner (until reaching the filesystem root) for the first occurrence a
* specific file name. Resolves with the directory path containing the located file, or `null` if the file was
* not found.
*
* @param dir The directory path in which to start the upward search.
* @param file The file name to look for.
*/
traverseForFile: (dir: string, file: string) => Promise<string | undefined>;
/**
* Read a file and convert it to JSON. Returns the contents of the file as a JSON object
*
* @param jsonPath The path of the file.
* @param throwOnEmpty Whether to throw an error if the JSON file is empty.
*/
readJson: (jsonPath: string, throwOnEmpty?: boolean | undefined) => Promise<AnyJson>;
/**
* Read a file and convert it to JSON, throwing an error if the parsed contents are not a `JsonMap`.
*
* @param jsonPath The path of the file.
* @param throwOnEmpty Whether to throw an error if the JSON file is empty.
*/
readJsonMap: (jsonPath: string, throwOnEmpty?: boolean | undefined) => Promise<JsonMap>;
/**
* Convert a JSON-compatible object to a `string` and write it to a file.
*
* @param jsonPath The path of the file to write.
* @param data The JSON object to write.
*/
writeJson: (jsonPath: string, data: AnyJson) => Promise<void>;
};

@@ -8,8 +8,5 @@ "use strict";

*/
/**
* @module fs
*/
Object.defineProperty(exports, "__esModule", { value: true });
const kit_1 = require("@salesforce/kit");
const fs = require("fs");
const fsLib = require("fs");
const mkdirpLib = require("mkdirp");

@@ -19,171 +16,135 @@ const path = require("path");

const sfdxError_1 = require("../sfdxError");
/**
* The default file system mode to use when creating directories.
*/
exports.DEFAULT_USER_DIR_MODE = '700';
/**
* The default file system mode to use when creating files.
*/
exports.DEFAULT_USER_FILE_MODE = '600';
/**
* A convenience reference to {@link https://nodejs.org/api/fs.html#fs_fs_constants}
* to reduce the need to import multiple `fs` modules.
*/
exports.constants = fs.constants;
/**
* Promisified version of {@link https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback|fs.readFile}.
*
* @function readFile
* @returns {Promise<string>|Promise<Buffer>|Promise<string|Buffer>}
*/
exports.readFile = util_1.promisify(fs.readFile);
/**
* Promisified version of {@link https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback|fs.readdir}.
*
* @function readdir
* @returns {Promise<Array<string>>|Promise<Array<Buffer>>|Promise<Array<string|Buffer>>}
*/
exports.readdir = util_1.promisify(fs.readdir);
/**
* Promisified version of {@link https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback|fs.writeFile}.
*
* @function writeFile
* @returns {Promise<void>}
*/
exports.writeFile = util_1.promisify(fs.writeFile);
/**
* Promisified version of {@link https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callback|fs.access}.
*
* @function access
* @returns {Promise<void>}
*/
exports.access = util_1.promisify(fs.access);
/**
* Promisified version of {@link https://nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback|fs.open}.
*
* @function open
* @returns {Promise<number>}
*/
exports.open = util_1.promisify(fs.open);
/**
* Promisified version of {@link https://nodejs.org/api/fs.html#fs_fs_unlink_path_callback|fs.unlink}.
*
* @function unlink
* @returns {Promise<void>}
*/
exports.unlink = util_1.promisify(fs.unlink);
/**
* Promisified version of {@link https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback|fs.rmdir}.
*
* @function rmdir
* @returns {Promise<void>}
*/
exports.rmdir = util_1.promisify(fs.rmdir);
/**
* Promisified version of {@link https://nodejs.org/api/fs.html#fs_fs_fstat_fd_callback|fs.stat}.
*
* @function stat
* @returns {Promise<fs.Stats>}
*/
exports.stat = util_1.promisify(fs.stat);
/**
* Promisified version of {@link https://npmjs.com/package/mkdirp|mkdirp}.
*
* @function mkdirp
* @returns {Promise<void>}
*/
exports.mkdirp = util_1.promisify(mkdirpLib);
/**
* Deletes a folder recursively, removing all descending files and folders.
*
* @param {string} dirPath The path to remove.
* @returns {Promise<void>}
* @throws {SfdxError}
* **`{name: 'PathIsNullOrUndefined'}`** The path is not defined.
* @throws {SfdxError}
* **`{name: 'DirMissingOrNoAccess'}`** The folder or any sub-folder is missing or has no access.
*/
async function remove(dirPath) {
if (!dirPath) {
throw new sfdxError_1.SfdxError('Path is null or undefined.', 'PathIsNullOrUndefined');
}
try {
await exports.access(dirPath, fs.constants.R_OK);
}
catch (err) {
throw new sfdxError_1.SfdxError(`The path: ${dirPath} doesn\'t exist or access is denied.`, 'DirMissingOrNoAccess');
}
const files = await exports.readdir(dirPath);
const stats = await Promise.all(files.map(file => exports.stat(path.join(dirPath, file))));
const metas = stats.map((value, index) => Object.assign(value, { path: path.join(dirPath, files[index]) }));
await Promise.all(metas.map(meta => (meta.isDirectory() ? remove(meta.path) : exports.unlink(meta.path))));
await exports.rmdir(dirPath);
}
exports.remove = remove;
/**
* Searches a file path in an ascending manner (until reaching the filesystem root) for the first occurrence a
* specific file name. Resolves with the directory path containing the located file, or `null` if the file was
* not found.
*
* @param {string} dir The directory path in which to start the upward search.
* @param {string} file The file name to look for.
* @returns {Promise<Optional<string>>}
*/
async function traverseForFile(dir, file) {
let foundProjectDir;
try {
await exports.stat(path.join(dir, file));
foundProjectDir = dir;
}
catch (err) {
if (err && err.code === 'ENOENT') {
const nextDir = path.resolve(dir, '..');
if (nextDir !== dir) {
// stop at root
foundProjectDir = await traverseForFile(nextDir, file);
exports.fs = {
/**
* The default file system mode to use when creating directories.
*/
DEFAULT_USER_DIR_MODE: '700',
/**
* The default file system mode to use when creating files.
*/
DEFAULT_USER_FILE_MODE: '600',
/**
* A convenience reference to {@link https://nodejs.org/api/fsLib.html#fs_fs_constants}
* to reduce the need to import multiple `fs` modules.
*/
constants: fsLib.constants,
/**
* Promisified version of {@link https://nodejs.org/api/fsLib.html#fs_fs_readfile_path_options_callback|fsLib.readFile}.
*/
readFile: util_1.promisify(fsLib.readFile),
/**
* Promisified version of {@link https://nodejs.org/api/fsLib.html#fs_fs_readdir_path_options_callback|fsLib.readdir}.
*/
readdir: util_1.promisify(fsLib.readdir),
/**
* Promisified version of {@link https://nodejs.org/api/fsLib.html#fs_fs_writefile_file_data_options_callback|fsLib.writeFile}.
*/
writeFile: util_1.promisify(fsLib.writeFile),
/**
* Promisified version of {@link https://nodejs.org/api/fsLib.html#fs_fs_access_path_mode_callback|fsLib.access}.
*/
access: util_1.promisify(fsLib.access),
/**
* Promisified version of {@link https://nodejs.org/api/fsLib.html#fs_fs_open_path_flags_mode_callback|fsLib.open}.
*/
open: util_1.promisify(fsLib.open),
/**
* Promisified version of {@link https://nodejs.org/api/fsLib.html#fs_fs_unlink_path_callback|fsLib.unlink}.
*/
unlink: util_1.promisify(fsLib.unlink),
/**
* Promisified version of {@link https://nodejs.org/api/fsLib.html#fs_fs_readdir_path_options_callback|fsLib.rmdir}.
*/
rmdir: util_1.promisify(fsLib.rmdir),
/**
* Promisified version of {@link https://nodejs.org/api/fsLib.html#fs_fs_fstat_fd_callback|fsLib.stat}.
*/
stat: util_1.promisify(fsLib.stat),
/**
* Promisified version of {@link https://npmjs.com/package/mkdirp|mkdirp}.
*/
// @ts-ignore TODO: figure out how to bind to correct promisify overload
mkdirp: (folderPath, mode) => util_1.promisify(mkdirpLib)(folderPath, mode),
/**
* Deletes a folder recursively, removing all descending files and folders.
*
* **Throws** *PathIsNullOrUndefined* The path is not defined.
* **Throws** *DirMissingOrNoAccess* The folder or any sub-folder is missing or has no access.
* @param {string} dirPath The path to remove.
*/
remove: async (dirPath) => {
if (!dirPath) {
throw new sfdxError_1.SfdxError('Path is null or undefined.', 'PathIsNullOrUndefined');
}
try {
await exports.fs.access(dirPath, fsLib.constants.R_OK);
}
catch (err) {
throw new sfdxError_1.SfdxError(`The path: ${dirPath} doesn\'t exist or access is denied.`, 'DirMissingOrNoAccess');
}
const files = await exports.fs.readdir(dirPath);
const stats = await Promise.all(files.map(file => exports.fs.stat(path.join(dirPath, file))));
const metas = stats.map((value, index) => Object.assign(value, { path: path.join(dirPath, files[index]) }));
await Promise.all(metas.map(meta => (meta.isDirectory() ? exports.fs.remove(meta.path) : exports.fs.unlink(meta.path))));
await exports.fs.rmdir(dirPath);
},
/**
* Searches a file path in an ascending manner (until reaching the filesystem root) for the first occurrence a
* specific file name. Resolves with the directory path containing the located file, or `null` if the file was
* not found.
*
* @param dir The directory path in which to start the upward search.
* @param file The file name to look for.
*/
traverseForFile: async (dir, file) => {
let foundProjectDir;
try {
await exports.fs.stat(path.join(dir, file));
foundProjectDir = dir;
}
catch (err) {
if (err && err.code === 'ENOENT') {
const nextDir = path.resolve(dir, '..');
if (nextDir !== dir) {
// stop at root
foundProjectDir = await exports.fs.traverseForFile(nextDir, file);
}
}
}
return foundProjectDir;
},
/**
* Read a file and convert it to JSON. Returns the contents of the file as a JSON object
*
* @param jsonPath The path of the file.
* @param throwOnEmpty Whether to throw an error if the JSON file is empty.
*/
readJson: async (jsonPath, throwOnEmpty) => {
const fileData = await exports.fs.readFile(jsonPath, 'utf8');
return await kit_1.parseJson(fileData, jsonPath, throwOnEmpty);
},
/**
* Read a file and convert it to JSON, throwing an error if the parsed contents are not a `JsonMap`.
*
* @param jsonPath The path of the file.
* @param throwOnEmpty Whether to throw an error if the JSON file is empty.
*/
readJsonMap: async (jsonPath, throwOnEmpty) => {
const fileData = await exports.fs.readFile(jsonPath, 'utf8');
return await kit_1.parseJsonMap(fileData, jsonPath, throwOnEmpty);
},
/**
* Convert a JSON-compatible object to a `string` and write it to a file.
*
* @param jsonPath The path of the file to write.
* @param data The JSON object to write.
*/
writeJson: async (jsonPath, data) => {
const fileData = JSON.stringify(data, null, 4);
await exports.fs.writeFile(jsonPath, fileData, {
encoding: 'utf8',
mode: exports.fs.DEFAULT_USER_FILE_MODE
});
}
return foundProjectDir;
}
exports.traverseForFile = traverseForFile;
/**
* Read a file and convert it to JSON.
*
* @param {string} jsonPath The path of the file.
* @param {boolean} [throwOnEmpty] Whether to throw an error if the JSON file is empty.
* @return {Promise<AnyJson>} The contents of the file as a JSON object.
*/
async function readJson(jsonPath, throwOnEmpty) {
const fileData = await exports.readFile(jsonPath, 'utf8');
return await kit_1.parseJson(fileData, jsonPath, throwOnEmpty);
}
exports.readJson = readJson;
/**
* Read a file and convert it to JSON, throwing an error if the parsed contents are not a `JsonMap`.
*
* @param {string} jsonPath The path of the file.
* @param {boolean} [throwOnEmpty] Whether to throw an error if the JSON file is empty.
* @return {Promise<JsonMap>} The contents of the file as a JSON object.
*/
async function readJsonMap(jsonPath, throwOnEmpty) {
const fileData = await exports.readFile(jsonPath, 'utf8');
return await kit_1.parseJsonMap(fileData, jsonPath, throwOnEmpty);
}
exports.readJsonMap = readJsonMap;
/**
* Convert a JSON-compatible object to a `string` and write it to a file.
*
* @param {string} jsonPath The path of the file to write.
* @param {object} data The JSON object to write.
* @return {Promise<void>}
*/
async function writeJson(jsonPath, data) {
const fileData = JSON.stringify(data, null, 4);
await exports.writeFile(jsonPath, fileData, {
encoding: 'utf8',
mode: exports.DEFAULT_USER_FILE_MODE
});
}
exports.writeJson = writeJson;
};
//# sourceMappingURL=fs.js.map
/**
* @property {string} SFDX_PROJECT_JSON The name of the project config file.
* @private
* The name of the project config file.
* @ignore
*/
export declare const SFDX_PROJECT_JSON = "sfdx-project.json";
/**
* Performs an upward directory search for an sfdx project file.
* Performs an upward directory search for an sfdx project file. Returns the absolute path to the project.
*
* @param {string} [dir=process.cwd()] The directory path to start traversing from.
* @returns {Promise<string>} The absolute path to the project.
* @throws {SfdxError} **`{name: 'InvalidProjectWorkspace'}`** If the current folder is not located in a workspace.
* @see util.SFDX_PROJECT_JSON
* @see util.traverseForFile
* @see {@link https://nodejs.org/api/process.html#process_process_cwd|process.cwd()}
* @private
* **See** {@link SFDX_PROJECT_JSON}
*
* **See** {@link traverseForFile}
*
* **Throws** *{@link SfdxError}{ name: 'InvalidProjectWorkspace' }* If the current folder is not located in a workspace.
* @param dir The directory path to start traversing from.
* @ignore
*/
export declare function resolveProjectPath(dir?: string): Promise<string>;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*

@@ -9,7 +8,8 @@ * Copyright (c) 2018, salesforce.com, inc.

*/
Object.defineProperty(exports, "__esModule", { value: true });
const sfdxError_1 = require("../sfdxError");
const fs_1 = require("./fs");
/**
* @property {string} SFDX_PROJECT_JSON The name of the project config file.
* @private
* The name of the project config file.
* @ignore
*/

@@ -19,14 +19,14 @@ // This has to be defined on util to prevent circular deps with project and configFile.

/**
* Performs an upward directory search for an sfdx project file.
* Performs an upward directory search for an sfdx project file. Returns the absolute path to the project.
*
* @param {string} [dir=process.cwd()] The directory path to start traversing from.
* @returns {Promise<string>} The absolute path to the project.
* @throws {SfdxError} **`{name: 'InvalidProjectWorkspace'}`** If the current folder is not located in a workspace.
* @see util.SFDX_PROJECT_JSON
* @see util.traverseForFile
* @see {@link https://nodejs.org/api/process.html#process_process_cwd|process.cwd()}
* @private
* **See** {@link SFDX_PROJECT_JSON}
*
* **See** {@link traverseForFile}
*
* **Throws** *{@link SfdxError}{ name: 'InvalidProjectWorkspace' }* If the current folder is not located in a workspace.
* @param dir The directory path to start traversing from.
* @ignore
*/
async function resolveProjectPath(dir = process.cwd()) {
const projectPath = await fs_1.traverseForFile(dir, exports.SFDX_PROJECT_JSON);
const projectPath = await fs_1.fs.traverseForFile(dir, exports.SFDX_PROJECT_JSON);
if (!projectPath) {

@@ -33,0 +33,0 @@ throw sfdxError_1.SfdxError.create('@salesforce/core', 'config', 'InvalidProjectWorkspace');

@@ -1,51 +0,43 @@

/**
* @module sfdc
*/
import { JsonMap, Optional } from '@salesforce/ts-types';
/**
* Returns `true` if a provided URL contains a Salesforce owned domain.
*
* @param {string} urlString The URL to inspect.
* @returns {boolean}
*/
export declare function isSalesforceDomain(urlString: string): boolean;
/**
* Converts an 18 character Salesforce ID to 15 characters.
*
* @param {string} id The id to convert.
* @return {Optional<string>}
*/
export declare function trimTo15(id?: string): Optional<string>;
/**
* Tests whether an API version matches the format `i.0`.
*
* @param value The API version as a string.
* @returns {boolean}
*/
export declare function validateApiVersion(value: string): boolean;
/**
* Tests whether an email matches the format `me@my.org`
*
* @param value The email as a string.
* @returns {boolean}
*/
export declare function validateEmail(value: string): boolean;
/**
* Tests whether a Salesforce ID is in the correct format, a 15- or 18-character length string with only letters and numbers
* @param value The ID as a string.
* @returns {boolean}
*/
export declare function validateSalesforceId(value: string): boolean;
/**
* Tests whether a path is in the correct format; the value doesn't include the characters "[", "]", "?", "<", ">", "?", "|"
* @param value The path as a string.
* @returns {boolean}
*/
export declare function validatePathDoesNotContainInvalidChars(value: string): boolean;
/**
* Returns the first key within the object that has an upper case first letter.
*
* @param {JsonMap} data The object in which to check key casing.
* @returns {Optional<string>}
*/
export declare function findUpperCaseKeys(data?: JsonMap): Optional<string>;
export declare const sfdc: {
/**
* Returns `true` if a provided URL contains a Salesforce owned domain.
*
* @param urlString The URL to inspect.
*/
isSalesforceDomain: (urlString: string) => boolean;
/**
* Converts an 18 character Salesforce ID to 15 characters.
*
* @param id The id to convert.
*/
trimTo15: (id?: string | undefined) => string | undefined;
/**
* Tests whether an API version matches the format `i.0`.
*
* @param value The API version as a string.
*/
validateApiVersion: (value: string) => boolean;
/**
* Tests whether an email matches the format `me@my.org`
*
* @param value The email as a string.
*/
validateEmail: (value: string) => boolean;
/**
* Tests whether a Salesforce ID is in the correct format, a 15- or 18-character length string with only letters and numbers
* @param value The ID as a string.
*/
validateSalesforceId: (value: string) => boolean;
/**
* Tests whether a path is in the correct format; the value doesn't include the characters "[", "]", "?", "<", ">", "?", "|"
* @param value The path as a string.
*/
validatePathDoesNotContainInvalidChars: (value: string) => boolean;
/**
* Returns the first key within the object that has an upper case first letter.
*
* @param data The object in which to check key casing.
*/
findUpperCaseKeys: (data?: Optional<JsonMap>) => string | undefined;
};

@@ -8,5 +8,2 @@ "use strict";

*/
/**
* @module sfdc
*/
Object.defineProperty(exports, "__esModule", { value: true });

@@ -16,101 +13,89 @@ const kit_1 = require("@salesforce/kit");

const url_1 = require("url");
/**
* Returns `true` if a provided URL contains a Salesforce owned domain.
*
* @param {string} urlString The URL to inspect.
* @returns {boolean}
*/
function isSalesforceDomain(urlString) {
let url;
try {
url = new url_1.URL(urlString);
}
catch (e) {
return false;
}
// Source https://help.salesforce.com/articleView?id=000003652&type=1
const whitelistOfSalesforceDomainPatterns = [
'.content.force.com',
'.force.com',
'.salesforce.com',
'.salesforceliveagent.com',
'.secure.force.com'
];
const whitelistOfSalesforceHosts = ['developer.salesforce.com', 'trailhead.salesforce.com'];
return whitelistOfSalesforceDomainPatterns.some(pattern => {
return url.hostname.endsWith(pattern) || whitelistOfSalesforceHosts.includes(url.hostname);
});
}
exports.isSalesforceDomain = isSalesforceDomain;
/**
* Converts an 18 character Salesforce ID to 15 characters.
*
* @param {string} id The id to convert.
* @return {Optional<string>}
*/
function trimTo15(id) {
if (id && id.length && id.length > 15) {
id = id.substring(0, 15);
}
return id;
}
exports.trimTo15 = trimTo15;
/**
* Tests whether an API version matches the format `i.0`.
*
* @param value The API version as a string.
* @returns {boolean}
*/
function validateApiVersion(value) {
return value == null || /[1-9]\d\.0/.test(value);
}
exports.validateApiVersion = validateApiVersion;
/**
* Tests whether an email matches the format `me@my.org`
*
* @param value The email as a string.
* @returns {boolean}
*/
function validateEmail(value) {
return /^[^.][^@]*@[^.]+(\.[^.\s]+)+$/.test(value);
}
exports.validateEmail = validateEmail;
/**
* Tests whether a Salesforce ID is in the correct format, a 15- or 18-character length string with only letters and numbers
* @param value The ID as a string.
* @returns {boolean}
*/
function validateSalesforceId(value) {
return /[a-zA-Z0-9]{18}|[a-zA-Z0-9]{15}/.test(value) && (value.length === 15 || value.length === 18);
}
exports.validateSalesforceId = validateSalesforceId;
/**
* Tests whether a path is in the correct format; the value doesn't include the characters "[", "]", "?", "<", ">", "?", "|"
* @param value The path as a string.
* @returns {boolean}
*/
function validatePathDoesNotContainInvalidChars(value) {
return !/[\[:"\?<>\|\]]+/.test(value);
}
exports.validatePathDoesNotContainInvalidChars = validatePathDoesNotContainInvalidChars;
/**
* Returns the first key within the object that has an upper case first letter.
*
* @param {JsonMap} data The object in which to check key casing.
* @returns {Optional<string>}
*/
function findUpperCaseKeys(data) {
let key;
kit_1.findKey(data, (val, k) => {
if (k[0] === k[0].toUpperCase()) {
key = k;
exports.sfdc = {
/**
* Returns `true` if a provided URL contains a Salesforce owned domain.
*
* @param urlString The URL to inspect.
*/
isSalesforceDomain: (urlString) => {
let url;
try {
url = new url_1.URL(urlString);
}
else if (ts_types_1.isJsonMap(val)) {
key = findUpperCaseKeys(ts_types_1.asJsonMap(val));
catch (e) {
return false;
}
// Source https://help.salesforce.com/articleView?id=000003652&type=1
const whitelistOfSalesforceDomainPatterns = [
'.content.force.com',
'.force.com',
'.salesforce.com',
'.salesforceliveagent.com',
'.secure.force.com'
];
const whitelistOfSalesforceHosts = ['developer.salesforce.com', 'trailhead.salesforce.com'];
return whitelistOfSalesforceDomainPatterns.some(pattern => {
return url.hostname.endsWith(pattern) || whitelistOfSalesforceHosts.includes(url.hostname);
});
},
/**
* Converts an 18 character Salesforce ID to 15 characters.
*
* @param id The id to convert.
*/
trimTo15: (id) => {
if (id && id.length && id.length > 15) {
id = id.substring(0, 15);
}
return id;
},
/**
* Tests whether an API version matches the format `i.0`.
*
* @param value The API version as a string.
*/
validateApiVersion: (value) => {
return value == null || /[1-9]\d\.0/.test(value);
},
/**
* Tests whether an email matches the format `me@my.org`
*
* @param value The email as a string.
*/
validateEmail: (value) => {
return /^[^.][^@]*@[^.]+(\.[^.\s]+)+$/.test(value);
},
/**
* Tests whether a Salesforce ID is in the correct format, a 15- or 18-character length string with only letters and numbers
* @param value The ID as a string.
*/
validateSalesforceId: (value) => {
return /[a-zA-Z0-9]{18}|[a-zA-Z0-9]{15}/.test(value) && (value.length === 15 || value.length === 18);
},
/**
* Tests whether a path is in the correct format; the value doesn't include the characters "[", "]", "?", "<", ">", "?", "|"
* @param value The path as a string.
*/
validatePathDoesNotContainInvalidChars: (value) => {
return !/[\[:"\?<>\|\]]+/.test(value);
},
/**
* Returns the first key within the object that has an upper case first letter.
*
* @param data The object in which to check key casing.
*/
findUpperCaseKeys: (data) => {
let key;
kit_1.findKey(data, (val, k) => {
if (k[0] === k[0].toUpperCase()) {
key = k;
}
else if (ts_types_1.isJsonMap(val)) {
key = exports.sfdc.findUpperCaseKeys(ts_types_1.asJsonMap(val));
}
return key;
});
return key;
});
return key;
}
exports.findUpperCaseKeys = findUpperCaseKeys;
}
};
//# sourceMappingURL=sfdc.js.map
{
"name": "@salesforce/core",
"version": "0.24.8",
"version": "0.26.1",
"description": "Core libraries to interact with SFDX projects, orgs, and APIs.",

@@ -5,0 +5,0 @@ "main": "lib/exported",

@@ -1,21 +0,22 @@

**As a beta feature, Salesforce Core Libraries is a preview and isn’t part of the “Services” under your master
subscription agreement with Salesforce. Use this feature at your sole discretion, and make your purchase decisions only
on the basis of generally available products and features. Salesforce doesn’t guarantee general availability of this
feature within any particular time frame or at all, and we can discontinue it at any time. This feature is for
evaluation purposes only, not for production use. It’s offered as is and isn’t supported, and Salesforce has no
liability for any harm or damage arising out of or in connection with it. All restrictions, Salesforce reservation of
rights, obligations concerning the Services, and terms for related Non-Salesforce Applications and Content apply equally
to your use of this feature.**
# Description
# Salesforce DX Core Library (Beta)
The @salesforce/core library provides client-side management of Salesforce DX projects, org authentication, connections to Salesforce APIs, and other utilities. Much of the core functionality that powers the Salesforcedx plug-ins comes from this library. You can use this functionality in your plug-ins, too.
This library provides client-side management of Salesforce DX projects, org authentication, connections to Salesforce APIs, and other various utilities.
# Usage
See the [API documentation](https://developer.salesforce.com/media/salesforce-cli/docs/@salesforce/core/index.html).
See the [API documentation](https://forcedotcom.github.io/sfdx-core/).
## Using TestSetup
## Contributing
The Salesforce DX Core Library provides a unit testing utility to help with mocking and sand-boxing core components.
This feature allows unit tests to execute without needing to make API calls to salesforce.com.
If you are interested in contributing, please take a look at the [CONTRIBUTING](https://github.com/forcedotcom/sfdx-core/blob/develop/CONTRIBUTING.md) guide.
# Related Docs and Repositories
* @forcedotcom/cli-packages - Base Salesforce CLI command
* @forcedotcom/sfdx-plugin-generate - The generator plug-in for building plug-ins for Salesforce CLI
# Using TestSetup
The Salesforce DX Core Library provides a unit testing utility to help with mocking and sand-boxing core components. This feature allows unit tests to execute without needing to make API calls to salesforce.com.
### Mocking AuthInfo

@@ -44,4 +45,3 @@

After having a valid AuthInfo object you can then create fake connections to a Salesforce.com scratch org. This allows
for writing tests that can validate result responses for SOQL queries and REST endpoints.
After having a valid AuthInfo object you can then create fake connections to a Salesforce.com scratch org. This allows for writing tests that can validate result responses for SOQL queries and REST endpoints.

@@ -70,13 +70,7 @@ ```typescript

} else {
return Promise.reject(
new SfdxError(`Unexpected request: ${_request.url}`)
);
return Promise.reject(new SfdxError(`Unexpected request: ${_request.url}`));
}
};
const connection: Connection = await Connection.create(
await AuthInfo.create(testData.username)
);
const result: QueryResult<{}> = await connection.query(
'select Id From Account'
);
const connection: Connection = await Connection.create(await AuthInfo.create(testData.username));
const result: QueryResult<{}> = await connection.query('select Id From Account');
deepStrictEqual(result, records);

@@ -87,13 +81,8 @@ });

### Using the Builtin Sinon Sandboxes
### Using the Built-in Sinon Sandboxes
sfdx-core uses Sinon as it's underlying mocking system. If you're unfamiliar with Sinon and it's sand-boxing concept you
can find more information here:
sfdx-core uses Sinon as its underlying mocking system. If you're unfamiliar with Sinon and it's sandboxing concept you can find more information here:
https://sinonjs.org/
Sinon stubs and spys must be cleaned up after test invocations. To ease the use of Sinon with sfdx core we've exposed our sandbox in TestSetup. After adding your own stubs and/or spys they will automatically be cleaned up after each test using mocha's afterEach method.
Sinon stubs and spys must be cleaned up after test invocations. To ease the use of Sinon with sfdx core we've exposed our
sandbox in TestSetup. After adding your own stubs and/or spys they will automatically be cleaned up after each test
using mocha's afterEach method.
```typescript

@@ -118,4 +107,3 @@ import { strictEqual } from 'assert';

It's important to have negative tests that ensure proper error handling. With _shouldThrow_ it's easy to test for expected
async rejections.
It's important to have negative tests that ensure proper error handling. With *shouldThrow* it's easy to test for expected async rejections.

@@ -146,4 +134,3 @@ ```typescript

It's also useful to check expected values and content from log lines. TestSetup configures the sfdx-core logger to use an
in memory LogLine storage structure. These can be easily accessed from tests.
It's also useful to check expected values and content from log lines. TestSetup configures the sfdx-core logger to use an in memory LogLine storage structure. These can be easily accessed from tests.

@@ -150,0 +137,0 @@ ```typescript

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc