@salesforce/core 4.0.0-v3.0 → 4.0.1

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 (160) hide show
  1. package/LICENSE.txt +1 -1
  2. package/README.md +93 -44
  3. package/lib/config/aliasesConfig.d.ts +12 -0
  4. package/lib/config/aliasesConfig.js +28 -0
  5. package/lib/config/authInfoConfig.d.ts +19 -0
  6. package/lib/config/authInfoConfig.js +35 -0
  7. package/lib/config/config.d.ts +181 -48
  8. package/lib/config/config.js +382 -159
  9. package/lib/config/configAggregator.d.ts +59 -42
  10. package/lib/config/configAggregator.js +135 -82
  11. package/lib/config/configFile.d.ts +2 -2
  12. package/lib/config/configFile.js +40 -31
  13. package/lib/config/configGroup.d.ts +9 -9
  14. package/lib/config/configGroup.js +13 -11
  15. package/lib/config/configStore.d.ts +9 -9
  16. package/lib/config/configStore.js +29 -26
  17. package/lib/config/envVars.d.ts +102 -0
  18. package/lib/config/envVars.js +457 -0
  19. package/lib/config/orgUsersConfig.d.ts +8 -0
  20. package/lib/config/orgUsersConfig.js +12 -0
  21. package/lib/config/sandboxOrgConfig.d.ts +8 -0
  22. package/lib/config/sandboxOrgConfig.js +12 -0
  23. package/lib/config/sandboxProcessCache.d.ts +16 -0
  24. package/lib/config/sandboxProcessCache.js +38 -0
  25. package/lib/config/tokensConfig.d.ts +10 -0
  26. package/lib/config/tokensConfig.js +29 -0
  27. package/lib/config/ttlConfig.d.ts +34 -0
  28. package/lib/config/ttlConfig.js +50 -0
  29. package/lib/crypto/crypto.js +29 -16
  30. package/lib/crypto/keyChain.js +4 -4
  31. package/lib/crypto/keyChainImpl.d.ts +5 -3
  32. package/lib/crypto/keyChainImpl.js +65 -66
  33. package/lib/crypto/secureBuffer.d.ts +1 -1
  34. package/lib/crypto/secureBuffer.js +1 -1
  35. package/lib/deviceOauthService.d.ts +5 -5
  36. package/lib/deviceOauthService.js +37 -33
  37. package/lib/exported.d.ts +22 -15
  38. package/lib/exported.js +49 -25
  39. package/lib/global.d.ts +17 -3
  40. package/lib/global.js +46 -13
  41. package/lib/lifecycleEvents.d.ts +39 -2
  42. package/lib/lifecycleEvents.js +77 -3
  43. package/lib/logger.d.ts +21 -11
  44. package/lib/logger.js +121 -105
  45. package/lib/messages.d.ts +53 -36
  46. package/lib/messages.js +89 -97
  47. package/lib/org/authInfo.d.ts +84 -72
  48. package/lib/org/authInfo.js +326 -320
  49. package/lib/org/authRemover.d.ts +16 -23
  50. package/lib/org/authRemover.js +62 -60
  51. package/lib/org/connection.d.ts +33 -59
  52. package/lib/org/connection.js +129 -190
  53. package/lib/org/index.js +6 -2
  54. package/lib/org/org.d.ts +263 -38
  55. package/lib/org/org.js +734 -149
  56. package/lib/org/orgConfigProperties.d.ts +69 -0
  57. package/lib/org/orgConfigProperties.js +121 -0
  58. package/lib/org/permissionSetAssignment.js +6 -15
  59. package/lib/org/scratchOrgCache.d.ts +20 -0
  60. package/lib/org/scratchOrgCache.js +33 -0
  61. package/lib/org/scratchOrgCreate.d.ts +54 -0
  62. package/lib/org/scratchOrgCreate.js +214 -0
  63. package/lib/org/scratchOrgErrorCodes.d.ts +10 -0
  64. package/lib/org/scratchOrgErrorCodes.js +79 -0
  65. package/lib/org/scratchOrgFeatureDeprecation.d.ts +26 -0
  66. package/lib/org/scratchOrgFeatureDeprecation.js +105 -0
  67. package/lib/org/scratchOrgInfoApi.d.ts +68 -0
  68. package/lib/org/scratchOrgInfoApi.js +416 -0
  69. package/lib/org/scratchOrgInfoGenerator.d.ts +64 -0
  70. package/lib/org/scratchOrgInfoGenerator.js +237 -0
  71. package/lib/org/scratchOrgLifecycleEvents.d.ts +10 -0
  72. package/lib/org/scratchOrgLifecycleEvents.js +41 -0
  73. package/lib/org/scratchOrgSettingsGenerator.d.ts +79 -0
  74. package/lib/org/scratchOrgSettingsGenerator.js +277 -0
  75. package/lib/org/scratchOrgTypes.d.ts +43 -0
  76. package/lib/{status/client.js → org/scratchOrgTypes.js} +1 -1
  77. package/lib/org/user.d.ts +7 -2
  78. package/lib/org/user.js +78 -54
  79. package/lib/schema/printer.d.ts +6 -0
  80. package/lib/schema/printer.js +49 -46
  81. package/lib/schema/validator.d.ts +12 -10
  82. package/lib/schema/validator.js +56 -76
  83. package/lib/{sfdxError.d.ts → sfError.d.ts} +12 -15
  84. package/lib/{sfdxError.js → sfError.js} +42 -24
  85. package/lib/{sfdxProject.d.ts → sfProject.d.ts} +75 -35
  86. package/lib/sfProject.js +651 -0
  87. package/lib/stateAggregator/accessors/aliasAccessor.d.ts +98 -0
  88. package/lib/stateAggregator/accessors/aliasAccessor.js +146 -0
  89. package/lib/stateAggregator/accessors/orgAccessor.d.ts +101 -0
  90. package/lib/stateAggregator/accessors/orgAccessor.js +240 -0
  91. package/lib/stateAggregator/accessors/sandboxAccessor.d.ts +8 -0
  92. package/lib/stateAggregator/accessors/sandboxAccessor.js +28 -0
  93. package/lib/stateAggregator/accessors/tokenAccessor.d.ts +63 -0
  94. package/lib/stateAggregator/accessors/tokenAccessor.js +80 -0
  95. package/lib/stateAggregator/index.d.ts +4 -0
  96. package/lib/stateAggregator/index.js +27 -0
  97. package/lib/stateAggregator/stateAggregator.d.ts +25 -0
  98. package/lib/stateAggregator/stateAggregator.js +46 -0
  99. package/lib/status/myDomainResolver.d.ts +1 -1
  100. package/lib/status/myDomainResolver.js +10 -10
  101. package/lib/status/pollingClient.d.ts +2 -6
  102. package/lib/status/pollingClient.js +38 -64
  103. package/lib/status/streamingClient.d.ts +5 -80
  104. package/lib/status/streamingClient.js +74 -94
  105. package/lib/status/types.d.ts +89 -0
  106. package/lib/status/types.js +18 -0
  107. package/lib/testSetup.d.ts +212 -79
  108. package/lib/testSetup.js +478 -182
  109. package/lib/util/cache.d.ts +11 -0
  110. package/lib/util/cache.js +70 -0
  111. package/lib/util/checkLightningDomain.d.ts +1 -0
  112. package/lib/util/checkLightningDomain.js +29 -0
  113. package/lib/util/directoryWriter.d.ts +12 -0
  114. package/lib/util/directoryWriter.js +54 -0
  115. package/lib/util/getJwtAudienceUrl.d.ts +4 -0
  116. package/lib/util/getJwtAudienceUrl.js +19 -0
  117. package/lib/util/internal.d.ts +28 -2
  118. package/lib/util/internal.js +65 -8
  119. package/lib/util/jsonXmlTools.d.ts +14 -0
  120. package/lib/util/jsonXmlTools.js +39 -0
  121. package/lib/util/mapKeys.d.ts +14 -0
  122. package/lib/util/mapKeys.js +52 -0
  123. package/lib/util/sfdc.d.ts +51 -63
  124. package/lib/util/sfdc.js +75 -127
  125. package/lib/util/sfdcUrl.d.ts +64 -0
  126. package/lib/util/sfdcUrl.js +197 -0
  127. package/lib/util/structuredWriter.d.ts +9 -0
  128. package/lib/util/structuredWriter.js +3 -0
  129. package/lib/util/zipWriter.d.ts +16 -0
  130. package/lib/util/zipWriter.js +68 -0
  131. package/lib/webOAuthServer.d.ts +20 -7
  132. package/lib/webOAuthServer.js +107 -60
  133. package/messageTransformer/messageTransformer.ts +93 -0
  134. package/messages/auth.md +11 -3
  135. package/messages/config.md +94 -6
  136. package/messages/connection.md +8 -0
  137. package/messages/core.json +3 -3
  138. package/messages/core.md +11 -1
  139. package/messages/envVars.md +313 -0
  140. package/messages/org.md +64 -0
  141. package/messages/scratchOrgCreate.md +23 -0
  142. package/messages/scratchOrgErrorCodes.md +115 -0
  143. package/messages/scratchOrgFeatureDeprecation.md +11 -0
  144. package/messages/scratchOrgInfoApi.md +20 -0
  145. package/messages/scratchOrgInfoGenerator.md +27 -0
  146. package/messages/user.md +12 -0
  147. package/package.json +138 -66
  148. package/CHANGELOG.md +0 -699
  149. package/lib/config/aliases.d.ts +0 -56
  150. package/lib/config/aliases.js +0 -96
  151. package/lib/config/globalInfoConfig.d.ts +0 -74
  152. package/lib/config/globalInfoConfig.js +0 -144
  153. package/lib/config/keychainConfig.d.ts +0 -19
  154. package/lib/config/keychainConfig.js +0 -43
  155. package/lib/config/sfdxDataHandler.d.ts +0 -36
  156. package/lib/config/sfdxDataHandler.js +0 -165
  157. package/lib/sfdxProject.js +0 -546
  158. package/lib/status/client.d.ts +0 -15
  159. package/lib/util/fs.d.ts +0 -198
  160. package/lib/util/fs.js +0 -374
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2021, salesforce.com, inc.
4
+ * All rights reserved.
5
+ * Licensed under the BSD 3-Clause license.
6
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.TokenAccessor = void 0;
10
+ const kit_1 = require("@salesforce/kit");
11
+ const tokensConfig_1 = require("../../config/tokensConfig");
12
+ class TokenAccessor extends kit_1.AsyncOptionalCreatable {
13
+ /**
14
+ * Return all tokens.
15
+ *
16
+ * @param decrypt
17
+ * @returns {SfTokens}
18
+ */
19
+ getAll(decrypt = false) {
20
+ return this.config.getContents(decrypt) || {};
21
+ }
22
+ /**
23
+ * Return a token for the provided name.
24
+ *
25
+ * @param name
26
+ * @param decrypt
27
+ * @returns {Optional<SfToken>}
28
+ */
29
+ get(name, decrypt = false) {
30
+ return this.config.get(name, decrypt);
31
+ }
32
+ /**
33
+ * Return true if a given name has a token associated with it.
34
+ *
35
+ * @param name
36
+ * @returns {boolean}
37
+ */
38
+ has(name) {
39
+ return !!this.getAll()[name];
40
+ }
41
+ /**
42
+ * Set the token for the provided name.
43
+ *
44
+ * @param name
45
+ * @param token
46
+ */
47
+ set(name, token) {
48
+ this.config.set(name, token);
49
+ }
50
+ /**
51
+ * Update the token for the provided name.
52
+ *
53
+ * @param name
54
+ * @param token
55
+ */
56
+ update(name, token) {
57
+ this.config.update(name, token);
58
+ }
59
+ /**
60
+ * Unet the token for the provided name.
61
+ *
62
+ * @param name
63
+ */
64
+ unset(name) {
65
+ this.config.unset(name);
66
+ }
67
+ /**
68
+ * Write the contents to the token file.
69
+ *
70
+ * @returns {Promise<SfTokens>}
71
+ */
72
+ async write() {
73
+ return this.config.write();
74
+ }
75
+ async init() {
76
+ this.config = await tokensConfig_1.TokensConfig.create();
77
+ }
78
+ }
79
+ exports.TokenAccessor = TokenAccessor;
80
+ //# sourceMappingURL=tokenAccessor.js.map
@@ -0,0 +1,4 @@
1
+ export * from './accessors/orgAccessor';
2
+ export * from './accessors/aliasAccessor';
3
+ export * from './accessors/tokenAccessor';
4
+ export * from './stateAggregator';
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2021, salesforce.com, inc.
4
+ * All rights reserved.
5
+ * Licensed under the BSD 3-Clause license.
6
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
7
+ */
8
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
+ if (k2 === undefined) k2 = k;
10
+ var desc = Object.getOwnPropertyDescriptor(m, k);
11
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12
+ desc = { enumerable: true, get: function() { return m[k]; } };
13
+ }
14
+ Object.defineProperty(o, k2, desc);
15
+ }) : (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ o[k2] = m[k];
18
+ }));
19
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
20
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
21
+ };
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ __exportStar(require("./accessors/orgAccessor"), exports);
24
+ __exportStar(require("./accessors/aliasAccessor"), exports);
25
+ __exportStar(require("./accessors/tokenAccessor"), exports);
26
+ __exportStar(require("./stateAggregator"), exports);
27
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,25 @@
1
+ import { AsyncOptionalCreatable } from '@salesforce/kit';
2
+ import { AliasAccessor } from './accessors/aliasAccessor';
3
+ import { OrgAccessor } from './accessors/orgAccessor';
4
+ import { SandboxAccessor } from './accessors/sandboxAccessor';
5
+ import { TokenAccessor } from './accessors/tokenAccessor';
6
+ export declare class StateAggregator extends AsyncOptionalCreatable {
7
+ private static instanceMap;
8
+ aliases: AliasAccessor;
9
+ orgs: OrgAccessor;
10
+ sandboxes: SandboxAccessor;
11
+ tokens: TokenAccessor;
12
+ /**
13
+ * Reuse a StateAggregator if one was already created for the current global state directory
14
+ * Otherwise, create one and adds it to map for future reuse.
15
+ * HomeDir might be stubbed in tests
16
+ */
17
+ static getInstance(): Promise<StateAggregator>;
18
+ /**
19
+ * Clear the cache to force reading from disk.
20
+ *
21
+ * *NOTE: Only call this method if you must and you know what you are doing.*
22
+ */
23
+ static clearInstance(path?: string): void;
24
+ protected init(): Promise<void>;
25
+ }
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2022, salesforce.com, inc.
4
+ * All rights reserved.
5
+ * Licensed under the BSD 3-Clause license.
6
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.StateAggregator = void 0;
10
+ const kit_1 = require("@salesforce/kit");
11
+ const global_1 = require("../global");
12
+ const aliasAccessor_1 = require("./accessors/aliasAccessor");
13
+ const orgAccessor_1 = require("./accessors/orgAccessor");
14
+ const sandboxAccessor_1 = require("./accessors/sandboxAccessor");
15
+ const tokenAccessor_1 = require("./accessors/tokenAccessor");
16
+ class StateAggregator extends kit_1.AsyncOptionalCreatable {
17
+ /**
18
+ * Reuse a StateAggregator if one was already created for the current global state directory
19
+ * Otherwise, create one and adds it to map for future reuse.
20
+ * HomeDir might be stubbed in tests
21
+ */
22
+ static async getInstance() {
23
+ if (!StateAggregator.instanceMap.has(global_1.Global.DIR)) {
24
+ StateAggregator.instanceMap.set(global_1.Global.DIR, await StateAggregator.create());
25
+ }
26
+ // TS assertion is valid because there either was one OR it was just now instantiated
27
+ return StateAggregator.instanceMap.get(global_1.Global.DIR);
28
+ }
29
+ /**
30
+ * Clear the cache to force reading from disk.
31
+ *
32
+ * *NOTE: Only call this method if you must and you know what you are doing.*
33
+ */
34
+ static clearInstance(path = global_1.Global.DIR) {
35
+ StateAggregator.instanceMap.delete(path);
36
+ }
37
+ async init() {
38
+ this.orgs = await orgAccessor_1.OrgAccessor.create();
39
+ this.sandboxes = await sandboxAccessor_1.SandboxAccessor.create();
40
+ this.aliases = await aliasAccessor_1.AliasAccessor.create();
41
+ this.tokens = await tokenAccessor_1.TokenAccessor.create();
42
+ }
43
+ }
44
+ exports.StateAggregator = StateAggregator;
45
+ StateAggregator.instanceMap = new Map();
46
+ //# sourceMappingURL=stateAggregator.js.map
@@ -2,7 +2,7 @@
2
2
  import { URL } from 'url';
3
3
  import { AsyncOptionalCreatable, Duration } from '@salesforce/kit';
4
4
  /**
5
- * A class used to resolve MyDomains. After a ScratchOrg is created it's host name my not be propagated to the
5
+ * A class used to resolve MyDomains. After a ScratchOrg is created its host name my not be propagated to the
6
6
  * Salesforce DNS service. This service is not exclusive to Salesforce My Domain URL and could be used for any hostname.
7
7
  *
8
8
  * ```
@@ -13,14 +13,14 @@ const util_1 = require("util");
13
13
  const ts_types_1 = require("@salesforce/ts-types");
14
14
  const kit_1 = require("@salesforce/kit");
15
15
  const logger_1 = require("../logger");
16
- const sfdc_1 = require("../util/sfdc");
16
+ const sfdcUrl_1 = require("../util/sfdcUrl");
17
17
  const pollingClient_1 = require("./pollingClient");
18
18
  // Timeout for DNS lookup polling defaults to 3 seconds and should always be at least 3 seconds
19
19
  const DNS_TIMEOUT = Math.max(3, new kit_1.Env().getNumber('SFDX_DNS_TIMEOUT', 3));
20
20
  // Retry frequency for DNS lookup polling defaults to 1 second and should be at least 1 second
21
21
  const DNS_RETRY_FREQ = Math.max(1, new kit_1.Env().getNumber('SFDX_DNS_RETRY_FREQUENCY', 1));
22
22
  /**
23
- * A class used to resolve MyDomains. After a ScratchOrg is created it's host name my not be propagated to the
23
+ * A class used to resolve MyDomains. After a ScratchOrg is created its host name my not be propagated to the
24
24
  * Salesforce DNS service. This service is not exclusive to Salesforce My Domain URL and could be used for any hostname.
25
25
  *
26
26
  * ```
@@ -45,13 +45,13 @@ class MyDomainResolver extends kit_1.AsyncOptionalCreatable {
45
45
  */
46
46
  constructor(options) {
47
47
  super(options);
48
- this.options = options || { url: MyDomainResolver.DEFAULT_DOMAIN };
48
+ this.options = options ?? { url: MyDomainResolver.DEFAULT_DOMAIN };
49
49
  }
50
50
  getTimeout() {
51
- return this.options.timeout || kit_1.Duration.seconds(DNS_TIMEOUT);
51
+ return this.options.timeout ?? kit_1.Duration.seconds(DNS_TIMEOUT);
52
52
  }
53
53
  getFrequency() {
54
- return this.options.frequency || kit_1.Duration.seconds(DNS_RETRY_FREQ);
54
+ return this.options.frequency ?? kit_1.Duration.seconds(DNS_RETRY_FREQ);
55
55
  }
56
56
  /**
57
57
  * Method that performs the dns lookup of the host. If the lookup fails the internal polling client will try again
@@ -69,17 +69,17 @@ class MyDomainResolver extends kit_1.AsyncOptionalCreatable {
69
69
  const self = this;
70
70
  const pollingOptions = {
71
71
  async poll() {
72
- const host = self.options.url.host;
72
+ const { host } = self.options.url;
73
73
  let dnsResult;
74
74
  try {
75
75
  self.logger.debug(`Attempting to resolve url: ${host}`);
76
- if (sfdc_1.sfdc.isLocalUrl(host)) {
76
+ if (new sfdcUrl_1.SfdcUrl(self.options.url).isLocalUrl()) {
77
77
  return {
78
78
  completed: true,
79
79
  payload: '127.0.0.1',
80
80
  };
81
81
  }
82
- dnsResult = await util_1.promisify(dns_1.lookup)(host);
82
+ dnsResult = await (0, util_1.promisify)(dns_1.lookup)(host);
83
83
  self.logger.debug(`Successfully resolved host: ${host} result: ${JSON.stringify(dnsResult)}`);
84
84
  return {
85
85
  completed: true,
@@ -100,12 +100,12 @@ class MyDomainResolver extends kit_1.AsyncOptionalCreatable {
100
100
  timeoutErrorName: 'MyDomainResolverTimeoutError',
101
101
  };
102
102
  const client = await pollingClient_1.PollingClient.create(pollingOptions);
103
- return ts_types_1.ensureString(await client.subscribe());
103
+ return (0, ts_types_1.ensureString)(await client.subscribe());
104
104
  }
105
105
  async getCnames() {
106
106
  try {
107
107
  await this.resolve();
108
- return await util_1.promisify(dns_1.resolveCname)(this.options.url.host);
108
+ return await (0, util_1.promisify)(dns_1.resolveCname)(this.options.url.host);
109
109
  }
110
110
  catch (e) {
111
111
  this.logger.debug(`An error occurred trying to resolve: ${this.options.url.host}`);
@@ -1,7 +1,7 @@
1
1
  import { AsyncOptionalCreatable, Duration } from '@salesforce/kit';
2
2
  import { AnyJson } from '@salesforce/ts-types';
3
3
  import { Logger } from '../logger';
4
- import { StatusResult } from './client';
4
+ import { StatusResult } from './types';
5
5
  /**
6
6
  * This is a polling client that can be used to poll the status of long running tasks. It can be used as a replacement
7
7
  * for Streaming when streaming topics are not available or when streaming handshakes are failing. Why wouldn't you
@@ -23,8 +23,6 @@ import { StatusResult } from './client';
23
23
  export declare class PollingClient extends AsyncOptionalCreatable<PollingClient.Options> {
24
24
  protected logger: Logger;
25
25
  private options;
26
- private timeout?;
27
- private interval?;
28
26
  /**
29
27
  * Constructor
30
28
  *
@@ -40,9 +38,7 @@ export declare class PollingClient extends AsyncOptionalCreatable<PollingClient.
40
38
  * Returns a promise to call the specified polling function using the interval and timeout specified
41
39
  * in the polling options.
42
40
  */
43
- subscribe(): Promise<AnyJson>;
44
- private doPoll;
45
- private clearAll;
41
+ subscribe<T = AnyJson>(): Promise<T>;
46
42
  }
47
43
  export declare namespace PollingClient {
48
44
  /**
@@ -1,17 +1,18 @@
1
1
  "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PollingClient = void 0;
2
4
  /*
3
5
  * Copyright (c) 2020, salesforce.com, inc.
4
6
  * All rights reserved.
5
7
  * Licensed under the BSD 3-Clause license.
6
8
  * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
7
9
  */
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.PollingClient = void 0;
10
- const timers_1 = require("timers");
11
10
  const kit_1 = require("@salesforce/kit");
12
11
  const ts_types_1 = require("@salesforce/ts-types");
12
+ const ts_retry_promise_1 = require("ts-retry-promise");
13
13
  const logger_1 = require("../logger");
14
- const sfdxError_1 = require("../sfdxError");
14
+ const sfError_1 = require("../sfError");
15
+ const lifecycleEvents_1 = require("../lifecycleEvents");
15
16
  /**
16
17
  * This is a polling client that can be used to poll the status of long running tasks. It can be used as a replacement
17
18
  * for Streaming when streaming topics are not available or when streaming handshakes are failing. Why wouldn't you
@@ -39,7 +40,7 @@ class PollingClient extends kit_1.AsyncOptionalCreatable {
39
40
  */
40
41
  constructor(options) {
41
42
  super(options);
42
- this.options = ts_types_1.ensure(options);
43
+ this.options = (0, ts_types_1.ensure)(options);
43
44
  }
44
45
  /**
45
46
  * Asynchronous initializer.
@@ -51,70 +52,43 @@ class PollingClient extends kit_1.AsyncOptionalCreatable {
51
52
  * Returns a promise to call the specified polling function using the interval and timeout specified
52
53
  * in the polling options.
53
54
  */
54
- subscribe() {
55
- // This promise is held open while setInterval tries to resolve or reject.
56
- // If set interval can't do it then the timeout will reject.
57
- return new Promise((resolve, reject) => {
58
- // Use set interval to periodically call the polling function
59
- // This try catch enables support for time{0} since setInterval only supports
60
- // time {1}. In other words, we should call first then wait for the first interval.
61
- this.doPoll()
62
- .then((result) => {
63
- if (result && result.completed) {
64
- resolve(result.payload);
65
- }
66
- else {
67
- this.interval = timers_1.setInterval(
68
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
69
- PollingClient.prototype.doPoll.bind(this, resolve, reject), this.options.frequency.milliseconds);
55
+ async subscribe() {
56
+ let errorInPollingFunction; // keep this around for returning in the catch block
57
+ const doPoll = async () => {
58
+ let result;
59
+ try {
60
+ result = await this.options.poll();
61
+ }
62
+ catch (error) {
63
+ const err = (errorInPollingFunction = error);
64
+ if (['ETIMEDOUT', 'ENOTFOUND', 'ECONNRESET', 'socket hang up'].some((retryableNetworkError) => err.message.includes(retryableNetworkError))) {
65
+ this.logger.debug('Network error on the request', err);
66
+ await lifecycleEvents_1.Lifecycle.getInstance().emitWarning('Network error occurred. Continuing to poll.');
67
+ throw sfError_1.SfError.wrap(err);
70
68
  }
71
- })
72
- .catch(() => {
73
- this.interval = timers_1.setInterval(
74
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
75
- PollingClient.prototype.doPoll.bind(this, resolve, reject), this.options.frequency.milliseconds);
76
- });
77
- // hard polling timeout.
78
- this.timeout = setTimeout(() => {
79
- this.logger.debug('Polling timed out');
80
- this.clearAll();
81
- // @todo should go in messages.
82
- reject(new sfdxError_1.SfdxError('The client has timed out.', this.options.timeoutErrorName || 'PollingClientTimeout'));
83
- }, this.options.timeout.milliseconds);
69
+ // there was an actual error thrown, so we don't want to keep retrying
70
+ throw new ts_retry_promise_1.NotRetryableError(err.name);
71
+ }
72
+ if (result.completed) {
73
+ return result.payload;
74
+ }
75
+ throw new Error('Operation did not complete. Retrying...'); // triggers a retry
76
+ };
77
+ const finalResult = (0, ts_retry_promise_1.retryDecorator)(doPoll, {
78
+ timeout: this.options.timeout.milliseconds,
79
+ delay: this.options.frequency.milliseconds,
80
+ retries: 'INFINITELY',
84
81
  });
85
- }
86
- async doPoll(resolve, reject) {
87
82
  try {
88
- // Poll can be an async function.
89
- const sample = await this.options.poll();
90
- if (sample.completed) {
91
- this.clearAll();
92
- if (resolve) {
93
- resolve(sample.payload);
94
- }
95
- else {
96
- return sample;
97
- }
98
- }
83
+ return await finalResult();
99
84
  }
100
- catch (e) {
101
- this.clearAll();
102
- if (reject) {
103
- reject(e);
85
+ catch (error) {
86
+ if (errorInPollingFunction) {
87
+ throw errorInPollingFunction;
104
88
  }
105
- else {
106
- throw e;
107
- }
108
- }
109
- }
110
- clearAll() {
111
- if (this.interval) {
112
- this.logger.debug('Clearing the polling interval');
113
- clearInterval(this.interval);
114
- }
115
- if (this.timeout) {
116
- this.logger.debug('Clearing the timeout interval');
117
- clearTimeout(this.timeout);
89
+ await lifecycleEvents_1.Lifecycle.getInstance().emit('POLLING_TIME_OUT', error);
90
+ this.logger.debug('Polling timed out');
91
+ throw new sfError_1.SfError('The client has timed out.', this.options.timeoutErrorName ?? 'PollingClientTimeout');
118
92
  }
119
93
  }
120
94
  }
@@ -1,75 +1,8 @@
1
- /// <reference types="node" />
2
- import { EventEmitter } from 'events';
3
1
  import { AsyncOptionalCreatable, Duration, Env } from '@salesforce/kit/lib';
4
- import { AnyFunction, AnyJson, JsonMap } from '@salesforce/ts-types/lib';
2
+ import { AnyJson } from '@salesforce/ts-types/lib';
5
3
  import { Org } from '../org/org';
6
- import { StatusResult } from './client';
7
- /**
8
- * Types for defining extensions.
9
- */
10
- export interface StreamingExtension {
11
- /**
12
- * Extension for outgoing message.
13
- *
14
- * @param message The message.
15
- * @param callback The callback to invoke after the message is processed.
16
- */
17
- outgoing?: (message: JsonMap, callback: AnyFunction) => void;
18
- /**
19
- * Extension for the incoming message.
20
- *
21
- * @param message The message.
22
- * @param callback The callback to invoke after the message is processed.
23
- */
24
- incoming?: (message: JsonMap, callback: AnyFunction) => void;
25
- }
26
- /**
27
- * Function type for processing messages
28
- */
29
- export declare type StreamProcessor = (message: JsonMap) => StatusResult;
30
- /**
31
- * Comet client interface. The is to allow for mocking the inner streaming Cometd implementation.
32
- * The Faye implementation is used by default but it could be used to adapt another Cometd impl.
33
- */
34
- export declare abstract class CometClient extends EventEmitter {
35
- /**
36
- * Disable polling features.
37
- *
38
- * @param label Polling feature label.
39
- */
40
- abstract disable(label: string): void;
41
- /**
42
- * Add a custom extension to the underlying client.
43
- *
44
- * @param extension The json function for the extension.
45
- */
46
- abstract addExtension(extension: StreamingExtension): void;
47
- /**
48
- * Sets an http header name/value.
49
- *
50
- * @param name The header name.
51
- * @param value The header value.
52
- */
53
- abstract setHeader(name: string, value: string): void;
54
- /**
55
- * handshake with the streaming channel
56
- *
57
- * @param callback Callback for the handshake when it successfully completes. The handshake should throw
58
- * errors when errors are encountered.
59
- */
60
- abstract handshake(callback: () => void): void;
61
- /**
62
- * Subscribes to Comet topics. Subscribe should perform a handshake if one hasn't been performed yet.
63
- *
64
- * @param channel The topic to subscribe to.
65
- * @param callback The callback to execute once a message has been received.
66
- */
67
- abstract subscribe(channel: string, callback: (message: JsonMap) => void): CometSubscription;
68
- /**
69
- * Method to call to disconnect the client from the server.
70
- */
71
- abstract disconnect(): void;
72
- }
4
+ import { CometClient, CometSubscription, Message, StatusResult, StreamingExtension, StreamProcessor } from './types';
5
+ export { CometClient, CometSubscription, Message, StatusResult, StreamingExtension, StreamProcessor };
73
6
  /**
74
7
  * Inner streaming client interface. This implements the Cometd behavior.
75
8
  * Also allows for mocking the functional behavior.
@@ -88,13 +21,6 @@ export interface StreamingClientIfc {
88
21
  */
89
22
  setLogger: (logLine: (message: string) => void) => void;
90
23
  }
91
- /**
92
- * The subscription object returned from the cometd subscribe object.
93
- */
94
- export interface CometSubscription {
95
- callback(callback: () => void): void;
96
- errback(callback: (error: Error) => void): void;
97
- }
98
24
  /**
99
25
  * Api wrapper to support Salesforce streaming. The client contains an internal implementation of a cometd specification.
100
26
  *
@@ -187,12 +113,12 @@ export declare class StreamingClient extends AsyncOptionalCreatable<StreamingCli
187
113
  * Subscribe to streaming events. When the streaming processor that's set in the options completes execution it
188
114
  * returns a payload in the StatusResult object. The payload is just echoed here for convenience.
189
115
  *
190
- * **Throws** *{@link SfdxError}{ name: '{@link StreamingClient.TimeoutErrorType.SUBSCRIBE}'}* When the subscribe timeout occurs.
116
+ * **Throws** *{@link SfError}{ name: '{@link StreamingClient.TimeoutErrorType.SUBSCRIBE}'}* When the subscribe timeout occurs.
191
117
  *
192
118
  * @param streamInit This function should call the platform apis that result in streaming updates on push topics.
193
119
  * {@link StatusResult}
194
120
  */
195
- subscribe(streamInit?: () => Promise<void>): Promise<AnyJson>;
121
+ subscribe(streamInit?: () => Promise<void>): Promise<AnyJson | void>;
196
122
  /**
197
123
  * Handler for incoming streaming messages.
198
124
  *
@@ -261,7 +187,6 @@ export declare namespace StreamingClient {
261
187
  handshakeTimeout: Duration;
262
188
  channel: string;
263
189
  streamingImpl: StreamingClientIfc;
264
- private envDep;
265
190
  /**
266
191
  * Constructor for DefaultStreamingOptions
267
192
  *