var gulp = require('gulp');

var requirejs = require('requirejs');
var typescript = require('./typescript');
var del = require('del');

var merge = require('merge2');

exports.optimize = function(packageName, source, target, done) {
	var sourceStream = gulp.src([
		'./typings/tsd.d.ts',
		'./' + source + '/**/*.ts',
	]);
	
	var result = typescript.compile(sourceStream, true);

	var out = merge([
		result.js.pipe(gulp.dest('bin')),
		result.dts.pipe(gulp.dest('./' + target)),
	]);
	out.on('end', function() {
		requirejs.optimize({
		    baseUrl: 'bin',
		    name: packageName,
		    out: target + '/' + packageName + '.js',
		}, function(buildResponse) {
			console.log(buildResponse);
		}, function(err) {
			console.log(err);
		});
		
		del('bin', done);
	});
	
	return out;
};

@@ -1,46 +1,19 @@
 var 
-gulp = require('gulp');%0A%0Avar requirejs
+runSequence
  = r
@@ -25,20 +25,24 @@
 e('r
-equirejs
+un-sequence
 ');%0A
+%0A
 var 
@@ -146,24 +146,22 @@
 exports.
-optimize
+config
  = funct
@@ -163,17 +163,24 @@
 function
-(
+ (gulp, 
 packageN
@@ -202,18 +202,61 @@
 rget
-, done
+) %7B%0A%09gulp.task('compile.release.bin', function (
 ) %7B%0A
+%09
 %09var
@@ -282,16 +282,17 @@
 p.src(%5B%0A
+%09
 %09%09'./typ
@@ -309,16 +309,17 @@
 .ts',%0A%09%09
+%09
 './' + s
@@ -342,15 +342,16 @@
 s',%0A
+%09
 %09%5D);%0A
-%09
 %0A
+%09
 %09var
@@ -406,17 +406,15 @@
 ;%0A%0A%09
-var out =
+%09return
  mer
@@ -418,16 +418,17 @@
 merge(%5B%0A
+%09
 %09%09result
@@ -455,16 +455,17 @@
 bin')),%0A
+%09
 %09%09result
@@ -505,25 +505,56 @@
 )),%0A
+%09
 %09%5D);%0A%09
-out.on('end
+%7D);%0A%0A%09gulp.task('compile.release.optimize
 ', f
@@ -560,17 +560,22 @@
 function
-(
+ (done
 ) %7B%0A%09%09re
@@ -595,20 +595,17 @@
 ize(%7B%0A%09%09
-    
+%09
 baseUrl:
@@ -614,20 +614,17 @@
 bin',%0A%09%09
-    
+%09
 name: pa
@@ -640,12 +640,9 @@
 ,%0A%09%09
-    
+%09
 out:
@@ -691,16 +691,17 @@
 function
+ 
 (buildRe
@@ -741,16 +741,27 @@
 ponse);%0A
+%09%09%09done();%0A
 %09%09%7D, fun
@@ -765,16 +765,17 @@
 function
+ 
 (err) %7B%0A
@@ -801,14 +801,82 @@
 ;%0A%09%09
-%7D);%0A%09%09
+%09done();%0A%09%09%7D);%0A%09%7D);%0A%0A%09gulp.task('compile.release.clean', function (done) %7B
 %0A%09%09d
@@ -901,22 +901,5 @@
 %7D);%0A
-%09%0A%09return out;%0A%7D;%0A
+%7D

Modify requirejs module to configure subtasks instead of providing a function. This lets us run tasks in sequence to get ordering of steps.