Code coverage report for ./fogbugz.js

Statements: 67.05% (234 / 349)      Branches: 50.85% (90 / 177)      Functions: 67.44% (58 / 86)      Lines: 67.05% (234 / 349)      Ignored: none     

All files » ./ » fogbugz.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972  1   1 1 1   1       1                                               1 1 1 1 11     1               1   19 19   1       1 2 2 2   1 2 2 2 2 2       1 2     2     1     1   1 36 36 67       1 40     1 19   19   19 19       19 19       19     1 19 19 19 1 1 18 1 17 2 2     2     2   15     19     1 19 19         1     1 15 15 28 28 28 5   23 23       10     1 25     1   155 155 25 130 55 55 75   14   61     1 156 156 1   155   156     1           1 153 156 156     156   156 32     153       1 36 37 180 180 180 153 153 153 32   27 2   25   148 148 148   37       1                                   1                                                                                         1   1 3                   1                                   1                                 1                         1               1                         1                                   1                                                                                             3                                                                                                               2           2           1   3 4   1 1     1 1                 1   24 1   23 2         21           21 16       21 21 21   21   1   12 12     1 1 1         1 9       1 145 145 8 8 8   8         1 5 5 5 13 13 13 9 9     5       1 3     3 1     1 2 2 2 2 2 2             2   2 2     2         1             1 2     1                                       1         1         1                                                       1                       12           1                             1         1             1         1         1                     1         1         1       1                                                       1     1       12         1                                                     1 1     1                                                                                                                                   2           21 12 1   11       9 9 9 2   7 2     5 1         1                     1 1      
// based on http://help.fogcreek.com/8202/xml-api
(function(){
 
	var extend, defer, promise, request, xml2js, parallel;
	var env = 'browser';
	Iif (typeof module !== 'undefined') {
		env = 'node';
	} else Iif (typeof Meteor !== 'undefined' && Meteor.isServer) {
		env = 'meteor';
	}
 
	switch (env){
		case 'node': {
			console.log('fogbugz.js: running in node environment');
			request = require('request');
			xml2js = require('xml2js');
			var Q = require('q');
			extend = require('underscore').extend;
			defer = Q.defer;
			promise = Q;
			parallel = require('async').parallel;
		}
		break;
		case 'meteor': {
			console.log('fogbugz.js: running in meteor environment');
			request = Npm.require('request');
			xml2js = Npm.require('xml2js');
			var q = Npm.require('q');
			extend = Npm.require('underscore').extend;
			defer = q.defer;
			promise = q;
			parallel = Npm.require('async').parallel;
		}
		break;
		default: {
			console.log('fogbugz.js: running in browser environment');
			extend = $.extend;
			defer = $.Deferred;
			promise = function(value){
				return $.Deferred().resolve(value).promise();
			};
			// TODO ensure that body is string not document object
			request = function(url, callback){
				$.get(url).done(function(body, status, xhr){
					callback(null, xhr.response, body);
				}).fail(function(err){
					callback(err, null, null);
				});
			};
			// requires jQuery-xml2json to be included before fogbugz.js script
			xml2js = {
				parseString: function(xml, cb) {
					try {
						cb(null, $.xml2json(xml));
					} catch (err) {
						cb(err, null);
					}
				}
			};
			parallel = function(funcs, callback){
				var count = 0;
				var result = [];
				var error = null;
 
				function done(err,res){
					count++;
					result.push(res);
					error = error || err;
					Eif (count === funcs.length){
						callback(error, result);
					}
				}
 
				function run(fn){
					fn(done);
				}
 
				funcs.forEach(run);
			};
		}
		break;
	}
 
	var log = false;
 
	function format(f) {
		var args = [].slice.call(arguments, 1);
		return f.replace(/\{(\d+)\}/g, function(match, i) {
			return typeof args[i] !== 'undefined' ? args[i] : "";
		});
	}
 
	function defer_promise(d){
		return typeof d.promise === 'function' ? d.promise() : d.promise;
	}
 
	function getUrl(url) {
		log && console.log("GET %s", url);
 
		var d = defer();
 
		request(url, function(err, res, body) {
			Iif (err) {
				log && console.log(err);
				d.reject(err);
			} else {
				log && console.log(body);
				d.resolve(body);
			}
		});
 
		return defer_promise(d);
	}
 
	function parseXml(xml) {
		var d = defer();
		xml2js.parseString(xml, function(err, obj) {
			if (err) {
				log && console.log(err);
				d.reject(err);
			} else if (!obj.response) {
				d.reject("unexpected response");
			} else if (obj.response.error) {
				err = obj.response.error;
				Iif (Array.isArray(err)) {
					err = err[0];
				}
				Iif (err._) {
					err = err._;
				}
				d.reject(err);
			} else {
				d.resolve(obj.response);
			}
		});
		return defer_promise(d);
	}
 
	function get() {
		var url = format.apply(null, [].slice.call(arguments));
		return getUrl(url).then(parseXml);
	}
 
	// converters from FogBugz XMLJS payloads to plain JS objects
 
	var convert = (function(){
 
		// resolves xmljs array
		function getarr(d) {
			var arr = [d];
			for (var i = 1; i < arguments.length; i++) {
				var p = arguments[i];
				var v = arr[0][p];
				if (v === null || v === undefined) {
					return [];
				}
				arr = Array.isArray(v) ? v : [v];
				Iif (arr.length === 0) {
					return [];
				}
			}
			return arr;
		}
 
		function bool(x) {
			return typeof x === "string" ? x.toLowerCase() === 'true' : !!x;
		}
 
		function parse(key, val) {
			// unwrap array
			var v = Array.isArray(val) ? val[0] : val;
			if (/^f.+$/.test(key)) {
				return bool(v);
			} else if (/^[in].+$/.test(key)) {
				var i = parseInt(v, 10);
				return isNaN(i) ? v : i;
			} else if (/^dt.*$/.test(key)) {
				// TODO handle invalid dates
				return new Date(v);
			}
			return v;
		}
 
		function get(obj, key) {
			var v;
			if (/^.+\[]$/.test(key)) {
				v = obj[key.substr(0, key.length - 2)] || [];
			} else {
				v = parse(key, obj[key]);
			}
			return v;
		}
 
		function mapget(arr, name) {
			return arr.map(function(x) {
				return get(x, name);
			});
		}
 
		function evalchain(chain, it) {
			for (var i = 0; i < chain.length; i++) {
				var name = chain[i];
				Iif (Array.isArray(it)) {
					it = mapget(it, name);
				} else {
					it = get(it, name);
				}
				if (it === null || it === undefined) {
					break;
				}
			}
			return it;
		}
 
		// creates convertion function from given schema
		function use(schema) {
			return function(it) {
				var props = Object.keys(schema).map(function(key) {
					var p = schema[key];
					var v;
					if (typeof p === "string") {
						var chain = p.split('.');
						v = evalchain(chain, it);
						if (v === null || v === undefined) {
							return {};
						}
					} else if (typeof p === 'function') {
						v = p(it);
					} else {
						v = use(p)(it);
					}
					var obj = {};
					obj[key] = v;
					return obj;
				});
				return extend.apply(null, props);
			};
		}
 
		var person = use({
			id: 'ixPerson',
			name: 'sFullName',
			email: 'sEmail',
			phone: 'sPhone',
			admin: 'fAdministrator',
			community: 'fCommunity',
			virtual: 'fVirtual',
			deleted: 'fDeleted',
			notify: 'fNotify',
			expert: 'fExpert',
			homepage: 'sHomepage',
			locale: 'sLocale',
			language: 'sLanguage',
			workingOn: 'ixBugWorkingOn',
			timeZoneKey: 'sTimeZoneKey'
		});
 
		var event = use({
			id: 'ixBugEvent',
			date: 'dt',
			verb: 'sVerb',
			description: 'evtDescription',
			person: {
				id: 'ixPerson',
				name: 'sPerson'
			},
			assignee: 'ixPersonAssignedTo',
			format: 'sFormat',
			text: 's',
			changes: 'sChanges',
			html: function(it){
				var val = it.sHTML || it.sHtml;
				if (!val) {
					return undefined;
				}
				if (Array.isArray(val)){
					val = val[0];
				}
				if (typeof val === 'string'){
					return val;
				}
				if (typeof val._ === 'string'){
					return val._;
				}
				return undefined;
			},
			isHtml: 'fHTML',
			isExternal: 'fExternal',
			isEmail: 'fEmail',
			message: {
				from: 'sFrom',
				to: 'sTo',
				cc: 'sCC',
				bcc: 'sBCC',
				replyTo: 'sReplyTo',
				subject: 'sSubject',
				date: 'sDate',
				bodyText: 'sBodyText',
				bodyHTML: 'sBodyHTML'
			}
		});
 
		return {
			filters: function(d) {
				return getarr(d, 'filters', 'filter').map(function(it) {
					return {
						id: it.$.sFilter,
						name: it._,
						type: it.$.type,
						status: it.$.status
					};
				});
			},
 
			projects: function(d) {
				return getarr(d, 'projects', 'project').map(use({
					id: 'ixProject',
					name: 'sProject',
					owner: {
						id: 'ixPersonOwner',
						name: 'sPersonOwner'
					},
					email: 'sEmail',
					phone: 'sPhone',
					workflowId: 'ixWorkflow',
					deleted: 'fDeleted',
					inbox: 'fInbox',
					type: 'iType',
					group: 'sGroup'
				}));
			},
 
			areas: function(d) {
				return getarr(d, 'areas', 'area').map(use({
					id: 'ixArea',
					name: 'sArea',
					project: {
						id: 'ixProject',
						name: 'sProject'
					},
					owner: {
						id: 'ixPersonOwner',
						name: 'sPersonOwner'
					},
					type: 'nType',
					doc: 'cDoc'
				}));
			},
 
			categories: function(d) {
				return getarr(d, 'categories', 'category').map(use({
					id: 'ixCategory',
					name: 'sCategory',
					plural: 'sPlural',
					on: {
						resolve: 'ixStatusDefault',
						open: 'ixStatusDefaultActive'
					},
					isScheduleItem: 'fIsScheduleItem'
				}));
			},
 
			priorities: function(d) {
				return getarr(d, 'priorities', 'priority').map(use({
					id: 'ixPriority',
					name: 'sPriority',
					isDefault: 'fDefault'
				}));
			},
 
			statuses: function(d) {
				return getarr(d, 'statuses', 'status').map(use({
					id: 'ixStatus',
					name: 'sStatus',
					category: 'ixCategory',
					isResolved: 'fResolved',
					isDuplicate: 'fDuplicate',
					isDeleted: 'fDeleted',
					workDone: 'fWorkDone',
					order: 'iOrder'
				}));
			},
 
			milestones: function(d) {
				return getarr(d, 'fixfors', 'fixfor').map(use({
					id: 'ixFixFor',
					name: 'sFixFor',
					project: {
						id: 'ixProject',
						name: 'sProject'
					},
					deleted: 'fDeleted',
					start: 'dtStart',
					end: 'dt',
					startNote: 'sStartNote'
				}));
			},
 
			person: function(d) {
				return getarr(d, 'person').map(person)[0];
			},
			people: function(d) {
				return getarr(d, 'people', 'person').map(person);
			},
 
			searchCols: [
				'ixBug',
				'ixStatus',
				'sStatus',
				'ixPersonAssignedTo',
				'sPersonAssignedTo',
				'sEmailAssignedTo',
				'ixPersonOpenedBy',
				'ixPersonResolvedBy',
				'ixBugParent',
				'ixBugChildren',
				'ixBugDuplicates',
				'ixBugOriginal',
				'sTitle',
				'ixPriority',
				'sPriority',
				'ixCategory',
				'sCategory',
				'ixFixFor',
				'sFixFor',
				'sVersion',
				'sComputer',
				'sTicket',
				'sLatestTextSummary',
				'fOpen',
				'tags',
				'ixProject',
				'sProject',
				'ixArea',
				'sArea',
				'fSubscribed',
				// TODO provide a way to configure this behavior
				// exclude events since fogbugz could fail with runtime error
				// on large number of cases (e.g. large product backlog)
				// 'events',
				// dates
				'dtOpened',
				'dtResolved',
				'dtClosed',
				'dtDue',
				'dtFixFor'
			].join(','),
 
			cases: function(d) {
				return getarr(d, 'cases', 'case').map(use({
					id: 'ixBug',
					status: {
						id: 'ixStatus',
						name: 'sStatus'
					},
					operations: '$.operations',
					opened: 'dtOpened',
					resolved: 'dtResolved',
					closed: 'dtClosed',
					due: 'dtDue',
					assignee: {
						id: 'ixPersonAssignedTo',
						name: 'sPersonAssignedTo',
						email: 'sEmailAssignedTo'
					},
					openedBy: {
						id: 'ixPersonOpenedBy'
					},
					resolvedBy: {
						id: 'ixPersonResolvedBy'
					},
					parentId: 'ixBugParent',
					originalId: 'ixBugOriginal',
					children: 'ixBugChildren',
					duplicates: 'ixBugDuplicates',
					title: 'sTitle',
					priority: {
						id: 'ixPriority',
						name: 'sPriority'
					},
					category: {
						id: 'ixCategory',
						name: 'sCategory'
					},
					project: {
						id: 'ixProject',
						name: 'sProject'
					},
					area: {
						id: 'ixArea',
						name: 'sArea'
					},
					milestone: {
						id: 'ixFixFor',
						name: 'sFixFor',
						end: 'dtFixFor'
					},
					version: 'sVersion',
					computer: 'sComputer',
					ticket: 'sTicket',
					latestSummary: 'sLatestTextSummary',
					isOpen: 'fOpen',
					isSubscribed: 'fSubscribed',
					tags: 'tags.tag[]',
					events: function(it) {
						return getarr(it, 'events', 'event').map(event);
					}
				}));
			},
 
			events: function(d) {
				return getarr(d, 'cases', 'case', 'events', 'event').map(event);
			}
		};
	})();
 
	// extend functions for fogbugz objects
	var fn = {
		milestone: function(fb) {
			return function(it) {
				return extend(it, {
					cases: function() {
						var q = "";
						Iif (it.project && it.project.name){
							q += 'project:"' + it.project.name + '" AND ';
						}
						q += 'fixfor:"' + it.name + '"';
						return fb.search(q);
					}
				});
			};
		}
	};
 
	// TODO verify api token
	// creates new client with specified options
	function fogbugz(options) {
 
		if (!options) {
			throw new Error("Options are not specified.");
		}
		if (!options.url || typeof options.url !== "string") {
			throw new Error("Required url option is not specified.");
		}
 
		// TODO verbose flag per client
		// use only for dev purposes!
		Iif (!!options.verbose){
			log = true;
		}
 
		// TODO if DEBUG only for testing purposes
		// allow to replace request module for testing purposes
		if (options.request){
			request = options.request;
		}
 
		// normalize url
		var apiUrl = options.url;
		Eif (apiUrl.charAt(apiUrl.length - 1) !== '/') {
			apiUrl += '/';
		}
		apiUrl += 'api.asp?';
 
		function client(token) {
 
			var clientUrl = format("{0}token={1}&", apiUrl, token);
			var fb;
 
			// returns function which map array elements with given function
			function map(fn) {
				return function(arr) {
					return arr.map(fn);
				};
			}
 
			// runs simple command without arguments
			function simpleCmd(name) {
				return get("{0}cmd={1}", clientUrl, name);
			}
 
			// runs list command
			function list(name) {
				var fns = [].slice.call(arguments, 1);
				return function() {
					var p = simpleCmd("list" + name);
					fns.forEach(function(fn) {
						p = p.then(fn);
					});
					return p;
				};
			}
 
			// performs given command with specified arguments
			function cmd(name) {
				var url = format("{0}cmd={1}&", clientUrl, name);
				var i = 1;
				while (i + 1 < arguments.length) {
					var arg = arguments[i++];
					var val = arguments[i++];
					if (val) {
						url += "&" + arg;
						url += "=" + encodeURIComponent(String(val));
					}
				}
				return get(url);
			}
 
			// runs search command
			function search(q, max, withoutEvents) {
				return cmd("search", "q", q, "max", max, "cols", convert.searchCols)
					.then(convert.cases)
					.then(function(list){
						if (withoutEvents){
							return list;
						}
 
						function fetchFn(i){
							var item = i;
							return function(cb){
								events(item.id).then(function(eventList){
									item.events = eventList;
									cb(null, item);
									return item;
								}).fail(function(err){
									cb(err, null);
								});
							};
						}
 
						var d = defer();
 
						parallel(list.map(fetchFn), function(){
							d.resolve(list);
						});
 
						return defer_promise(d);
					});
			}
 
			// fetch case details by given case number
			function caseInfo(id){
				return search("ixBug:" + id).then(function(list){
					return list.length === 0 ? null : list[0];
				});
			}
 
			// fetch events of given case
			function events(id) {
				return cmd("search", "q", "ixBug:" + id, "cols", "events").then(convert.events);
			}
 
			function caseCmd(cmdname, data) {
				var userArg = isNaN(parseInt(data.user, 10)) ? "sPersonAssignedTo" : "ixPersonAssignedTo";
				var statusArg = isNaN(parseInt(data.status, 10)) ? "sStatus" : "ixStatus";
				return cmd(cmdname,
						"ixBug", data.id,
						"sTitle", data.title,
						"sProject", data.project,  // TODO id or name
						"sArea", data.area,  // TODO id or name
						"sFixFor", data.milestone, // TODO id or name
						"sCategory", data.category, // TODO map categories
						userArg, data.user,
						statusArg, data.status,
						"sPriority", data.priority, // TODO id or name
						"sTags", data.tags,
						"sCustomerEmail", data.customerEmail,
						"sEvent", data.comment
				);
			}
 
			// creates new case with given info
			function create(info) {
				return caseCmd("new", info);
			}
 
			// edits specified case
			function edit(info) {
				return caseCmd("edit", info);
			}
 
			// adds comment to specified case
			function comment(opts, text, format) {
 
				var id;
 
				// allow to pass options as first argument
				if (typeof opts === 'object'){
					id = opts.id;
					text = opts.text || opts.comment || opts.message;
					format = opts.format || '';
				} else {
					id = opts;
					format = format || '';
				}
 
				// check required options
				if (!id) {
					throw new Error("case number is not specified");
				}
				if (!text) {
					throw new Error("comment is not specified");
				}
 
				// TODO how to post comment in specified format?
 
				return edit({id: id, comment: text, format: format});
			}
 
			// assigns given case to specified command with optional comment
			function assign(id, user, comment) {
				if (!id) {
					throw new Error("case number is not specified");
				}
				if (!user) {
					throw new Error("user is not specified");
				}
				var userArg = isNaN(parseInt(user, 10)) ? "sPersonAssignedTo" : "ixPersonAssignedTo";
				return cmd("assign", "ixBug", id, userArg, user, "sEvent", comment);
			}
 
			// internal API for extenders
			fb = {
				search: search,
				events: events
			};
 
			// fetch user info for given user id/email
			function userInfo(user) {
				if (user || user.id || user.email) {
					if (user.id) {
						return cmd("viewPerson", "ixPerson", user.id).then(convert.person);
					}
					if (user.email) {
						return cmd("viewPerson", "sEmail", user.email).then(convert.person);
					}
					var userArg = isNaN(parseInt(user, 10)) ? "ixPerson" : "sEmail";
					return cmd("viewPerson", userArg, user).then(convert.person);
				}
				return simpleCmd("viewPerson").then(convert.person);
			}
 
			// resolves info about currently logon user
			function currentUser() {
				return userInfo();
			}
 
			// assign given case to current user with optional comment
			function take(id, comment) {
				return currentUser().then(function(user) {
					return assign(id, user.id, comment);
				});
			}
 
			// closes given case with optional comment
			function close(id, comment) {
				return cmd("close", "ixBug", id, "sEvent", comment);
			}
 
			// reopens given case with optional comment
			function reopen(id, comment) {
				return cmd("reopen", "ixBug", id, "sEvent", comment);
			}
 
			// resolves specified case
			function resolve(data) {
				var userArg = isNaN(parseInt(data.user, 10)) ? "sPersonAssignedTo" : "ixPersonAssignedTo";
				var statusArg = isNaN(parseInt(data.status, 10)) ? "sStatus" : "ixStatus";
				return cmd("resolve",
						"ixBug", data.id,
						statusArg, data.status,
						userArg, data.user,
						"sEvent", data.comment);
			}
 
			// fetch user settings
			function userSettings(){
				return simpleCmd('viewSettings');
			}
 
			// start working on this case and charge time to it (start the stopwatch)
			function startWork(id){
				return cmd("startWork", "ixBug", id);
			}
 
			// stop working on everything (stop the stopwatch)
			function stopWork(){
				return simpleCmd("stopWork");
			}
 
			function starImpl(cmdname, id, type){
				type = type || 'bug';
				switch (type.toLowerCase()){
					case 'bug':
						type = 'Bug';
						break;
					case 'case':
						type = 'Bug';
						break;
					case 'wikipage':
						type = 'WikiPage';
						break;
					case 'wiki':
						type = 'WikiPage';
						break;
					case 'discusstopic':
						type = 'DiscussTopic';
						break;
					case 'discuss':
						type = 'DiscussTopic';
						break;
					case 'topic':
						type = 'DiscussTopic';
						break;
				}
				return cmd(cmdname, "sType", type, "ixItem", id);
			}
 
			function star(id, type){
				return starImpl('star', id, type);
			}
			function unstar(id, type){
				return starImpl('unstar', id, type);
			}
 
			return {
				token: token,
 
				// runs logoff command
				logout: function() {
					return simpleCmd("logoff");
				},
 
				// fetch list of filters
				filters: list("Filters", convert.filters),
 
				// fetch list of projects
				projects: list("Projects", convert.projects),
 
				// fetch list of users
				people: list("People", convert.people),
				users: list("People", convert.people),
 
				// fetch list of areas
				areas: list("Areas", convert.areas),
 
				// fetch list of available case categories
				categories: list("Categories", convert.categories),
 
				// fetch list of available case priorities
				priorities: list("Priorities", convert.priorities),
 
				// fetch list of available case statuses
				statuses: list("Statuses", convert.statuses),
 
				// fetch list of milestones
				milestones: function(plain){
					var p = list("FixFors", convert.milestones)();
					Iif (!!plain){
						return p;
					}
					return p.then(map(fn.milestone(fb)));
				},
 
				// TODO provide converters for lists below
				mailboxes: list("Mailboxes"),
				wikis: list("Wikis"),
				templates: list("Templates"), // wiki templates
				snippets: list("Snippets"),
 
				// performs search with given options
				search: search,
 
				// fetch events of given case number
				events: events,
 
				// fetch case details by given case number
				caseInfo: caseInfo,
 
				// editing cases
 
				// creates new case with given info
				open: create,
				"new": create,
				create: create,
 
				// edits specfied case updating fields from info
				edit: edit,
 
				// assigns given case to specified command with optional comment
				assign: assign,
 
				// assign given case to current user with optional comment
				take: take,
 
				// adds comment to given case
				log: comment,
				comment: comment,
 
				// resolves specified case
				resolve: resolve,
 
				// closes given case with optional comment
				close: close,
 
				// reopens given case with optional comment
				reopen: reopen,
 
				// start working on this case and charge time to it (start the stopwatch)
				start: startWork,
				startWork: startWork,
 
				// stop working on everything (stop the stopwatch)
				stop: stopWork,
				stopWork: stopWork,
 
				star: star,
				unstar: unstar,
 
				// fetch user info
				userInfo: userInfo,
 
				// fetch user settings
				userSettings: userSettings,
 
				// extends specified milestone object with cases
				milestone: function(m){
					return fn.milestone(fb)(m);
				}
			};
		}
 
		// creating client with given token
		if (typeof options.token === "string") {
			if (!options.token) {
				throw new Error("token option is empty.");
			}
			return promise(client(options.token));
		}
 
		// login then create client
		var user = options.email || options.user;
		var pwd = options.password || options.pwd;
		if (!user || typeof user !== "string") {
			throw new Error("Required email option is not specified.");
		}
		if (!pwd || typeof pwd !== "string") {
			throw new Error("Required password option is not specified.");
		}
 
		return get("{0}cmd=logon&email={1}&password={2}", apiUrl, user, pwd).then(function(d) {
			return client(Array.isArray(d.token) ? d.token[0] : d.token);
		});
	}
 
	// expose public api for different environments
	switch (env) {
		case 'node':
			module.exports = fogbugz;
			break;
		case 'meteor':
			FogBugz = fogbugz;
			// aliases
			FogBugz.connect = fogbugz;
			FogBugz.create = fogbugz;
			break;
		default:
			window.fogbugz = fogbugz;
			break;
	}
 
})();