@salesforce/core 4.0.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/LICENSE.txt +1 -1
  2. package/README.md +93 -44
  3. package/lib/config/authInfoConfig.d.ts +19 -0
  4. package/lib/config/authInfoConfig.js +35 -0
  5. package/lib/config/config.d.ts +87 -22
  6. package/lib/config/config.js +117 -65
  7. package/lib/config/configAggregator.d.ts +41 -35
  8. package/lib/config/configAggregator.js +102 -73
  9. package/lib/config/configFile.d.ts +2 -2
  10. package/lib/config/configFile.js +38 -29
  11. package/lib/config/configStore.d.ts +9 -9
  12. package/lib/config/configStore.js +17 -15
  13. package/lib/config/envVars.d.ts +15 -9
  14. package/lib/config/envVars.js +71 -47
  15. package/lib/config/orgUsersConfig.js +2 -0
  16. package/lib/config/sandboxOrgConfig.js +2 -0
  17. package/lib/config/sandboxProcessCache.d.ts +16 -0
  18. package/lib/config/sandboxProcessCache.js +38 -0
  19. package/lib/config/tokensConfig.d.ts +10 -0
  20. package/lib/config/tokensConfig.js +29 -0
  21. package/lib/config/ttlConfig.d.ts +34 -0
  22. package/lib/config/ttlConfig.js +50 -0
  23. package/lib/crypto/crypto.js +15 -22
  24. package/lib/crypto/keyChain.js +2 -3
  25. package/lib/crypto/keyChainImpl.d.ts +5 -3
  26. package/lib/crypto/keyChainImpl.js +58 -61
  27. package/lib/crypto/secureBuffer.d.ts +1 -1
  28. package/lib/deviceOauthService.d.ts +3 -3
  29. package/lib/deviceOauthService.js +27 -25
  30. package/lib/exported.d.ts +15 -12
  31. package/lib/exported.js +28 -16
  32. package/lib/global.d.ts +11 -3
  33. package/lib/global.js +39 -12
  34. package/lib/lifecycleEvents.d.ts +1 -1
  35. package/lib/lifecycleEvents.js +3 -0
  36. package/lib/logger.d.ts +19 -9
  37. package/lib/logger.js +112 -86
  38. package/lib/messages.d.ts +53 -36
  39. package/lib/messages.js +81 -91
  40. package/lib/org/authInfo.d.ts +56 -20
  41. package/lib/org/authInfo.js +232 -131
  42. package/lib/org/authRemover.d.ts +8 -7
  43. package/lib/org/authRemover.js +32 -28
  44. package/lib/org/connection.d.ts +13 -37
  45. package/lib/org/connection.js +78 -124
  46. package/lib/org/index.js +5 -1
  47. package/lib/org/org.d.ts +151 -48
  48. package/lib/org/org.js +468 -225
  49. package/lib/org/orgConfigProperties.d.ts +64 -3
  50. package/lib/org/orgConfigProperties.js +96 -4
  51. package/lib/org/permissionSetAssignment.js +4 -13
  52. package/lib/org/scratchOrgCache.d.ts +20 -0
  53. package/lib/org/scratchOrgCache.js +33 -0
  54. package/lib/org/scratchOrgCreate.d.ts +28 -17
  55. package/lib/org/scratchOrgCreate.js +125 -53
  56. package/lib/org/scratchOrgErrorCodes.d.ts +9 -3
  57. package/lib/org/scratchOrgErrorCodes.js +34 -17
  58. package/lib/org/scratchOrgFeatureDeprecation.js +1 -6
  59. package/lib/org/scratchOrgInfoApi.d.ts +21 -47
  60. package/lib/org/scratchOrgInfoApi.js +129 -63
  61. package/lib/org/scratchOrgInfoGenerator.d.ts +6 -5
  62. package/lib/org/scratchOrgInfoGenerator.js +76 -62
  63. package/lib/org/scratchOrgLifecycleEvents.d.ts +10 -0
  64. package/lib/org/scratchOrgLifecycleEvents.js +41 -0
  65. package/lib/org/scratchOrgSettingsGenerator.d.ts +44 -21
  66. package/lib/org/scratchOrgSettingsGenerator.js +165 -98
  67. package/lib/org/scratchOrgTypes.d.ts +43 -0
  68. package/lib/org/scratchOrgTypes.js +9 -0
  69. package/lib/org/user.d.ts +1 -1
  70. package/lib/org/user.js +25 -34
  71. package/lib/schema/printer.d.ts +6 -0
  72. package/lib/schema/printer.js +34 -31
  73. package/lib/schema/validator.d.ts +12 -10
  74. package/lib/schema/validator.js +56 -76
  75. package/lib/{sfdxError.d.ts → sfError.d.ts} +12 -20
  76. package/lib/{sfdxError.js → sfError.js} +40 -30
  77. package/lib/{sfdxProject.d.ts → sfProject.d.ts} +75 -35
  78. package/lib/sfProject.js +651 -0
  79. package/lib/stateAggregator/accessors/aliasAccessor.d.ts +129 -0
  80. package/lib/stateAggregator/accessors/aliasAccessor.js +263 -0
  81. package/lib/stateAggregator/accessors/orgAccessor.d.ts +101 -0
  82. package/lib/stateAggregator/accessors/orgAccessor.js +240 -0
  83. package/lib/stateAggregator/accessors/sandboxAccessor.d.ts +8 -0
  84. package/lib/stateAggregator/accessors/sandboxAccessor.js +28 -0
  85. package/lib/stateAggregator/accessors/tokenAccessor.d.ts +63 -0
  86. package/lib/stateAggregator/accessors/tokenAccessor.js +80 -0
  87. package/lib/stateAggregator/index.d.ts +4 -0
  88. package/lib/stateAggregator/index.js +27 -0
  89. package/lib/stateAggregator/stateAggregator.d.ts +25 -0
  90. package/lib/stateAggregator/stateAggregator.js +46 -0
  91. package/lib/status/myDomainResolver.d.ts +1 -1
  92. package/lib/status/myDomainResolver.js +4 -4
  93. package/lib/status/pollingClient.js +4 -4
  94. package/lib/status/streamingClient.d.ts +2 -2
  95. package/lib/status/streamingClient.js +58 -63
  96. package/lib/status/types.d.ts +2 -2
  97. package/lib/testSetup.d.ts +204 -75
  98. package/lib/testSetup.js +468 -164
  99. package/lib/util/cache.d.ts +2 -2
  100. package/lib/util/cache.js +6 -6
  101. package/lib/util/checkLightningDomain.js +3 -4
  102. package/lib/util/directoryWriter.d.ts +12 -0
  103. package/lib/util/directoryWriter.js +54 -0
  104. package/lib/util/getJwtAudienceUrl.js +1 -1
  105. package/lib/util/internal.d.ts +28 -2
  106. package/lib/util/internal.js +65 -8
  107. package/lib/util/jsonXmlTools.js +2 -4
  108. package/lib/util/mapKeys.d.ts +9 -9
  109. package/lib/util/mapKeys.js +13 -9
  110. package/lib/util/sfdc.d.ts +51 -51
  111. package/lib/util/sfdc.js +74 -79
  112. package/lib/util/sfdcUrl.d.ts +5 -19
  113. package/lib/util/sfdcUrl.js +40 -49
  114. package/lib/util/structuredWriter.d.ts +9 -0
  115. package/lib/util/structuredWriter.js +3 -0
  116. package/lib/util/zipWriter.d.ts +8 -6
  117. package/lib/util/zipWriter.js +13 -13
  118. package/lib/webOAuthServer.d.ts +20 -6
  119. package/lib/webOAuthServer.js +102 -56
  120. package/messageTransformer/messageTransformer.ts +93 -0
  121. package/messages/auth.md +9 -1
  122. package/messages/config.md +42 -6
  123. package/messages/connection.md +8 -0
  124. package/messages/core.md +10 -0
  125. package/messages/envVars.md +37 -3
  126. package/messages/org.md +21 -1
  127. package/messages/scratchOrgCreate.md +2 -6
  128. package/messages/scratchOrgErrorCodes.md +17 -1
  129. package/messages/scratchOrgInfoApi.md +9 -0
  130. package/messages/scratchOrgInfoGenerator.md +9 -1
  131. package/package.json +123 -46
  132. package/CHANGELOG.md +0 -1244
  133. package/lib/config/keychainConfig.d.ts +0 -19
  134. package/lib/config/keychainConfig.js +0 -43
  135. package/lib/globalInfo/accessors/aliasAccessor.d.ts +0 -83
  136. package/lib/globalInfo/accessors/aliasAccessor.js +0 -130
  137. package/lib/globalInfo/accessors/orgAccessor.d.ts +0 -13
  138. package/lib/globalInfo/accessors/orgAccessor.js +0 -45
  139. package/lib/globalInfo/accessors/tokenAccessor.d.ts +0 -13
  140. package/lib/globalInfo/accessors/tokenAccessor.js +0 -35
  141. package/lib/globalInfo/globalInfoConfig.d.ts +0 -36
  142. package/lib/globalInfo/globalInfoConfig.js +0 -105
  143. package/lib/globalInfo/index.d.ts +0 -6
  144. package/lib/globalInfo/index.js +0 -29
  145. package/lib/globalInfo/sfdxDataHandler.d.ts +0 -43
  146. package/lib/globalInfo/sfdxDataHandler.js +0 -217
  147. package/lib/globalInfo/types.d.ts +0 -39
  148. package/lib/globalInfo/types.js +0 -10
  149. package/lib/sfdxProject.js +0 -557
  150. package/lib/util/fs.d.ts +0 -201
  151. package/lib/util/fs.js +0 -378
@@ -13,18 +13,11 @@ const lib_1 = require("@salesforce/kit/lib");
13
13
  const lib_2 = require("@salesforce/ts-types/lib");
14
14
  const Faye = require("faye");
15
15
  const logger_1 = require("../logger");
16
- const sfdxError_1 = require("../sfdxError");
16
+ const sfError_1 = require("../sfError");
17
17
  const messages_1 = require("../messages");
18
18
  const types_1 = require("./types");
19
19
  Object.defineProperty(exports, "CometClient", { enumerable: true, get: function () { return types_1.CometClient; } });
20
- messages_1.Messages.importMessagesDirectory(__dirname);
21
- const messages = messages_1.Messages.load('@salesforce/core', 'streaming', [
22
- 'waitParamValidValueError',
23
- 'genericHandshakeTimeout',
24
- 'invalidApiVersion',
25
- 'genericTimeout',
26
- 'handshakeApiVersionError',
27
- ]);
20
+ const messages = new messages_1.Messages('@salesforce/core', 'streaming', new Map([["genericTimeout", "Socket timeout occurred while listening for results."], ["genericHandshakeTimeout", "The streaming request failed to handshake at %s."], ["handshakeApiVersionError", "Invalid API version specified for streaming connection handshake: %s"], ["handshakeApiVersionError.actions", ["Set the API version to match the org as an environment variable (e.g., SFDX_API_VERSION=XX.0)."]], ["waitParamValidValueError", "Invalid value was specified for wait. Please provide a wait value greater than %s minutes."], ["invalidApiVersion", "Invalid api version is being reported by config (apiVersion=%s)."]]));
28
21
  /**
29
22
  * Validation helper
30
23
  *
@@ -151,7 +144,7 @@ class StreamingClient extends lib_1.AsyncOptionalCreatable {
151
144
  this.cometClient.setHeader('Authorization', `OAuth ${accessToken}`);
152
145
  }
153
146
  else {
154
- throw new sfdxError_1.SfdxError('Missing or invalid access token', 'MissingOrInvalidAccessToken');
147
+ throw new sfError_1.SfError('Missing or invalid access token', 'MissingOrInvalidAccessToken');
155
148
  }
156
149
  this.log(`Streaming client target url: ${this.targetUrl}`);
157
150
  this.log(`options.subscribeTimeout (ms): ${this.options.subscribeTimeout.milliseconds}`);
@@ -201,7 +194,7 @@ class StreamingClient extends lib_1.AsyncOptionalCreatable {
201
194
  * Subscribe to streaming events. When the streaming processor that's set in the options completes execution it
202
195
  * returns a payload in the StatusResult object. The payload is just echoed here for convenience.
203
196
  *
204
- * **Throws** *{@link SfdxError}{ name: '{@link StreamingClient.TimeoutErrorType.SUBSCRIBE}'}* When the subscribe timeout occurs.
197
+ * **Throws** *{@link SfError}{ name: '{@link StreamingClient.TimeoutErrorType.SUBSCRIBE}'}* When the subscribe timeout occurs.
205
198
  *
206
199
  * @param streamInit This function should call the platform apis that result in streaming updates on push topics.
207
200
  * {@link StatusResult}
@@ -211,54 +204,52 @@ class StreamingClient extends lib_1.AsyncOptionalCreatable {
211
204
  // This outer promise is to hold the streaming promise chain open until the streaming processor
212
205
  // says it's complete.
213
206
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
214
- return new Promise((subscribeResolve, subscribeReject) => {
215
- // This is the inner promise chain that's satisfied when the client impl (Faye/Mock) says it's subscribed.
216
- return new Promise((subscriptionResolve, subscriptionReject) => {
217
- timeout = setTimeout(() => {
218
- const timeoutError = messages.createError('genericTimeout');
219
- this.doTimeout(timeout, timeoutError);
220
- subscribeReject(timeoutError);
221
- }, this.options.subscribeTimeout.milliseconds);
222
- // Initialize the subscription.
223
- const subscription = this.cometClient.subscribe(this.options.channel, (message) => {
224
- try {
225
- // The result of the stream processor determines the state of the outer promise.
226
- const result = this.options.streamProcessor(message);
227
- // The stream processor says it's complete. Clean up and resolve the outer promise.
228
- if (result && result.completed) {
229
- clearTimeout(timeout);
230
- this.disconnectClient();
231
- subscribeResolve(result.payload);
232
- } // This 'if' is intended to be evaluated until it's completed or until the timeout fires.
233
- }
234
- catch (e) {
235
- // it's completely valid for the stream processor to throw an error. If it does we will
236
- // reject the outer promise. Keep in mind if we are here the subscription was resolved.
207
+ return new Promise((subscribeResolve, subscribeReject) =>
208
+ // This is the inner promise chain that's satisfied when the client impl (Faye/Mock) says it's subscribed.
209
+ new Promise((subscriptionResolve, subscriptionReject) => {
210
+ timeout = setTimeout(() => {
211
+ const timeoutError = messages.createError('genericTimeout');
212
+ this.doTimeout(timeout, timeoutError);
213
+ subscribeReject(timeoutError);
214
+ }, this.options.subscribeTimeout.milliseconds);
215
+ // Initialize the subscription.
216
+ const subscription = this.cometClient.subscribe(this.options.channel, (message) => {
217
+ try {
218
+ // The result of the stream processor determines the state of the outer promise.
219
+ const result = this.options.streamProcessor(message);
220
+ // The stream processor says it's complete. Clean up and resolve the outer promise.
221
+ if (result?.completed) {
237
222
  clearTimeout(timeout);
238
223
  this.disconnectClient();
239
- subscribeReject(e);
240
- }
241
- });
242
- subscription.callback(() => {
243
- subscriptionResolve();
244
- });
245
- subscription.errback((error) => {
246
- subscriptionReject(error);
247
- });
248
- })
249
- .then(() => {
250
- // Now that we successfully have a subscription started up we are safe to initialize the function that
251
- // will affect the streaming events. I.E. create an org or run apex tests.
252
- return streamInit && streamInit();
253
- })
254
- .catch((error) => {
255
- this.disconnect();
256
- // Need to catch the subscription rejection or it will result in an unhandled rejection error.
257
- clearTimeout(timeout);
258
- // No subscription so we can reject the out promise as well.
259
- subscribeReject(error);
224
+ subscribeResolve(result.payload);
225
+ } // This 'if' is intended to be evaluated until it's completed or until the timeout fires.
226
+ }
227
+ catch (e) {
228
+ // it's completely valid for the stream processor to throw an error. If it does we will
229
+ // reject the outer promise. Keep in mind if we are here the subscription was resolved.
230
+ clearTimeout(timeout);
231
+ this.disconnectClient();
232
+ subscribeReject(e);
233
+ }
260
234
  });
261
- });
235
+ subscription.callback(() => {
236
+ subscriptionResolve();
237
+ });
238
+ subscription.errback((error) => {
239
+ subscriptionReject(error);
240
+ });
241
+ })
242
+ .then(() =>
243
+ // Now that we successfully have a subscription started up we are safe to initialize the function that
244
+ // will affect the streaming events. I.E. create an org or run apex tests.
245
+ streamInit?.())
246
+ .catch((error) => {
247
+ this.disconnect();
248
+ // Need to catch the subscription rejection or it will result in an unhandled rejection error.
249
+ clearTimeout(timeout);
250
+ // No subscription so we can reject the out promise as well.
251
+ subscribeReject(error);
252
+ }));
262
253
  }
263
254
  /**
264
255
  * Handler for incoming streaming messages.
@@ -296,12 +287,17 @@ class StreamingClient extends lib_1.AsyncOptionalCreatable {
296
287
  // unauthenticated connections are being made to salesforce. Let's close the dispatcher if it exists and
297
288
  // has no clientId.
298
289
  // @ts-ignore
290
+ // eslint-disable-next-line no-underscore-dangle
299
291
  if (this.cometClient._dispatcher) {
300
292
  this.log('Closing the faye dispatcher');
301
293
  // @ts-ignore
294
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, no-underscore-dangle
302
295
  const dispatcher = this.cometClient._dispatcher;
296
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-unsafe-member-access
303
297
  this.log(`dispatcher.clientId: ${dispatcher.clientId}`);
298
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
304
299
  if (!dispatcher.clientId) {
300
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
305
301
  dispatcher.close();
306
302
  }
307
303
  else {
@@ -342,13 +338,13 @@ exports.StreamingClient = StreamingClient;
342
338
  logger.warn('envDep is deprecated');
343
339
  }
344
340
  if (!streamProcessor) {
345
- throw new sfdxError_1.SfdxError('Missing stream processor', 'MissingArg');
341
+ throw new sfError_1.SfError('Missing stream processor', 'MissingArg');
346
342
  }
347
343
  if (!org) {
348
- throw new sfdxError_1.SfdxError('Missing org', 'MissingArg');
344
+ throw new sfError_1.SfError('Missing org', 'MissingArg');
349
345
  }
350
346
  if (!channel) {
351
- throw new sfdxError_1.SfdxError('Missing streaming channel', 'MissingArg');
347
+ throw new sfError_1.SfError('Missing streaming channel', 'MissingArg');
352
348
  }
353
349
  this.org = org;
354
350
  this.apiVersion = org.getConnection().getApiVersion();
@@ -363,10 +359,9 @@ exports.StreamingClient = StreamingClient;
363
359
  this.subscribeTimeout = StreamingClient.DefaultOptions.DEFAULT_SUBSCRIBE_TIMEOUT;
364
360
  this.handshakeTimeout = StreamingClient.DefaultOptions.DEFAULT_HANDSHAKE_TIMEOUT;
365
361
  this.streamingImpl = {
366
- getCometClient: (url) => {
367
- // @ts-ignore
368
- return new Faye.Client(url);
369
- },
362
+ getCometClient: (url) =>
363
+ // @ts-ignore
364
+ new Faye.Client(url),
370
365
  setLogger: (logLine) => {
371
366
  // @ts-ignore
372
367
  Faye.logger = {};
@@ -1,8 +1,8 @@
1
1
  /// <reference types="node" />
2
2
  import { EventEmitter } from 'events';
3
3
  import { AnyFunction, AnyJson, JsonMap } from '@salesforce/ts-types';
4
- export declare type Message = JsonMap;
5
- export declare type Callback<T = unknown> = (...args: any[]) => T;
4
+ export type Message = JsonMap;
5
+ export type Callback<T = unknown> = (...args: any[]) => T;
6
6
  export interface StatusResult {
7
7
  /**
8
8
  * If the result of the streaming or polling client is expected to return a result
@@ -1,24 +1,26 @@
1
1
  /// <reference types="node" />
2
2
  import { EventEmitter } from 'events';
3
- import * as sinonType from 'sinon';
3
+ import { SinonSandbox, SinonStatic, SinonStub } from 'sinon';
4
4
  import { AnyJson, JsonMap, Optional } from '@salesforce/ts-types';
5
5
  import { ConfigContents } from './config/configStore';
6
+ import { Connection } from './org/connection';
6
7
  import { Logger } from './logger';
7
- import { SfdxError } from './sfdxError';
8
+ import { SfError } from './sfError';
8
9
  import { CometClient, CometSubscription, Message, StreamingExtension } from './status/streamingClient';
9
- import { SfOrg } from './globalInfo';
10
+ import { AuthFields, SandboxFields } from './org';
10
11
  /**
11
12
  * Different parts of the system that are mocked out. They can be restored for
12
13
  * individual tests. Test's stubs should always go on the DEFAULT which is exposed
13
14
  * on the TestContext.
14
15
  */
15
16
  export interface SandboxTypes {
16
- DEFAULT: sinon.SinonSandbox;
17
- CRYPTO: sinon.SinonSandbox;
18
- CONFIG: sinon.SinonSandbox;
19
- PROJECT: sinon.SinonSandbox;
20
- CONNECTION: sinon.SinonSandbox;
21
- FS: sinonType.SinonSandbox;
17
+ DEFAULT: SinonSandbox;
18
+ CRYPTO: SinonSandbox;
19
+ CONFIG: SinonSandbox;
20
+ PROJECT: SinonSandbox;
21
+ CONNECTION: SinonSandbox;
22
+ FS: SinonSandbox;
23
+ ORGS: SinonSandbox;
22
24
  }
23
25
  /**
24
26
  * Different hooks into {@link ConfigFile} used for testing instead of doing file IO.
@@ -52,15 +54,15 @@ export interface ConfigStub {
52
54
  updateContents?: () => Promise<JsonMap>;
53
55
  }
54
56
  /**
55
- * Different configuration options when running before each
57
+ * Instantiate a @salesforce/core test context.
56
58
  */
57
- export interface TestContext {
59
+ export declare class TestContext {
58
60
  /**
59
61
  * The default sandbox is cleared out before each test run.
60
62
  *
61
- * **See** [sinon sandbox]{@link http://sinonjs.org/releases/v1.17.7/sandbox/}.
63
+ * **See** [sinon sandbox]{@link https://sinonjs.org/releases/v14/sandbox/}.
62
64
  */
63
- SANDBOX: sinonType.SinonSandbox;
65
+ SANDBOX: SinonSandbox;
64
66
  /**
65
67
  * An object of different sandboxes. Used when
66
68
  * needing to restore parts of the system for customized testing.
@@ -74,58 +76,68 @@ export interface TestContext {
74
76
  * id A unique id for the test run.
75
77
  */
76
78
  id: string;
77
- /**
78
- * A function that returns unique strings.
79
- */
80
- uniqid: () => string;
81
79
  /**
82
80
  * An object used in tests that interact with config files.
83
81
  */
84
82
  configStubs: {
85
83
  [configName: string]: Optional<ConfigStub>;
86
- GlobalInfo?: ConfigStub;
87
- Aliases?: ConfigStub;
88
- SfdxProjectJson?: ConfigStub;
89
- SfdxConfig?: ConfigStub;
84
+ AuthInfoConfig?: ConfigStub;
85
+ Config?: ConfigStub;
86
+ SfProjectJson?: ConfigStub;
87
+ TokensConfig?: ConfigStub;
88
+ OrgUsersConfig?: ConfigStub;
90
89
  };
90
+ /**
91
+ * A record of stubs created during instantiation.
92
+ */
93
+ stubs: Record<string, SinonStub>;
94
+ constructor(options?: {
95
+ sinon?: SinonStatic;
96
+ sandbox?: SinonSandbox;
97
+ setup?: boolean;
98
+ });
99
+ /**
100
+ * Generate unique string.
101
+ */
102
+ uniqid(): string;
91
103
  /**
92
104
  * A function used when resolving the local path. Calls localPathResolverSync by default.
93
105
  *
94
106
  * @param uid Unique id.
95
107
  */
96
- localPathRetriever: (uid: string) => Promise<string>;
108
+ localPathRetriever(uid: string): Promise<string>;
97
109
  /**
98
110
  * A function used when resolving the local path.
99
111
  *
100
112
  * @param uid Unique id.
101
113
  */
102
- localPathRetrieverSync: (uid: string) => string;
114
+ localPathRetrieverSync(uid: string): string;
103
115
  /**
104
116
  * A function used when resolving the global path. Calls globalPathResolverSync by default.
105
117
  *
106
118
  * @param uid Unique id.
107
119
  */
108
- globalPathRetriever: (uid: string) => Promise<string>;
120
+ globalPathRetriever(uid: string): Promise<string>;
109
121
  /**
110
122
  * A function used when resolving the global path.
111
123
  *
112
124
  * @param uid Unique id.
113
125
  */
114
- globalPathRetrieverSync: (uid: string) => string;
126
+ globalPathRetrieverSync(uid: string): string;
115
127
  /**
116
128
  * A function used for resolving paths. Calls localPathRetriever and globalPathRetriever.
117
129
  *
118
130
  * @param isGlobal `true` if the config is global.
119
131
  * @param uid user id.
120
132
  */
121
- rootPathRetriever: (isGlobal: boolean, uid?: string) => Promise<string>;
133
+ rootPathRetriever(isGlobal: boolean, uid?: string): Promise<string>;
122
134
  /**
123
135
  * A function used for resolving paths. Calls localPathRetrieverSync and globalPathRetrieverSync.
124
136
  *
125
137
  * @param isGlobal `true` if the config is global.
126
138
  * @param uid user id.
127
139
  */
128
- rootPathRetrieverSync: (isGlobal: boolean, uid?: string) => string;
140
+ rootPathRetrieverSync(isGlobal: boolean, uid?: string): string;
129
141
  /**
130
142
  * Used to mock http request to Salesforce.
131
143
  *
@@ -134,7 +146,7 @@ export interface TestContext {
134
146
  *
135
147
  * **See** {@link Connection.request}
136
148
  */
137
- fakeConnectionRequest: (request: AnyJson, options?: AnyJson) => Promise<AnyJson>;
149
+ fakeConnectionRequest(request: AnyJson, options?: AnyJson): Promise<AnyJson>;
138
150
  /**
139
151
  * Gets a config stub contents by name.
140
152
  *
@@ -149,8 +161,62 @@ export interface TestContext {
149
161
  * @param value The actual stub contents. The Mock data.
150
162
  */
151
163
  setConfigStubContents(name: string, value: ConfigContents): void;
152
- inProject(inProject: boolean): void;
164
+ /**
165
+ * Set stubs for working in the context of a SfProject
166
+ */
167
+ inProject(inProject?: boolean): void;
168
+ /**
169
+ * Stub salesforce org authorizations.
170
+ */
171
+ stubAuths(...orgs: MockTestOrgData[]): Promise<void>;
172
+ /**
173
+ * Stub salesforce user authorizations.
174
+ *
175
+ * @param users The users to stub.
176
+ * The key is the username of the admin user and it must be included in the users array in order to obtain the orgId key for the remaining users.
177
+ * The admin user is excluded from the users array.
178
+ *
179
+ */
180
+ stubUsers(users: Record<string, MockTestOrgData[]>): void;
181
+ /**
182
+ * Stub salesforce sandbox authorizations.
183
+ */
184
+ stubSandboxes(...sandboxes: MockTestSandboxData[]): Promise<void>;
185
+ /**
186
+ * Stub the aliases in the global aliases config file.
187
+ */
188
+ stubAliases(aliases: Record<string, string>, group?: string): void;
189
+ /**
190
+ * Stub contents in the config file.
191
+ */
192
+ stubConfig(config: Record<string, string>): Promise<void>;
193
+ /**
194
+ * Stub the tokens in the global token config file.
195
+ */
196
+ stubTokens(tokens: Record<string, string>): void;
197
+ restore(): void;
198
+ init(): void;
199
+ /**
200
+ * Add beforeEach and afterEach hooks to init the stubs and restore them.
201
+ * This is called automatically when the class is instantiated unless the setup option is set to false.
202
+ */
203
+ setup(): void;
204
+ private requireSinon;
153
205
  }
206
+ /**
207
+ * A function to generate a unique id and return it in the context of a template, if supplied.
208
+ *
209
+ * A template is a string that can contain `${%s}` to be replaced with a unique id.
210
+ * If the template contains the "%s" placeholder, it will be replaced with the unique id otherwise the id will be appended to the template.
211
+ *
212
+ * @param options an object with the following properties:
213
+ * - template: a template string.
214
+ * - length: the length of the unique id as presented in hexadecimal.
215
+ */
216
+ export declare function uniqid(options?: {
217
+ template?: string;
218
+ length?: number;
219
+ }): string;
154
220
  /**
155
221
  * Instantiate a @salesforce/core test context. This is automatically created by `const $$ = testSetup()`
156
222
  * but is useful if you don't want to have a global stub of @salesforce/core and you want to isolate it to
@@ -163,16 +229,16 @@ export interface TestContext {
163
229
  * const $$ = instantiateContext();
164
230
  *
165
231
  * beforeEach(() => {
166
- * stubContext($$);
232
+ * $$.init()
167
233
  * });
168
234
  *
169
235
  * afterEach(() => {
170
- * restoreContext($$);
236
+ * $$.restore();
171
237
  * });
172
238
  * ```
173
239
  * @param sinon
174
240
  */
175
- export declare const instantiateContext: (sinon?: any) => TestContext;
241
+ export declare const instantiateContext: (sinon?: SinonStatic) => TestContext;
176
242
  /**
177
243
  * Stub a @salesforce/core test context. This will mock out logging to a file, config file reading and writing,
178
244
  * local and global path resolution, and http request using connection (soon)*.
@@ -188,16 +254,16 @@ export declare const instantiateContext: (sinon?: any) => TestContext;
188
254
  * const $$ = instantiateContext();
189
255
  *
190
256
  * beforeEach(() => {
191
- * stubContext($$);
257
+ * $$.init()
192
258
  * });
193
259
  *
194
260
  * afterEach(() => {
195
- * restoreContext($$);
261
+ * $$.restore();
196
262
  * });
197
263
  * ```
198
264
  * @param testContext
199
265
  */
200
- export declare const stubContext: (testContext: TestContext) => void;
266
+ export declare const stubContext: (testContext: TestContext) => Record<string, SinonStub>;
201
267
  /**
202
268
  * Restore a @salesforce/core test context. This is automatically stubbed in the global beforeEach created by
203
269
  * `const $$ = testSetup()` but is useful if you don't want to have a global stub of @salesforce/core and you
@@ -208,57 +274,28 @@ export declare const stubContext: (testContext: TestContext) => void;
208
274
  * const $$ = instantiateContext();
209
275
  *
210
276
  * beforeEach(() => {
211
- * stubContext($$);
277
+ * $$.init()
212
278
  * });
213
279
  *
214
280
  * afterEach(() => {
215
- * restoreContext($$);
281
+ * $$.restore();
216
282
  * });
217
283
  * ```
218
284
  * @param testContext
219
285
  */
220
286
  export declare const restoreContext: (testContext: TestContext) => void;
221
- /**
222
- * Use to mock out different pieces of sfdx-core to make testing easier. This will mock out
223
- * logging to a file, config file reading and writing, local and global path resolution, and
224
- * *http request using connection (soon)*.
225
- *
226
- * **Note:** The testSetup should be outside of the describe. If you need to stub per test, use
227
- * `instantiateContext`, `stubContext`, and `restoreContext`.
228
- * ```
229
- * // In a mocha tests
230
- * import testSetup from '@salesforce/core/lib/testSetup';
231
- *
232
- * const $$ = testSetup();
233
- *
234
- * describe(() => {
235
- * it('test', () => {
236
- * // Stub out your own method
237
- * $$.SANDBOX.stub(MyClass.prototype, 'myMethod').returnsFake(() => {});
238
- *
239
- * // Set the contents that is used when aliases are read. Same for all config files.
240
- * $$.configStubs.Aliases = { contents: { 'myTestAlias': 'user@company.com' } };
241
- *
242
- * // Will use the contents set above.
243
- * const username = Aliases.fetch('myTestAlias');
244
- * expect(username).to.equal('user@company.com');
245
- * });
246
- * });
247
- * ```
248
- */
249
- export declare const testSetup: (sinon?: any) => TestContext;
250
287
  /**
251
288
  * A pre-canned error for try/catch testing.
252
289
  *
253
290
  * **See** {@link shouldThrow}
254
291
  */
255
- export declare const unexpectedResult: SfdxError;
292
+ export declare const unexpectedResult: SfError;
256
293
  /**
257
294
  * Use for this testing pattern:
258
295
  * ```
259
296
  * try {
260
297
  * await call()
261
- * assert.fail('this should never happen');
298
+ * assert.fail("this should never happen");
262
299
  * } catch (e) {
263
300
  * ...
264
301
  * }
@@ -274,7 +311,29 @@ export declare const unexpectedResult: SfdxError;
274
311
  *
275
312
  * @param f The async function that is expected to throw.
276
313
  */
277
- export declare function shouldThrow(f: Promise<unknown>): Promise<never>;
314
+ export declare function shouldThrow(f: Promise<unknown>, message?: string): Promise<never>;
315
+ /**
316
+ * Use for this testing pattern:
317
+ * ```
318
+ * try {
319
+ * call()
320
+ * assert.fail("this should never happen");
321
+ * } catch (e) {
322
+ * ...
323
+ * }
324
+ *
325
+ * Just do this
326
+ *
327
+ * try {
328
+ * shouldThrowSync(call); // If this succeeds unexpectedResultError is thrown.
329
+ * } catch(e) {
330
+ * ...
331
+ * }
332
+ * ```
333
+ *
334
+ * @param f The function that is expected to throw.
335
+ */
336
+ export declare function shouldThrowSync(f: () => unknown, message?: string): never;
278
337
  /**
279
338
  * A helper to determine if a subscription will use callback or errorback.
280
339
  * Enable errback to simulate a subscription failure.
@@ -302,7 +361,7 @@ export interface StreamingMockCometSubscriptionOptions {
302
361
  /**
303
362
  * If it's an error that states what that error should be.
304
363
  */
305
- subscriptionErrbackError?: SfdxError;
364
+ subscriptionErrbackError?: SfError;
306
365
  /**
307
366
  * A list of messages to playback for the client. One message per process tick.
308
367
  */
@@ -372,12 +431,32 @@ export declare class StreamingMockCometClient extends CometClient {
372
431
  */
373
432
  disconnect(): Promise<void>;
374
433
  }
434
+ type MockUserInfo = {
435
+ Id: string;
436
+ Username: string;
437
+ LastName: string;
438
+ Alias: string;
439
+ Configs: string[] | undefined;
440
+ TimeZoneSidKey: string;
441
+ LocaleSidKey: string;
442
+ EmailEncodingKey: string;
443
+ ProfileId: string;
444
+ LanguageLocaleKey: string;
445
+ Email: string;
446
+ };
375
447
  /**
376
- * Mock class for OrgData.
448
+ * Mock class for Salesforce Orgs.
449
+ *
450
+ * @example
451
+ * ```
452
+ * const testOrg = new MockTestOrgData();
453
+ * await $$.stubAuths(testOrg)
454
+ * ```
377
455
  */
378
456
  export declare class MockTestOrgData {
379
457
  testId: string;
380
- alias?: string;
458
+ aliases?: string[];
459
+ configs?: string[];
381
460
  username: string;
382
461
  devHubUsername?: string;
383
462
  orgId: string;
@@ -387,15 +466,65 @@ export declare class MockTestOrgData {
387
466
  clientSecret: string;
388
467
  authcode: string;
389
468
  accessToken: string;
390
- refreshToken: string;
469
+ refreshToken: string | undefined;
470
+ tracksSource: boolean | undefined;
391
471
  userId: string;
392
472
  redirectUri: string;
473
+ isDevHub?: boolean;
474
+ isScratchOrg?: boolean;
475
+ isExpired?: boolean | 'unknown';
476
+ password?: string;
393
477
  constructor(id?: string, options?: {
394
478
  username: string;
395
479
  });
480
+ /**
481
+ * Add devhub username to properties.
482
+ */
396
483
  createDevHubUsername(username: string): void;
484
+ /**
485
+ * Mark this org as a devhub.
486
+ */
397
487
  makeDevHub(): void;
488
+ /**
489
+ * Returns a MockTestOrgData that represents a user created in the org.
490
+ */
398
491
  createUser(user: string): MockTestOrgData;
399
- getMockUserInfo(): JsonMap;
400
- getConfig(): Promise<SfOrg>;
492
+ /**
493
+ * Return mock user information based on this org.
494
+ */
495
+ getMockUserInfo(): MockUserInfo;
496
+ /**
497
+ * Return the auth config file contents.
498
+ */
499
+ getConfig(): Promise<AuthFields>;
500
+ /**
501
+ * Return the Connection for the org.
502
+ */
503
+ getConnection(): Promise<Connection>;
504
+ }
505
+ /**
506
+ * Mock class for Salesforce Sandboxes.
507
+ *
508
+ * @example
509
+ * ```
510
+ * const testOrg = new MockTestSandboxData();
511
+ * await $$.stubSandboxes(testOrg)
512
+ * ```
513
+ */
514
+ export declare class MockTestSandboxData {
515
+ id: string;
516
+ sandboxOrgId: string;
517
+ prodOrgUsername: string;
518
+ sandboxName?: string;
519
+ username?: string;
520
+ constructor(id?: string, options?: Partial<{
521
+ prodOrgUsername: string;
522
+ name: string;
523
+ username: string;
524
+ }>);
525
+ /**
526
+ * Return the auth config file contents.
527
+ */
528
+ getConfig(): Promise<SandboxFields>;
401
529
  }
530
+ export {};