@salesforce/core
Version:
Core libraries to interact with SFDX projects, orgs, and APIs.
613 lines (612 loc) • 21.9 kB
TypeScript
import { AsyncOptionalCreatable, Duration } from '@salesforce/kit';
import { AnyJson, JsonMap, Nullable } from '@salesforce/ts-types';
import { ConfigAggregator } from '../config/configAggregator';
import { OrgUsersConfig } from '../config/orgUsersConfig';
import { Connection } from './connection';
import { AuthFields, AuthInfo } from './authInfo';
import { ScratchOrgCreateOptions, ScratchOrgCreateResult } from './scratchOrgCreate';
export type OrganizationInformation = {
Name: string;
InstanceName: string;
IsSandbox: boolean;
TrialExpirationDate: string | null;
NamespacePrefix: string | null;
};
export declare enum OrgTypes {
Scratch = "scratch",
Sandbox = "sandbox"
}
export type StatusEvent = {
sandboxProcessObj: SandboxProcessObject;
interval: number;
remainingWait: number;
waitingOnAuth: boolean;
};
export type ResultEvent = {
sandboxProcessObj: SandboxProcessObject;
sandboxRes: SandboxUserAuthResponse;
};
export type SandboxUserAuthRequest = {
sandboxName: string;
clientId: string;
callbackUrl: string;
};
export declare enum SandboxEvents {
EVENT_STATUS = "status",
EVENT_ASYNC_RESULT = "asyncResult",
EVENT_RESULT = "result",
EVENT_AUTH = "auth",
EVENT_RESUME = "resume",
EVENT_MULTIPLE_SBX_PROCESSES = "multipleMatchingSbxProcesses"
}
export type SandboxUserAuthResponse = {
authUserName: string;
authCode: string;
instanceUrl: string;
loginUrl: string;
};
export declare function sandboxIsResumable(value: string): boolean;
export type SandboxProcessObject = {
Id: string;
Status: string;
SandboxName: string;
SandboxInfoId: string;
LicenseType: string;
CreatedDate: string;
SandboxOrganization?: string;
CopyProgress?: number;
SourceId?: string;
Description?: string;
ApexClassId?: string;
EndDate?: string;
};
export type SandboxRequest = {
SandboxName: string;
LicenseType?: string;
/** Should match a SandboxInfoId, not a SandboxProcessId */
SourceId?: string;
Description?: string;
ApexClassId?: string;
ActivationUserGroupId?: string;
};
export type ResumeSandboxRequest = {
SandboxName?: string;
SandboxProcessObjId?: string;
};
export type SandboxInfo = {
Id: string;
IsDeleted: boolean;
CreatedDate: string;
CreatedById: string;
LastModifiedDate: string;
LastModifiedById: string;
SandboxName: string;
LicenseType: 'DEVELOPER' | 'DEVELOPER PRO' | 'PARTIAL' | 'FULL';
TemplateId?: string;
HistoryDays: -1 | 0 | 10 | 20 | 30 | 60 | 90 | 120 | 150 | 180;
CopyChatter: boolean;
AutoActivate: boolean;
ApexClassId?: string;
Description?: string;
SourceId?: string;
ActivationUserGroupId?: string;
CopyArchivedActivities?: boolean;
};
export type ScratchOrgRequest = Omit<ScratchOrgCreateOptions, 'hubOrg'>;
export type SandboxFields = {
sandboxOrgId: string;
prodOrgUsername: string;
sandboxName?: string;
sandboxUsername?: string;
sandboxProcessId?: string;
sandboxInfoId?: string;
timestamp?: string;
};
/**
* Provides a way to manage a locally authenticated Org.
*
* **See** {@link AuthInfo}
*
* **See** {@link Connection}
*
* **See** {@link Aliases}
*
* **See** {@link Config}
*
* ```
* // Email username
* const org1: Org = await Org.create({ aliasOrUsername: 'foo@example.com' });
* // The target-org config property
* const org2: Org = await Org.create();
* // Full Connection
* const org3: Org = await Org.create({
* connection: await Connection.create({
* authInfo: await AuthInfo.create({ username: 'username' })
* })
* });
* ```
*
* **See** https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_usernames_orgs.htm
*/
export declare class Org extends AsyncOptionalCreatable<Org.Options> {
private status;
private configAggregator;
private logger;
private connection;
private options;
private orgId?;
/**
* @ignore
*/
constructor(options?: Org.Options);
/**
* create a sandbox from a production org
* 'this' needs to be a production org with sandbox licenses available
*
* @param sandboxReq SandboxRequest options to create the sandbox with
* @param options Wait: The amount of time to wait before timing out, Interval: The time interval between polling
*/
createSandbox(sandboxReq: SandboxRequest, options?: {
wait?: Duration;
interval?: Duration;
async?: boolean;
}): Promise<SandboxProcessObject>;
/**
* Refresh (update) a sandbox from a production org.
* 'this' needs to be a production org with sandbox licenses available
*
* @param sandboxInfo SandboxInfo to update the sandbox with
* @param options Wait: The amount of time to wait before timing out, Interval: The time interval between polling
*/
refreshSandbox(sandboxInfo: SandboxInfo, options?: {
wait?: Duration;
interval?: Duration;
async?: boolean;
}): Promise<SandboxProcessObject>;
/**
*
* @param sandboxReq SandboxRequest options to create the sandbox with
* @param sourceSandboxName the name of the sandbox that your new sandbox will be based on
* @param options Wait: The amount of time to wait before timing out, defaults to 0, Interval: The time interval between polling defaults to 30 seconds
* @returns {SandboxProcessObject} the newly created sandbox process object
*/
cloneSandbox(sandboxReq: SandboxRequest, sourceSandboxName: string, options: {
wait?: Duration;
interval?: Duration;
}): Promise<SandboxProcessObject>;
/**
* Resume a sandbox create or refresh from a production org.
* `this` needs to be a production org with sandbox licenses available.
*
* @param resumeSandboxRequest SandboxRequest options to create/refresh the sandbox with
* @param options Wait: The amount of time to wait (default: 0 minutes) before timing out,
* Interval: The time interval (default: 30 seconds) between polling
*/
resumeSandbox(resumeSandboxRequest: ResumeSandboxRequest, options?: {
wait?: Duration;
interval?: Duration;
async?: boolean;
}): Promise<SandboxProcessObject>;
/**
* Creates a scratchOrg
* 'this' needs to be a valid dev-hub
*
* @param {options} ScratchOrgCreateOptions
* @returns {ScratchOrgCreateResult}
*/
scratchOrgCreate(options: ScratchOrgRequest): Promise<ScratchOrgCreateResult>;
/**
* Reports sandbox org creation status. If the org is ready, authenticates to the org.
*
* @param {sandboxname} string the sandbox name
* @param options Wait: The amount of time to wait before timing out, Interval: The time interval between polling
* @returns {SandboxProcessObject} the sandbox process object
*/
sandboxStatus(sandboxname: string, options: {
wait?: Duration;
interval?: Duration;
}): Promise<SandboxProcessObject>;
/**
* Clean all data files in the org's data path. Usually <workspace>/.sfdx/orgs/<username>.
*
* @param orgDataPath A relative path other than "orgs/".
* @param throwWhenRemoveFails Should the remove org operations throw an error on failure?
*/
cleanLocalOrgData(orgDataPath?: string, throwWhenRemoveFails?: boolean): Promise<void>;
/**
* @ignore
*/
retrieveOrgUsersConfig(): Promise<OrgUsersConfig>;
/**
* Cleans up all org related artifacts including users, sandbox config (if a sandbox), source tracking files, and auth file.
*
* @param throwWhenRemoveFails Determines if the call should throw an error or fail silently.
*/
remove(throwWhenRemoveFails?: boolean): Promise<void>;
/**
* Check if org is a sandbox org by checking its SandboxOrgConfig.
*
*/
isSandbox(): Promise<boolean>;
/**
* Check that this org is a scratch org by asking the dev hub if it knows about it.
*
* **Throws** *{@link SfError}{ name: 'NotADevHubError' }* Not a Dev Hub.
*
* **Throws** *{@link SfError}{ name: 'NoResultsError' }* No results.
*
* @param devHubUsernameOrAlias The username or alias of the dev hub org.
*/
checkScratchOrg(devHubUsernameOrAlias?: 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).
*/
getDevHubOrg(): Promise<Org | undefined>;
/**
* Returns `true` if the org is a Dev Hub.
*
* **Note** This relies on a cached value in the auth file. If that property
* is not cached, this method will **always return false even if the org is a
* dev hub**. If you need accuracy, use the {@link Org.determineIfDevHubOrg} method.
*/
isDevHubOrg(): boolean;
/**
* Will delete 'this' instance remotely and any files locally
*
* @param controllingOrg username or Org that 'this.devhub' or 'this.production' refers to. AKA a DevHub for a scratch org, or a Production Org for a sandbox
*/
deleteFrom(controllingOrg: string | Org): Promise<void>;
/**
* Will delete 'this' instance remotely and any files locally
*/
delete(): Promise<void>;
/**
* Returns `true` if the org is a Dev Hub.
*
* Use a cached value. If the cached value is not set, then check access to the
* ScratchOrgInfo object to determine if the org is a dev hub.
*
* @param forceServerCheck Ignore the cached value and go straight to the server
* which will be required if the org flips on the dev hub after the value is already
* cached locally.
*/
determineIfDevHubOrg(forceServerCheck?: boolean): Promise<boolean>;
/**
* Returns `true` if the org is a scratch org.
*
* **Note** This relies on a cached value in the auth file. If that property
* is not cached, this method will **always return false even if the org is a
* scratch org**. If you need accuracy, use the {@link Org.determineIfScratch} method.
*/
isScratch(): boolean;
/**
* Returns `true` if the org uses source tracking.
* Side effect: updates files where the property doesn't currently exist
*/
tracksSource(): Promise<boolean>;
/**
* Set the tracking property on the org's auth file
*
* @param value true or false (whether the org should use source tracking or not)
*/
setTracksSource(value: boolean): Promise<void>;
/**
* Returns `true` if the org is a scratch org.
*
* Use a cached value. If the cached value is not set, then check
* `Organization.IsSandbox == true && Organization.TrialExpirationDate != null`
* using {@link Org.retrieveOrganizationInformation}.
*/
determineIfScratch(): Promise<boolean>;
/**
* Returns `true` if the org is a sandbox.
*
* Use a cached value. If the cached value is not set, then check
* `Organization.IsSandbox == true && Organization.TrialExpirationDate == null`
* using {@link Org.retrieveOrganizationInformation}.
*/
determineIfSandbox(): Promise<boolean>;
/**
* Retrieve a handful of fields from the Organization table in Salesforce. If this does not have the
* data you need, just use {@link Connection.singleRecordQuery} with `SELECT <needed fields> FROM Organization`.
*
* @returns org information
*/
retrieveOrganizationInformation(): Promise<OrganizationInformation>;
/**
* Some organization information is locally cached, such as if the org name or if it is a scratch org.
* This method populates/updates the filesystem from information retrieved from the org.
*/
updateLocalInformation(): Promise<Pick<AuthFields, Org.Fields.NAME | Org.Fields.INSTANCE_NAME | Org.Fields.NAMESPACE_PREFIX | Org.Fields.IS_SANDBOX | Org.Fields.IS_SCRATCH | Org.Fields.TRIAL_EXPIRATION_DATE> | undefined>;
/**
* Executes a HEAD request on the baseUrl to force an auth refresh.
* This is useful for the raw methods (request, requestRaw) that use the accessToken directly and don't handle refreshes.
*
* This method issues a request using the current access token to check if it is still valid.
* If the request returns 200, no refresh happens, and we keep the token.
* If it returns 401, jsforce will request a new token and set it in the connection instance.
*/
refreshAuth(): Promise<void>;
/**
* Reads and returns the content of all user auth files for this org as an array.
*/
readUserAuthFiles(): Promise<AuthInfo[]>;
/**
* Adds a username to the user config for this org. For convenience `this` object is returned.
*
* ```
* const org: Org = await Org.create({
* connection: await Connection.create({
* authInfo: await AuthInfo.create('foo@example.com')
* })
* });
* const userAuth: AuthInfo = await AuthInfo.create({
* username: '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. For convenience `this` object is returned.
*
* **Throws** *{@link SfError}{ name: 'MissingAuthInfoError' }* Auth info is missing.
*
* @param {AuthInfo | string} auth The AuthInfo containing the username to remove.
*/
removeUsername(auth: AuthInfo | string): Promise<Org>;
/**
* set the sandbox config related to this given org
*
* @param orgId {string} orgId of the sandbox
* @param config {SandboxFields} config of the sandbox
*/
setSandboxConfig(orgId: string, config: SandboxFields): Promise<Org>;
/**
* get the sandbox config for the given orgId
*
* @param orgId {string} orgId of the sandbox
*/
getSandboxConfig(orgId: string): Promise<Nullable<SandboxFields>>;
/**
* Retrieves the highest api version that is supported by the target server instance. If the apiVersion configured for
* Sfdx is greater than the one returned in this call an api version mismatch occurs. In the case of the CLI that
* results in a warning.
*/
retrieveMaxApiVersion(): Promise<string>;
/**
* Returns the admin username used to create the org.
*/
getUsername(): string | undefined;
/**
* Returns the orgId for this org.
*/
getOrgId(): string;
/**
* Returns for the config aggregator.
*/
getConfigAggregator(): ConfigAggregator;
/**
* Returns an org field. Returns undefined if the field is not set or invalid.
*/
getField<T = AnyJson>(key: Org.Fields): T;
/**
* Returns a map of requested fields.
*/
getFields(keys: Org.Fields[]): JsonMap;
/**
* Returns the JSForce connection for the org.
* side effect: If you pass it an apiVersion, it will set it on the Org
* so that future calls to getConnection() will also use that version.
*
* @param apiVersion The API version to use for the connection.
*/
getConnection(apiVersion?: string): Connection;
supportsSourceTracking(): Promise<boolean>;
/**
* query SandboxProcess via sandbox name
*
* @param name SandboxName to query for
*/
querySandboxProcessBySandboxName(name: string): Promise<SandboxProcessObject>;
/**
* query SandboxProcess via SandboxInfoId
*
* @param id SandboxInfoId to query for
*/
querySandboxProcessBySandboxInfoId(id: string): Promise<SandboxProcessObject>;
/**
* query SandboxProcess via Id
*
* @param id SandboxProcessId to query for
*/
querySandboxProcessById(id: string): Promise<SandboxProcessObject>;
/**
* query SandboxProcess via SandboxOrganization (sandbox Org ID)
*
* @param sandboxOrgId SandboxOrganization ID to query for
*/
querySandboxProcessByOrgId(sandboxOrgId: string): Promise<SandboxProcessObject>;
/**
* Initialize async components.
*/
protected init(): Promise<void>;
/**
* **Throws** *{@link SfError}{ name: 'NotSupportedError' }* Throws an unsupported error.
*/
protected getDefaultOptions(): Org.Options;
private getLocalDataDir;
/**
* Gets the sandboxProcessObject and then polls for it to complete.
*
* @param sandboxProcessName sanbox process name
* @param options { wait?: Duration; interval?: Duration }
* @returns {SandboxProcessObject} The SandboxProcessObject for the sandbox
*/
private authWithRetriesByName;
/**
* Polls the sandbox org for the sandboxProcessObject.
*
* @param sandboxProcessObj: The in-progress sandbox signup request
* @param options { wait?: Duration; interval?: Duration }
* @returns {SandboxProcessObject}
*/
private authWithRetries;
/**
* Query the sandbox for the SandboxProcessObject by sandbox name
*
* @param sandboxName The name of the sandbox to query
* @returns {SandboxProcessObject} The SandboxProcessObject for the sandbox
*/
private queryLatestSandboxProcessBySandboxName;
private queryProduction;
private destroySandbox;
private destroyScratchOrg;
/**
* this method will delete the sandbox org from the production org and clean up any local files
*
* @param prodOrg - Production org associated with this sandbox
* @private
*/
private deleteSandbox;
/**
* If this Org is a scratch org, calling this method will delete the scratch org from the DevHub and clean up any local files
*
* @param devHub - optional DevHub Org of the to-be-deleted scratch org
* @private
*/
private deleteScratchOrg;
/**
* Delete an auth info file from the local file system and any related cache information for
* this Org. You don't want to call this method directly. Instead consider calling Org.remove()
*/
private removeAuth;
/**
* Deletes the users config file
*/
private removeUsersConfig;
private manageDelete;
/**
* Remove the org users auth file.
*
* @param throwWhenRemoveFails true if manageDelete should throw or not if the deleted fails.
*/
private removeUsers;
private removeSandboxConfig;
private writeSandboxAuthFile;
private pollStatusAndAuth;
/**
* query SandboxProcess using supplied where clause
*
* @param where clause to query for
* @private
*/
private querySandboxProcess;
/**
* determines if the sandbox has successfully been created
*
* @param sandboxProcessObj sandbox signup progress
* @private
*/
private sandboxSignupComplete;
private validateWaitOptions;
/**
* removes source tracking files hosted in the project/.sf/orgs/<org id>/
*
* @private
*/
private removeSourceTrackingFiles;
}
export declare namespace Org {
/**
* Constructor Options for and Org.
*/
type Options = {
aliasOrUsername?: string;
connection?: Connection;
aggregator?: ConfigAggregator;
isDevHub?: boolean;
};
/**
* 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",
NAME = "name",
NAMESPACE_PREFIX = "namespacePrefix",
INSTANCE_NAME = "instanceName",
TRIAL_EXPIRATION_DATE = "trailExpirationDate",
/**
* 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",
/**
* Is the current org a scratch org. e.g. Organization has IsSandbox == true and TrialExpirationDate != null.
*/
IS_SCRATCH = "isScratch",
/**
* Is the current org a sandbox (not a scratch org on a non-prod instance), but an actual Sandbox org). e.g. Organization has IsSandbox == true and TrialExpirationDate == null.
*/
IS_SANDBOX = "isSandbox",
/**
* 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",
/**
* true: the org supports and wants source tracking
* false: the org opted out of tracking or can't support it
*/
TRACKS_SOURCE = "tracksSource"
}
}