jsforce2 1.11.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 (80) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +74 -0
  3. package/bin/jsforce +3 -0
  4. package/bower.json +30 -0
  5. package/build/jsforce-api-analytics.js +393 -0
  6. package/build/jsforce-api-analytics.min.js +2 -0
  7. package/build/jsforce-api-analytics.min.js.map +1 -0
  8. package/build/jsforce-api-apex.js +183 -0
  9. package/build/jsforce-api-apex.min.js +2 -0
  10. package/build/jsforce-api-apex.min.js.map +1 -0
  11. package/build/jsforce-api-bulk.js +1054 -0
  12. package/build/jsforce-api-bulk.min.js +2 -0
  13. package/build/jsforce-api-bulk.min.js.map +1 -0
  14. package/build/jsforce-api-chatter.js +320 -0
  15. package/build/jsforce-api-chatter.min.js +2 -0
  16. package/build/jsforce-api-chatter.min.js.map +1 -0
  17. package/build/jsforce-api-metadata.js +3020 -0
  18. package/build/jsforce-api-metadata.min.js +2 -0
  19. package/build/jsforce-api-metadata.min.js.map +1 -0
  20. package/build/jsforce-api-soap.js +403 -0
  21. package/build/jsforce-api-soap.min.js +2 -0
  22. package/build/jsforce-api-soap.min.js.map +1 -0
  23. package/build/jsforce-api-streaming.js +3479 -0
  24. package/build/jsforce-api-streaming.min.js +2 -0
  25. package/build/jsforce-api-streaming.min.js.map +1 -0
  26. package/build/jsforce-api-tooling.js +319 -0
  27. package/build/jsforce-api-tooling.min.js +2 -0
  28. package/build/jsforce-api-tooling.min.js.map +1 -0
  29. package/build/jsforce-core.js +25250 -0
  30. package/build/jsforce-core.min.js +2 -0
  31. package/build/jsforce-core.min.js.map +1 -0
  32. package/build/jsforce.js +31637 -0
  33. package/build/jsforce.min.js +2 -0
  34. package/build/jsforce.min.js.map +1 -0
  35. package/core.js +1 -0
  36. package/index.js +1 -0
  37. package/lib/VERSION.js +2 -0
  38. package/lib/_required.js +29 -0
  39. package/lib/api/analytics.js +387 -0
  40. package/lib/api/apex.js +177 -0
  41. package/lib/api/bulk.js +862 -0
  42. package/lib/api/chatter.js +314 -0
  43. package/lib/api/index.js +8 -0
  44. package/lib/api/metadata.js +848 -0
  45. package/lib/api/soap.js +397 -0
  46. package/lib/api/streaming-extension.js +136 -0
  47. package/lib/api/streaming.js +270 -0
  48. package/lib/api/tooling.js +313 -0
  49. package/lib/browser/canvas.js +90 -0
  50. package/lib/browser/client.js +241 -0
  51. package/lib/browser/core.js +5 -0
  52. package/lib/browser/jsforce.js +6 -0
  53. package/lib/browser/jsonp.js +52 -0
  54. package/lib/browser/request.js +70 -0
  55. package/lib/cache.js +252 -0
  56. package/lib/cli/cli.js +431 -0
  57. package/lib/cli/repl.js +337 -0
  58. package/lib/connection.js +1881 -0
  59. package/lib/core.js +16 -0
  60. package/lib/csv.js +50 -0
  61. package/lib/date.js +163 -0
  62. package/lib/http-api.js +300 -0
  63. package/lib/jsforce.js +10 -0
  64. package/lib/logger.js +52 -0
  65. package/lib/oauth2.js +206 -0
  66. package/lib/process.js +275 -0
  67. package/lib/promise.js +164 -0
  68. package/lib/query.js +881 -0
  69. package/lib/quick-action.js +90 -0
  70. package/lib/record-stream.js +305 -0
  71. package/lib/record.js +107 -0
  72. package/lib/registry/file-registry.js +48 -0
  73. package/lib/registry/index.js +3 -0
  74. package/lib/registry/registry.js +111 -0
  75. package/lib/require.js +14 -0
  76. package/lib/soap.js +207 -0
  77. package/lib/sobject.js +558 -0
  78. package/lib/soql-builder.js +236 -0
  79. package/lib/transport.js +233 -0
  80. package/package.json +110 -0
package/lib/oauth2.js ADDED
@@ -0,0 +1,206 @@
1
+ /**
2
+ * @file Manages Salesforce OAuth2 operations
3
+ * @author Shinichi Tomita <shinichi.tomita@gmail.com>
4
+ */
5
+
6
+ 'use strict';
7
+
8
+ var querystring = require('querystring'),
9
+ _ = require('lodash/core'),
10
+ Transport = require('./transport');
11
+
12
+ var defaults = {
13
+ loginUrl : "https://login.salesforce.com"
14
+ };
15
+
16
+ /**
17
+ * OAuth2 class
18
+ *
19
+ * @class
20
+ * @constructor
21
+ * @param {Object} options - OAuth2 config options
22
+ * @param {String} [options.loginUrl] - Salesforce login server URL
23
+ * @param {String} [options.authzServiceUrl] - OAuth2 authorization service URL. If not specified, it generates from default by adding to login server URL.
24
+ * @param {String} [options.tokenServiceUrl] - OAuth2 token service URL. If not specified it generates from default by adding to login server URL.
25
+ * @param {String} options.clientId - OAuth2 client ID.
26
+ * @param {String} [options.clientSecret] - OAuth2 client secret (This is optional for public client).
27
+ * @param {String} options.redirectUri - URI to be callbacked from Salesforce OAuth2 authorization service.
28
+ */
29
+ var OAuth2 = module.exports = function(options) {
30
+ if (options.authzServiceUrl && options.tokenServiceUrl) {
31
+ this.loginUrl = options.authzServiceUrl.split('/').slice(0, 3).join('/');
32
+ this.authzServiceUrl = options.authzServiceUrl;
33
+ this.tokenServiceUrl = options.tokenServiceUrl;
34
+ this.revokeServiceUrl = options.revokeServiceUrl;
35
+ } else {
36
+ this.loginUrl = options.loginUrl || defaults.loginUrl;
37
+ this.authzServiceUrl = this.loginUrl + "/services/oauth2/authorize";
38
+ this.tokenServiceUrl = this.loginUrl + "/services/oauth2/token";
39
+ this.revokeServiceUrl = this.loginUrl + "/services/oauth2/revoke";
40
+ }
41
+ this.clientId = options.clientId;
42
+ this.clientSecret = options.clientSecret;
43
+ this.redirectUri = options.redirectUri;
44
+ if (options.proxyUrl) {
45
+ this._transport = new Transport.ProxyTransport(options.proxyUrl);
46
+ } else if (options.httpProxy) {
47
+ this._transport = new Transport.HttpProxyTransport(options.httpProxy);
48
+ } else {
49
+ this._transport = new Transport();
50
+ }
51
+ };
52
+
53
+
54
+
55
+ /**
56
+ *
57
+ */
58
+ _.extend(OAuth2.prototype, /** @lends OAuth2.prototype **/ {
59
+
60
+ /**
61
+ * Get Salesforce OAuth2 authorization page URL to redirect user agent.
62
+ *
63
+ * @param {Object} params - Parameters
64
+ * @param {String} [params.scope] - Scope values in space-separated string
65
+ * @param {String} [params.state] - State parameter
66
+ * @param {String} [params.code_challenge] - Code challenge value (RFC 7636 - Proof Key of Code Exchange)
67
+ * @returns {String} Authorization page URL
68
+ */
69
+ getAuthorizationUrl : function(params) {
70
+ params = _.extend({
71
+ response_type : "code",
72
+ client_id : this.clientId,
73
+ redirect_uri : this.redirectUri
74
+ }, params || {});
75
+ return this.authzServiceUrl +
76
+ (this.authzServiceUrl.indexOf('?') >= 0 ? "&" : "?") +
77
+ querystring.stringify(params);
78
+ },
79
+
80
+ /**
81
+ * @typedef TokenResponse
82
+ * @type {Object}
83
+ * @property {String} access_token
84
+ * @property {String} refresh_token
85
+ */
86
+
87
+ /**
88
+ * OAuth2 Refresh Token Flow
89
+ *
90
+ * @param {String} refreshToken - Refresh token
91
+ * @param {Callback.<TokenResponse>} [callback] - Callback function
92
+ * @returns {Promise.<TokenResponse>}
93
+ */
94
+ refreshToken : function(refreshToken, callback) {
95
+ var params = {
96
+ grant_type : "refresh_token",
97
+ refresh_token : refreshToken,
98
+ client_id : this.clientId
99
+ };
100
+ if (this.clientSecret) {
101
+ params.client_secret = this.clientSecret;
102
+ }
103
+ return this._postParams(params, callback);
104
+ },
105
+
106
+ /**
107
+ * OAuth2 Web Server Authentication Flow (Authorization Code)
108
+ * Access Token Request
109
+ *
110
+ * @param {String} code - Authorization code
111
+ * @param {Object} [params] - Optional parameters to send in token retrieval
112
+ * @param {String} [params.code_verifier] - Code verifier value (RFC 7636 - Proof Key of Code Exchange)
113
+ * @param {Callback.<TokenResponse>} [callback] - Callback function
114
+ * @returns {Promise.<TokenResponse>}
115
+ */
116
+ requestToken : function(code, params, callback) {
117
+ if (typeof params === 'function') {
118
+ callback = params;
119
+ params = {};
120
+ }
121
+ params = _.extend({
122
+ grant_type : "authorization_code",
123
+ code : code,
124
+ client_id : this.clientId,
125
+ redirect_uri : this.redirectUri
126
+ }, params || {});
127
+ if (this.clientSecret) {
128
+ params.client_secret = this.clientSecret;
129
+ }
130
+ return this._postParams(params, callback);
131
+ },
132
+
133
+ /**
134
+ * OAuth2 Username-Password Flow (Resource Owner Password Credentials)
135
+ *
136
+ * @param {String} username - Salesforce username
137
+ * @param {String} password - Salesforce password
138
+ * @param {Callback.<TokenResponse>} [callback] - Callback function
139
+ * @returns {Promise.<TokenResponse>}
140
+ */
141
+ authenticate : function(username, password, callback) {
142
+ return this._postParams({
143
+ grant_type : "password",
144
+ username : username,
145
+ password : password,
146
+ client_id : this.clientId,
147
+ client_secret : this.clientSecret,
148
+ redirect_uri : this.redirectUri
149
+ }, callback);
150
+ },
151
+
152
+ /**
153
+ * OAuth2 Revoke Session or API Token
154
+ *
155
+ * @param {String} token - Access or Refresh token to revoke. Passing in the Access token revokes the session. Passing in the Refresh token revokes API Access.
156
+ * @param {Callback.<undefined>} [callback] - Callback function
157
+ * @returns {Promise.<undefined>}
158
+ */
159
+ revokeToken : function(token, callback) {
160
+ return this._transport.httpRequest({
161
+ method : 'POST',
162
+ url : this.revokeServiceUrl,
163
+ body: querystring.stringify({ token: token }),
164
+ headers: {
165
+ "Content-Type": "application/x-www-form-urlencoded"
166
+ }
167
+ }).then(function(response) {
168
+ if (response.statusCode >= 400) {
169
+ var res = querystring.parse(response.body);
170
+ if (!res || !res.error) {
171
+ res = { error: "ERROR_HTTP_"+response.statusCode, error_description: response.body };
172
+ }
173
+ var err = new Error(res.error_description);
174
+ err.name = res.error;
175
+ throw err;
176
+ }
177
+ }).thenCall(callback);
178
+ },
179
+
180
+ /**
181
+ * @private
182
+ */
183
+ _postParams : function(params, callback) {
184
+ return this._transport.httpRequest({
185
+ method : 'POST',
186
+ url : this.tokenServiceUrl,
187
+ body : querystring.stringify(params),
188
+ headers : {
189
+ "content-type" : "application/x-www-form-urlencoded"
190
+ }
191
+ }).then(function(response) {
192
+ var res;
193
+ try {
194
+ res = JSON.parse(response.body);
195
+ } catch(e) {}
196
+ if (response.statusCode >= 400) {
197
+ res = res || { error: "ERROR_HTTP_"+response.statusCode, error_description: response.body };
198
+ var err = new Error(res.error_description);
199
+ err.name = res.error;
200
+ throw err;
201
+ }
202
+ return res;
203
+ }).thenCall(callback);
204
+ }
205
+
206
+ });
package/lib/process.js ADDED
@@ -0,0 +1,275 @@
1
+ /**
2
+ * @file Process class to manage/run workflow rule and approval process
3
+ * @author Shinichi Tomita <shinichi.tomita@gmail.com>
4
+ */
5
+
6
+ 'use strict';
7
+
8
+ var _ = require('lodash/core'),
9
+ Promise = require('./promise'),
10
+ Conneciton = require('./connection');
11
+
12
+ /**
13
+ * A class which manages process rules and approval processes
14
+ *
15
+ * @class
16
+ * @param {Connection} conn - Connection object
17
+ */
18
+ var Process = module.exports = function(conn) {
19
+ /**
20
+ * Object which mangages process rules
21
+ * @member {Process~ProcessRule} Process#rule
22
+ */
23
+ this.rule = new ProcessRule(conn);
24
+ /**
25
+ * Object which mangages approval process
26
+ * @member {Process~ApprovalProcess} Process#approval
27
+ */
28
+ this.approval = new ApprovalProcess(conn);
29
+ };
30
+
31
+ /**
32
+ * A class which manages process (workflow) rules
33
+ *
34
+ * @class Process~ProcessRule
35
+ * @param {Connection} conn - Connection object
36
+ */
37
+ var ProcessRule = function(conn) {
38
+ this._conn = conn;
39
+ };
40
+
41
+ /**
42
+ * @typedef {Object} Process~ProcessRuleDefinition
43
+ * @prop {String} id - Id of approval process definition
44
+ * @prop {String} name - Name of process rule definition
45
+ * @prop {String} object - SObject name which process rule is defined
46
+ */
47
+
48
+ /**
49
+ * Get all process rule definitions registered to sobjects
50
+ *
51
+ * @method Process~ProcessRule#list
52
+ * @param {Callback.<Map.<String, Array.<Process~ProcessRuleDefinition>>>} [callback] - Callback function
53
+ * @returns {Promise.<Map.<String, Array.<Process~ProcessRuleDefinition>>>}
54
+ */
55
+ ProcessRule.prototype.list = function(callback) {
56
+ return this._conn.request("/process/rules").then(function(res) {
57
+ return res.rules;
58
+ }).thenCall(callback);
59
+ };
60
+
61
+
62
+ /**
63
+ * @typedef {Object} Process~ProcessRuleTriggerResult
64
+ * @prop {Boolean} success - Is process rule trigger succeeded or not
65
+ * @prop {Array.<Object>} errors - Array of errors returned if the request failed
66
+ */
67
+
68
+ /**
69
+ * Trigger process rule for given entities
70
+ *
71
+ * @method Process~ProcessRule#trigger
72
+ * @param {String|Array.<String>} contextIds - Entity ID(s) to trigger workflow process
73
+ * @param {Callback.<Process~ProcessRuleTriggerResult>} [callback] - Callback function
74
+ * @returns {Promise.<Process~ProcessRuleTriggerResult>}
75
+ */
76
+ ProcessRule.prototype.trigger = function(contextIds, callback) {
77
+ contextIds = _.isArray(contextIds) ? contextIds : [ contextIds ];
78
+ return this._conn.request({
79
+ method: "POST",
80
+ url: "/process/rules/",
81
+ body: JSON.stringify({
82
+ contextIds: contextIds
83
+ }),
84
+ headers: {
85
+ "content-type": "application/json"
86
+ }
87
+ }).thenCall(callback);
88
+ };
89
+
90
+ /**
91
+ * A class which manages approval processes
92
+ *
93
+ * @class Process~ApprovalProcess
94
+ * @param {Connection} conn - Connection object
95
+ */
96
+ var ApprovalProcess = function(conn) {
97
+ this._conn = conn;
98
+ };
99
+
100
+ /**
101
+ * @typedef {Object} Process~ApprovalProcessDefinition
102
+ * @prop {String} id - Id of approval process definition
103
+ * @prop {String} name - Name of approval process definition
104
+ * @prop {String} object - SObject name which approval process is defined
105
+ * @prop {Number} sortOrder - Processing order of approval in SObject
106
+ */
107
+ /**
108
+ * Get all approval process definitions registered to sobjects
109
+ *
110
+ * @method Process~ApprovalProcess#list
111
+ * @param {Callback.<Map.<String, Array.<ApprovalProcessDefinition>>>} [callback] - Callback function
112
+ * @returns {Promise.<Map.<String, Array.<ApprovalProcessDefinition>>>}
113
+ */
114
+ ApprovalProcess.prototype.list = function(callback) {
115
+ return this._conn.request("/process/approvals").then(function(res) {
116
+ return res.approvals;
117
+ }).thenCall(callback);
118
+ };
119
+
120
+ /**
121
+ * @typedef {Object} Process~ApprovalProcessRequestResult
122
+ * @prop {Boolean} success - True if processing or approval completed successfully
123
+ * @prop {Array.<Object>} errors - The set of errors returned if the request failed
124
+ * @prop {Array.<String>} actorIds - IDs of the users who are currently assigned to this approval step
125
+ * @prop {String} entityId - Object being processed
126
+ * @prop {String} instanceId - ID of the ProcessInstance associated with the object submitted for processing
127
+ * @prop {String} instanceStatus - Status of the current process instance (not an individual object but the entire process instance)
128
+ * @prop {Array.<String>} newWorkItemIds - Case-insensitive IDs that point to ProcessInstanceWorkitem items (the set of pending approval requests)
129
+ */
130
+
131
+ /**
132
+ * Send bulk requests for approval process
133
+ *
134
+ * @method Process~ApprovalProcess#request
135
+ * @param {Array.<ApprovalProcessRequest>} requests - Array of approval process request to send
136
+ * @param {Callback.<Array.<ApprovalProcessRequestResult>>} - Callback function
137
+ * @param {Promise.<Array.<ApprovalProcessRequestResult>>}
138
+ */
139
+ ApprovalProcess.prototype.request = function(requests, callback) {
140
+ requests = requests.map(function(req) {
141
+ return req._request ? req._request : req;
142
+ });
143
+ return this._conn.request({
144
+ method: 'POST',
145
+ url: '/process/approvals',
146
+ headers: { "content-type": "application/json" },
147
+ body: JSON.stringify({ requests: requests })
148
+ }).thenCall(callback);
149
+ };
150
+
151
+ /**
152
+ * Create approval process request
153
+ *
154
+ * @private
155
+ */
156
+ ApprovalProcess.prototype._createRequest = function(actionType, contextId, comments, options, callback) {
157
+ if (typeof comments === "function") {
158
+ callback = comments;
159
+ options = null;
160
+ comments = null;
161
+ }
162
+ if (typeof options === "function") {
163
+ callback = options;
164
+ options = null;
165
+ }
166
+ options = options || {};
167
+ var request = {
168
+ actionType: actionType,
169
+ contextId: contextId,
170
+ comments: comments
171
+ };
172
+ _.extend(request, options);
173
+ return new ApprovalProcessRequest(this, request).thenCall(callback);
174
+ };
175
+
176
+ /**
177
+ * Submit approval request for an item
178
+ *
179
+ * @method Process~ApprovalProcess#submit
180
+ * @param {String} contextId - ID of the item that is being acted upon
181
+ * @param {String} [comments] - Comment to add to the history step associated with this request
182
+ * @param {Object} [options] - Request parameters
183
+ * @param {Array.<String>} [options.nextApproverIds] - If the process requires specification of the next approval, the ID of the user to be assigned the next request
184
+ * @param {String} [options.processDefinitionNameOrId] - Developer name or ID of the process definition
185
+ * @param {Boolean} [options.skipEntryCriteria] - Determines whether to evaluate the entry criteria for the process (true) or not (false) if the process definition name or ID isn’t null
186
+ * @param {Callback.<ApprovalProcessRequestResult>} [callback] - Callback function
187
+ * @returns {ApprovalProcessRequest}
188
+ */
189
+ ApprovalProcess.prototype.submit = function(contextId, comments, options, callback) {
190
+ return this._createRequest("Submit", contextId, comments, options, callback);
191
+ };
192
+
193
+ /**
194
+ * Approve approval request for an item
195
+ *
196
+ * @method Process~ApprovalProcess#approve
197
+ * @param {String} workitemId - ID of the item that is being acted upon
198
+ * @param {String} [comments] - Comment to add to the history step associated with this request
199
+ * @param {Object} [options] - Request parameters
200
+ * @param {Array.<String>} [options.nextApproverIds] - If the process requires specification of the next approval, the ID of the user to be assigned the next request
201
+ * @param {String} [options.processDefinitionNameOrId] - Developer name or ID of the process definition
202
+ * @param {Boolean} [options.skipEntryCriteria] - Determines whether to evaluate the entry criteria for the process (true) or not (false) if the process definition name or ID isn’t null
203
+ * @param {Callback.<ApprovalProcessRequestResult>} [callback] - Callback function
204
+ * @returns {ApprovalProcessRequest}
205
+ */
206
+ ApprovalProcess.prototype.approve = function(workitemId, comments, options, callback) {
207
+ return this._createRequest("Approve", workitemId, comments, options, callback);
208
+ };
209
+
210
+ /**
211
+ * Reject approval request for an item
212
+ *
213
+ * @method Process~ApprovalProcess#reject
214
+ * @param {String} workitemId - ID of the item that is being acted upon
215
+ * @param {String} [comments] - Comment to add to the history step associated with this request
216
+ * @param {Object} [options] - Request parameters
217
+ * @param {Array.<String>} [options.nextApproverIds] - If the process requires specification of the next approval, the ID of the user to be assigned the next request
218
+ * @param {String} [options.processDefinitionNameOrId] - Developer name or ID of the process definition
219
+ * @param {Boolean} [options.skipEntryCriteria] - Determines whether to evaluate the entry criteria for the process (true) or not (false) if the process definition name or ID isn’t null
220
+ * @param {Callback.<ApprovalProcessRequestResult>} [callback] - Callback function
221
+ * @returns {ApprovalProcessRequest}
222
+ */
223
+ ApprovalProcess.prototype.reject = function(workitemId, comments, options, callback) {
224
+ return this._createRequest("Reject", workitemId, comments, options, callback);
225
+ };
226
+
227
+ /**
228
+ * A class representing approval process request
229
+ *
230
+ * @protected
231
+ * @class Process~ApprovalProcessRequest
232
+ * @implements {Promise.<Process~ApprovalProcessRequestResult>}
233
+ * @param {Process~ApprovalProcess} process - ApprovalProcess
234
+ * @param {Object} request - Request parameters
235
+ * @param {String} request.actionType - Represents the kind of action to take: Submit, Approve, or Reject
236
+ * @param {String} request.contextId - ID of the item that is being acted upon
237
+ * @param {String} request.comments - Comment to add to the history step associated with this request
238
+ * @param {Array.<String>} [request.nextApproverIds] - If the process requires specification of the next approval, the ID of the user to be assigned the next request
239
+ * @param {String} [request.processDefinitionNameOrId] - Developer name or ID of the process definition
240
+ * @param {Boolean} [request.skipEntryCriteria] - Determines whether to evaluate the entry criteria for the process (true) or not (false) if the process definition name or ID isn’t null
241
+ */
242
+ var ApprovalProcessRequest = function(process, request) {
243
+ this._process = process;
244
+ this._request = request;
245
+ };
246
+
247
+ /**
248
+ * Promise/A+ interface
249
+ * http://promises-aplus.github.io/promises-spec/
250
+ *
251
+ * @method Process~ApprovalProcessRequest#then
252
+ */
253
+ ApprovalProcessRequest.prototype.then = function(onResolve, onReject) {
254
+ if (!this._promise) {
255
+ this._promise = this._process.request([ this ]).then(function(rets) {
256
+ return rets[0];
257
+ });
258
+ }
259
+ this._promise.then(onResolve, onReject);
260
+ };
261
+
262
+ /**
263
+ * Promise/A+ extension
264
+ * Call "then" using given node-style callback function
265
+ *
266
+ * @method Process~ApprovalProcessRequest#thenCall
267
+ */
268
+ ApprovalProcessRequest.prototype.thenCall = function(callback) {
269
+ return callback ? this.then(function(res) {
270
+ callback(null, res);
271
+ }, function(err) {
272
+ callback(err);
273
+ }) :
274
+ this;
275
+ };
package/lib/promise.js ADDED
@@ -0,0 +1,164 @@
1
+ /*global process*/
2
+
3
+ 'use strict';
4
+
5
+ var _ = require('lodash/core');
6
+
7
+ /**
8
+ * @callback ResolvedCallback
9
+ * @param {T} result - Resolved value
10
+ * @returns {S}
11
+ * @template T,S
12
+ */
13
+
14
+ /**
15
+ * @callback RejectedCallback
16
+ * @param {Error} reason - Rejected reason
17
+ * @returns {S}
18
+ * @template S
19
+ */
20
+
21
+ /**
22
+ * @callback ResolveCallback
23
+ * @param {T} result
24
+ * @template T
25
+ */
26
+
27
+ /**
28
+ * @callback RejectedCallback
29
+ * @param {Error} reason - Rejected reason
30
+ * @returns {S}
31
+ * @template S
32
+ */
33
+
34
+ /**
35
+ * @callback PromiseCallback
36
+ * @param {ResolveCallback.<T>} resolve
37
+ * @param {RejectCallback} reject
38
+ * @template T
39
+ */
40
+
41
+ /**
42
+ * Promise class with a little extension
43
+ *
44
+ * @class Promise
45
+ * @constructor
46
+ * @param {PromiseCallback.<T>}
47
+ * @template T
48
+ */
49
+ var Promise = require('promise/lib/es6-extensions');
50
+
51
+ /**
52
+ * The "then" method from the Promises/A+ specification
53
+ *
54
+ * @method Promise#then
55
+ * @param {FulfilledCallback.<T, S1>} [onFulfilled]
56
+ * @param {RejectedCallback.<S2>} [onRejected]
57
+ * @returns {Promise.<S1|S2>}
58
+ */
59
+
60
+ /**
61
+ * Call "then" using given node-style callback function.
62
+ * This is basically same as "nodeify" except that it always return the original promise
63
+ *
64
+ * @method Promise#thenCall
65
+ * @param {Callback.<T>} [callback] - Callback function
66
+ * @returns {Promise}
67
+ */
68
+ Promise.prototype.thenCall = function(callback) {
69
+ if (_.isFunction(callback)) {
70
+ this.then(function(res) {
71
+ process.nextTick(function() {
72
+ callback(null, res);
73
+ });
74
+ }, function(err) {
75
+ process.nextTick(function() {
76
+ callback(err);
77
+ });
78
+ });
79
+ }
80
+ return this;
81
+ };
82
+
83
+ /**
84
+ * A sugar method, equivalent to promise.then(undefined, onRejected).
85
+ *
86
+ * @method Promise#catch
87
+ * @param {RejectedCallback.<S>} onRejected
88
+ * @returns {Promise.<S>}
89
+ */
90
+
91
+ /**
92
+ * Synonym of Promise#catch
93
+ *
94
+ * @method Promise#fail
95
+ * @param {RejectedCallback.<S>} onRejected
96
+ * @returns {Promise.<S>}
97
+ */
98
+ Promise.prototype.fail = Promise.prototype['catch'];
99
+
100
+ /**
101
+ * Returns resolving promise with given reason
102
+ *
103
+ * @method Promise.resolve
104
+ * @param {*} result - Resolved value
105
+ * @returns {Promise}
106
+ */
107
+
108
+ /**
109
+ * Returns rejecting promise with given reason
110
+ *
111
+ * @method Promise.reject
112
+ * @param {Error} reason - Rejecting reason
113
+ * @returns {Promise}
114
+ */
115
+
116
+ /**
117
+ * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise,
118
+ * or is rejected with the same rejection reason as the first promise to be rejected.
119
+ *
120
+ * @method Promise.all
121
+ * @param {Array.<Promise.<*>|*>} promises
122
+ * @returns {Promise.<Array.<*>>}
123
+ */
124
+
125
+ /**
126
+ * Returns a deferred object
127
+ *
128
+ * @method Promise.defer
129
+ * @returns {Deferred}
130
+ */
131
+ Promise.defer = function() {
132
+ return new Deferred();
133
+ };
134
+
135
+ /**
136
+ * Deferred object
137
+ *
138
+ * @protected
139
+ * @constructor
140
+ */
141
+ var Deferred = function() {
142
+ var self = this;
143
+ this.promise = new Promise(function(resolve, reject) {
144
+ self.resolve = resolve;
145
+ self.reject = reject;
146
+ });
147
+ };
148
+
149
+ /**
150
+ * Resolve promise
151
+ * @method Deferred#resolve
152
+ * @param {*} result - Resolving result
153
+ */
154
+
155
+ /**
156
+ * Reject promise
157
+ * @method Deferred#reject
158
+ * @param {Error} error - Rejecting reason
159
+ */
160
+
161
+ /**
162
+ *
163
+ */
164
+ module.exports = Promise;