jsforce
Version:
Salesforce API Library for JavaScript
3 lines • 200 kB
JavaScript
/*! jsforce - v1.3.0 - 2014-09-15 */
!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;"undefined"!=typeof window?b=window:"undefined"!=typeof global?b=global:"undefined"!=typeof self&&(b=self),b.jsforce=a()}}(function(){var a;return function b(a,c,d){function e(g,h){if(!c[g]){if(!a[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};a[g][0].call(k.exports,function(b){var c=a[g][1][b];return e(c?c:b)},k,k.exports,b,a,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b){function c(a){var b={};return a.split(/\n/).forEach(function(a){var c=a.split(/\s*:\s*/),d=c[0].toLowerCase(),e=c[1];b[d]=e}),b}var d=a("stream"),e=a("underscore");b.exports={supported:"object"==typeof Sfdc&&"undefined"!=typeof Sfdc.canvas,createRequest:function(a){return function(b,f){function g(d){var g={client:a.client,method:b.method,data:d};if(b.headers){g.headers={};for(var j in b.headers)"content-type"===j.toLowerCase()?g.contentType=b.headers[j]:g.headers[j]=b.headers[j]}g.success=function(a){var b=c(a.responseHeaders),d=a.payload;e.isString(d)||(d=JSON.stringify(d)),h={statusCode:a.status,headers:b,body:d},f&&f(null,h,h.body),i.end()},g.failure=function(a){f&&f(a)},Sfdc.canvas.client.ajax(b.url,g)}var h,i=new d.Duplex;i._read=function(){h&&i.push(h.body)};var j=[],k=!1;return i._write=function(a,b,c){j.push(a.toString(b)),c()},i.on("finish",function(){k||(g(j.join("")),k=!0)}),(b.body||""===b.body||!/^(put|post|patch)$/i.test(b.method))&&(g(b.body),k=!0),i}}}},{stream:35,underscore:54}],2:[function(a,b){function c(a,b,c){var d=screen.width/2-b/2,e=screen.height/2-c/2;return window.open(a,null,"location=yes,toolbar=no,status=no,menubar=no,width="+b+",height="+c+",top="+e+",left="+d)}function d(){var a=e(),b=localStorage.getItem("jsforce_state");if(a&&b&&a.body.state===b){localStorage.removeItem("jsforce_state");var c=b.split("."),d=c[0],f=c[1],g=new m(d);return a.success?(g._storeTokens(a.body),location.hash=""):g._storeError(a.body),"popup"===f&&window.close(),!0}}function e(){var a;if(window.location.hash){if(a=h.parse(window.location.hash.substring(1)),a.access_token)return{success:!0,body:a}}else if(window.location.search&&(a=h.parse(window.location.search.substring(1)),a.error))return{success:!1,body:a}}var f=a("events"),g=a("util"),h=a("querystring"),i=a("underscore"),j=a("../connection"),k=a("../oauth2"),l=0,m=function(a){this._prefix=a||"jsforce"+l++,this.connection=null};g.inherits(m,f.EventEmitter),m.prototype.init=function(a){if(!d()){this.config=a,this.connection=new j(a);var b=this._getTokens();if(b){this.connection.initialize(b);var c=this;setTimeout(function(){c.emit("connect",c.connection)},10)}}},m.prototype.login=function(a,b){i.isFunction(a)&&(b=a,a={}),a=a||{},b=b||function(){},i.extend(a,this.config);this._prompt(a,b)},m.prototype._prompt=function(a,b){var d=this,e=new k(a),f=Math.random().toString(36).substring(2),g=[this._prefix,"popup",f].join(".");localStorage.setItem("jsforce_state",g);var h=e.getAuthorizationUrl({response_type:"token",scope:a.scope,state:g}),i=a.size||{},j=c(h,i.width||912,i.height||513);if(!j)return g=[this._prefix,"redirect",f].join("."),localStorage.setItem("jsforce_state",g),h=e.getAuthorizationUrl({response_type:"token",scope:a.scope,state:g}),void(location.href=h);d._removeTokens();var l=setInterval(function(){try{if(!j||j.closed){clearInterval(l);var a=d._getTokens();if(a)d.connection.initialize(a),d.emit("connect",d.connection),b(null,{status:"connect"});else{var c=d._getError();c?b(new Error(c.error+": "+c.error_description)):b(null,{status:"cancel"})}}}catch(e){}},1e3)},m.prototype.isLoggedIn=function(){return!(!this.connection||!this.connection.accessToken)},m.prototype.logout=function(){this.connection.logout(),this._removeTokens(),this.emit("disconnect")},m.prototype._getTokens=function(){var a=new RegExp("(^|;\\s*)"+this._prefix+"_loggedin=true(;|$)");if(document.cookie.match(a)){var b=Number(localStorage.getItem(this._prefix+"_issued_at"));if(Date.now()<b+72e5){var c,d=localStorage.getItem(this._prefix+"_id");if(d){var e=d.split("/");c={id:e.pop(),organizationId:e.pop(),url:d}}return{accessToken:localStorage.getItem(this._prefix+"_access_token"),instanceUrl:localStorage.getItem(this._prefix+"_instance_url"),userInfo:c}}}return null},m.prototype._storeTokens=function(a){localStorage.setItem(this._prefix+"_access_token",a.access_token),localStorage.setItem(this._prefix+"_instance_url",a.instance_url),localStorage.setItem(this._prefix+"_issued_at",a.issued_at),localStorage.setItem(this._prefix+"_id",a.id),document.cookie=this._prefix+"_loggedin=true;"},m.prototype._removeTokens=function(){localStorage.removeItem(this._prefix+"_access_token"),localStorage.removeItem(this._prefix+"_instance_url"),localStorage.removeItem(this._prefix+"_issued_at"),localStorage.removeItem(this._prefix+"_id"),document.cookie=this._prefix+"_loggedin="},m.prototype._getError=function(){try{var a=JSON.parse(localStorage.getItem(this._prefix+"_error"));return localStorage.removeItem(this._prefix+"_error"),a}catch(b){}},m.prototype._storeError=function(a){localStorage.setItem(this._prefix+"_error",JSON.stringify(a))},b.exports=new m,b.exports.Client=m},{"../connection":7,"../oauth2":13,events:29,querystring:34,underscore:54,util:38}],3:[function(a,b){var c,d=a("../jsforce");try{c=a("../core-require")}catch(e){}d.browser=a("./client"),d.modules=d.modules||{},d.require=function(a){try{return c(a)}catch(b){if("jsforce"===a||"./jsforce"===a)return d;if("./"===a.substring(0,2)){var e=a.substring(2).split("/"),f=e.pop();e.push(f.replace(/(^|\-)([a-zA-Z])/g,function(a,b,c){return c.toUpperCase()}));for(var g=d.modules;g&&e.length>0;)g=g[e.shift()];return g}}},b.exports=d},{"../core-require":8,"../jsforce":11,"./client":2}],4:[function(a,b){var c=0;b.exports={supported:"undefined"!=typeof window,createRequest:function(a,b){return a=a||"callback",b=b||1e4,function(d,e){if("GET"!==d.method.toUpperCase())return e(new Error("JSONP only supports GET request."));var f="_jsforce_jsonpCallback_"+ ++c,g=window,h=d.url;h+=h.indexOf("?")>0?"&":"?",h+=a+"="+f;var i=document.createElement("script");i.type="text/javascript",i.src=h,document.documentElement.appendChild(i);var j=setTimeout(function(){k(),e(new Error("JSONP call time out."))},b);g[f]=function(a){k(),e(null,{statusCode:200,headers:{"content-type":"application/json"},body:JSON.stringify(a)})};var k=function(){clearTimeout(j),document.documentElement.removeChild(i),delete g[f]}}}}},{}],5:[function(a,b){var c=a("stream");b.exports=function(a,b){var d=new XMLHttpRequest;if(d.open(a.method,a.url),a.headers)for(var e in a.headers)d.setRequestHeader(e,a.headers[e]);d.setRequestHeader("Accept","*/*");var f,g=new c.Duplex;g._read=function(){f&&g.push(f.body)};var h=[],i=!1;return g._write=function(a,b,c){h.push(a.toString("buffer"===b?"binary":b)),c()},g.on("finish",function(){i||(d.send(h.join("")),i=!0)}),(a.body||""===a.body||!/^(put|post|patch)$/i.test(a.method))&&(d.send(a.body),i=!0),d.onreadystatechange=function(){if(4===d.readyState){var a={"content-type":d.getResponseHeader("content-type")};f={statusCode:d.status,headers:a,body:d.response},f.statusCode||(f.statusCode=400,f.body="Access Declined"),b&&b(null,f,f.body),g.end()}},g}},{stream:35}],6:[function(a,b){function c(a,b){return b=Array.prototype.slice.apply(b),a+"("+f.map(b,function(a){return JSON.stringify(a)}).join(",")+")"}var d=a("events"),e=a("util"),f=a("underscore")._,g=function(){this.fetching=!1};e.inherits(g,d.EventEmitter),g.prototype.get=function(a){return a?(this.once("value",a),void(f.isUndefined(this._value)||this.emit("value",this._value))):this._value},g.prototype.set=function(a){this._value=a,this.emit("value",this._value)},g.prototype.clear=function(){this.fetching=!1,delete this._value};var h=function(){this._entries={}};h.prototype.get=function(a){if(a&&this._entries[a])return this._entries[a];var b=new g;return this._entries[a]=b,b},h.prototype.clear=function(a){for(var b in this._entries)a&&0!==b.indexOf(a)||this._entries[b].clear()},h.prototype.makeResponseCacheable=function(a,b,d){var e=this;return d=d||{},function(){var g=Array.prototype.slice.apply(arguments),h=g.pop();f.isFunction(h)||(g.push(h),h=null);var i=f.isString(d.key)?d.key:f.isFunction(d.key)?d.key.apply(b,g):c(d.namespace,g),j=e.get(i);j.fetching=!0,h&&g.push(function(a,b){j.set({error:a,result:b}),h(a,b)});var k,l;try{k=a.apply(b||this,g)}catch(m){l=m}if(k&&f.isFunction(k.then))return h?k:k.then(function(a){return j.set({error:void 0,result:a}),a},function(a){throw j.set({error:a,result:void 0}),a});if(j.set({error:l,result:k}),l)throw l;return k}},h.prototype.makeCacheable=function(a,b,d){var e=this;d=d||{};var g=function(){var g=Array.prototype.slice.apply(arguments),h=g.pop();f.isFunction(h)||g.push(h);var i=f.isString(d.key)?d.key:f.isFunction(d.key)?d.key.apply(b,g):c(d.namespace,g),j=e.get(i);if(!f.isFunction(h)){var k=j.get();if(!k)throw new Error("Function call result is not cached yet.");if(k.error)throw k.error;return k.result}j.get(function(a){h(a.error,a.result)}),j.fetching||(j.fetching=!0,g.push(function(a,b){j.set({error:a,result:b})}),a.apply(b||this,g))};return g.clear=function(){var a=f.isString(d.key)?d.key:f.isFunction(d.key)?d.key.apply(b,arguments):c(d.namespace,arguments);e.clear(a)},g},b.exports=h},{events:29,underscore:54,util:38}],7:[function(a,b){(function(c){function d(a){if(n.isString(a)){if("{"===a[0])return JSON.parse(a);var b=a.split(".").pop(),d=new c(b,"base64").toString("utf-8");return JSON.parse(d)}return a}function e(a){return JSON.parse(a)}function f(b){var c={};if(a("xml2js").parseString(b,{explicitArray:!1},function(a,b){c={error:a,result:b}}),c.error)throw c.error;return c.result}function g(b){return a("./csv").parseCSV(b)}function h(a){return a}function i(a){function b(a){return 10>a?"0"+a:a}return a.getUTCFullYear()+"-"+b(a.getUTCMonth()+1)+"-"+b(a.getUTCDate())+"T"+b(a.getUTCHours())+":"+b(a.getUTCMinutes())+":"+b(a.getUTCSeconds())+"+00:00"}function j(a){var b=a.split("/"),c=b.pop(),d=b.pop();return{id:c,organizationId:d,url:a}}function k(a){return a&&String(a).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}var l=a("events"),m=a("util"),n=(a("async"),a("underscore")._),o=a("./promise"),p=a("./logger"),q=a("./oauth2"),r=a("./query"),s=a("./sobject"),t=a("./transport"),u=a("./cache"),v={loginUrl:"https://login.salesforce.com",instanceUrl:"",version:"31.0"},w=b.exports=function(a){var b=jsforce.require("./api/bulk"),c=jsforce.require("./api/streaming"),d=jsforce.require("./api/tooling"),e=jsforce.require("./api/analytics"),f=jsforce.require("./api/chatter"),g=jsforce.require("./api/apex"),h=jsforce.require("./api/metadata");a=a||{},this._logger=new p(a.logLevel);var i=a.oauth2||{loginUrl:a.loginUrl,clientId:a.clientId,clientSecret:a.clientSecret,redirectUri:a.redirectUri};this.oauth2=i instanceof q?i:new q(i),this.loginUrl=a.loginUrl||i.loginUrl||v.loginUrl,this.version=a.version||v.version,this.maxRequest=a.maxRequest||this.maxRequest||10,this._transport=a.proxyUrl?new t.ProxyTransport(a.proxyUrl):new t,c&&(this.streaming=new c(this)),b&&(this.bulk=new b(this)),d&&(this.tooling=new d(this)),e&&(this.analytics=new e(this)),f&&(this.chatter=new f(this)),h&&(this.metadata=new h(this)),g&&(this.apex=new g(this)),this.cache=new u,a.refreshFn&&(this._refreshDelegate={refreshToken:a.refreshFn});var j={key:function(a){return a?"describe."+a:"describe"}};this.describe$=this.cache.makeCacheable(this.describe,this,j),this.describe=this.cache.makeResponseCacheable(this.describe,this,j),this.describeSObject$=this.describe$,this.describeSObject=this.describe,j={key:"describeGlobal"},this.describeGlobal$=this.cache.makeCacheable(this.describeGlobal,this,j),this.describeGlobal=this.cache.makeResponseCacheable(this.describeGlobal,this,j),this.initialize(a)};m.inherits(w,l.EventEmitter),w.prototype.initialize=function(a){if(!a.instanceUrl&&a.serverUrl&&(a.instanceUrl=a.serverUrl.split("/").slice(0,3).join("/")),this.instanceUrl=a.instanceUrl||a.serverUrl||this.instanceUrl||v.instanceUrl,this.urls={soap:{login:[this.loginUrl,"services/Soap/u",this.version].join("/"),service:[this.instanceUrl,"services/Soap/u",this.version].join("/")},rest:{base:[this.instanceUrl,"services/data","v"+this.version].join("/")}},this.accessToken=a.sessionId||a.accessToken||this.accessToken,this.refreshToken=a.refreshToken||this.refreshToken,this.refreshToken&&!this.oauth2&&!this._refreshDelegate)throw new Error("Refresh token is specified without oauth2 client information");this.signedRequest=a.signedRequest&&d(a.signedRequest),this.signedRequest&&(this.accessToken=this.signedRequest.client.oauthToken),a.userInfo&&(this.userInfo=a.userInfo),this.limitInfo={},this.sobjects={},this.cache.clear(),this.cache.get("describeGlobal").on("value",n.bind(function(a){if(a.result){var b=n.map(a.result.sobjects,function(a){return a.name});n.each(b,this.sobject,this)}},this)),this.tooling&&this.tooling.initialize(),this._sessionType=a.sessionId?"soap":"oauth2",this._initializedAt=Date.now()},w.prototype._baseUrl=function(){return this.urls.rest.base},w.prototype._request=function(a,b,c){c=c||{},n.isString(a)&&(a={method:"GET",url:a}),"/"===a.url[0]&&(a.url=this.instanceUrl+a.url);var d=this,i=this._logger,j=o.defer(),k=function(b){return b?void j.reject(b):void d._request(a,null,c).then(function(a){j.resolve(a)},function(a){j.reject(a)})};if(d._suspended)return d.once("resume",k),j.promise.thenCall(b);a.headers=a.headers||{},this.accessToken&&(a.headers.Authorization="Bearer "+this.accessToken),c.beforesend&&c.beforesend(this,a),this.signedRequest&&(c.signedRequest=this.signedRequest),d.emit("request",a.method,a.url,a),i.debug("<request> method="+a.method+", url="+a.url);var l=Date.now(),m=function(a){var b=Date.now();throw i.debug("elappsed time : "+(b-l)+"msec"),i.error(a),a},p=function(b){var m=Date.now();if(i.debug("elappsed time : "+(m-l)+"msec"),i.debug("<response> status="+b.statusCode+", url="+a.url),d.emit("response",b.statusCode,b.body,b),b.headers&&b.headers["sforce-limit-info"]){var o=b.headers["sforce-limit-info"].match(/api\-usage=(\d+)\/(\d+)/);o&&(d.limitInfo={apiUsage:{used:parseInt(o[1],10),limit:parseInt(o[2],10)}})}if(401===b.statusCode&&(d._refreshDelegate||d.oauth2&&d.refreshToken))return d._initializedAt>l?k():(d.once("resume",k),d._suspended||(d._suspended=!0,d._refresh())),j.promise;var p,q=c.responseContentType||b.headers&&b.headers["content-type"],r=/^application\/xml(;|$)/.test(q)?f:/^application\/json(;|$)/.test(q)?e:/^text\/csv(;|$)/.test(q)?g:h;if(b.statusCode>=400){var s;try{var t=c.parseError||function(a){var b=n.isArray(a)?a[0]:a;return n.isObject(b)&&n.isString(b.message)?b:void 0};s=t(r(b.body))}catch(u){}s||(s={message:b.body,errorCode:"ERROR_HTTP_"+b.statusCode}),p=new Error(s.message),p.name=s.errorCode;for(var v in s)p[v]=s[v];throw p}if(204===b.statusCode)return c.noContentResponse;var w=r(b.body);if(300===b.statusCode)throw p=new Error("Multiple records found"),p.name="MULTIPLE_CHOICES",p.content=w,p;return w};return this._transport.httpRequest(a,null,c).then(p,m).thenCall(b)},w.prototype._refresh=function(){var a=this,b=this._logger;b.debug("<refresh token>");var c=this._refreshDelegate||this.oauth2;return c.refreshToken(this.refreshToken,function(c,d){if(!c){var e=j(d.id);a.initialize({instanceUrl:d.instance_url,accessToken:d.access_token,userInfo:e}),b.debug("token refresh completed. result = "+JSON.stringify(d)),a.emit("refresh",d.access_token,d)}a._suspended=!1,a.emit("resume",c)})},w.prototype.query=function(a,b){var c=new r(this,a);return b&&c.run(b),c},w.prototype.queryAll=function(a,b){var c=new r(this,a);return c.scanAll(!0),b&&c.run(b),c},w.prototype.queryMore=function(a,b){var c=new r(this,null,a);return b&&c.run(b),c},w.prototype.retrieve=function(a,b,c,d){"function"==typeof c&&(d=c,c={});var e=this,f=n.isArray(b);return b=f?b:[b],b.length>e.maxRequest?o.reject(new Error("Exceeded max limit of concurrent call")).thenCall(d):o.all(n.map(b,function(b){var c=[e._baseUrl(),"sobjects",a,b].join("/");return e._request(c)})).then(function(a){return!f&&n.isArray(a)?a[0]:a}).thenCall(d)},w.prototype.insert=w.prototype.create=function(a,b,c,d){n.isString(a)||(d=c,c=b,b=a,a=null),"function"==typeof c&&(d=c,c={}),c=c||{};var e=this,f=n.isArray(b);return b=f?b:[b],b.length>e.maxRequest?o.reject(new Error("Exceeded max limit of concurrent call")).thenCall(d):o.all(n.map(b,function(b){var d=a||b.attributes&&b.attributes.type||b.type;if(!d)throw new Error("No SObject Type defined in record");b=n.clone(b),delete b.Id,delete b.type,delete b.attributes;var f=[e._baseUrl(),"sobjects",d].join("/");return e._request({method:"POST",url:f,body:JSON.stringify(b),headers:n.defaults(c.headers||{},{"Content-Type":"application/json"})})})).then(function(a){return!f&&n.isArray(a)?a[0]:a}).thenCall(d)},w.prototype.update=function(a,b,c,d){n.isString(a)||(d=c,c=b,b=a,a=null),"function"==typeof c&&(d=c,c={}),c=c||{};var e=this,f=n.isArray(b);return b=f?b:[b],b.length>e.maxRequest?o.reject(new Error("Exceeded max limit of concurrent call")).thenCall(d):o.all(n.map(b,function(b){var d=b.Id;if(!d)throw new Error("Record id is not found in record.");var f=a||b.attributes&&b.attributes.type||b.type;if(!f)throw new Error("No SObject Type defined in record");b=n.clone(b),delete b.Id,delete b.type,delete b.attributes;var g=[e._baseUrl(),"sobjects",f,d].join("/");return e._request({method:"PATCH",url:g,body:JSON.stringify(b),headers:n.defaults(c.headers||{},{"Content-Type":"application/json"})},null,{noContentResponse:{id:d,success:!0,errors:[]}})})).then(function(a){return!f&&n.isArray(a)?a[0]:a}).thenCall(d)},w.prototype.upsert=function(a,b,c,d,e){n.isString(a)||(e=d,d=c,c=b,b=a,a=null),"function"==typeof d&&(e=d,d={}),d=d||{};var f=this,g=n.isArray(b);return b=g?b:[b],b.length>f.maxRequest?o.reject(new Error("Exceeded max limit of concurrent call")).thenCall(e):o.all(n.map(b,function(b){var e=a||b.attributes&&b.attributes.type||b.type,g=b[c];if(!g)return o.reject(new Error("External ID is not defined in the record"));b=n.clone(b),delete b[c],delete b.type,delete b.attributes;var h=[f._baseUrl(),"sobjects",e,c,g].join("/");return f._request({method:"PATCH",url:h,body:JSON.stringify(b),headers:n.defaults(d.headers||{},{"Content-Type":"application/json"})},null,{noContentResponse:{success:!0,errors:[]}})})).then(function(a){return!g&&n.isArray(a)?a[0]:a}).thenCall(e)},w.prototype["delete"]=w.prototype.del=w.prototype.destroy=function(a,b,c,d){"function"==typeof c&&(d=c,c={}),c=c||{};var e=this,f=n.isArray(b);return b=f?b:[b],b.length>e.maxRequest?o.reject(new Error("Exceeded max limit of concurrent call")).thenCall(d):o.all(n.map(b,function(b){var d=[e._baseUrl(),"sobjects",a,b].join("/");return e._request({method:"DELETE",url:d,headers:c.headers||null},null,{noContentResponse:{id:b,success:!0,errors:[]}})})).then(function(a){return!f&&n.isArray(a)?a[0]:a}).thenCall(d)},w.prototype.search=function(a,b){var c=this._baseUrl()+"/search?q="+encodeURIComponent(a);return this._request(c).thenCall(b)},w.prototype.describe=w.prototype.describeSObject=function(a,b){var c=[this._baseUrl(),"sobjects",a,"describe"].join("/");return this._request(c).thenCall(b)},w.prototype.describeGlobal=function(a){var b=this._baseUrl()+"/sobjects";return this._request(b).thenCall(a)},w.prototype.sobject=function(a){this.sobjects=this.sobjects||{};var b=this.sobjects[a]=this.sobjects[a]||new s(this,a);return b},w.prototype.identity=function(a){var b=this,c=this.userInfo&&this.userInfo.url;return new o(c?{identity:c}:this._request(this._baseUrl())).then(function(a){var c=a.identity;return c+="?format=json&oauth_token="+encodeURIComponent(b.accessToken),b._request(c,null,{jsonp:"callback"})}).then(function(a){return b.userInfo={id:a.user_id,organizationId:a.organization_id,url:a.id},a}).thenCall(a)},w.prototype.authorize=function(a,b){var c=this,d=this._logger;return this.oauth2.requestToken(a).then(function(a){d.debug("OAuth2 token response = "+JSON.stringify(a));var b=j(a.id);return c.initialize({instanceUrl:a.instance_url,accessToken:a.access_token,refreshToken:a.refresh_token,userInfo:b}),d.debug("<login> completed. user id = "+b.id+", org id = "+b.organizationId),b}).thenCall(b)},w.prototype.login=function(a,b,c){return this.oauth2&&this.oauth2.clientId&&this.oauth2.clientSecret?this.loginByOAuth2(a,b,c):this.loginBySoap(a,b,c)},w.prototype.loginByOAuth2=function(a,b,c){var d=this,e=this._logger;return this.oauth2.authenticate(a,b).then(function(a){e.debug("OAuth2 token response = "+JSON.stringify(a));var b=j(a.id);return d.initialize({instanceUrl:a.instance_url,accessToken:a.access_token,userInfo:b}),e.debug("<login> completed. user id = "+b.id+", org id = "+b.organizationId),b}).thenCall(c)},w.prototype.loginBySoap=function(a,b,c){var d=this,e=this._logger,f=['<se:Envelope xmlns:se="http://schemas.xmlsoap.org/soap/envelope/">',"<se:Header/>","<se:Body>",'<login xmlns="urn:partner.soap.sforce.com">',"<username>"+k(a)+"</username>","<password>"+k(b)+"</password>","</login>","</se:Body>","</se:Envelope>"].join("");return this._transport.httpRequest({method:"POST",url:this.urls.soap.login,body:f,headers:{"Content-Type":"text/xml",SOAPAction:'""'}}).then(function(a){var b;if(a.statusCode>=400){b=a.body.match(/<faultstring>([^<]+)<\/faultstring>/);var c=b&&b[1];throw new Error(c||a.body)}e.debug("SOAP response = "+a.body),b=a.body.match(/<serverUrl>([^<]+)<\/serverUrl>/);var f=b&&b[1];b=a.body.match(/<sessionId>([^<]+)<\/sessionId>/);var g=b&&b[1];b=a.body.match(/<userId>([^<]+)<\/userId>/);var h=b&&b[1];b=a.body.match(/<organizationId>([^<]+)<\/organizationId>/);var i=b&&b[1],j=d.urls.soap.login.split("/").slice(0,3).join("/");j+="/id/"+i+"/"+h;var k={id:h,organizationId:i,url:j};return d.initialize({serverUrl:f.split("/").slice(0,3).join("/"),sessionId:g,userInfo:k}),e.debug("<login> completed. user id = "+h+", org id = "+i),k}).thenCall(c)},w.prototype.logout=function(a){return"oauth2"===this._sessionType?this.logoutByOAuth2(a):this.logoutBySoap(a)},w.prototype.logoutByOAuth2=function(a){{var b=this;this._logger}return this.oauth2.revokeToken(this.accessToken).then(function(){return b.accessToken=null,b.userInfo=null,b.refreshToken=null,b.instanceUrl=null,void b.cache.clear()}).thenCall(a)},w.prototype.logoutBySoap=function(a){var b=this,c=this._logger,d=['<se:Envelope xmlns:se="http://schemas.xmlsoap.org/soap/envelope/">',"<se:Header>",'<SessionHeader xmlns="urn:partner.soap.sforce.com">',"<sessionId>"+k(this.accessToken)+"</sessionId>","</SessionHeader>","</se:Header>","<se:Body>",'<logout xmlns="urn:partner.soap.sforce.com"/>',"</se:Body>","</se:Envelope>"].join("");return this._transport.httpRequest({method:"POST",url:this.urls.soap.service,body:d,headers:{"Content-Type":"text/xml",SOAPAction:'""'}}).then(function(a){if(c.debug("SOAP statusCode = "+a.statusCode+", response = "+a.body),a.statusCode>=400){var d=a.body.match(/<faultstring>([^<]+)<\/faultstring>/),e=d&&d[1];throw new Error(e||a.body)}return b.accessToken=null,b.userInfo=null,b.refreshToken=null,b.instanceUrl=null,void b.cache.clear()}).thenCall(a)},w.prototype.recent=function(a,b,c){n.isString(a)||(c=b,b=a,a=void 0),n.isNumber(b)||(c=b,b=void 0);var d;return a?(d=[this._baseUrl(),"sobjects",a].join("/"),this._request(d).then(function(a){return b?a.recentItems.slice(0,b):a.recentItems}).thenCall(c)):(d=this._baseUrl()+"/recent",b&&(d+="?limit="+b),this._request(d).thenCall(c))},w.prototype.updated=function(a,b,c,d){var e=[this._baseUrl(),"sobjects",a,"updated"].join("/");return"string"==typeof b&&(b=new Date(b)),b instanceof Date&&(b=i(b)),b&&(e+="?start="+encodeURIComponent(b)),"string"==typeof c&&(c=new Date(c)),c instanceof Date&&(c=i(c)),c&&(e+="&end="+encodeURIComponent(c)),this._request(e).thenCall(d)},w.prototype.deleted=function(a,b,c,d){var e=[this._baseUrl(),"sobjects",a,"deleted"].join("/");return"string"==typeof b&&(b=new Date(b)),b instanceof Date&&(b=i(b)),b&&(e+="?start="+encodeURIComponent(b)),"string"==typeof c&&(c=new Date(c)),c instanceof Date&&(c=i(c)),c&&(e+="&end="+encodeURIComponent(c)),this._request(e).thenCall(d)}}).call(this,a("buffer").Buffer)},{"./cache":6,"./csv":9,"./logger":12,"./oauth2":13,"./promise":14,"./query":15,"./sobject":18,"./transport":20,async:21,buffer:25,events:29,underscore:54,util:38,xml2js:57}],8:[function(a,b){b.exports=function(b){return a(b)},a("events"),a("util"),a("underscore"),a("async"),a("./promise"),a("./logger"),a("./oauth2"),a("./query"),a("./sobject"),a("./transport"),a("./cache"),a("xml2js"),a("./csv"),a("./date"),a("./connection"),a("./record-stream"),a("querystring"),a("q"),a("./soql-builder"),a("stream"),a("./record"),a("request"),a("./browser/request"),a("./browser/canvas"),a("./browser/jsonp")},{"./browser/canvas":1,"./browser/jsonp":4,"./browser/request":5,"./cache":6,"./connection":7,"./csv":9,"./date":10,"./logger":12,"./oauth2":13,"./promise":14,"./query":15,"./record":17,"./record-stream":16,"./sobject":18,"./soql-builder":19,"./transport":20,async:21,events:29,q:39,querystring:34,request:23,stream:35,underscore:54,util:38,xml2js:57}],9:[function(a,b){function c(a,b,c){c=c||{},b||(b=d(a,c));var g=i.map(a,function(a){return e(a,b,c)});return f(b)+"\n"+g.join("\n")}function d(a,b){b=b||{};var c={};return i.forEach(a,function(a){for(var b in a){var d=a[b];!a.hasOwnProperty(b)||null!==d&&"object"==typeof d||(c[b]=!0)}}),i.keys(c)}function e(a,b,c){c=c||{};var d=[];return i.forEach(b,function(b){var e=a[b];null===e&&"undefined"!=typeof c.nullValue&&(e=c.nullValue),"undefined"==typeof e&&(e=null),d.push(e)}),f(d)}function f(a){return i.map(a,g).join(",")}function g(a){return(null===a||"undefined"==typeof a)&&(a=""),a=String(a),(a.indexOf('"')>=0||a.indexOf(",")>=0||/[\n\r]/.test(a))&&(a='"'+a.replace(/"/g,'""')+'"'),a}function h(a){var b,c=new j(a),d=[];if(c.nextLine())for(b=c.nextToken();!i.isUndefined(b)&&!i.isNull(b);)d.push(b),b=c.nextToken();for(var e=[];c.nextLine();){var f={};b=c.nextToken();for(var g=0;!i.isUndefined(b)&&!i.isNull(b);){var h=d[g++];f[h]=b,b=c.nextToken()}e.push(f)}return e}var i=a("underscore"),j=(a("./date"),function(a){this.text=a,this.cursor=0});j.prototype={nextToken:function(){var a,b=!1,c=this.text.charAt(this.cursor);if(""===c||"\r"===c||"\n"===c)return null;if('"'===c&&(b=!0),b){for(var d=this.cursor;;){if(d++,d=this.text.indexOf('"',d),0>d||'"'!==this.text.charAt(d+1))break;d++}if(d>=0){var e=this.text.charAt(d+1);a=this.text.substring(this.cursor,d+1),this.cursor=d+(","===e?2:1)}else a=this.text.substring(this.cursor),this.cursor=this.text.length;return a.replace(/""/g,'"').replace(/^"/,"").replace(/"$/,"")}var f=this.text.indexOf(",",this.cursor),g=this.text.indexOf("\r",this.cursor),h=this.text.indexOf("\n",this.cursor);f=0>f?this.text.length+1:f,g=0>g?this.text.length+1:g,h=0>h?this.text.length+1:h;var i=Math.min(f,g,h,this.text.length);return a=this.text.substring(this.cursor,i),this.cursor=i,f===i&&this.cursor++,a},nextLine:function(){for(var a=this.text.charAt(this.cursor);"\r"===a||"\n"===a;a=this.text.charAt(++this.cursor));return this.cursor!==this.text.length}},b.exports={toCSV:c,extractHeaders:d,recordToCSV:e,arrayToCSV:f,parseCSV:h}},{"./date":10,underscore:54}],10:[function(a,b){function c(a){return(10>a?"0":"")+a}function d(a){return function(b){return new f(a+":"+b)}}var e=a("underscore")._,f=b.exports=function(a){this._literal=a};f.prototype.toString=f.prototype.toJSON=function(){return this._literal},f.toDateLiteral=function(a){e.isNumber(a)?a=new Date(a):e.isString(a)&&(a=f.parseDate(a));var b=a.getFullYear(),d=a.getMonth()+1,g=a.getDate(),h=[b,c(d),c(g)].join("-");return new f(h)},f.toDateTimeLiteral=function(a){e.isNumber(a)?a=new Date(a):e.isString(a)&&(a=f.parseDate(a));var b=a.getUTCFullYear(),d=a.getUTCMonth()+1,g=a.getUTCDate(),h=a.getUTCHours(),i=a.getUTCMinutes(),j=a.getUTCSeconds(),k=[b,c(d),c(g)].join("-")+"T"+[c(h),c(i),c(j)].join(":")+"Z";return new f(k)},f.parseDate=function(a){var b=new Date,c=/^([\d]{4})-?([\d]{2})-?([\d]{2})(T([\d]{2}):?([\d]{2}):?([\d]{2})(.([\d]{3}))?(Z|([\+\-])([\d]{2}):?([\d]{2})))?$/,d=a.match(c);if(d){if(b=new Date(0),d[4]){if(b.setUTCFullYear(parseInt(d[1],10)),b.setUTCDate(parseInt(d[3],10)),b.setUTCMonth(parseInt(d[2],10)-1),b.setUTCHours(parseInt(d[5],10)),b.setUTCMinutes(parseInt(d[6],10)),b.setUTCSeconds(parseInt(d[7],10)),b.setUTCMilliseconds(parseInt(d[9]||"0",10)),d[10]&&"Z"!==d[10]){var e=60*parseInt(d[12],10)+parseInt(d[13],10);b.setTime(("+"===d[11]?-1:1)*e*60*1e3+b.getTime())}}else b.setFullYear(parseInt(d[1],10)),b.setDate(parseInt(d[3],10)),b.setMonth(parseInt(d[2],10)-1),b.setHours(0),b.setMinutes(0),b.setSeconds(0),b.setMilliseconds(0);return b}throw new Error("Invalid date format is specified : "+a)};var g={YESTERDAY:1,TODAY:1,TOMORROW:1,LAST_WEEK:1,THIS_WEEK:1,NEXT_WEEK:1,LAST_MONTH:1,THIS_MONTH:1,NEXT_MONTH:1,LAST_90_DAYS:1,NEXT_90_DAYS:1,LAST_N_DAYS:2,NEXT_N_DAYS:2,NEXT_N_WEEKS:2,LAST_N_WEEKS:2,NEXT_N_MONTHS:2,LAST_N_MONTHS:2,THIS_QUARTER:1,LAST_QUARTER:1,NEXT_QUARTER:1,NEXT_N_QUARTERS:2,LAST_N_QUARTERS:2,THIS_YEAR:1,LAST_YEAR:1,NEXT_YEAR:1,NEXT_N_YEARS:2,LAST_N_YEARS:2,THIS_FISCAL_QUARTER:1,LAST_FISCAL_QUARTER:1,NEXT_FISCAL_QUARTER:1,NEXT_N_FISCAL_QUARTERS:2,LAST_N_FISCAL_QUARTERS:2,THIS_FISCAL_YEAR:1,LAST_FISCAL_YEAR:1,NEXT_FISCAL_YEAR:1,NEXT_N_FISCAL_YEARS:2,LAST_N_FISCAL_YEARS:2};for(var h in g){var i=g[h];f[h]=1===i?new f(h):d(h)}},{underscore:54}],11:[function(a,b,c){c.Connection=a("./connection"),c.OAuth2=a("./oauth2"),c.Date=c.SfDate=a("./date"),c.RecordStream=a("./record-stream")},{"./connection":7,"./date":10,"./oauth2":13,"./record-stream":16}],12:[function(a,b){function c(a){return function(b){this.log(a,b)}}var d=b.exports=function(a){"string"==typeof a&&(a=e[a]),a||(a=e.INFO),this._logLevel=a},e=d.LogLevels={DEBUG:1,INFO:2,WARN:3,ERROR:4,FATAL:5};d.prototype.log=function(a,b){this._logLevel<=a&&(a<e.ERROR?console.log(b):console.error(b))};for(var f in e)d.prototype[f.toLowerCase()]=c(e[f])},{}],13:[function(a,b){var c=a("querystring"),d=a("underscore"),e=a("./transport"),f={loginUrl:"https://login.salesforce.com"},g=b.exports=function(a){a.authzServiceUrl&&a.tokenServiceUrl?(this.loginUrl=a.authzServiceUrl.split("/").slice(0,3).join("/"),this.authzServiceUrl=a.authzServiceUrl,this.tokenServiceUrl=a.tokenServiceUrl,this.revokeServiceUrl=a.revokeServiceUrl):(this.loginUrl=a.loginUrl||f.loginUrl,this.authzServiceUrl=this.loginUrl+"/services/oauth2/authorize",this.tokenServiceUrl=this.loginUrl+"/services/oauth2/token",this.revokeServiceUrl=this.loginUrl+"/services/oauth2/revoke"),this.clientId=a.clientId,this.clientSecret=a.clientSecret,this.redirectUri=a.redirectUri,this._transport=a.proxyUrl?new e.ProxyTransport(a.proxyUrl):new e};d.extend(g.prototype,{getAuthorizationUrl:function(a){return a=d.extend({response_type:"code",client_id:this.clientId,redirect_uri:this.redirectUri},a||{}),this.authzServiceUrl+(this.authzServiceUrl.indexOf("?")>=0?"&":"?")+c.stringify(a)},refreshToken:function(a,b){return this._postParams({grant_type:"refresh_token",refresh_token:a,client_id:this.clientId,client_secret:this.clientSecret},b)},requestToken:function(a,b){return this._postParams({grant_type:"authorization_code",code:a,client_id:this.clientId,client_secret:this.clientSecret,redirect_uri:this.redirectUri},b)},authenticate:function(a,b,c){return this._postParams({grant_type:"password",username:a,password:b,client_id:this.clientId,client_secret:this.clientSecret,redirect_uri:this.redirectUri},c)},revokeToken:function(a,b){return this._transport.httpRequest({method:"POST",url:this.revokeServiceUrl,body:c.stringify({token:a}),headers:{"content-type":"application/x-www-form-urlencoded"}}).then(function(a){if(a.statusCode>=400){var b=c.parse(a.body);
b&&b.error||(b={error:"ERROR_HTTP_"+a.statusCode,error_description:a.body});var d=new Error(b.error_description);throw d.name=b.error,d}}).thenCall(b)},_postParams:function(a,b){return this._transport.httpRequest({method:"POST",url:this.tokenServiceUrl,body:c.stringify(a),headers:{"content-type":"application/x-www-form-urlencoded"}}).then(function(a){var b;try{b=JSON.parse(a.body)}catch(c){}if(a.statusCode>=400){b=b||{error:"ERROR_HTTP_"+a.statusCode,error_description:a.body};var d=new Error(b.error_description);throw d.name=b.error,d}return b}).thenCall(b)}})},{"./transport":20,querystring:34,underscore:54}],14:[function(a,b){(function(c){var d=a("q"),e=a("underscore")._,f=function(a){this._promise=d(a)};f.prototype.then=function(){return new f(this._promise.then.apply(this._promise,arguments))},f.prototype.thenCall=function(a){return e.isFunction(a)&&this.then(function(b){c.nextTick(function(){a(null,b)})},function(b){c.nextTick(function(){a(b)})}),this},f.prototype.fail=function(){return new f(this._promise.fail.apply(this._promise,arguments))},f.prototype.done=function(){return new f(this._promise.done.apply(this._promise,arguments))},f.when=function(){return new f(d.when.apply(d,arguments))},f.reject=function(a){return new f(d.reject(a))},f.all=function(){return new f(d.all.apply(d,arguments))},f.defer=function(){return new g};var g=function(){this._deferred=d.defer(),this.promise=new f(this._deferred.promise)};g.prototype.resolve=function(){return this._deferred.resolve.apply(this._promise,arguments)},g.prototype.reject=function(){return this._deferred.reject.apply(this._promise,arguments)},b.exports=f}).call(this,a("_process"))},{_process:31,q:39,underscore:54}],15:[function(a,b){(function(c){var d=a("util"),e=(a("events"),a("underscore")._),f=a("q"),g=a("./promise"),h=(a("./date"),a("./soql-builder")),i=a("./record-stream"),j=b.exports=function(a,b,c){j.super_.apply(this),this.receivable=!0,this._conn=a,b&&(e.isString(b)?this._soql=b:(this._config=b,this.select(b.fields),b.includes&&this.include(b.includes))),c&&c.indexOf("/")>=0&&(c=c.split("/").pop()),this._locator=c,this._buffer=[],this._paused=!0,this._closed=!1,this._deferred=f.defer()};d.inherits(j,i),j.prototype.select=function(a){if(this._soql)throw Error("Cannot set select fields for the query which has already built SOQL.");if(a=a||"*",e.isString(a))a=a.split(/\s*,\s*/);else if(e.isObject(a)&&!e.isArray(a)){var b=[];for(var c in a)a[c]&&b.push(c);a=b}return this._config.fields=a,this},j.prototype.where=function(a){if(this._soql)throw Error("Cannot set where conditions for the query which has already built SOQL.");return this._config.conditions=a,this},j.prototype.limit=function(a){if(this._soql)throw Error("Cannot set limit for the query which has already built SOQL.");return this._config.limit=a,this},j.prototype.skip=j.prototype.offset=function(a){if(this._soql)throw Error("Cannot set skip/offset for the query which has already built SOQL.");return this._config.offset=a,this},j.prototype.sort=j.prototype.orderby=function(a,b){if(this._soql)throw Error("Cannot set sort for the query which has already built SOQL.");return e.isString(a)&&e.isString(b)&&(a=[[a,b]]),this._config.sort=a,this},j.prototype.include=function(a,b,c,d){if(this._soql)throw Error("Cannot include child relationship into the query which has already built SOQL.");{if(!e.isObject(a)){var f={table:a,conditions:b,fields:c,limit:d&&d.limit,offset:d&&(d.offset||d.skip)};this._config.includes=this._config.includes||[],this._config.includes.push(f);var g=new l(this._conn,this,f);return this._children=this._children||[],this._children.push(g),g}var h=a;for(var i in h){var j=h[i];this.include(i,j.conditions,j.fields,j)}}},j.prototype._maxFetch=1e4,j.prototype.maxFetch=function(a){return this._maxFetch=a,this},j.prototype._autoFetch=!1,j.prototype.autoFetch=function(a){return this._autoFetch=a,this},j.prototype._scanAll=!1,j.prototype.scanAll=function(a){return this._scanAll=a,this};var k=j.ResponseTargets={};["QueryResult","Records","SingleRecord","Count"].forEach(function(a){k[a]=a}),j.prototype._responseTarget=k.QueryResult,j.prototype.setResponseTarget=function(a){return a in k&&(this._responseTarget=a),this},j.prototype.pause=function(){this._paused=!0},j.prototype.resume=function(){if(this._closed)throw new Error("resuming already closed stream");if(this._paused){for(this._paused=!1;!this._paused&&this._buffer.length>0;){if(this.totalFetched>=this._maxFetch)return void this.close();var a=this._buffer.shift();this.emit("record",a,this.totalFetched++,this)}this._paused||(this._finished?this.close():this.execute({autoFetch:!0}))}},j.prototype.close=function(){this.pause(),this._closed=!0,this.emit("end",this)},j.prototype.run=j.prototype.exec=j.prototype.execute=function(a,b){var c=this,d=this._conn._logger,f=this._deferred;if(this._closed)return f.reject(new Error("executing already closed query")),this;this._paused=!1,"function"==typeof a&&(b=a,a={}),a=a||{},a={responseTarget:a.responseTarget||c._responseTarget,autoFetch:a.autoFetch||c._autoFetch,maxFetch:a.maxFetch||c._maxFetch,scanAll:a.scanAll||c._scanAll};var g=function(a,c){if(e.isFunction(b))try{c=b(a,c),a=null}catch(d){a=d}a?f.reject(a):f.resolve(c)};return this.once("response",function(a){g(null,a)}),this.once("error",function(a){g(a)}),this.once("fetch",function(){if(a.responseTarget===k.Records&&(c._chaining||b)){d.debug("--- collecting all fetched records ---");var e=[],f=function(a){e.push(a)};c.on("record",f),c.once("end",function(){c.removeListener("record",f),c.emit("response",e,c)})}}),d.debug(">>> Query start >>>"),this._execute(a).then(function(){d.debug("*** Query finished ***")}).fail(function(a){d.debug("--- Query error ---"),c.emit("error",a)}),this},j.prototype._execute=function(a){var b=this,c=this._conn._logger,d=a.responseTarget,e=a.autoFetch,f=a.maxFetch,i=a.scanAll;return new g(b._locator?b._conn._baseUrl()+"/query/"+b._locator:new g(b._soql||b._expandFields().then(function(){return h.createSOQL(b._config)})).then(function(a){return b.totalFetched=0,c.debug("SOQL = "+a),b._conn._baseUrl()+"/"+(i?"queryAll":"query")+"?q="+encodeURIComponent(a)})).then(function(a){return b._conn._request(a)}).then(function(c){b.emit("fetch"),b.totalSize=c.totalSize;var g;switch(d){case k.SingleRecord:g=c.records&&c.records.length>0?c.records[0]:null;break;case k.Records:g=c.records;break;case k.Count:g=c.totalSize;break;default:g=c}d!==k.Records&&b.emit("response",g,b);for(var h=0,i=c.records.length;i>h;h++){if(b.totalFetched>=f){b._finished=!0;break}var j=c.records[h];b._paused?b._buffer.push(j):b.emit("record",j,b.totalFetched++,b)}if(b._finished=b._finished||c.done,c.nextRecordsUrl&&(b._locator=c.nextRecordsUrl.split("/").pop()),e&&!b._finished){if(!b._paused)return b._execute(a)}else b._paused||b.close();return g})},j.prototype._expandFields=function(){function a(a){var c=d._parent._config.table;return f.debug('finding table for relation "'+a+'" in "'+c+'"...'),b(c).then(function(b){var c=a.toUpperCase(),d=e.find(b.childRelationships,function(a){return(a.relationshipName||"").toUpperCase()===c});return d?d.childSObject:g.reject(new Error("No child relationship found: "+a))})}function b(a){f.debug("describe cache: "+a);var b=g.defer();return h.describe$(a,function(a,c){f.debug("... done."),a?b.reject(a):b.resolve(c)}),b.promise}function c(a,d){f.debug('expanding field "'+d+'" in "'+a+'"...');var h=d.split(".");return"*"===h[h.length-1]?b(a).then(function(b){if(f.debug("table "+a+"has been described"),h.length>1){var d=h.shift(),g=e.find(b.fields,function(a){return a.relationshipName&&a.relationshipName.toUpperCase()===d.toUpperCase()});if(g){var i=1===g.referenceTo.length?g.referenceTo[0]:"Name";return c(i,h.join(".")).then(function(a){return e.map(a,function(a){return d+"."+a})})}return[]}return e.map(b.fields,function(a){return a.name})}):new g([d])}if(this._soql)return g.reject(new Error("Cannot expand fields for the query which has already built SOQL."));var d=this,f=d._conn._logger,h=this._conn,i=this._config.table,j=this._config.fields||[];return f.debug("_expandFields: table = "+i+", fields = "+j.join(", ")),g.all([new g(d._parent?a(i):i).then(function(a){return g.all(e.map(j,function(b){return c(a,b)})).then(function(a){d._config.fields=e.flatten(a)})}),g.all(e.map(d._children||[],function(a){return a._expandFields()}))])},j.prototype.pipe=function(){var a=i.prototype.pipe.apply(this,arguments);return this.resume(),a},j.prototype["delete"]=j.prototype.del=j.prototype.destroy=function(a,b){if("function"==typeof a&&(b=a,a=null),a=a||this._config&&this._config.table,!a)throw new Error("SOQL based query needs SObject type information to bulk delete.");return this.pipe(this._conn.sobject(a).deleteBulk(b))},j.prototype.update=function(a,b,c){if("function"==typeof b&&(c=b,b=null),b=b||this._config&&this._config.table,!b)throw new Error("SOQL based query needs SObject type information to bulk update.");var d=e.isFunction(a)?i.map(a):i.recordMapStream(a);return this.pipe(d).pipe(this._conn.sobject(b).updateBulk(c))},j.prototype.then=function(){return this._chaining=!0,!this._closed&&this._paused&&this.execute(),this._deferred.promise.then.apply(this._deferred.promise,arguments)},j.prototype.thenCall=function(a){return e.isFunction(a)&&this.then(function(b){c.nextTick(function(){a(null,b)})},function(b){c.nextTick(function(){a(b)})}),this};var l=function(a,b,c){l.super_.call(this,a,c),this._parent=b};d.inherits(l,j),l.prototype.include=function(){throw new Error("Not allowed to include another subquery in subquery.")},l.prototype.end=function(){return this._parent},l.prototype.run=l.prototype.exec=l.prototype.execute=function(){return this._parent.execute.apply(this._parent,arguments)}}).call(this,a("_process"))},{"./date":10,"./promise":14,"./record-stream":16,"./soql-builder":19,_process:31,events:29,q:39,underscore:54,util:38}],16:[function(a,b){var c=a("events"),d=a("stream"),e=d.PassThrough,f=a("util"),g=a("underscore"),h=a("./csv"),i=b.exports=function(){this.sendable=!1,this.receivable=!1,this.on("error",function(){this.sendable=!1,this.receivable=!1}),this.on("end",function(){this.receivable=!1})};f.inherits(i,c.EventEmitter),i.prototype.send=function(){},i.prototype.end=function(){this.sendable=!1},i.prototype.destroy=function(){this.reciebable=!1,this.sendable=!1},i.prototype.destroySoon=function(){},i.prototype.pause=function(){},i.prototype.resume=function(){},i.prototype.pipe=function(a,b){var c=this,d=function(b){a.send&&!1===a.send(b)&&c.pause()};c.on("record",d);var e=function(){c.resume()};a.on("drain",e);var f=!1,g=function(){f||(f=!0,a.end())},h=function(){f||(f=!0,"function"==typeof a.destroy&&a.destroy())};b&&b.end===!1||(c.on("end",g),c.on("close",h));var i=function(a){if(j(),0===this.listeners("error").length)throw a};c.on("error",i),a.on("error",i);var j=function(){c.removeListener("record",d),a.removeListener("drain",e),c.removeListener("end",g),c.removeListener("close",h),c.removeListener("error",i),a.removeListener("error",i),c.removeListener("end",j),c.removeListener("close",j),a.removeListener("end",j),a.removeListener("close",j)};return c.on("end",j),c.on("close",j),a.on("end",j),a.on("close",j),a.emit("pipe",c),a},i.prototype.map=function(a){return this.pipe(i.map(a))},i.prototype.filter=function(a){return this.pipe(i.filter(a))},i.prototype.stream=function(a){a=a||"csv";var b;if("csv"===a&&(b=new i.CSVStream),!b)throw new Error("No stream type defined for '"+a+"'.");return this.receivable?this.pipe(b):this.sendable&&b.pipe(this),b.stream()},i.map=function(a){var b=new i;return b.receivable=!0,b.send=function(b){var c=a(b)||b;this.emit("record",c)},b.end=function(){this.emit("end")},b},i.recordMapStream=function(a,b){function c(a,b){if(g.isString(a)){var c=/^\$\{(\w+)\}$/.exec(a);return c?b[c[1]]:a.replace(/\$\{(\w+)\}/g,function(a,c){var d=b[c];return g.isNull(d)||g.isUndefined(d)?"":String(d)})}return a}return i.map(function(d){var e={Id:d.Id};for(var f in a)e[f]=b?a[f]:c(a[f],d);return e})},i.filter=function(a){var b=new i;return b.receivable=!0,b.send=function(b){a(b)&&this.emit("record",b)},b.end=function(){this.emit("end")},b};var j=i.CSVStream=function(a,b){a=a||{},this.headers=a.headers,this.nullValue=a.nullValue,this.wroteHeaders=!1,this.sendable=!0,this.receivable=!0,this._stream=b||new e,this._buffer=[];var c=this;this._stream.on("data",function(a){c._handleData(a)}),this._stream.on("end",function(a){c._handleEnd(a)})};f.inherits(j,i),j.prototype.send=function(a){this.sendable=!1,this.wroteHeaders||(this.headers||(this.headers=h.extractHeaders([a])),this._stream.emit("data",h.arrayToCSV(this.headers)+"\n"),this.wroteHeaders=!0),this._stream.emit("data",h.recordToCSV(a,this.headers,{nullValue:this.nullValue})+"\n")},j.prototype.end=function(a){a&&this.send(a),this.sendable=!1,this.receivable=!1,this._stream.emit("end")},j.prototype._handleData=function(a,b){this.sendable&&this._buffer.push([a,b])},j.prototype._handleEnd=function(a,b){if(this.sendable&&0!==this.listeners("record").length){a&&this._buffer.push([a,b]),a=this._buffer.map(function(a){return a[0].toString(a[1]||"utf-8")}).join("");var c=h.parseCSV(a);c.forEach(function(a){this.emit("record",a)},this),this.emit("end")}},j.prototype.stream=function(){return this._stream}},{"./csv":9,events:29,stream:35,underscore:54,util:38}],17:[function(a,b){var c=a("underscore")._,d=b.exports=function(a,b,c){this._conn=a,this.type=b,this.id=c};d.prototype.retrieve=function(a,b){return"function"==typeof a&&(b=a,a={}),this._conn.retrieve(this.type,this.id,a,b)},d.prototype.update=function(a,b,d){return"function"==typeof b&&(d=b,b={}),a=c.clone(a),a.Id=this.id,this._conn.update(this.type,a,b,d)},d.prototype["delete"]=d.prototype.del=d.prototype.destroy=function(a,b){return"function"==typeof a&&(b=a,a={}),this._conn.destroy(this.type,this.id,a,b)},d.prototype.blob=function(a){var b=[this._conn._baseUrl(),"sobjects",this.type,this.id,a].join("/");return this._conn._request(b).stream()}},{underscore:54}],18:[function(a,b){var c=a("underscore"),d=a("./record"),e=a("./query"),f=(a("./cache"),b.exports=function(a,b){this._conn=a,this.type=b;var c={key:"describe."+this.type};this.describe$=a.cache.makeCacheable(this.describe,this,c),this.describe=a.cache.makeResponseCacheable(this.describe,this,c)});f.prototype.insert=f.prototype.create=function(a,b,c){return"function"==typeof b&&(c=b,b={}),this._conn.create(this.type,a,b,c)},f.prototype.retrieve=function(a,b,c){return"function"==typeof b&&(c=b,b={}),this._conn.retrieve(this.type,a,b,c)},f.prototype.update=function(a,b,c){return"function"==typeof b&&(c=b,b={}),this._conn.update(this.type,a,b,c)},f.prototype.upsert=function(a,b,c,d){return"function"==typeof c&&(d=c,c={}),this._conn.upsert(this.type,a,b,c,d)},f.prototype["delete"]=f.prototype.del=f.prototype.destroy=function(a,b,c){return"function"==typeof b&&(c=b,b={}),this._conn.destroy(this.type,a,b,c)},f.prototype.describe=function(a){return this._conn.describe(this.type,a)},f.prototype.record=function(a){return new d(this._conn,this.type,a)},f.prototype.find=function(a,b,c,d){"function"==typeof a?(d=a,a={},b=null,c=null):"function"==typeof b?(d=b,b=null,c=null):"function"==typeof c&&(d=c,c=null),c=c||{};var f={fields:b,includes:c.includes,table:this.type,conditions:a,limit:c.limit,offset:c.offset||c.skip},g=new e(this._conn,f);return g.setResponseTarget(e.ResponseTargets.Records),d&&g.run(d),g},f.prototype.findOne=function(a,b,d,f){"function"==typeof a?(f=a,a={},b=null,d=null):"function"==typeof b?(f=b,b=null,d=null):"function"==typeof d&&(f=d,d=null),d=c.extend(d||{},{limit:1});var g=this.find(a,b,d);return g.setResponseTarget(e.ResponseTargets.SingleRecord),f&&g.run(f),g},f.prototype.select=function(a,b){return this.find(null,a,null,b)},f.prototype.count=function(a,b){"function"==typeof a&&(b=a,a={});var c=this.find(a,{"count()":!0});return c.setResponseTarget("Count"),b&&c.run(b),c},f.prototype.bulkload=function(a,b,c,d){return this._conn.bulk.load(this.type,a,b,c,d)},f.prototype.insertBulk=f.prototype.createBulk=function(a,b){return this.bulkload("insert",a,b)},f.prototype.updateBulk=function(a,b){return this.bulkload("update",a,b)},f.prototype.upsertBulk=function(a,b,c){return this.bulkload("upsert",{extIdField:b},a,c)},f.prototype.deleteBulk=f.prototype.destroyBulk=function(a,b){return this.bulkload("delete",a,b)},f.prototype.deleteHardBulk=f.prototype.destroyHardBulk=function(a,b){return this.bulkload("hardDelete",a,b)},f.prototype.recent=function(a){return this._conn.recent(this.type,a)},f.prototype.updated=function(a,b,c){return this._conn.updated(this.type,a,b,c)},f.prototype.deleted=function(a,b,c){return this._conn.deleted(this.type,a,b,c)}},{"./cache":6,"./query":15,"./record":17,underscore:54}],19:[function(a,b,c){function d(a){var b=["SELECT ",e(a.fields,a.includes)," FROM ",a.table].join(""),c=f(a.conditions);c&&(b+=" WHERE "+c);var d=k(a.sort);return d&&(b+=" ORDER BY "+d),a.limit&&(b+=" LIMIT "+a.limit),a.offset&&(b+=" OFFSET "+a.offset),b}function e(a,b){return b=l.map(l.values(b||{}),function(a){return"("+d(a)+")"}),(a||["Id"]).concat(b).join(", ")}function f(a,b,c){if(l.isString(a))return a;a=a||[],b=b||"AND",c=c||0,a=j(a)?a.map(function(a){var b=[];for(var c in a)b.push({key:c,value:a[c]});return b.length>1?b:b[0]}):l.keys(a).map(function(b){return{key:b,value:a[b]}}),a=a.map(function(d){var e,h=c+1;switch(d.key){case"$or":case"$and":case"$not":return"NOT"!==b&&1===a.length&&(h=c),e="$or"===d.key?"OR":"$and"===d.key?"AND":"NOT",f(d.value,e,h);default:return g(d.key,d.value)}}).filter(function(a){return a});var d;return"NOT"===b?(d=c>0,(d?"(":"")+"NOT "+a[0]+(d?")":"")):(d=c>0&&a.length>1,(d?"(":"")+a.join(" "+b+" ")+(d?")":""))}function g(a,b){var c="$eq";if(l.isArray(b))c="$in";else if(l.isObject(b)){for(var d in b)if("$"===d[0]){c=d,b