{"version":3,"sources":["node_modules/browser-pack/_prelude.js","jsforce-api-bulk.min.js","lib/api/bulk.js","node_modules/process/browser.js"],"names":["f","exports","module","define","amd","g","window","global","self","this","jsforce","modules","api","Bulk","r","e","n","t","o","i","c","require","u","a","Error","code","p","call","length","1","process","inherits","stream","Duplex","events","_","joinStreams","RecordStream","Promise","HttpApi","Job","bulk","type","operation","options","jobId","_bulk","id","state","_batches","EventEmitter","prototype","info","callback","_jobInfo","check","thenCall","open","_logger","toLowerCase","body","extIdField","concurrencyMode","assignmentRuleId","join","_request","method","path","headers","Content-Type","responseType","then","res","emit","jobInfo","err","createBatch","batch","Batch","on","batchId","logger","_waitAssign","debug","object","resolve","list","batchInfoList","batchInfo","isArray","close","_changeState","abort","job","super_","objectMode","_deferred","defer","_setupDataStreams","Writable","converterOptions","nullValue","_uploadStream","Serializable","_uploadDataStream","_downloadStream","Parsable","_downloadDataStream","end","once","pipe","_createRequestStream","dataStream","_dataStream","_write","data","enc","cb","write","read","push","_read","size","chunk","record","clone","Id","attributes","run","exec","execute","input","_result","rdeferred","promise","reject","isObject","isFunction","forEach","Object","keys","key","String","isString","onResolved","onReject","onProgress","nextTick","poll","interval","timeout","startTime","Date","getTime","now","name","parseInt","numberRecordsProcessed","retrieve","stateMessage","setTimeout","results","_conn","result","map","ret","success","Success","errors","fail","resultId","resultStream","resultDataStream","BulkApi","apply","arguments","beforeSend","request","accessToken","isSessionExpired","response","statusCode","test","hasErrorInResponseBody","error","parseError","errorCode","exceptionCode","message","exceptionMessage","conn","pollInterval","pollTimeout","baseUrl","instanceUrl","version","url","load","constructor","createJob","cleanup","cleanupOnError","query","soql","m","replace","match","recordStream","streams","_process","2","defaultSetTimout","defaultClearTimeout","runTimeout","fun","cachedSetTimeout","runClearTimeout","marker","cachedClearTimeout","clearTimeout","cleanUpNextTick","draining","currentQueue","queue","concat","queueIndex","drainQueue","len","Item","array","noop","args","Array","title","browser","env","argv","versions","addListener","off","removeListener","removeAllListeners","prependListener","prependOnce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AmN,mBAAAX,EACAxM,EAAA2C,KAAA6J,EACAxM,EAAAoN,gBAAAZ,EACAxM,EAAAqN,oBAAAb,EAEAxM,EAAAsN,UAAA,SAAAzF,GAAA,UAEA7H,EAAAuN,QAAA,SAAA1F,GACA,KAAA,IAAAnI,OAAA,qCAGAM,EAAAwN,IAAA,WAAA,MAAA,KACAxN,EAAAyN,MAAA,SAAAC,GACA,KAAA,IAAAhO,OAAA,mCAEAM,EAAA2N,MAAA,WAAA,MAAA,cFm2BW,IAAI","file":"jsforce-api-bulk.min.js","sourcesContent":["(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c=\"function\"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error(\"Cannot find module '\"+i+\"'\");throw a.code=\"MODULE_NOT_FOUND\",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u=\"function\"==typeof require&&require,i=0;i\n */\n\n'use strict';\n\nvar inherits = window.jsforce.require('inherits'),\n stream = window.jsforce.require('readable-stream'),\n Duplex = stream.Duplex,\n events = window.jsforce.require('events'),\n _ = window.jsforce.require('lodash/core'),\n joinStreams = window.jsforce.require('multistream'),\n jsforce = window.jsforce.require('./core'),\n RecordStream = window.jsforce.require('./record-stream'),\n Promise = window.jsforce.require('./promise'),\n HttpApi = window.jsforce.require('./http-api');\n\n/*--------------------------------------------*/\n\n/**\n * Class for Bulk API Job\n *\n * @protected\n * @class Bulk~Job\n * @extends events.EventEmitter\n *\n * @param {Bulk} bulk - Bulk API object\n * @param {String} [type] - SObject type\n * @param {String} [operation] - Bulk load operation ('insert', 'update', 'upsert', 'delete', or 'hardDelete')\n * @param {Object} [options] - Options for bulk loading operation\n * @param {String} [options.extIdField] - External ID field name (used when upsert operation).\n * @param {String} [options.concurrencyMode] - 'Serial' or 'Parallel'. Defaults to Parallel.\n * @param {String} [jobId] - Job ID (if already available)\n */\nvar Job = function(bulk, type, operation, options, jobId) {\n this._bulk = bulk;\n this.type = type;\n this.operation = operation;\n this.options = options || {};\n this.id = jobId;\n this.state = this.id ? 'Open' : 'Unknown';\n this._batches = {};\n};\n\ninherits(Job, events.EventEmitter);\n\n/**\n * @typedef {Object} Bulk~JobInfo\n * @prop {String} id - Job ID\n * @prop {String} object - Object type name\n * @prop {String} operation - Operation type of the job\n * @prop {String} state - Job status\n */\n\n/**\n * Return latest jobInfo from cache\n *\n * @method Bulk~Job#info\n * @param {Callback.} [callback] - Callback function\n * @returns {Promise.}\n */\nJob.prototype.info = function(callback) {\n var self = this;\n // if cache is not available, check the latest\n if (!this._jobInfo) {\n this._jobInfo = this.check();\n }\n return this._jobInfo.thenCall(callback);\n};\n\n/**\n * Open new job and get jobinfo\n *\n * @method Bulk~Job#open\n * @param {Callback.} [callback] - Callback function\n * @returns {Promise.}\n */\nJob.prototype.open = function(callback) {\n var self = this;\n var bulk = this._bulk;\n var logger = bulk._logger;\n\n // if not requested opening job\n if (!this._jobInfo) {\n var operation = this.operation.toLowerCase();\n if (operation === 'harddelete') { operation = 'hardDelete'; }\n var body = [\n '',\n '',\n '' + operation + '',\n '' + this.type + '',\n (this.options.extIdField ?\n ''+this.options.extIdField+'' :\n ''),\n (this.options.concurrencyMode ?\n ''+this.options.concurrencyMode+'' :\n ''),\n (this.options.assignmentRuleId ?\n '' + this.options.assignmentRuleId + '' :\n ''),\n 'CSV',\n ''\n ].join('');\n\n this._jobInfo = bulk._request({\n method : 'POST',\n path : \"/job\",\n body : body,\n headers : {\n \"Content-Type\" : \"application/xml; charset=utf-8\"\n },\n responseType: \"application/xml\"\n }).then(function(res) {\n self.emit(\"open\", res.jobInfo);\n self.id = res.jobInfo.id;\n self.state = res.jobInfo.state;\n return res.jobInfo;\n }, function(err) {\n self.emit(\"error\", err);\n throw err;\n });\n }\n return this._jobInfo.thenCall(callback);\n};\n\n/**\n * Create a new batch instance in the job\n *\n * @method Bulk~Job#createBatch\n * @returns {Bulk~Batch}\n */\nJob.prototype.createBatch = function() {\n var batch = new Batch(this);\n var self = this;\n batch.on('queue', function() {\n self._batches[batch.id] = batch;\n });\n return batch;\n};\n\n/**\n * Get a batch instance specified by given batch ID\n *\n * @method Bulk~Job#batch\n * @param {String} batchId - Batch ID\n * @returns {Bulk~Batch}\n */\nJob.prototype.batch = function(batchId) {\n var batch = this._batches[batchId];\n if (!batch) {\n batch = new Batch(this, batchId);\n this._batches[batchId] = batch;\n }\n return batch;\n};\n\n/**\n * Check the latest job status from server\n *\n * @method Bulk~Job#check\n * @param {Callback.} [callback] - Callback function\n * @returns {Promise.}\n */\nJob.prototype.check = function(callback) {\n var self = this;\n var bulk = this._bulk;\n var logger = bulk._logger;\n\n this._jobInfo = this._waitAssign().then(function() {\n return bulk._request({\n method : 'GET',\n path : \"/job/\" + self.id,\n responseType: \"application/xml\"\n });\n }).then(function(res) {\n logger.debug(res.jobInfo);\n self.id = res.jobInfo.id;\n self.type = res.jobInfo.object;\n self.operation = res.jobInfo.operation;\n self.state = res.jobInfo.state;\n return res.jobInfo;\n });\n return this._jobInfo.thenCall(callback);\n};\n\n/**\n * Wait till the job is assigned to server\n *\n * @method Bulk~Job#info\n * @param {Callback.} [callback] - Callback function\n * @returns {Promise.}\n */\nJob.prototype._waitAssign = function(callback) {\n return (this.id ? Promise.resolve({ id: this.id }) : this.open()).thenCall(callback);\n};\n\n\n/**\n * List all registered batch info in job\n *\n * @method Bulk~Job#list\n * @param {Callback.>} [callback] - Callback function\n * @returns {Promise.>}\n */\nJob.prototype.list = function(callback) {\n var self = this;\n var bulk = this._bulk;\n var logger = bulk._logger;\n\n return this._waitAssign().then(function() {\n return bulk._request({\n method : 'GET',\n path : \"/job/\" + self.id + \"/batch\",\n responseType: \"application/xml\"\n });\n }).then(function(res) {\n logger.debug(res.batchInfoList.batchInfo);\n var batchInfoList = res.batchInfoList;\n batchInfoList = _.isArray(batchInfoList.batchInfo) ? batchInfoList.batchInfo : [ batchInfoList.batchInfo ];\n return batchInfoList;\n }).thenCall(callback);\n\n};\n\n/**\n * Close opened job\n *\n * @method Bulk~Job#close\n * @param {Callback.} [callback] - Callback function\n * @returns {Promise.}\n */\nJob.prototype.close = function() {\n var self = this;\n return this._changeState(\"Closed\").then(function(jobInfo) {\n self.id = null;\n self.emit(\"close\", jobInfo);\n return jobInfo;\n }, function(err) {\n self.emit(\"error\", err);\n throw err;\n });\n};\n\n/**\n * Set the status to abort\n *\n * @method Bulk~Job#abort\n * @param {Callback.} [callback] - Callback function\n * @returns {Promise.}\n */\nJob.prototype.abort = function() {\n var self = this;\n return this._changeState(\"Aborted\").then(function(jobInfo) {\n self.id = null;\n self.emit(\"abort\", jobInfo);\n return jobInfo;\n }, function(err) {\n self.emit(\"error\", err);\n throw err;\n });\n};\n\n/**\n * @private\n */\nJob.prototype._changeState = function(state, callback) {\n var self = this;\n var bulk = this._bulk;\n var logger = bulk._logger;\n\n this._jobInfo = this._waitAssign().then(function() {\n var body = [\n '',\n '',\n '' + state + '',\n ''\n ].join('');\n return bulk._request({\n method : 'POST',\n path : \"/job/\" + self.id,\n body : body,\n headers : {\n \"Content-Type\" : \"application/xml; charset=utf-8\"\n },\n responseType: \"application/xml\"\n });\n }).then(function(res) {\n logger.debug(res.jobInfo);\n self.state = res.jobInfo.state;\n return res.jobInfo;\n });\n return this._jobInfo.thenCall(callback);\n\n};\n\n\n/*--------------------------------------------*/\n\n/**\n * Batch (extends RecordStream)\n *\n * @protected\n * @class Bulk~Batch\n * @extends {stream.Writable}\n * @implements {Promise.>}\n * @param {Bulk~Job} job - Bulk job object\n * @param {String} [batchId] - Batch ID (if already available)\n */\nvar Batch = function(job, batchId) {\n Batch.super_.call(this, { objectMode: true });\n this.job = job;\n this.id = batchId;\n this._bulk = job._bulk;\n this._deferred = Promise.defer();\n this._setupDataStreams();\n};\n\ninherits(Batch, stream.Writable);\n\n\n/**\n * @private\n */\nBatch.prototype._setupDataStreams = function() {\n var batch = this;\n var converterOptions = { nullValue : '#N/A' };\n this._uploadStream = new RecordStream.Serializable();\n this._uploadDataStream = this._uploadStream.stream('csv', converterOptions);\n this._downloadStream = new RecordStream.Parsable();\n this._downloadDataStream = this._downloadStream.stream('csv', converterOptions);\n\n this.on('finish', function() {\n batch._uploadStream.end();\n });\n this._uploadDataStream.once('readable', function() {\n batch.job.open().then(function() {\n // pipe upload data to batch API request stream\n batch._uploadDataStream.pipe(batch._createRequestStream());\n });\n });\n\n // duplex data stream, opened access to API programmers by Batch#stream()\n var dataStream = this._dataStream = new Duplex();\n dataStream._write = function(data, enc, cb) {\n batch._uploadDataStream.write(data, enc, cb);\n };\n dataStream.on('finish', function() {\n batch._uploadDataStream.end();\n });\n\n this._downloadDataStream.on('readable', function() {\n dataStream.read(0);\n });\n this._downloadDataStream.on('end', function() {\n dataStream.push(null);\n });\n dataStream._read = function(size) {\n var chunk;\n while ((chunk = batch._downloadDataStream.read()) !== null) {\n dataStream.push(chunk);\n }\n };\n};\n\n/**\n * Connect batch API and create stream instance of request/response\n *\n * @private\n * @returns {stream.Duplex}\n */\nBatch.prototype._createRequestStream = function() {\n var batch = this;\n var bulk = batch._bulk;\n var logger = bulk._logger;\n\n return bulk._request({\n method : 'POST',\n path : \"/job/\" + batch.job.id + \"/batch\",\n headers: {\n \"Content-Type\": \"text/csv\"\n },\n responseType: \"application/xml\"\n }, function(err, res) {\n if (err) {\n batch.emit('error', err);\n } else {\n logger.debug(res.batchInfo);\n batch.id = res.batchInfo.id;\n batch.emit('queue', res.batchInfo);\n }\n }).stream();\n};\n\n/**\n * Implementation of Writable\n *\n * @override\n * @private\n */\nBatch.prototype._write = function(record, enc, cb) {\n record = _.clone(record);\n if (this.job.operation === \"insert\") {\n delete record.Id;\n } else if (this.job.operation === \"delete\") {\n record = { Id: record.Id };\n }\n delete record.type;\n delete record.attributes;\n this._uploadStream.write(record, enc, cb);\n};\n\n/**\n * Returns duplex stream which accepts CSV data input and batch result output\n *\n * @returns {stream.Duplex}\n */\nBatch.prototype.stream = function() {\n return this._dataStream;\n};\n\n/**\n * Execute batch operation\n *\n * @method Bulk~Batch#execute\n * @param {Array.|stream.Stream|String} [input] - Input source for batch operation. Accepts array of records, CSV string, and CSV data input stream in insert/update/upsert/delete/hardDelete operation, SOQL string in query operation.\n * @param {Callback.|Array.>} [callback] - Callback function\n * @returns {Bulk~Batch}\n */\nBatch.prototype.run =\nBatch.prototype.exec =\nBatch.prototype.execute = function(input, callback) {\n var self = this;\n\n if (typeof input === 'function') { // if input argument is omitted\n callback = input;\n input = null;\n }\n\n // if batch is already executed\n if (this._result) {\n throw new Error(\"Batch already executed.\");\n }\n\n var rdeferred = Promise.defer();\n this._result = rdeferred.promise;\n this._result.then(function(res) {\n self._deferred.resolve(res);\n }, function(err) {\n self._deferred.reject(err);\n });\n this.once('response', function(res) {\n rdeferred.resolve(res);\n });\n this.once('error', function(err) {\n rdeferred.reject(err);\n });\n\n if (_.isObject(input) && _.isFunction(input.pipe)) { // if input has stream.Readable interface\n input.pipe(this._dataStream);\n } else {\n var data;\n if (_.isArray(input)) {\n _.forEach(input, function(record) {\n Object.keys(record).forEach(function(key) {\n if (typeof record[key] === 'boolean') {\n record[key] = String(record[key])\n }\n })\n self.write(record);\n });\n self.end();\n } else if (_.isString(input)){\n data = input;\n this._dataStream.write(data, 'utf8');\n this._dataStream.end();\n }\n }\n\n // return Batch instance for chaining\n return this.thenCall(callback);\n};\n\n/**\n * Promise/A+ interface\n * http://promises-aplus.github.io/promises-spec/\n *\n * Delegate to deferred promise, return promise instance for batch result\n *\n * @method Bulk~Batch#then\n */\nBatch.prototype.then = function(onResolved, onReject, onProgress) {\n return this._deferred.promise.then(onResolved, onReject, onProgress);\n};\n\n/**\n * Promise/A+ extension\n * Call \"then\" using given node-style callback function\n *\n * @method Bulk~Batch#thenCall\n */\nBatch.prototype.thenCall = function(callback) {\n if (_.isFunction(callback)) {\n this.then(function(res) {\n process.nextTick(function() {\n callback(null, res);\n });\n }, function(err) {\n process.nextTick(function() {\n callback(err);\n });\n });\n }\n return this;\n};\n\n/**\n * @typedef {Object} Bulk~BatchInfo\n * @prop {String} id - Batch ID\n * @prop {String} jobId - Job ID\n * @prop {String} state - Batch state\n * @prop {String} stateMessage - Batch state message\n */\n\n/**\n * Check the latest batch status in server\n *\n * @method Bulk~Batch#check\n * @param {Callback.} [callback] - Callback function\n * @returns {Promise.}\n */\nBatch.prototype.check = function(callback) {\n var self = this;\n var bulk = this._bulk;\n var logger = bulk._logger;\n var jobId = this.job.id;\n var batchId = this.id;\n\n if (!jobId || !batchId) {\n throw new Error(\"Batch not started.\");\n }\n return bulk._request({\n method : 'GET',\n path : \"/job/\" + jobId + \"/batch/\" + batchId,\n responseType: \"application/xml\"\n }).then(function(res) {\n logger.debug(res.batchInfo);\n return res.batchInfo;\n }).thenCall(callback);\n};\n\n\n/**\n * Polling the batch result and retrieve\n *\n * @method Bulk~Batch#poll\n * @param {Number} interval - Polling interval in milliseconds\n * @param {Number} timeout - Polling timeout in milliseconds\n */\nBatch.prototype.poll = function(interval, timeout) {\n var self = this;\n var jobId = this.job.id;\n var batchId = this.id;\n\n if (!jobId || !batchId) {\n throw new Error(\"Batch not started.\");\n }\n var startTime = new Date().getTime();\n var poll = function() {\n var now = new Date().getTime();\n if (startTime + timeout < now) {\n var err = new Error(\"Polling time out. Job Id = \" + jobId + \" , batch Id = \" + batchId);\n err.name = 'PollingTimeout';\n err.jobId = jobId;\n err.batchId = batchId;\n self.emit('error', err);\n return;\n }\n self.check(function(err, res) {\n if (err) {\n self.emit('error', err);\n } else {\n if (res.state === \"Failed\") {\n if (parseInt(res.numberRecordsProcessed, 10) > 0) {\n self.retrieve();\n } else {\n self.emit('error', new Error(res.stateMessage));\n }\n } else if (res.state === \"Completed\") {\n self.retrieve();\n } else {\n self.emit('progress', res);\n setTimeout(poll, interval);\n }\n }\n });\n };\n setTimeout(poll, interval);\n};\n\n/**\n * @typedef {Object} Bulk~BatchResultInfo\n * @prop {String} id - Batch result ID\n * @prop {String} batchId - Batch ID which includes this batch result.\n * @prop {String} jobId - Job ID which includes this batch result.\n */\n\n/**\n * Retrieve batch result\n *\n * @method Bulk~Batch#retrieve\n * @param {Callback.|Array.>} [callback] - Callback function\n * @returns {Promise.|Array.>}\n */\nBatch.prototype.retrieve = function(callback) {\n var self = this;\n var bulk = this._bulk;\n var jobId = this.job.id;\n var job = this.job;\n var batchId = this.id;\n\n if (!jobId || !batchId) {\n throw new Error(\"Batch not started.\");\n }\n\n return job.info().then(function(jobInfo) {\n return bulk._request({\n method : 'GET',\n path : \"/job/\" + jobId + \"/batch/\" + batchId + \"/result\"\n });\n }).then(function(res) {\n var results;\n if (job.operation === 'query') {\n var conn = bulk._conn;\n var resultIds = res['result-list'].result;\n results = res['result-list'].result;\n results = _.map(_.isArray(results) ? results : [ results ], function(id) {\n return {\n id: id,\n batchId: batchId,\n jobId: jobId\n };\n });\n } else {\n results = _.map(res, function(ret) {\n return {\n id: ret.Id || null,\n success: ret.Success === \"true\",\n errors: ret.Error ? [ ret.Error ] : []\n };\n });\n }\n self.emit('response', results);\n return results;\n }).fail(function(err) {\n self.emit('error', err);\n throw err;\n }).thenCall(callback);\n};\n\n/**\n * Fetch query result as a record stream\n * @param {String} resultId - Result id\n * @returns {RecordStream} - Record stream, convertible to CSV data stream\n */\nBatch.prototype.result = function(resultId) {\n var jobId = this.job.id;\n var batchId = this.id;\n if (!jobId || !batchId) {\n throw new Error(\"Batch not started.\");\n }\n var resultStream = new RecordStream.Parsable();\n var resultDataStream = resultStream.stream('csv');\n var reqStream = this._bulk._request({\n method : 'GET',\n path : \"/job/\" + jobId + \"/batch/\" + batchId + \"/result/\" + resultId,\n responseType: \"application/octet-stream\"\n }).stream().pipe(resultDataStream);\n return resultStream;\n};\n\n/*--------------------------------------------*/\n/**\n * @private\n */\nvar BulkApi = function() {\n BulkApi.super_.apply(this, arguments);\n};\n\ninherits(BulkApi, HttpApi);\n\nBulkApi.prototype.beforeSend = function(request) {\n request.headers = request.headers || {};\n request.headers[\"X-SFDC-SESSION\"] = this._conn.accessToken;\n};\n\nBulkApi.prototype.isSessionExpired = function(response) {\n return response.statusCode === 400 &&\n /InvalidSessionId<\\/exceptionCode>/.test(response.body);\n};\n\nBulkApi.prototype.hasErrorInResponseBody = function(body) {\n return !!body.error;\n};\n\nBulkApi.prototype.parseError = function(body) {\n return {\n errorCode: body.error.exceptionCode,\n message: body.error.exceptionMessage\n };\n};\n\n/*--------------------------------------------*/\n\n/**\n * Class for Bulk API\n *\n * @class\n * @param {Connection} conn - Connection object\n */\nvar Bulk = function(conn) {\n this._conn = conn;\n this._logger = conn._logger;\n};\n\n/**\n * Polling interval in milliseconds\n * @type {Number}\n */\nBulk.prototype.pollInterval = 1000;\n\n/**\n * Polling timeout in milliseconds\n * @type {Number}\n */\nBulk.prototype.pollTimeout = 10000;\n\n/** @private **/\nBulk.prototype._request = function(request, callback) {\n var conn = this._conn;\n request = _.clone(request);\n var baseUrl = [ conn.instanceUrl, \"services/async\", conn.version ].join('/');\n request.url = baseUrl + request.path;\n var options = { responseType: request.responseType };\n delete request.path;\n delete request.responseType;\n return new BulkApi(this._conn, options).request(request).thenCall(callback);\n};\n\n/**\n * Create and start bulkload job and batch\n *\n * @param {String} type - SObject type\n * @param {String} operation - Bulk load operation ('insert', 'update', 'upsert', 'delete', or 'hardDelete')\n * @param {Object} [options] - Options for bulk loading operation\n * @param {String} [options.extIdField] - External ID field name (used when upsert operation).\n * @param {String} [options.concurrencyMode] - 'Serial' or 'Parallel'. Defaults to Parallel.\n * @param {Array.|stream.Stream|String} [input] - Input source for bulkload. Accepts array of records, CSV string, and CSV data input stream in insert/update/upsert/delete/hardDelete operation, SOQL string in query operation.\n * @param {Callback.|Array.>} [callback] - Callback function\n * @returns {Bulk~Batch}\n */\nBulk.prototype.load = function(type, operation, options, input, callback) {\n var self = this;\n if (!type || !operation) {\n throw new Error(\"Insufficient arguments. At least, 'type' and 'operation' are required.\");\n }\n if (!_.isObject(options) || options.constructor !== Object) { // when options is not plain hash object, it is omitted\n callback = input;\n input = options;\n options = null;\n }\n var job = this.createJob(type, operation, options);\n job.once('error', function (error) {\n if (batch) {\n batch.emit('error', error); // pass job error to batch\n }\n });\n var batch = job.createBatch();\n var cleanup = function() {\n batch = null;\n job.close();\n };\n var cleanupOnError = function(err) {\n if (err.name !== 'PollingTimeout') {\n cleanup();\n }\n };\n batch.on('response', cleanup);\n batch.on('error', cleanupOnError);\n batch.on('queue', function() { batch.poll(self.pollInterval, self.pollTimeout); });\n return batch.execute(input, callback);\n};\n\n/**\n * Execute bulk query and get record stream\n *\n * @param {String} soql - SOQL to execute in bulk job\n * @returns {RecordStream.Parsable} - Record stream, convertible to CSV data stream\n */\nBulk.prototype.query = function(soql) {\n var m = soql.replace(/\\([\\s\\S]+\\)/g, '').match(/FROM\\s+(\\w+)/i);\n if (!m) {\n throw new Error(\"No sobject type found in query, maybe caused by invalid SOQL.\");\n }\n var type = m[1];\n var self = this;\n var recordStream = new RecordStream.Parsable();\n var dataStream = recordStream.stream('csv');\n this.load(type, \"query\", soql).then(function(results) {\n var streams = results.map(function(result) {\n return self\n .job(result.jobId)\n .batch(result.batchId)\n .result(result.id)\n .stream();\n });\n\n joinStreams(streams).pipe(dataStream);\n }).fail(function(err) {\n recordStream.emit('error', err);\n });\n return recordStream;\n};\n\n\n/**\n * Create a new job instance\n *\n * @param {String} type - SObject type\n * @param {String} operation - Bulk load operation ('insert', 'update', 'upsert', 'delete', 'hardDelete', or 'query')\n * @param {Object} [options] - Options for bulk loading operation\n * @returns {Bulk~Job}\n */\nBulk.prototype.createJob = function(type, operation, options) {\n return new Job(this, type, operation, options);\n};\n\n/**\n * Get a job instance specified by given job ID\n *\n * @param {String} jobId - Job ID\n * @returns {Bulk~Job}\n */\nBulk.prototype.job = function(jobId) {\n return new Job(this, null, null, null, jobId);\n};\n\n\n/*--------------------------------------------*/\n/*\n * Register hook in connection instantiation for dynamically adding this API module features\n */\njsforce.on('connection:new', function(conn) {\n conn.bulk = new Bulk(conn);\n});\n\n\nmodule.exports = Bulk;\n\n}).call(this,require('_process'))\n\n},{\"_process\":2}],2:[function(require,module,exports){\n// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n\n},{}]},{},[1])(1)\n});\n\n","/*global process*/\n/**\n * @file Manages Salesforce Bulk API related operations\n * @author Shinichi Tomita \n */\n\n'use strict';\n\nvar inherits = window.jsforce.require('inherits'),\n stream = window.jsforce.require('readable-stream'),\n Duplex = stream.Duplex,\n events = window.jsforce.require('events'),\n _ = window.jsforce.require('lodash/core'),\n joinStreams = window.jsforce.require('multistream'),\n jsforce = window.jsforce.require('./core'),\n RecordStream = window.jsforce.require('./record-stream'),\n Promise = window.jsforce.require('./promise'),\n HttpApi = window.jsforce.require('./http-api');\n\n/*--------------------------------------------*/\n\n/**\n * Class for Bulk API Job\n *\n * @protected\n * @class Bulk~Job\n * @extends events.EventEmitter\n *\n * @param {Bulk} bulk - Bulk API object\n * @param {String} [type] - SObject type\n * @param {String} [operation] - Bulk load operation ('insert', 'update', 'upsert', 'delete', or 'hardDelete')\n * @param {Object} [options] - Options for bulk loading operation\n * @param {String} [options.extIdField] - External ID field name (used when upsert operation).\n * @param {String} [options.concurrencyMode] - 'Serial' or 'Parallel'. Defaults to Parallel.\n * @param {String} [jobId] - Job ID (if already available)\n */\nvar Job = function(bulk, type, operation, options, jobId) {\n this._bulk = bulk;\n this.type = type;\n this.operation = operation;\n this.options = options || {};\n this.id = jobId;\n this.state = this.id ? 'Open' : 'Unknown';\n this._batches = {};\n};\n\ninherits(Job, events.EventEmitter);\n\n/**\n * @typedef {Object} Bulk~JobInfo\n * @prop {String} id - Job ID\n * @prop {String} object - Object type name\n * @prop {String} operation - Operation type of the job\n * @prop {String} state - Job status\n */\n\n/**\n * Return latest jobInfo from cache\n *\n * @method Bulk~Job#info\n * @param {Callback.} [callback] - Callback function\n * @returns {Promise.}\n */\nJob.prototype.info = function(callback) {\n var self = this;\n // if cache is not available, check the latest\n if (!this._jobInfo) {\n this._jobInfo = this.check();\n }\n return this._jobInfo.thenCall(callback);\n};\n\n/**\n * Open new job and get jobinfo\n *\n * @method Bulk~Job#open\n * @param {Callback.} [callback] - Callback function\n * @returns {Promise.}\n */\nJob.prototype.open = function(callback) {\n var self = this;\n var bulk = this._bulk;\n var logger = bulk._logger;\n\n // if not requested opening job\n if (!this._jobInfo) {\n var operation = this.operation.toLowerCase();\n if (operation === 'harddelete') { operation = 'hardDelete'; }\n var body = [\n '',\n '',\n '' + operation + '',\n '' + this.type + '',\n (this.options.extIdField ?\n ''+this.options.extIdField+'' :\n ''),\n (this.options.concurrencyMode ?\n ''+this.options.concurrencyMode+'' :\n ''),\n (this.options.assignmentRuleId ?\n '' + this.options.assignmentRuleId + '' :\n ''),\n 'CSV',\n ''\n ].join('');\n\n this._jobInfo = bulk._request({\n method : 'POST',\n path : \"/job\",\n body : body,\n headers : {\n \"Content-Type\" : \"application/xml; charset=utf-8\"\n },\n responseType: \"application/xml\"\n }).then(function(res) {\n self.emit(\"open\", res.jobInfo);\n self.id = res.jobInfo.id;\n self.state = res.jobInfo.state;\n return res.jobInfo;\n }, function(err) {\n self.emit(\"error\", err);\n throw err;\n });\n }\n return this._jobInfo.thenCall(callback);\n};\n\n/**\n * Create a new batch instance in the job\n *\n * @method Bulk~Job#createBatch\n * @returns {Bulk~Batch}\n */\nJob.prototype.createBatch = function() {\n var batch = new Batch(this);\n var self = this;\n batch.on('queue', function() {\n self._batches[batch.id] = batch;\n });\n return batch;\n};\n\n/**\n * Get a batch instance specified by given batch ID\n *\n * @method Bulk~Job#batch\n * @param {String} batchId - Batch ID\n * @returns {Bulk~Batch}\n */\nJob.prototype.batch = function(batchId) {\n var batch = this._batches[batchId];\n if (!batch) {\n batch = new Batch(this, batchId);\n this._batches[batchId] = batch;\n }\n return batch;\n};\n\n/**\n * Check the latest job status from server\n *\n * @method Bulk~Job#check\n * @param {Callback.} [callback] - Callback function\n * @returns {Promise.}\n */\nJob.prototype.check = function(callback) {\n var self = this;\n var bulk = this._bulk;\n var logger = bulk._logger;\n\n this._jobInfo = this._waitAssign().then(function() {\n return bulk._request({\n method : 'GET',\n path : \"/job/\" + self.id,\n responseType: \"application/xml\"\n });\n }).then(function(res) {\n logger.debug(res.jobInfo);\n self.id = res.jobInfo.id;\n self.type = res.jobInfo.object;\n self.operation = res.jobInfo.operation;\n self.state = res.jobInfo.state;\n return res.jobInfo;\n });\n return this._jobInfo.thenCall(callback);\n};\n\n/**\n * Wait till the job is assigned to server\n *\n * @method Bulk~Job#info\n * @param {Callback.} [callback] - Callback function\n * @returns {Promise.}\n */\nJob.prototype._waitAssign = function(callback) {\n return (this.id ? Promise.resolve({ id: this.id }) : this.open()).thenCall(callback);\n};\n\n\n/**\n * List all registered batch info in job\n *\n * @method Bulk~Job#list\n * @param {Callback.>} [callback] - Callback function\n * @returns {Promise.>}\n */\nJob.prototype.list = function(callback) {\n var self = this;\n var bulk = this._bulk;\n var logger = bulk._logger;\n\n return this._waitAssign().then(function() {\n return bulk._request({\n method : 'GET',\n path : \"/job/\" + self.id + \"/batch\",\n responseType: \"application/xml\"\n });\n }).then(function(res) {\n logger.debug(res.batchInfoList.batchInfo);\n var batchInfoList = res.batchInfoList;\n batchInfoList = _.isArray(batchInfoList.batchInfo) ? batchInfoList.batchInfo : [ batchInfoList.batchInfo ];\n return batchInfoList;\n }).thenCall(callback);\n\n};\n\n/**\n * Close opened job\n *\n * @method Bulk~Job#close\n * @param {Callback.} [callback] - Callback function\n * @returns {Promise.}\n */\nJob.prototype.close = function() {\n var self = this;\n return this._changeState(\"Closed\").then(function(jobInfo) {\n self.id = null;\n self.emit(\"close\", jobInfo);\n return jobInfo;\n }, function(err) {\n self.emit(\"error\", err);\n throw err;\n });\n};\n\n/**\n * Set the status to abort\n *\n * @method Bulk~Job#abort\n * @param {Callback.} [callback] - Callback function\n * @returns {Promise.}\n */\nJob.prototype.abort = function() {\n var self = this;\n return this._changeState(\"Aborted\").then(function(jobInfo) {\n self.id = null;\n self.emit(\"abort\", jobInfo);\n return jobInfo;\n }, function(err) {\n self.emit(\"error\", err);\n throw err;\n });\n};\n\n/**\n * @private\n */\nJob.prototype._changeState = function(state, callback) {\n var self = this;\n var bulk = this._bulk;\n var logger = bulk._logger;\n\n this._jobInfo = this._waitAssign().then(function() {\n var body = [\n '',\n '',\n '' + state + '',\n ''\n ].join('');\n return bulk._request({\n method : 'POST',\n path : \"/job/\" + self.id,\n body : body,\n headers : {\n \"Content-Type\" : \"application/xml; charset=utf-8\"\n },\n responseType: \"application/xml\"\n });\n }).then(function(res) {\n logger.debug(res.jobInfo);\n self.state = res.jobInfo.state;\n return res.jobInfo;\n });\n return this._jobInfo.thenCall(callback);\n\n};\n\n\n/*--------------------------------------------*/\n\n/**\n * Batch (extends RecordStream)\n *\n * @protected\n * @class Bulk~Batch\n * @extends {stream.Writable}\n * @implements {Promise.>}\n * @param {Bulk~Job} job - Bulk job object\n * @param {String} [batchId] - Batch ID (if already available)\n */\nvar Batch = function(job, batchId) {\n Batch.super_.call(this, { objectMode: true });\n this.job = job;\n this.id = batchId;\n this._bulk = job._bulk;\n this._deferred = Promise.defer();\n this._setupDataStreams();\n};\n\ninherits(Batch, stream.Writable);\n\n\n/**\n * @private\n */\nBatch.prototype._setupDataStreams = function() {\n var batch = this;\n var converterOptions = { nullValue : '#N/A' };\n this._uploadStream = new RecordStream.Serializable();\n this._uploadDataStream = this._uploadStream.stream('csv', converterOptions);\n this._downloadStream = new RecordStream.Parsable();\n this._downloadDataStream = this._downloadStream.stream('csv', converterOptions);\n\n this.on('finish', function() {\n batch._uploadStream.end();\n });\n this._uploadDataStream.once('readable', function() {\n batch.job.open().then(function() {\n // pipe upload data to batch API request stream\n batch._uploadDataStream.pipe(batch._createRequestStream());\n });\n });\n\n // duplex data stream, opened access to API programmers by Batch#stream()\n var dataStream = this._dataStream = new Duplex();\n dataStream._write = function(data, enc, cb) {\n batch._uploadDataStream.write(data, enc, cb);\n };\n dataStream.on('finish', function() {\n batch._uploadDataStream.end();\n });\n\n this._downloadDataStream.on('readable', function() {\n dataStream.read(0);\n });\n this._downloadDataStream.on('end', function() {\n dataStream.push(null);\n });\n dataStream._read = function(size) {\n var chunk;\n while ((chunk = batch._downloadDataStream.read()) !== null) {\n dataStream.push(chunk);\n }\n };\n};\n\n/**\n * Connect batch API and create stream instance of request/response\n *\n * @private\n * @returns {stream.Duplex}\n */\nBatch.prototype._createRequestStream = function() {\n var batch = this;\n var bulk = batch._bulk;\n var logger = bulk._logger;\n\n return bulk._request({\n method : 'POST',\n path : \"/job/\" + batch.job.id + \"/batch\",\n headers: {\n \"Content-Type\": \"text/csv\"\n },\n responseType: \"application/xml\"\n }, function(err, res) {\n if (err) {\n batch.emit('error', err);\n } else {\n logger.debug(res.batchInfo);\n batch.id = res.batchInfo.id;\n batch.emit('queue', res.batchInfo);\n }\n }).stream();\n};\n\n/**\n * Implementation of Writable\n *\n * @override\n * @private\n */\nBatch.prototype._write = function(record, enc, cb) {\n record = _.clone(record);\n if (this.job.operation === \"insert\") {\n delete record.Id;\n } else if (this.job.operation === \"delete\") {\n record = { Id: record.Id };\n }\n delete record.type;\n delete record.attributes;\n this._uploadStream.write(record, enc, cb);\n};\n\n/**\n * Returns duplex stream which accepts CSV data input and batch result output\n *\n * @returns {stream.Duplex}\n */\nBatch.prototype.stream = function() {\n return this._dataStream;\n};\n\n/**\n * Execute batch operation\n *\n * @method Bulk~Batch#execute\n * @param {Array.|stream.Stream|String} [input] - Input source for batch operation. Accepts array of records, CSV string, and CSV data input stream in insert/update/upsert/delete/hardDelete operation, SOQL string in query operation.\n * @param {Callback.|Array.>} [callback] - Callback function\n * @returns {Bulk~Batch}\n */\nBatch.prototype.run =\nBatch.prototype.exec =\nBatch.prototype.execute = function(input, callback) {\n var self = this;\n\n if (typeof input === 'function') { // if input argument is omitted\n callback = input;\n input = null;\n }\n\n // if batch is already executed\n if (this._result) {\n throw new Error(\"Batch already executed.\");\n }\n\n var rdeferred = Promise.defer();\n this._result = rdeferred.promise;\n this._result.then(function(res) {\n self._deferred.resolve(res);\n }, function(err) {\n self._deferred.reject(err);\n });\n this.once('response', function(res) {\n rdeferred.resolve(res);\n });\n this.once('error', function(err) {\n rdeferred.reject(err);\n });\n\n if (_.isObject(input) && _.isFunction(input.pipe)) { // if input has stream.Readable interface\n input.pipe(this._dataStream);\n } else {\n var data;\n if (_.isArray(input)) {\n _.forEach(input, function(record) {\n Object.keys(record).forEach(function(key) {\n if (typeof record[key] === 'boolean') {\n record[key] = String(record[key])\n }\n })\n self.write(record);\n });\n self.end();\n } else if (_.isString(input)){\n data = input;\n this._dataStream.write(data, 'utf8');\n this._dataStream.end();\n }\n }\n\n // return Batch instance for chaining\n return this.thenCall(callback);\n};\n\n/**\n * Promise/A+ interface\n * http://promises-aplus.github.io/promises-spec/\n *\n * Delegate to deferred promise, return promise instance for batch result\n *\n * @method Bulk~Batch#then\n */\nBatch.prototype.then = function(onResolved, onReject, onProgress) {\n return this._deferred.promise.then(onResolved, onReject, onProgress);\n};\n\n/**\n * Promise/A+ extension\n * Call \"then\" using given node-style callback function\n *\n * @method Bulk~Batch#thenCall\n */\nBatch.prototype.thenCall = function(callback) {\n if (_.isFunction(callback)) {\n this.then(function(res) {\n process.nextTick(function() {\n callback(null, res);\n });\n }, function(err) {\n process.nextTick(function() {\n callback(err);\n });\n });\n }\n return this;\n};\n\n/**\n * @typedef {Object} Bulk~BatchInfo\n * @prop {String} id - Batch ID\n * @prop {String} jobId - Job ID\n * @prop {String} state - Batch state\n * @prop {String} stateMessage - Batch state message\n */\n\n/**\n * Check the latest batch status in server\n *\n * @method Bulk~Batch#check\n * @param {Callback.} [callback] - Callback function\n * @returns {Promise.}\n */\nBatch.prototype.check = function(callback) {\n var self = this;\n var bulk = this._bulk;\n var logger = bulk._logger;\n var jobId = this.job.id;\n var batchId = this.id;\n\n if (!jobId || !batchId) {\n throw new Error(\"Batch not started.\");\n }\n return bulk._request({\n method : 'GET',\n path : \"/job/\" + jobId + \"/batch/\" + batchId,\n responseType: \"application/xml\"\n }).then(function(res) {\n logger.debug(res.batchInfo);\n return res.batchInfo;\n }).thenCall(callback);\n};\n\n\n/**\n * Polling the batch result and retrieve\n *\n * @method Bulk~Batch#poll\n * @param {Number} interval - Polling interval in milliseconds\n * @param {Number} timeout - Polling timeout in milliseconds\n */\nBatch.prototype.poll = function(interval, timeout) {\n var self = this;\n var jobId = this.job.id;\n var batchId = this.id;\n\n if (!jobId || !batchId) {\n throw new Error(\"Batch not started.\");\n }\n var startTime = new Date().getTime();\n var poll = function() {\n var now = new Date().getTime();\n if (startTime + timeout < now) {\n var err = new Error(\"Polling time out. Job Id = \" + jobId + \" , batch Id = \" + batchId);\n err.name = 'PollingTimeout';\n err.jobId = jobId;\n err.batchId = batchId;\n self.emit('error', err);\n return;\n }\n self.check(function(err, res) {\n if (err) {\n self.emit('error', err);\n } else {\n if (res.state === \"Failed\") {\n if (parseInt(res.numberRecordsProcessed, 10) > 0) {\n self.retrieve();\n } else {\n self.emit('error', new Error(res.stateMessage));\n }\n } else if (res.state === \"Completed\") {\n self.retrieve();\n } else {\n self.emit('progress', res);\n setTimeout(poll, interval);\n }\n }\n });\n };\n setTimeout(poll, interval);\n};\n\n/**\n * @typedef {Object} Bulk~BatchResultInfo\n * @prop {String} id - Batch result ID\n * @prop {String} batchId - Batch ID which includes this batch result.\n * @prop {String} jobId - Job ID which includes this batch result.\n */\n\n/**\n * Retrieve batch result\n *\n * @method Bulk~Batch#retrieve\n * @param {Callback.|Array.>} [callback] - Callback function\n * @returns {Promise.|Array.>}\n */\nBatch.prototype.retrieve = function(callback) {\n var self = this;\n var bulk = this._bulk;\n var jobId = this.job.id;\n var job = this.job;\n var batchId = this.id;\n\n if (!jobId || !batchId) {\n throw new Error(\"Batch not started.\");\n }\n\n return job.info().then(function(jobInfo) {\n return bulk._request({\n method : 'GET',\n path : \"/job/\" + jobId + \"/batch/\" + batchId + \"/result\"\n });\n }).then(function(res) {\n var results;\n if (job.operation === 'query') {\n var conn = bulk._conn;\n var resultIds = res['result-list'].result;\n results = res['result-list'].result;\n results = _.map(_.isArray(results) ? results : [ results ], function(id) {\n return {\n id: id,\n batchId: batchId,\n jobId: jobId\n };\n });\n } else {\n results = _.map(res, function(ret) {\n return {\n id: ret.Id || null,\n success: ret.Success === \"true\",\n errors: ret.Error ? [ ret.Error ] : []\n };\n });\n }\n self.emit('response', results);\n return results;\n }).fail(function(err) {\n self.emit('error', err);\n throw err;\n }).thenCall(callback);\n};\n\n/**\n * Fetch query result as a record stream\n * @param {String} resultId - Result id\n * @returns {RecordStream} - Record stream, convertible to CSV data stream\n */\nBatch.prototype.result = function(resultId) {\n var jobId = this.job.id;\n var batchId = this.id;\n if (!jobId || !batchId) {\n throw new Error(\"Batch not started.\");\n }\n var resultStream = new RecordStream.Parsable();\n var resultDataStream = resultStream.stream('csv');\n var reqStream = this._bulk._request({\n method : 'GET',\n path : \"/job/\" + jobId + \"/batch/\" + batchId + \"/result/\" + resultId,\n responseType: \"application/octet-stream\"\n }).stream().pipe(resultDataStream);\n return resultStream;\n};\n\n/*--------------------------------------------*/\n/**\n * @private\n */\nvar BulkApi = function() {\n BulkApi.super_.apply(this, arguments);\n};\n\ninherits(BulkApi, HttpApi);\n\nBulkApi.prototype.beforeSend = function(request) {\n request.headers = request.headers || {};\n request.headers[\"X-SFDC-SESSION\"] = this._conn.accessToken;\n};\n\nBulkApi.prototype.isSessionExpired = function(response) {\n return response.statusCode === 400 &&\n /InvalidSessionId<\\/exceptionCode>/.test(response.body);\n};\n\nBulkApi.prototype.hasErrorInResponseBody = function(body) {\n return !!body.error;\n};\n\nBulkApi.prototype.parseError = function(body) {\n return {\n errorCode: body.error.exceptionCode,\n message: body.error.exceptionMessage\n };\n};\n\n/*--------------------------------------------*/\n\n/**\n * Class for Bulk API\n *\n * @class\n * @param {Connection} conn - Connection object\n */\nvar Bulk = function(conn) {\n this._conn = conn;\n this._logger = conn._logger;\n};\n\n/**\n * Polling interval in milliseconds\n * @type {Number}\n */\nBulk.prototype.pollInterval = 1000;\n\n/**\n * Polling timeout in milliseconds\n * @type {Number}\n */\nBulk.prototype.pollTimeout = 10000;\n\n/** @private **/\nBulk.prototype._request = function(request, callback) {\n var conn = this._conn;\n request = _.clone(request);\n var baseUrl = [ conn.instanceUrl, \"services/async\", conn.version ].join('/');\n request.url = baseUrl + request.path;\n var options = { responseType: request.responseType };\n delete request.path;\n delete request.responseType;\n return new BulkApi(this._conn, options).request(request).thenCall(callback);\n};\n\n/**\n * Create and start bulkload job and batch\n *\n * @param {String} type - SObject type\n * @param {String} operation - Bulk load operation ('insert', 'update', 'upsert', 'delete', or 'hardDelete')\n * @param {Object} [options] - Options for bulk loading operation\n * @param {String} [options.extIdField] - External ID field name (used when upsert operation).\n * @param {String} [options.concurrencyMode] - 'Serial' or 'Parallel'. Defaults to Parallel.\n * @param {Array.|stream.Stream|String} [input] - Input source for bulkload. Accepts array of records, CSV string, and CSV data input stream in insert/update/upsert/delete/hardDelete operation, SOQL string in query operation.\n * @param {Callback.|Array.>} [callback] - Callback function\n * @returns {Bulk~Batch}\n */\nBulk.prototype.load = function(type, operation, options, input, callback) {\n var self = this;\n if (!type || !operation) {\n throw new Error(\"Insufficient arguments. At least, 'type' and 'operation' are required.\");\n }\n if (!_.isObject(options) || options.constructor !== Object) { // when options is not plain hash object, it is omitted\n callback = input;\n input = options;\n options = null;\n }\n var job = this.createJob(type, operation, options);\n job.once('error', function (error) {\n if (batch) {\n batch.emit('error', error); // pass job error to batch\n }\n });\n var batch = job.createBatch();\n var cleanup = function() {\n batch = null;\n job.close();\n };\n var cleanupOnError = function(err) {\n if (err.name !== 'PollingTimeout') {\n cleanup();\n }\n };\n batch.on('response', cleanup);\n batch.on('error', cleanupOnError);\n batch.on('queue', function() { batch.poll(self.pollInterval, self.pollTimeout); });\n return batch.execute(input, callback);\n};\n\n/**\n * Execute bulk query and get record stream\n *\n * @param {String} soql - SOQL to execute in bulk job\n * @returns {RecordStream.Parsable} - Record stream, convertible to CSV data stream\n */\nBulk.prototype.query = function(soql) {\n var m = soql.replace(/\\([\\s\\S]+\\)/g, '').match(/FROM\\s+(\\w+)/i);\n if (!m) {\n throw new Error(\"No sobject type found in query, maybe caused by invalid SOQL.\");\n }\n var type = m[1];\n var self = this;\n var recordStream = new RecordStream.Parsable();\n var dataStream = recordStream.stream('csv');\n this.load(type, \"query\", soql).then(function(results) {\n var streams = results.map(function(result) {\n return self\n .job(result.jobId)\n .batch(result.batchId)\n .result(result.id)\n .stream();\n });\n\n joinStreams(streams).pipe(dataStream);\n }).fail(function(err) {\n recordStream.emit('error', err);\n });\n return recordStream;\n};\n\n\n/**\n * Create a new job instance\n *\n * @param {String} type - SObject type\n * @param {String} operation - Bulk load operation ('insert', 'update', 'upsert', 'delete', 'hardDelete', or 'query')\n * @param {Object} [options] - Options for bulk loading operation\n * @returns {Bulk~Job}\n */\nBulk.prototype.createJob = function(type, operation, options) {\n return new Job(this, type, operation, options);\n};\n\n/**\n * Get a job instance specified by given job ID\n *\n * @param {String} jobId - Job ID\n * @returns {Bulk~Job}\n */\nBulk.prototype.job = function(jobId) {\n return new Job(this, null, null, null, jobId);\n};\n\n\n/*--------------------------------------------*/\n/*\n * Register hook in connection instantiation for dynamically adding this API module features\n */\njsforce.on('connection:new', function(conn) {\n conn.bulk = new Bulk(conn);\n});\n\n\nmodule.exports = Bulk;\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n"]}