<commit_before>/*
 * Copyright (c) 2013, Liferay Inc. All rights reserved.
 * Code licensed under the BSD License:
 * https://github.com/liferay/alloy-ui/blob/master/LICENSE.md
 *
 * @author Zeno Rocha <zeno.rocha@liferay.com>
 * @author Eduardo Lundgren <eduardo.lundgren@liferay.com>
 */

var path  = require('path');
var spawn = require('child_process').spawn;

// -- Globals ------------------------------------------------------------------
var ROOT        = process.cwd();

// -- Config -------------------------------------------------------------------
module.exports = function(grunt) {
    grunt.initConfig({

        pkg: grunt.file.readJSON('.alloy.json'),

        'api-build': {
            'src': ROOT,
            'dist': path.join(ROOT, 'api'),
            'aui-version': '<%= pkg["version"] %>',
            'theme': path.join(ROOT, '<%= pkg.dependencies["alloy-apidocs-theme"].folder %>')
        },

        'api-push': {
            'src': path.join(ROOT, 'api'),
            'dist': path.join(ROOT, '<%= pkg.dependencies["alloyui.com"].folder %>', 'api'),
            'repo': path.join(ROOT, '<%= pkg.dependencies["alloyui.com"].folder %>'),
            'branch': 'gh-pages',
            'remote': 'origin'
        },

        'api-watch': {
            'aui-version': '<%= pkg["version"] %>',
            'theme': path.join(ROOT, '<%= pkg.dependencies["alloy-apidocs-theme"].folder %>')
        },

        build: {
            yui: {
                'src': path.join(ROOT, '<%= pkg.dependencies.yui3.folder %>', 'src'),
                'dist': path.join(ROOT, 'build'),
                'cache': true,
                'coverage': false,
                'lint': false,
                'replace-yuivar': 'Y',
                'replace-version': '<%= pkg["yui-version"] %>',
            },
            aui: {
                'src': path.join(ROOT, 'src'),
                'dist': path.join(ROOT, 'build'),
                'cache': false,
                'coverage': false,
                'lint': false,
                'replace-yuivar': 'A',
                'replace-version': '<%= pkg["version"] %>',
            }
        },

        cdn: {
            combine: true,
            comboBase: 'http://cdn.alloyui.com/combo/combo.php?',
            filter: 'min',
            root: '../<%= pkg["version"] %>/'
        },

        compass: {
            dist: {
                options: {
                    sassDir: path.join(ROOT, '<%= pkg.dependencies["alloy-bootstrap"].folder %>', 'lib'),
                    cssDir: 'build/aui-css/css/'
                }
            }
        },

        copy: {
            css: {
                files: [
                    {
                        src: 'build/aui-css/css/responsive.css',
                        dest: 'build/aui-css/css/bootstrap-responsive.css'
                    }
                ]
            },
            img: {
                files: [
                    {
                        src: path.join(ROOT, '<%= pkg.dependencies["alloy-bootstrap"].folder %>', 'img/glyphicons-halflings-white.png'),
                        dest: 'build/aui-css/img/glyphicons-halflings-white.png'
                    },
                    {
                        src: path.join(ROOT, '<%= pkg.dependencies["alloy-bootstrap"].folder %>', 'img/glyphicons-halflings.png'),
                        dest: 'build/aui-css/img/glyphicons-halflings.png'
                    }
                ]
            }
        },

        compress: {
            cdn: {
                name: 'cdn-alloy-<%= pkg["version"] %>'
            },
            release: {
                name: 'alloy-<%= pkg["version"] %>'
            }
        },

        clean: {
            css: [
                'build/aui-css/css/responsive.css',
            ]
        },

        create: {
            name: 'aui-test'
        },

        cssmin: {
            dist: {
                files: {
                    'build/aui-css/css/bootstrap.min.css': ['build/aui-css/css/bootstrap.css'],
                    'build/aui-css/css/bootstrap-responsive.min.css': ['build/aui-css/css/bootstrap-responsive.css']
                }
            }
        },

        init: {
            dependencies: '<%= pkg.dependencies %>'
        },

        jsbeautifier: {
            files: ['src/**/*.js', 'src/**/*.css', 'grunt/*.js'],
            options: {
                config: '.jsbeautifyrc'
            }
        },

        test: {
            coverage: false
        },

        watch: {
            'src': ROOT,
            'replace-yuivar': 'A',
            'replace-version': '<%= pkg["version"] %>'
        }
    });

    grunt.loadTasks('grunt');

    grunt.loadNpmTasks('grunt-contrib-compass');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-jsbeautifier');

    grunt.registerTask('all', ['bootstrap', 'build']);
    grunt.registerTask('api-deploy', ['api-build', 'api-push']);
    grunt.registerTask('bootstrap', ['compass', 'copy:css', 'cssmin', 'copy:img', 'clean']);
    grunt.registerTask('format', ['jsbeautifier']);
    grunt.registerTask('release', ['all', 'compress:release']);
    grunt.registerTask('release-cdn', ['all', 'cdn', 'compress:cdn', 'build:aui']);
};<commit_msg>AUI-1003 Source formatting<commit_after>/*
 * Copyright (c) 2013, Liferay Inc. All rights reserved.
 * Code licensed under the BSD License:
 * https://github.com/liferay/alloy-ui/blob/master/LICENSE.md
 *
 * @author Zeno Rocha <zeno.rocha@liferay.com>
 * @author Eduardo Lundgren <eduardo.lundgren@liferay.com>
 */

var path  = require('path');
var spawn = require('child_process').spawn;

// -- Globals ------------------------------------------------------------------
var ROOT = process.cwd();

// -- Config -------------------------------------------------------------------
module.exports = function(grunt) {
    grunt.initConfig({

        pkg: grunt.file.readJSON('.alloy.json'),

        'api-build': {
            'src': ROOT,
            'dist': path.join(ROOT, 'api'),
            'aui-version': '<%= pkg["version"] %>',
            'theme': path.join(ROOT, '<%= pkg.dependencies["alloy-apidocs-theme"].folder %>')
        },

        'api-push': {
            'src': path.join(ROOT, 'api'),
            'dist': path.join(ROOT, '<%= pkg.dependencies["alloyui.com"].folder %>', 'api'),
            'repo': path.join(ROOT, '<%= pkg.dependencies["alloyui.com"].folder %>'),
            'branch': 'gh-pages',
            'remote': 'origin'
        },

        'api-watch': {
            'aui-version': '<%= pkg["version"] %>',
            'theme': path.join(ROOT, '<%= pkg.dependencies["alloy-apidocs-theme"].folder %>')
        },

        build: {
            yui: {
                'src': path.join(ROOT, '<%= pkg.dependencies.yui3.folder %>', 'src'),
                'dist': path.join(ROOT, 'build'),
                'cache': true,
                'coverage': false,
                'lint': false,
                'replace-yuivar': 'Y',
                'replace-version': '<%= pkg["yui-version"] %>',
            },
            aui: {
                'src': path.join(ROOT, 'src'),
                'dist': path.join(ROOT, 'build'),
                'cache': false,
                'coverage': false,
                'lint': false,
                'replace-yuivar': 'A',
                'replace-version': '<%= pkg["version"] %>',
            }
        },

        cdn: {
            combine: true,
            comboBase: 'http://cdn.alloyui.com/combo/combo.php?',
            filter: 'min',
            root: '../<%= pkg["version"] %>/'
        },

        compass: {
            dist: {
                options: {
                    sassDir: path.join(ROOT, '<%= pkg.dependencies["alloy-bootstrap"].folder %>', 'lib'),
                    cssDir: 'build/aui-css/css/'
                }
            }
        },

        copy: {
            css: {
                files: [
                    {
                        src: 'build/aui-css/css/responsive.css',
                        dest: 'build/aui-css/css/bootstrap-responsive.css'
                    }
                ]
            },
            img: {
                files: [
                    {
                        src: path.join(ROOT, '<%= pkg.dependencies["alloy-bootstrap"].folder %>', 'img/glyphicons-halflings-white.png'),
                        dest: 'build/aui-css/img/glyphicons-halflings-white.png'
                    },
                    {
                        src: path.join(ROOT, '<%= pkg.dependencies["alloy-bootstrap"].folder %>', 'img/glyphicons-halflings.png'),
                        dest: 'build/aui-css/img/glyphicons-halflings.png'
                    }
                ]
            }
        },

        compress: {
            cdn: {
                name: 'cdn-alloy-<%= pkg["version"] %>'
            },
            release: {
                name: 'alloy-<%= pkg["version"] %>'
            }
        },

        clean: {
            css: [
                'build/aui-css/css/responsive.css',
            ]
        },

        create: {
            name: 'aui-test'
        },

        cssmin: {
            dist: {
                files: {
                    'build/aui-css/css/bootstrap.min.css': ['build/aui-css/css/bootstrap.css'],
                    'build/aui-css/css/bootstrap-responsive.min.css': ['build/aui-css/css/bootstrap-responsive.css']
                }
            }
        },

        init: {
            dependencies: '<%= pkg.dependencies %>'
        },

        jsbeautifier: {
            files: ['src/**/*.js', 'src/**/*.css', 'grunt/*.js'],
            options: {
                config: '.jsbeautifyrc'
            }
        },

        test: {
            coverage: false
        },

        watch: {
            'src': ROOT,
            'replace-yuivar': 'A',
            'replace-version': '<%= pkg["version"] %>'
        }
    });

    grunt.loadTasks('grunt');

    grunt.loadNpmTasks('grunt-contrib-compass');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-jsbeautifier');

    grunt.registerTask('all', ['bootstrap', 'build']);
    grunt.registerTask('api-deploy', ['api-build', 'api-push']);
    grunt.registerTask('bootstrap', ['compass', 'copy:css', 'cssmin', 'copy:img', 'clean']);
    grunt.registerTask('format', ['jsbeautifier']);
    grunt.registerTask('release', ['all', 'compress:release']);
    grunt.registerTask('release-cdn', ['all', 'cdn', 'compress:cdn', 'build:aui']);
};<|endoftext|>


<commit_before>module.exports = function(grunt) {
	"use strict";

	var banner = '/*! Copyright (C) NAVER <http://www.navercorp.com> */\n';
	var banner_xe_js = banner + '/**!\n * @file   common.js + js_app.js + xml_handler.js + xml_js_filter.js\n * @brief  XE Common JavaScript\n **/\n';

	grunt.file.defaultEncoding = 'utf8';

	grunt.initConfig({
		clean: {
			minify: [
				'common/js/xe.js',
				'common/js/xe.min.js',
				'common/css/xe.min.css',
				'common/css/mobile.min.css'
			]
		},
		concat: {
			'common-js': {
				options: {
					stripBanners: true,
					banner: banner_xe_js
				},
				src: [
					'common/js/common.js',
					'common/js/js_app.js',
					'common/js/xml_handler.js',
					'common/js/xml_js_filter.js'
				],
				dest: 'common/js/xe.js'
			},
			'xpresseditor': {
				options: {
					stripBanners: true,
					banner: banner_xe_js
				},
				src: [
					'modules/editor/skins/xpresseditor/js/Xpress_Editor.js',
					'modules/editor/skins/xpresseditor/js/xe_interface.js',
				],
				dest: 'modules/editor/skins/xpresseditor/js/xpresseditor.js'
			}
		},
		uglify: {
			'common-js': {
				options: {
					banner: banner_xe_js
				},
				files: {
					'common/js/xe.min.js': ['common/js/xe.js']
				}
			},
			'modules': {
				files: {
					// addon
					'addons/captcha/captcha.min.js' : ['addons/captcha/captcha.js'],
					'addons/captcha_member/captcha.min.js' : ['addons/captcha_member/captcha.js'],
					'addons/resize_image/js/resize_image.min.js' : ['addons/resize_image/js/resize_image.js'],
					// module/editor
					'modules/editor/skins/xpresseditor/js/xpresseditor.min.js': ['modules/editor/skins/xpresseditor/js/xpresseditor.js'],
					'modules/editor/skins/xpresseditor/js/xe_textarea.min.js': ['modules/editor/skins/xpresseditor/js/xe_textarea.js'],
					'modules/editor/tpl/js/editor_common.min.js': ['modules/editor/tpl/js/editor_common.js'],
					// module/admin
					'modules/admin/tpl/js/admin.min.js': ['modules/admin/tpl/js/admin.js'],
					'modules/admin/tpl/js/config.min.js': ['modules/admin/tpl/js/config.js'],
					'modules/admin/tpl/js/menu_setup.min.js': ['modules/admin/tpl/js/menu_setup.js'],
					'modules/admin/tpl/js/sitemap.min.js': ['modules/admin/tpl/js/sitemap.js'],
					'modules/admin/tpl/js/theme.min.js': ['modules/admin/tpl/js/theme.js'],
					// editor-component-multimedia-link
					'modules/editor/components/multimedia_link/tpl/popup.min.js': ['modules/editor/components/multimedia_link/tpl/popup.js'],
					// editor-component-image-gallery
					'modules/editor/components/image_gallery/tpl/gallery.min.js' : ['modules/editor/components/image_gallery/tpl/gallery.js'],
					'modules/editor/components/image_gallery/tpl/list_gallery.min.js' : ['modules/editor/components/image_gallery/tpl/list_gallery.js'],
					'modules/editor/components/image_gallery/tpl/popup.min.js' : ['modules/editor/components/image_gallery/tpl/popup.js'],
					'modules/editor/components/image_gallery/tpl/slide_gallery.min.js' : ['modules/editor/components/image_gallery/tpl/slide_gallery.js'],
					// module/importer
					'modules/importer/tpl/js/importer_admin.min.js': ['modules/importer/tpl/js/importer_admin.js'],
					// modules/widget
					'modules/widget/tpl/js/generate_code.min.js': ['modules/widget/tpl/js/generate_code.js'],
					'modules/widget/tpl/js/widget.min.js': ['modules/widget/tpl/js/widget.js'],
					'modules/widget/tpl/js/widget_admin.min.js': ['modules/widget/tpl/js/widget_admin.js'],
				}
			}
		},
		cssmin: {
			'common-css': {
				files: {
					'common/css/xe.min.css': ['common/css/xe.css'],
					'common/css/mobile.min.css': ['common/css/mobile.css']
				}
			},
			'module-admin-css': {
				files: {
					'modules/admin/tpl/css/admin.min.css': ['modules/admin/tpl/css/admin.css']
				}
			},
			'editor-component-image-gallery': {
				files: {
					'modules/editor/components/image_gallery/tpl/popup.min.css': ['modules/editor/components/image_gallery/tpl/popup.css'],
					'modules/editor/components/image_gallery/tpl/slide_gallery.min.css': ['modules/editor/components/image_gallery/tpl/slide_gallery.css'],
				}
			},
			'editor-component-multimedia-link': {
				files: {
					'modules/editor/components/multimedia_link/tpl/popup.min.css': ['modules/editor/components/multimedia_link/tpl/popup.css'],
				}
			},
			'moudle-widget-tpl': {
				files: {
					'modules/widget/tpl/css/widget.min.css': ['modules/widget/tpl/css/widget.css'],
				}
			}
		},
		jshint: {
			files: [
				'Gruntfile.js',
				'common/js/*.js', '!common/js/html5.js', '!common/js/jquery.js', '!common/js/x.js', '!common/js/xe.js',
				'modules/widget/tpl/js/generate_code.js',
				'modules/widget/tpl/js/widget.js',
				'modules/widget/tpl/js/widget_admin.js',
				'!**/jquery*.js',
				'!**/*.min.js',
				'!**/*-packed.js'
			],
			options : {
				globalstrict: false,
				undef : false,
				eqeqeq: false,
				browser : true,
				globals: {
					"jQuery" : true,
					"console" : true,
					"window" : true
				},
				ignores : [
					'skins/xe_2010_gallery/js/jquery.easing.1.3.js',
					'skins/xe_2010_gallery/js/json2007.js',
					'**/*.min.js',
					'**/*.compressed.js'
				]
			}
		},
		csslint: {
			'common-css': {
				options: {
					import : 2,
					'adjoining-classes' : false,
					'box-model' : false,
					'duplicate-background-images' : false,
					'ids' : false,
					'important' : false,
					'overqualified-elements' : false,
					'qualified-headings' : false,
					'star-property-hack' : false,
					'underscore-property-hack' : false,
				},
				src: [
					'common/css/*.css',
					'!common/css/bootstrap.css',
					'!common/css/bootstrap-responsive.css',
					'!**/*.min.css',
				]
			}
		}
	});

	function createPackageChecksum(target_file) {
		/* https://gist.github.com/onelaview/6475037 */
		var fs = require('fs');
		var crypto = require('crypto');
		var md5 = crypto.createHash('md5');
		var file = grunt.template.process(target_file);
		var buffer = fs.readFileSync(file);
		md5.update(buffer);
		var md5Hash = md5.digest('hex');
		grunt.verbose.writeln('file md5: ' + md5Hash);

		var md5FileName = file + '.md5';
		grunt.file.write(md5FileName, md5Hash);
		grunt.verbose.writeln('File "' + md5FileName + '" created.').writeln('...');
	}

	grunt.registerTask('build', '', function(A, B) {
		var _only_export = false;
		var tasks = ['krzip', 'syndication'];

		if(!A) {
			grunt.fail.warn('Undefined build target.');
		} else if(A && !B) {
			_only_export = true;
		}

		if(!_only_export) {
			tasks.push('changed');
			target = A + '...' + B;
			version = B;
		} else {
			target = A;
			version = A;
		}

		var done = this.async();
		var build_dir = 'build';
		var archive_full = build_dir + '/xe.' + version + '.tar.gz';
		var archive_changed = build_dir + '/xe.' + version + '.changed.tar.gz';
		var diff, target, version;

		var taskDone = function() {
			tasks.pop();
			grunt.verbose.writeln('remain tasks : '+tasks.length);

			if(tasks.length === 0) {
				grunt.util.spawn({
					cmd: "tar",
					args: ['cfz', 'xe.'+version+'.tar.gz', 'xe/'],
					opts: {
						cwd: 'build'
					}
				}, function (error, result, code) {
					grunt.log.ok('Archived(full) : ' + build_dir + '/xe.'+version+'.tar.gz');
					createPackageChecksum(build_dir + '/xe.'+version+'.tar.gz');

					grunt.util.spawn({
						cmd: "zip",
						args: ['-r', 'xe.'+version+'.zip', 'xe/'],
						opts: {
							cwd: 'build'
						}
					}, function (error, result, code) {
						grunt.log.ok('Archived(full) : ' + build_dir + '/xe.'+version+'.zip');
						createPackageChecksum(build_dir + '/xe.'+version+'.zip');

						grunt.file.delete('build/xe');
						grunt.file.delete('build/temp.full.tar');

						grunt.log.ok('Done!');
					});
				});
			}
		};

		if(grunt.file.isDir(build_dir)) {
			grunt.file.delete(build_dir);
		}
		grunt.file.mkdir(build_dir);
		grunt.file.mkdir(build_dir + '/xe');

		grunt.log.subhead('Archiving...');
		grunt.log.writeln('Target : ' + target);

		grunt.util.spawn({
			cmd: "git",
			args: ['archive', '--output=build/temp.full.tar', version, '.']
		}, function (error, result, code){
			if(!_only_export) {
				// changed
				grunt.util.spawn({
					cmd: "git",
					args: ['diff', '--name-only', target]
				}, function (error, result, code) {
					diff = result.stdout;

					if(diff) {
						diff = diff.split(grunt.util.linefeed);
					}

					// changed
					if(diff.length) {
						var args_tar = ['archive', '--prefix=xe/', '-o', 'build/xe.'+version+'.changed.tar.gz', version];
						var args_zip = ['archive', '--prefix=xe/', '-o', 'build/xe.'+version+'.changed.zip', version];
						args_tar = args_tar.concat(diff);
						args_zip = args_zip.concat(diff);

						grunt.util.spawn({
							cmd: "git",
							args: args_tar
						}, function (error, result, code) {
							grunt.log.ok('Archived(changed) : ' + build_dir + '/xe.'+version+'.changed.tar.gz');
							createPackageChecksum(build_dir + '/xe.'+version+'.changed.tar.gz');

							grunt.util.spawn({
								cmd: "git",
								args: args_zip
							}, function (error, result, code) {
								grunt.log.ok('Archived(changed) : ' + build_dir + '/xe.'+version+'.changed.zip');
								createPackageChecksum(build_dir + '/xe.'+version+'.changed.zip');

								taskDone();
							});
						});
					} else {
						taskDone();
					}
				});
			}

			// full
			grunt.util.spawn({
				cmd: "tar",
				args: ['xf', 'build/temp.full.tar', '-C', 'build/xe']
			}, function (error, result, code) {
				// krzip
				grunt.util.spawn({
					cmd: "git",
					args: ['clone', 'git@github.com:xpressengine/xe-module-krzip.git', 'build/xe/modules/krzip']
				}, function (error, result, code) {
					grunt.file.delete('build/xe/modules/krzip/.git');
					taskDone();
				});

				// syndication
				grunt.util.spawn({
					cmd: "git",
					args: ['clone', 'git@github.com:xpressengine/xe-module-syndication.git', 'build/xe/modules/syndication']
				}, function (error, result, code) {
					grunt.file.delete('build/xe/modules/syndication/.git');
					taskDone();
				});
			});
		});
	});

	grunt.loadNpmTasks('grunt-contrib-clean');
	grunt.loadNpmTasks('grunt-contrib-concat');
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-csslint');
	grunt.loadNpmTasks('grunt-contrib-cssmin');

	grunt.registerTask('default', ['jshint', 'csslint']);
	grunt.registerTask('lint', ['jshint', 'csslint']);
	grunt.registerTask('minify', ['jshint', 'csslint', 'clean', 'concat', 'uglify', 'cssmin']);
};
<commit_msg>minify 설정 추가.<commit_after>module.exports = function(grunt) {
	"use strict";

	var banner = '/*! Copyright (C) NAVER <http://www.navercorp.com> */\n';
	var banner_xe_js = banner + '/**!\n * @file   common.js + js_app.js + xml_handler.js + xml_js_filter.js\n * @brief  XE Common JavaScript\n **/\n';

	grunt.file.defaultEncoding = 'utf8';

	grunt.initConfig({
		clean: {
			minify: [
				'common/js/xe.js',
				'common/js/xe.min.js',
				'common/css/xe.min.css',
				'common/css/mobile.min.css'
			]
		},
		concat: {
			'common-js': {
				options: {
					stripBanners: true,
					banner: banner_xe_js
				},
				src: [
					'common/js/common.js',
					'common/js/js_app.js',
					'common/js/xml_handler.js',
					'common/js/xml_js_filter.js'
				],
				dest: 'common/js/xe.js'
			},
			'xpresseditor': {
				options: {
					stripBanners: true,
					banner: banner_xe_js
				},
				src: [
					'modules/editor/skins/xpresseditor/js/Xpress_Editor.js',
					'modules/editor/skins/xpresseditor/js/xe_interface.js',
				],
				dest: 'modules/editor/skins/xpresseditor/js/xpresseditor.js'
			}
		},
		uglify: {
			'common-js': {
				options: {
					banner: banner_xe_js
				},
				files: {
					'common/js/xe.min.js': ['common/js/xe.js']
				}
			},
			'modules': {
				files: {
					// addon
					'addons/captcha/captcha.min.js' : ['addons/captcha/captcha.js'],
					'addons/captcha_member/captcha.min.js' : ['addons/captcha_member/captcha.js'],
					'addons/resize_image/js/resize_image.min.js' : ['addons/resize_image/js/resize_image.js'],
					// module/editor
					'modules/editor/skins/xpresseditor/js/xpresseditor.min.js': ['modules/editor/skins/xpresseditor/js/xpresseditor.js'],
					'modules/editor/skins/xpresseditor/js/xe_textarea.min.js': ['modules/editor/skins/xpresseditor/js/xe_textarea.js'],
					'modules/editor/tpl/js/editor_common.min.js': ['modules/editor/tpl/js/editor_common.js'],
					// module/admin
					'modules/admin/tpl/js/admin.min.js': ['modules/admin/tpl/js/admin.js'],
					'modules/admin/tpl/js/config.min.js': ['modules/admin/tpl/js/config.js'],
					'modules/admin/tpl/js/menu_setup.min.js': ['modules/admin/tpl/js/menu_setup.js'],
					'modules/admin/tpl/js/sitemap.min.js': ['modules/admin/tpl/js/sitemap.js'],
					'modules/admin/tpl/js/theme.min.js': ['modules/admin/tpl/js/theme.js'],
					// editor-component-multimedia-link
					'modules/editor/components/multimedia_link/tpl/popup.min.js': ['modules/editor/components/multimedia_link/tpl/popup.js'],
					// editor-component-image-gallery
					'modules/editor/components/image_gallery/tpl/gallery.min.js' : ['modules/editor/components/image_gallery/tpl/gallery.js'],
					'modules/editor/components/image_gallery/tpl/list_gallery.min.js' : ['modules/editor/components/image_gallery/tpl/list_gallery.js'],
					'modules/editor/components/image_gallery/tpl/popup.min.js' : ['modules/editor/components/image_gallery/tpl/popup.js'],
					'modules/editor/components/image_gallery/tpl/slide_gallery.min.js' : ['modules/editor/components/image_gallery/tpl/slide_gallery.js'],
					// module/importer
					'modules/importer/tpl/js/importer_admin.min.js': ['modules/importer/tpl/js/importer_admin.js'],
					// modules/widget
					'modules/widget/tpl/js/generate_code.min.js': ['modules/widget/tpl/js/generate_code.js'],
					'modules/widget/tpl/js/widget.min.js': ['modules/widget/tpl/js/widget.js'],
					'modules/widget/tpl/js/widget_admin.min.js': ['modules/widget/tpl/js/widget_admin.js'],
					// modules/poll
					'modules/poll/tpl/js/poll_admin.min.js': ['modules/poll/tpl/js/poll_admin.js'],
					'modules/poll/tpl/js/poll.min.js': ['modules/poll/tpl/js/poll.js'],
				}
			}
		},
		cssmin: {
			'common-css': {
				files: {
					'common/css/xe.min.css': ['common/css/xe.css'],
					'common/css/mobile.min.css': ['common/css/mobile.css']
				}
			},
			'module-admin-css': {
				files: {
					'modules/admin/tpl/css/admin.min.css': ['modules/admin/tpl/css/admin.css']
				}
			},
			'editor-component-image-gallery': {
				files: {
					'modules/editor/components/image_gallery/tpl/popup.min.css': ['modules/editor/components/image_gallery/tpl/popup.css'],
					'modules/editor/components/image_gallery/tpl/slide_gallery.min.css': ['modules/editor/components/image_gallery/tpl/slide_gallery.css'],
				}
			},
			'editor-component-multimedia-link': {
				files: {
					'modules/editor/components/multimedia_link/tpl/popup.min.css': ['modules/editor/components/multimedia_link/tpl/popup.css'],
				}
			},
			'moudle-widget-tpl': {
				files: {
					'modules/widget/tpl/css/widget.min.css': ['modules/widget/tpl/css/widget.css'],
				}
			},
			'moudle-poll': {
				files: {
					'modules/poll/tpl/css/poll.min.css': ['modules/poll/tpl/css/poll.css'],
					'modules/poll/skins/default/css/poll.min.css': ['modules/poll/skins/default/css/poll.css'],
					'modules/poll/skins/simple/css/poll.min.css': ['modules/poll/skins/simple/css/poll.css'],
				}
			},
			'moudle-editor': {
				files: {
					'modules/editor/skins/xpresseditor/css/default.min.css': ['modules/editor/skins/xpresseditor/css/default.css'],
				}
			}
		},
		jshint: {
			files: [
				'Gruntfile.js',
				'common/js/*.js', '!common/js/html5.js', '!common/js/jquery.js', '!common/js/x.js', '!common/js/xe.js',
				'modules/widget/tpl/js/generate_code.js',
				'modules/widget/tpl/js/widget.js',
				'modules/widget/tpl/js/widget_admin.js',
				'!**/jquery*.js',
				'!**/*.min.js',
				'!**/*-packed.js'
			],
			options : {
				globalstrict: false,
				undef : false,
				eqeqeq: false,
				browser : true,
				globals: {
					"jQuery" : true,
					"console" : true,
					"window" : true
				},
				ignores : [
					'skins/xe_2010_gallery/js/jquery.easing.1.3.js',
					'skins/xe_2010_gallery/js/json2007.js',
					'**/*.min.js',
					'**/*.compressed.js'
				]
			}
		},
		csslint: {
			'common-css': {
				options: {
					import : 2,
					'adjoining-classes' : false,
					'box-model' : false,
					'duplicate-background-images' : false,
					'ids' : false,
					'important' : false,
					'overqualified-elements' : false,
					'qualified-headings' : false,
					'star-property-hack' : false,
					'underscore-property-hack' : false,
				},
				src: [
					'common/css/*.css',
					'!common/css/bootstrap.css',
					'!common/css/bootstrap-responsive.css',
					'!**/*.min.css',
				]
			}
		}
	});

	function createPackageChecksum(target_file) {
		/* https://gist.github.com/onelaview/6475037 */
		var fs = require('fs');
		var crypto = require('crypto');
		var md5 = crypto.createHash('md5');
		var file = grunt.template.process(target_file);
		var buffer = fs.readFileSync(file);
		md5.update(buffer);
		var md5Hash = md5.digest('hex');
		grunt.verbose.writeln('file md5: ' + md5Hash);

		var md5FileName = file + '.md5';
		grunt.file.write(md5FileName, md5Hash);
		grunt.verbose.writeln('File "' + md5FileName + '" created.').writeln('...');
	}

	grunt.registerTask('build', '', function(A, B) {
		var _only_export = false;
		var tasks = ['krzip', 'syndication'];

		if(!A) {
			grunt.fail.warn('Undefined build target.');
		} else if(A && !B) {
			_only_export = true;
		}

		if(!_only_export) {
			tasks.push('changed');
			target = A + '...' + B;
			version = B;
		} else {
			target = A;
			version = A;
		}

		var done = this.async();
		var build_dir = 'build';
		var archive_full = build_dir + '/xe.' + version + '.tar.gz';
		var archive_changed = build_dir + '/xe.' + version + '.changed.tar.gz';
		var diff, target, version;

		var taskDone = function() {
			tasks.pop();
			grunt.verbose.writeln('remain tasks : '+tasks.length);

			if(tasks.length === 0) {
				grunt.util.spawn({
					cmd: "tar",
					args: ['cfz', 'xe.'+version+'.tar.gz', 'xe/'],
					opts: {
						cwd: 'build'
					}
				}, function (error, result, code) {
					grunt.log.ok('Archived(full) : ' + build_dir + '/xe.'+version+'.tar.gz');
					createPackageChecksum(build_dir + '/xe.'+version+'.tar.gz');

					grunt.util.spawn({
						cmd: "zip",
						args: ['-r', 'xe.'+version+'.zip', 'xe/'],
						opts: {
							cwd: 'build'
						}
					}, function (error, result, code) {
						grunt.log.ok('Archived(full) : ' + build_dir + '/xe.'+version+'.zip');
						createPackageChecksum(build_dir + '/xe.'+version+'.zip');

						grunt.file.delete('build/xe');
						grunt.file.delete('build/temp.full.tar');

						grunt.log.ok('Done!');
					});
				});
			}
		};

		if(grunt.file.isDir(build_dir)) {
			grunt.file.delete(build_dir);
		}
		grunt.file.mkdir(build_dir);
		grunt.file.mkdir(build_dir + '/xe');

		grunt.log.subhead('Archiving...');
		grunt.log.writeln('Target : ' + target);

		grunt.util.spawn({
			cmd: "git",
			args: ['archive', '--output=build/temp.full.tar', version, '.']
		}, function (error, result, code){
			if(!_only_export) {
				// changed
				grunt.util.spawn({
					cmd: "git",
					args: ['diff', '--name-only', target]
				}, function (error, result, code) {
					diff = result.stdout;

					if(diff) {
						diff = diff.split(grunt.util.linefeed);
					}

					// changed
					if(diff.length) {
						var args_tar = ['archive', '--prefix=xe/', '-o', 'build/xe.'+version+'.changed.tar.gz', version];
						var args_zip = ['archive', '--prefix=xe/', '-o', 'build/xe.'+version+'.changed.zip', version];
						args_tar = args_tar.concat(diff);
						args_zip = args_zip.concat(diff);

						grunt.util.spawn({
							cmd: "git",
							args: args_tar
						}, function (error, result, code) {
							grunt.log.ok('Archived(changed) : ' + build_dir + '/xe.'+version+'.changed.tar.gz');
							createPackageChecksum(build_dir + '/xe.'+version+'.changed.tar.gz');

							grunt.util.spawn({
								cmd: "git",
								args: args_zip
							}, function (error, result, code) {
								grunt.log.ok('Archived(changed) : ' + build_dir + '/xe.'+version+'.changed.zip');
								createPackageChecksum(build_dir + '/xe.'+version+'.changed.zip');

								taskDone();
							});
						});
					} else {
						taskDone();
					}
				});
			}

			// full
			grunt.util.spawn({
				cmd: "tar",
				args: ['xf', 'build/temp.full.tar', '-C', 'build/xe']
			}, function (error, result, code) {
				// krzip
				grunt.util.spawn({
					cmd: "git",
					args: ['clone', 'git@github.com:xpressengine/xe-module-krzip.git', 'build/xe/modules/krzip']
				}, function (error, result, code) {
					grunt.file.delete('build/xe/modules/krzip/.git');
					taskDone();
				});

				// syndication
				grunt.util.spawn({
					cmd: "git",
					args: ['clone', 'git@github.com:xpressengine/xe-module-syndication.git', 'build/xe/modules/syndication']
				}, function (error, result, code) {
					grunt.file.delete('build/xe/modules/syndication/.git');
					taskDone();
				});
			});
		});
	});

	grunt.loadNpmTasks('grunt-contrib-clean');
	grunt.loadNpmTasks('grunt-contrib-concat');
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-csslint');
	grunt.loadNpmTasks('grunt-contrib-cssmin');

	grunt.registerTask('default', ['jshint', 'csslint']);
	grunt.registerTask('lint', ['jshint', 'csslint']);
	grunt.registerTask('minify', ['jshint', 'csslint', 'clean', 'concat', 'uglify', 'cssmin']);
};
<|endoftext|>


<commit_before>/* global jsPDF */
/**
 * @name utf8
 * @module
 */
(function(jsPDF) {
  "use strict";
  var jsPDFAPI = jsPDF.API;

  /***************************************************************************************************/
  /* function : pdfEscape16                                                                          */
  /* comment : The character id of a 2-byte string is converted to a hexadecimal number by obtaining */
  /*   the corresponding glyph id and width, and then adding padding to the string.                  */
  /***************************************************************************************************/
  var pdfEscape16 = (jsPDFAPI.pdfEscape16 = function(text, font) {
    var widths = font.metadata.Unicode.widths;
    var padz = ["", "0", "00", "000", "0000"];
    var ar = [""];
    for (var i = 0, l = text.length, t; i < l; ++i) {
      t = font.metadata.characterToGlyph(text.charCodeAt(i));
      font.metadata.glyIdsUsed.push(t);
      font.metadata.toUnicode[t] = text.charCodeAt(i);
      if (widths.indexOf(t) == -1) {
        widths.push(t);
        widths.push([parseInt(font.metadata.widthOfGlyph(t), 10)]);
      }
      if (t == "0") {
        //Spaces are not allowed in cmap.
        return ar.join("");
      } else {
        t = t.toString(16);
        ar.push(padz[4 - t.length], t);
      }
    }
    return ar.join("");
  });

  var toUnicodeCmap = function(map) {
    var code, codes, range, unicode, unicodeMap, _i, _len;
    unicodeMap =
      "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo <<\n  /Registry (Adobe)\n  /Ordering (UCS)\n  /Supplement 0\n>> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<0000><ffff>\nendcodespacerange";
    codes = Object.keys(map).sort(function(a, b) {
      return a - b;
    });

    range = [];
    for (_i = 0, _len = codes.length; _i < _len; _i++) {
      code = codes[_i];
      if (range.length >= 100) {
        unicodeMap +=
          "\n" +
          range.length +
          " beginbfchar\n" +
          range.join("\n") +
          "\nendbfchar";
        range = [];
      }

      if (
        map[code] !== undefined &&
        map[code] !== null &&
        typeof map[code].toString === "function"
      ) {
        unicode = ("0000" + map[code].toString(16)).slice(-4);
        code = ("0000" + (+code).toString(16)).slice(-4);
        range.push("<" + code + "><" + unicode + ">");
      }
    }

    if (range.length) {
      unicodeMap +=
        "\n" +
        range.length +
        " beginbfchar\n" +
        range.join("\n") +
        "\nendbfchar\n";
    }
    unicodeMap +=
      "endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend";
    return unicodeMap;
  };

  var identityHFunction = function(options) {
    var font = options.font;
    var out = options.out;
    var newObject = options.newObject;
    var putStream = options.putStream;
    var pdfEscapeWithNeededParanthesis = options.pdfEscapeWithNeededParanthesis;

    if (
      font.metadata instanceof jsPDF.API.TTFFont &&
      font.encoding === "Identity-H"
    ) {
      //Tag with Identity-H
      var widths = font.metadata.Unicode.widths;
      var data = font.metadata.subset.encode(font.metadata.glyIdsUsed, 1);
      var pdfOutput = data;
      var pdfOutput2 = "";
      for (var i = 0; i < pdfOutput.length; i++) {
        pdfOutput2 += String.fromCharCode(pdfOutput[i]);
      }
      var fontTable = newObject();
      putStream({ data: pdfOutput2, addLength1: true });
      out("endobj");

      var cmap = newObject();
      var cmapData = toUnicodeCmap(font.metadata.toUnicode);
      putStream({ data: cmapData, addLength1: true });
      out("endobj");

      var fontDescriptor = newObject();
      out("<<");
      out("/Type /FontDescriptor");
      out("/FontName /" + pdfEscapeWithNeededParanthesis(font.fontName));
      out("/FontFile2 " + fontTable + " 0 R");
      out("/FontBBox " + jsPDF.API.PDFObject.convert(font.metadata.bbox));
      out("/Flags " + font.metadata.flags);
      out("/StemV " + font.metadata.stemV);
      out("/ItalicAngle " + font.metadata.italicAngle);
      out("/Ascent " + font.metadata.ascender);
      out("/Descent " + font.metadata.decender);
      out("/CapHeight " + font.metadata.capHeight);
      out(">>");
      out("endobj");

      var DescendantFont = newObject();
      out("<<");
      out("/Type /Font");
      out("/BaseFont /" + pdfEscapeWithNeededParanthesis(font.fontName));
      out("/FontDescriptor " + fontDescriptor + " 0 R");
      out("/W " + jsPDF.API.PDFObject.convert(widths));
      out("/CIDToGIDMap /Identity");
      out("/DW 1000");
      out("/Subtype /CIDFontType2");
      out("/CIDSystemInfo");
      out("<<");
      out("/Supplement 0");
      out("/Registry (Adobe)");
      out("/Ordering (" + font.encoding + ")");
      out(">>");
      out(">>");
      out("endobj");

      font.objectNumber = newObject();
      out("<<");
      out("/Type /Font");
      out("/Subtype /Type0");
      out("/ToUnicode " + cmap + " 0 R");
      out("/BaseFont /" + font.fontName);
      out("/Encoding /" + font.encoding);
      out("/DescendantFonts [" + DescendantFont + " 0 R]");
      out(">>");
      out("endobj");

      font.isAlreadyPutted = true;
    }
  };

  jsPDFAPI.events.push([
    "putFont",
    function(args) {
      identityHFunction(args);
    }
  ]);

  var winAnsiEncodingFunction = function(options) {
    var font = options.font;
    var out = options.out;
    var newObject = options.newObject;
    var putStream = options.putStream;
    var pdfEscapeWithNeededParanthesis = options.pdfEscapeWithNeededParanthesis;

    if (
      font.metadata instanceof jsPDF.API.TTFFont &&
      font.encoding === "WinAnsiEncoding"
    ) {
      //Tag with WinAnsi encoding
      var data = font.metadata.rawData;
      var pdfOutput = data;
      var pdfOutput2 = "";
      for (var i = 0; i < pdfOutput.length; i++) {
        pdfOutput2 += String.fromCharCode(pdfOutput[i]);
      }
      var fontTable = newObject();
      putStream({ data: pdfOutput2, addLength1: true });
      out("endobj");

      var cmap = newObject();
      var cmapData = toUnicodeCmap(font.metadata.toUnicode);
      putStream({ data: cmapData, addLength1: true });
      out("endobj");

      var fontDescriptor = newObject();
      out("<<");
      out("/Descent " + font.metadata.decender);
      out("/CapHeight " + font.metadata.capHeight);
      out("/StemV " + font.metadata.stemV);
      out("/Type /FontDescriptor");
      out("/FontFile2 " + fontTable + " 0 R");
      out("/Flags 96");
      out("/FontBBox " + jsPDF.API.PDFObject.convert(font.metadata.bbox));
      out("/FontName /" + pdfEscapeWithNeededParanthesis(font.fontName));
      out("/ItalicAngle " + font.metadata.italicAngle);
      out("/Ascent " + font.metadata.ascender);
      out(">>");
      out("endobj");
      font.objectNumber = newObject();
      for (var j = 0; j < font.metadata.hmtx.widths.length; j++) {
        font.metadata.hmtx.widths[j] = parseInt(
          font.metadata.hmtx.widths[j] * (1000 / font.metadata.head.unitsPerEm)
        ); //Change the width of Em units to Point units.
      }
      out(
        "<</Subtype/TrueType/Type/Font/ToUnicode " +
          cmap +
          " 0 R/BaseFont/" +
          font.fontName +
          "/FontDescriptor " +
          fontDescriptor +
          " 0 R" +
          "/Encoding/" +
          font.encoding +
          " /FirstChar 29 /LastChar 255 /Widths " +
          jsPDF.API.PDFObject.convert(font.metadata.hmtx.widths) +
          ">>"
      );
      out("endobj");
      font.isAlreadyPutted = true;
    }
  };

  jsPDFAPI.events.push([
    "putFont",
    function(args) {
      winAnsiEncodingFunction(args);
    }
  ]);

  var utf8TextFunction = function(args) {
    var text = args.text || "";
    var x = args.x;
    var y = args.y;
    var options = args.options || {};
    var mutex = args.mutex || {};

    var pdfEscape = mutex.pdfEscape;
    var activeFontKey = mutex.activeFontKey;
    var fonts = mutex.fonts;
    var key = activeFontKey;

    var str = "",
      s = 0,
      cmapConfirm;
    var strText = "";
    var encoding = fonts[key].encoding;

    if (fonts[key].encoding !== "Identity-H") {
      return {
        text: text,
        x: x,
        y: y,
        options: options,
        mutex: mutex
      };
    }
    strText = text;

    key = activeFontKey;
    if (Array.isArray(text)) {
      strText = text[0];
    }
    for (s = 0; s < strText.length; s += 1) {
      if (fonts[key].metadata.hasOwnProperty("cmap")) {
        cmapConfirm =
          fonts[key].metadata.cmap.unicode.codeMap[strText[s].charCodeAt(0)];
        /*
             if (Object.prototype.toString.call(text) === '[object Array]') {
                var i = 0;
               // for (i = 0; i < text.length; i += 1) {
                    if (Object.prototype.toString.call(text[s]) === '[object Array]') {
                        cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s][0].charCodeAt(0)]; //Make sure the cmap has the corresponding glyph id
                    } else {

                    }
                //}

            } else {
                cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s].charCodeAt(0)]; //Make sure the cmap has the corresponding glyph id
            }*/
      }
      if (!cmapConfirm) {
        if (
          strText[s].charCodeAt(0) < 256 &&
          fonts[key].metadata.hasOwnProperty("Unicode")
        ) {
          str += strText[s];
        } else {
          str += "";
        }
      } else {
        str += strText[s];
      }
    }
    var result = "";
    if (parseInt(key.slice(1)) < 14 || encoding === "WinAnsiEncoding") {
      //For the default 13 font
      result = pdfEscape(str, key)
        .split("")
        .map(function(cv) {
          return cv.charCodeAt(0).toString(16);
        })
        .join("");
    } else if (encoding === "Identity-H") {
      result = pdfEscape16(str, fonts[key]);
    }
    mutex.isHex = true;

    return {
      text: result,
      x: x,
      y: y,
      options: options,
      mutex: mutex
    };
  };

  var utf8EscapeFunction = function(parms) {
    var text = parms.text || "",
      x = parms.x,
      y = parms.y,
      options = parms.options,
      mutex = parms.mutex;
    var tmpText = [];
    var args = {
      text: text,
      x: x,
      y: y,
      options: options,
      mutex: mutex
    };

    if (Array.isArray(text)) {
      var i = 0;
      for (i = 0; i < text.length; i += 1) {
        if (Array.isArray(text[i])) {
          if (text[i].length === 3) {
            tmpText.push([
              utf8TextFunction(Object.assign({}, args, { text: text[i][0] }))
                .text,
              text[i][1],
              text[i][2]
            ]);
          } else {
            tmpText.push(
              utf8TextFunction(Object.assign({}, args, { text: text[i] })).text
            );
          }
        } else {
          tmpText.push(
            utf8TextFunction(Object.assign({}, args, { text: text[i] })).text
          );
        }
      }
      parms.text = tmpText;
    } else {
      parms.text = utf8TextFunction(
        Object.assign({}, args, { text: text })
      ).text;
    }
  };

  jsPDFAPI.events.push(["postProcessText", utf8EscapeFunction]);
})(jsPDF);
<commit_msg>fix escaping of font names<commit_after>/* global jsPDF */
/**
 * @name utf8
 * @module
 */
(function(jsPDF) {
  "use strict";
  var jsPDFAPI = jsPDF.API;

  /***************************************************************************************************/
  /* function : pdfEscape16                                                                          */
  /* comment : The character id of a 2-byte string is converted to a hexadecimal number by obtaining */
  /*   the corresponding glyph id and width, and then adding padding to the string.                  */
  /***************************************************************************************************/
  var pdfEscape16 = (jsPDFAPI.pdfEscape16 = function(text, font) {
    var widths = font.metadata.Unicode.widths;
    var padz = ["", "0", "00", "000", "0000"];
    var ar = [""];
    for (var i = 0, l = text.length, t; i < l; ++i) {
      t = font.metadata.characterToGlyph(text.charCodeAt(i));
      font.metadata.glyIdsUsed.push(t);
      font.metadata.toUnicode[t] = text.charCodeAt(i);
      if (widths.indexOf(t) == -1) {
        widths.push(t);
        widths.push([parseInt(font.metadata.widthOfGlyph(t), 10)]);
      }
      if (t == "0") {
        //Spaces are not allowed in cmap.
        return ar.join("");
      } else {
        t = t.toString(16);
        ar.push(padz[4 - t.length], t);
      }
    }
    return ar.join("");
  });

  var toUnicodeCmap = function(map) {
    var code, codes, range, unicode, unicodeMap, _i, _len;
    unicodeMap =
      "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo <<\n  /Registry (Adobe)\n  /Ordering (UCS)\n  /Supplement 0\n>> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<0000><ffff>\nendcodespacerange";
    codes = Object.keys(map).sort(function(a, b) {
      return a - b;
    });

    range = [];
    for (_i = 0, _len = codes.length; _i < _len; _i++) {
      code = codes[_i];
      if (range.length >= 100) {
        unicodeMap +=
          "\n" +
          range.length +
          " beginbfchar\n" +
          range.join("\n") +
          "\nendbfchar";
        range = [];
      }

      if (
        map[code] !== undefined &&
        map[code] !== null &&
        typeof map[code].toString === "function"
      ) {
        unicode = ("0000" + map[code].toString(16)).slice(-4);
        code = ("0000" + (+code).toString(16)).slice(-4);
        range.push("<" + code + "><" + unicode + ">");
      }
    }

    if (range.length) {
      unicodeMap +=
        "\n" +
        range.length +
        " beginbfchar\n" +
        range.join("\n") +
        "\nendbfchar\n";
    }
    unicodeMap +=
      "endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend";
    return unicodeMap;
  };

  var identityHFunction = function(options) {
    var font = options.font;
    var out = options.out;
    var newObject = options.newObject;
    var putStream = options.putStream;
    var pdfEscapeWithNeededParanthesis = options.pdfEscapeWithNeededParanthesis;

    if (
      font.metadata instanceof jsPDF.API.TTFFont &&
      font.encoding === "Identity-H"
    ) {
      //Tag with Identity-H
      var widths = font.metadata.Unicode.widths;
      var data = font.metadata.subset.encode(font.metadata.glyIdsUsed, 1);
      var pdfOutput = data;
      var pdfOutput2 = "";
      for (var i = 0; i < pdfOutput.length; i++) {
        pdfOutput2 += String.fromCharCode(pdfOutput[i]);
      }
      var fontTable = newObject();
      putStream({ data: pdfOutput2, addLength1: true });
      out("endobj");

      var cmap = newObject();
      var cmapData = toUnicodeCmap(font.metadata.toUnicode);
      putStream({ data: cmapData, addLength1: true });
      out("endobj");

      var fontDescriptor = newObject();
      out("<<");
      out("/Type /FontDescriptor");
      out("/FontName /" + pdfEscapeWithNeededParanthesis(font.fontName));
      out("/FontFile2 " + fontTable + " 0 R");
      out("/FontBBox " + jsPDF.API.PDFObject.convert(font.metadata.bbox));
      out("/Flags " + font.metadata.flags);
      out("/StemV " + font.metadata.stemV);
      out("/ItalicAngle " + font.metadata.italicAngle);
      out("/Ascent " + font.metadata.ascender);
      out("/Descent " + font.metadata.decender);
      out("/CapHeight " + font.metadata.capHeight);
      out(">>");
      out("endobj");

      var DescendantFont = newObject();
      out("<<");
      out("/Type /Font");
      out("/BaseFont /" + pdfEscapeWithNeededParanthesis(font.fontName));
      out("/FontDescriptor " + fontDescriptor + " 0 R");
      out("/W " + jsPDF.API.PDFObject.convert(widths));
      out("/CIDToGIDMap /Identity");
      out("/DW 1000");
      out("/Subtype /CIDFontType2");
      out("/CIDSystemInfo");
      out("<<");
      out("/Supplement 0");
      out("/Registry (Adobe)");
      out("/Ordering (" + font.encoding + ")");
      out(">>");
      out(">>");
      out("endobj");

      font.objectNumber = newObject();
      out("<<");
      out("/Type /Font");
      out("/Subtype /Type0");
      out("/ToUnicode " + cmap + " 0 R");
      out("/BaseFont /" + pdfEscapeWithNeededParanthesis(font.fontName));
      out("/Encoding /" + font.encoding);
      out("/DescendantFonts [" + DescendantFont + " 0 R]");
      out(">>");
      out("endobj");

      font.isAlreadyPutted = true;
    }
  };

  jsPDFAPI.events.push([
    "putFont",
    function(args) {
      identityHFunction(args);
    }
  ]);

  var winAnsiEncodingFunction = function(options) {
    var font = options.font;
    var out = options.out;
    var newObject = options.newObject;
    var putStream = options.putStream;
    var pdfEscapeWithNeededParanthesis = options.pdfEscapeWithNeededParanthesis;

    if (
      font.metadata instanceof jsPDF.API.TTFFont &&
      font.encoding === "WinAnsiEncoding"
    ) {
      //Tag with WinAnsi encoding
      var data = font.metadata.rawData;
      var pdfOutput = data;
      var pdfOutput2 = "";
      for (var i = 0; i < pdfOutput.length; i++) {
        pdfOutput2 += String.fromCharCode(pdfOutput[i]);
      }
      var fontTable = newObject();
      putStream({ data: pdfOutput2, addLength1: true });
      out("endobj");

      var cmap = newObject();
      var cmapData = toUnicodeCmap(font.metadata.toUnicode);
      putStream({ data: cmapData, addLength1: true });
      out("endobj");

      var fontDescriptor = newObject();
      out("<<");
      out("/Descent " + font.metadata.decender);
      out("/CapHeight " + font.metadata.capHeight);
      out("/StemV " + font.metadata.stemV);
      out("/Type /FontDescriptor");
      out("/FontFile2 " + fontTable + " 0 R");
      out("/Flags 96");
      out("/FontBBox " + jsPDF.API.PDFObject.convert(font.metadata.bbox));
      out("/FontName /" + pdfEscapeWithNeededParanthesis(font.fontName));
      out("/ItalicAngle " + font.metadata.italicAngle);
      out("/Ascent " + font.metadata.ascender);
      out(">>");
      out("endobj");
      font.objectNumber = newObject();
      for (var j = 0; j < font.metadata.hmtx.widths.length; j++) {
        font.metadata.hmtx.widths[j] = parseInt(
          font.metadata.hmtx.widths[j] * (1000 / font.metadata.head.unitsPerEm)
        ); //Change the width of Em units to Point units.
      }
      out(
        "<</Subtype/TrueType/Type/Font/ToUnicode " +
          cmap +
          " 0 R/BaseFont/" +
          font.fontName +
          "/FontDescriptor " +
          fontDescriptor +
          " 0 R" +
          "/Encoding/" +
          font.encoding +
          " /FirstChar 29 /LastChar 255 /Widths " +
          jsPDF.API.PDFObject.convert(font.metadata.hmtx.widths) +
          ">>"
      );
      out("endobj");
      font.isAlreadyPutted = true;
    }
  };

  jsPDFAPI.events.push([
    "putFont",
    function(args) {
      winAnsiEncodingFunction(args);
    }
  ]);

  var utf8TextFunction = function(args) {
    var text = args.text || "";
    var x = args.x;
    var y = args.y;
    var options = args.options || {};
    var mutex = args.mutex || {};

    var pdfEscape = mutex.pdfEscape;
    var activeFontKey = mutex.activeFontKey;
    var fonts = mutex.fonts;
    var key = activeFontKey;

    var str = "",
      s = 0,
      cmapConfirm;
    var strText = "";
    var encoding = fonts[key].encoding;

    if (fonts[key].encoding !== "Identity-H") {
      return {
        text: text,
        x: x,
        y: y,
        options: options,
        mutex: mutex
      };
    }
    strText = text;

    key = activeFontKey;
    if (Array.isArray(text)) {
      strText = text[0];
    }
    for (s = 0; s < strText.length; s += 1) {
      if (fonts[key].metadata.hasOwnProperty("cmap")) {
        cmapConfirm =
          fonts[key].metadata.cmap.unicode.codeMap[strText[s].charCodeAt(0)];
        /*
             if (Object.prototype.toString.call(text) === '[object Array]') {
                var i = 0;
               // for (i = 0; i < text.length; i += 1) {
                    if (Object.prototype.toString.call(text[s]) === '[object Array]') {
                        cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s][0].charCodeAt(0)]; //Make sure the cmap has the corresponding glyph id
                    } else {

                    }
                //}

            } else {
                cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s].charCodeAt(0)]; //Make sure the cmap has the corresponding glyph id
            }*/
      }
      if (!cmapConfirm) {
        if (
          strText[s].charCodeAt(0) < 256 &&
          fonts[key].metadata.hasOwnProperty("Unicode")
        ) {
          str += strText[s];
        } else {
          str += "";
        }
      } else {
        str += strText[s];
      }
    }
    var result = "";
    if (parseInt(key.slice(1)) < 14 || encoding === "WinAnsiEncoding") {
      //For the default 13 font
      result = pdfEscape(str, key)
        .split("")
        .map(function(cv) {
          return cv.charCodeAt(0).toString(16);
        })
        .join("");
    } else if (encoding === "Identity-H") {
      result = pdfEscape16(str, fonts[key]);
    }
    mutex.isHex = true;

    return {
      text: result,
      x: x,
      y: y,
      options: options,
      mutex: mutex
    };
  };

  var utf8EscapeFunction = function(parms) {
    var text = parms.text || "",
      x = parms.x,
      y = parms.y,
      options = parms.options,
      mutex = parms.mutex;
    var tmpText = [];
    var args = {
      text: text,
      x: x,
      y: y,
      options: options,
      mutex: mutex
    };

    if (Array.isArray(text)) {
      var i = 0;
      for (i = 0; i < text.length; i += 1) {
        if (Array.isArray(text[i])) {
          if (text[i].length === 3) {
            tmpText.push([
              utf8TextFunction(Object.assign({}, args, { text: text[i][0] }))
                .text,
              text[i][1],
              text[i][2]
            ]);
          } else {
            tmpText.push(
              utf8TextFunction(Object.assign({}, args, { text: text[i] })).text
            );
          }
        } else {
          tmpText.push(
            utf8TextFunction(Object.assign({}, args, { text: text[i] })).text
          );
        }
      }
      parms.text = tmpText;
    } else {
      parms.text = utf8TextFunction(
        Object.assign({}, args, { text: text })
      ).text;
    }
  };

  jsPDFAPI.events.push(["postProcessText", utf8EscapeFunction]);
})(jsPDF);
<|endoftext|>


<commit_before>$(function() {
  $('#sign-in-modal').modal();
});

$('#magic').click(function() {
  console.log("hi");
  window.location = '/loggedin.html';
});

$('#magic2').click(function() {
  console.log("hi");
  window.location = '/loggedin.html';
});

var audio;
var first = true;

$('#play').click(function() {
  if(first) {
    audio = new Audio('/music.mp3');
    first = false;
  }
  audio.play();
  $('#pause').toggle();
  $('#play').toggle();
});

$('#pause').click(function() {
  $('#pause').toggle();
  $('#play').toggle();
  audio.pause();
});

$('#fast-forward').click(function() {
  audio.pause();
});

$('#fast-backward').click(function() {
  audio.pause();
});
<commit_msg>New music<commit_after>$(function() {
  $('#sign-in-modal').modal();
});

$('#magic').click(function() {
  console.log("hi");
  window.location = '/loggedin.html';
});

$('#magic2').click(function() {
  console.log("hi");
  window.location = '/loggedin.html';
});

var audio;
var first = true;

$('#play').click(function() {
  if(first) {
    audio = new Audio('/test.mp3');
    first = false;
  }
  audio.play();
  $('#pause').toggle();
  $('#play').toggle();
});

$('#pause').click(function() {
  $('#pause').toggle();
  $('#play').toggle();
  audio.pause();
});

$('#fast-forward').click(function() {
  audio.pause();
});

$('#fast-backward').click(function() {
  audio.pause();
});
<|endoftext|>


<commit_before>/**
 * @module http
 * @submodule Child
 * @private
 */

/*!
 * @private
 * @ignore
 */
/*global require, exports, log, sync, java, io */
(function() {
    "use strict";

    global.io = global.io || 'net';

    var Thread = require('Threads').Thread,
        InputStream = require(io).InputStream,
        OutputStream = require(io).OutputStream,
//        InputStream = require('net').InputStream,
//        OutputStream = require('net').OutputStream,
        Request = require('Request').Request,
        Response = require('Response').Response,
        WebSocket = require('WebSocket').WebSocket;

    function handleRequest(is, os, fn, webSockets) {
        var request = new Request(is),
            response = new Response(os, request),
            keepAlive = true;

        this.req = request;
        this.res = response;
        request.threadId = this.threadId;
        request.scope = this;

        this.fire('startRequest', request, response);

        var connection = (request.headers['connection'] || '').toLowerCase(),
            headers = response.headers;
        if (connection === 'upgrade') {
            if (request.headers['upgrade'].toLowerCase() !== 'websocket') {
                return false;
            }
            var parts = request.uri.split('/');
            if (webSockets[parts[0]]) {
                var ws = new WebSocket(request, response);
                webSockets[parts[0]](ws);    // socket connect
                ws.run();                       // handle the socket until close, etc.
            }
            return false;
        }
        else if (connection === 'keep-alive') {
            headers['Connection'] = 'Keep-Alive';
            headers['keep-alive'] = 'timeout: 5; max = 10000000';
        }
        else {
            headers['Connection'] = 'close';
            keepAlive = false;
        }
        if (fn.call(this, request, response) === false) {
            headers['Connection'] = 'close';
            keepAlive = false;
        }
        return keepAlive;
    }

    /**
     * Thread to handle HTTP requests.
     *
     * There are typically numChildren (see Server.listen) Child threads spawned at start.
     *
     * The Child logic is two nested loops.  The outer loop accepts connections.  The inner loop
     * processes requests on the accepted connection until the connection is closed or until
     * the HTTP protocol requires the connection to be closed (Connection: close).
     *
     * If a request is an upgrade to WebSocket, the thread becomes dedicated to servicing the
     * socket.
     *
     * A Request and Response object are created for each request handled.  See http/Request.js
     * and http/Response.js for details.
     *
     * @param {Socket} serverSocket the Socket to accept connections from
     * @param {object} server instance of the http Server that spawned this child
     * @constructor
     */
    function Child(serverSocket, server) {
        var me = this;      // current Thread

        me.on('exit', function() {
            new Thread(Child, serverSocket, server).start();
        });

        var accept = sync(function() {
            return serverSocket.accept();
        });

        var fn = server.fn,
            webSockets = server.webSockets;

        while (true) {
            var sock = serverSocket.accept();
//            var sock = accept();

            var is = new InputStream(sock),
                os = new OutputStream(sock);

            var keepAlive = true;
            while (keepAlive) {
                try {
//                    var start = new Date().getTime(); // java.lang.System.nanoTime();
                    keepAlive = keepAlive && handleRequest.call(this, is, os, fn, webSockets);
                    me.fire('endRequest');
//                    var elapsed = new Date().getTime() - start; // java.lang.System.nanoTime() - start;
//                    console.log(elapsed);
                }
                catch (e) {
                    if (e === 'THREAD.EXIT') {
                        throw e;
                    }
                    if (e === 'EOF') {
                        break;
                    }
                    if (e.dumpText) {
                        e.dumpText();
                    }
					else if (e === 'RES.STOP') {
						continue;
					}
                    else {
                        console.log(e);
                    }
                    keepAlive = false;
                }
            }
            is.destroy();
            os.destroy();
            sock.destroy();
        }
    }

    decaf.extend(exports, {
        Child : Child
    });

}());
<commit_msg>Improve websockets<commit_after>/**
 * @module http
 * @submodule Child
 * @private
 */

/*!
 * @private
 * @ignore
 */
/*global require, exports, log, sync, java, io */
(function() {
    "use strict";

    global.io = global.io || 'net';

    var Thread = require('Threads').Thread,
        InputStream = require(io).InputStream,
        OutputStream = require(io).OutputStream,
//        InputStream = require('net').InputStream,
//        OutputStream = require('net').OutputStream,
        Request = require('Request').Request,
        Response = require('Response').Response,
        WebSocket = require('WebSocket').WebSocket;

    function handleRequest(is, os, fn, webSockets) {
        var request = new Request(is),
            response = new Response(os, request),
            keepAlive = true;

        this.req = request;
        this.res = response;
        request.threadId = this.threadId;
        request.scope = this;

        this.fire('startRequest', request, response);

        var connection = (request.headers['connection'] || '').toLowerCase(),
            headers = response.headers;
        if (connection === 'upgrade') {
            if (request.headers['upgrade'].toLowerCase() !== 'websocket') {
                return false;
            }
            var parts = request.uri.split('/'),
                part = parts[0] || parts[1];
            if (webSockets[part]) {
                var ws = new WebSocket(request, response);
                webSockets[part](ws);    // socket connect
                ws.run();                       // handle the socket until close, etc.
            }
            return false;
        }
        else if (connection === 'keep-alive') {
            headers['Connection'] = 'Keep-Alive';
            headers['keep-alive'] = 'timeout: 5; max = 10000000';
        }
        else {
            headers['Connection'] = 'close';
            keepAlive = false;
        }
        if (fn.call(this, request, response) === false) {
            headers['Connection'] = 'close';
            keepAlive = false;
        }
        return keepAlive;
    }

    /**
     * Thread to handle HTTP requests.
     *
     * There are typically numChildren (see Server.listen) Child threads spawned at start.
     *
     * The Child logic is two nested loops.  The outer loop accepts connections.  The inner loop
     * processes requests on the accepted connection until the connection is closed or until
     * the HTTP protocol requires the connection to be closed (Connection: close).
     *
     * If a request is an upgrade to WebSocket, the thread becomes dedicated to servicing the
     * socket.
     *
     * A Request and Response object are created for each request handled.  See http/Request.js
     * and http/Response.js for details.
     *
     * @param {Socket} serverSocket the Socket to accept connections from
     * @param {object} server instance of the http Server that spawned this child
     * @constructor
     */
    function Child(serverSocket, server) {
        var me = this;      // current Thread

        me.on('exit', function() {
            new Thread(Child, serverSocket, server).start();
        });

        var accept = sync(function() {
            return serverSocket.accept();
        });

        var fn = server.fn,
            webSockets = server.webSockets;

        while (true) {
            var sock = serverSocket.accept();
//            var sock = accept();

            var is = new InputStream(sock),
                os = new OutputStream(sock);

            var keepAlive = true;
            while (keepAlive) {
                try {
//                    var start = new Date().getTime(); // java.lang.System.nanoTime();
                    keepAlive = keepAlive && handleRequest.call(this, is, os, fn, webSockets);
                    me.fire('endRequest');
//                    var elapsed = new Date().getTime() - start; // java.lang.System.nanoTime() - start;
//                    console.log(elapsed);
                }
                catch (e) {
                    if (e === 'THREAD.EXIT') {
                        throw e;
                    }
                    if (e === 'EOF') {
                        break;
                    }
                    if (e.dumpText) {
                        e.dumpText();
                    }
					else if (e === 'RES.STOP') {
						continue;
					}
                    else {
                        console.log(e);
                    }
                    keepAlive = false;
                }
            }
            is.destroy();
            os.destroy();
            sock.destroy();
        }
    }

    decaf.extend(exports, {
        Child : Child
    });

}());
<|endoftext|>


<commit_before>var should = require('chai').should();
var expect = require('chai').expect;
require('fake-dom');
describe('yaws.socketConnect', function() {
  window={location:{href:"https://127.0.0.1/example"}};
  require('../src/yawsSocketConnect.js');
  it('yaws should be an object', function() {
    window.yaws.should.be.a('object');
  });
  it('yaws.socketConnect should be a function', function() {
    window.yaws.socketConnect.should.be.a('function');
  });
  it('yaws.socketConnect() should throw an error on missing argument', function() {
    expect(window.yaws.socketConnect).to.throw("The first parameter 'onMessage' is required to be a function accepting a single parameter of type Blob.");
  });
  it('yaws.socketConnect() should throw an error on missing Websocket', function() {
    expect(window.yaws.socketConnect(function(blob){},{},'/')).to.throw("No Websocket Implementation found");
  });
  //basic socket
  window.Websocket = function(){};
  Websocket = window.Websocket;
  it('yaws.socketConnect() should be an object', function() {
    window.yaws.socketConnect(function(blob){},{},'/').should.be.a('object');
  });
  it('yaws.socketConnect() should be a Websocket', function() {
    window.yaws.socketConnect(function(blob){},{},'/').should.be.a(Websocket);
  });
  //reconnecting socket
  window.ReconnectingWebSocket = function(){};
  ReconnectingWebSocket = window.ReconnectingWebSocket;
  it('yaws.socketConnect() should be an object', function() {
    window.yaws.socketConnect(function(blob){},{},'/').should.be.a('object');
  });
  it('yaws.socketConnect() should be a ReconnectingWebSocket', function() {
    window.yaws.socketConnect(function(blob){},{},'/').should.be.a(ReconnectingWebSocket);
  });
  //robust socket
  window.RobustWebSocket = function(){};
  RobustWebSocket = window.RobustWebSocket;
  it('yaws.socketConnect() should be an object', function() {
    window.yaws.socketConnect(function(blob){},{},'/').should.be.a('object');
  });
  it('yaws.socketConnect() should be a RobustWebSocket', function() {
    window.yaws.socketConnect(function(blob){},{},'/').should.be.a(RobustWebSocket);
  });
});
<commit_msg>Update yawsSocketConnect.js<commit_after>var should = require('chai').should();
var expect = require('chai').expect;
require('fake-dom');
describe('yaws.socketConnect', function() {
  window={location:{href:"https://127.0.0.1/example"}};
  require('../src/yawsSocketConnect.js');
  it('yaws should be an object', function() {
    window.yaws.should.be.a('object');
  });
  it('yaws.socketConnect should be a function', function() {
    window.yaws.socketConnect.should.be.a('function');
  });
  it('yaws.socketConnect() should throw an error on missing argument', function() {
    expect(window.yaws.socketConnect).to.throw("The first parameter 'onMessage' is required to be a function accepting a single parameter of type Blob.");
  });
  it('yaws.socketConnect() should throw an error on missing Websocket', function() {
    expect(function(){window.yaws.socketConnect(function(blob){},{},'/')}).to.throw("No Websocket Implementation found");
  });
  //basic socket
  window.Websocket = function(){};
  Websocket = window.Websocket;
  it('yaws.socketConnect() should be an object', function() {
    window.yaws.socketConnect(function(blob){},{},'/').should.be.a('object');
  });
  it('yaws.socketConnect() should be a Websocket', function() {
    window.yaws.socketConnect(function(blob){},{},'/').should.be.a(Websocket);
  });
  //reconnecting socket
  window.ReconnectingWebSocket = function(){};
  ReconnectingWebSocket = window.ReconnectingWebSocket;
  it('yaws.socketConnect() should be an object', function() {
    window.yaws.socketConnect(function(blob){},{},'/').should.be.a('object');
  });
  it('yaws.socketConnect() should be a ReconnectingWebSocket', function() {
    window.yaws.socketConnect(function(blob){},{},'/').should.be.a(ReconnectingWebSocket);
  });
  //robust socket
  window.RobustWebSocket = function(){};
  RobustWebSocket = window.RobustWebSocket;
  it('yaws.socketConnect() should be an object', function() {
    window.yaws.socketConnect(function(blob){},{},'/').should.be.a('object');
  });
  it('yaws.socketConnect() should be a RobustWebSocket', function() {
    window.yaws.socketConnect(function(blob){},{},'/').should.be.a(RobustWebSocket);
  });
});
<|endoftext|>


<commit_before>var browserify = require('browserify'),
    concat = require('gulp-concat'),
    es6ify = require('es6ify'),
    gulp = require('gulp'),
    bower = require('gulp-bower'),
    jshint = require('gulp-jshint'),
    gutil = require('gulp-util'),
    jade = require('gulp-jade'),
    jshint = require('gulp-jshint'),
    less = require('gulp-less'),
    minifyCss = require('gulp-minify-css'),
    minifyHtml = require('gulp-minify-html'),
    nodemon = require('gulp-nodemon'),
    path = require('path'),
    rev = require('gulp-rev'),
    source = require('vinyl-source-stream'),
    streamify = require('gulp-streamify'),
    stringify = require('stringify'),
    uglify = require('gulp-uglify'),
    karma = require('gulp-karma'),
    exit = require('gulp-exit'),
    watchify = require('watchify'),
    mocha = require('gulp-mocha');

var paths = {
    public: 'public/**',
    jade: 'app/**/*.jade',
    scripts: 'app/**/*.js',
    img:['app/**/*.jpg',
        'app/**/*.png',
        'app/**/*.jpeg',
        'app/**/*.ico'],
    libTest: ['lib/tests/service.spec.js'],
    unitTest: [
      'public/lib/angular/angular.js',
      'public/lib/angular-mocks/angular-mocks.js',
      'public/lib/moment/moment.js',
      'public/lib/firebase/firebase.js',
      'public/lib/angular-aria/angular-aria.js',
      'public/lib/angular-ui-router/release/angular-ui-router.min.js',
      'public/lib/hammerjs/hammer.min.js',
      'public/lib/angular-material/angular-material.js',
      'public/lib/angular-route/angular-route.js',
      'public/lib/angular-cookies/angular-cookies.js',
      'public/lib/angular-bootstrap/ui-bootstrap.js',
      'public/lib/angular-animate/angular-animate.js',
      'public/lib/angular-sanitize/angular-sanitize.js',
      'public/lib/angularfire/dist/angularfire.js',
      'public/lib/lodash/dist/lodash.min.js',
      'public/js/index.js',
      'app/test/specs.js'
    ],
    styles: 'app/styles/*.+(less|css)'
};

gulp.task('bower', function() {
  return bower()
    .pipe(gulp.dest('public/lib/'))
});

gulp.task('lint', function() {
  return gulp.src('./lib/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('YOUR_REPORTER_HERE'));
});

gulp.task('jade', function() {
    gulp.src('./app/**/*.jade')
        .pipe(jade())
        .pipe(gulp.dest('./public/'))
});

gulp.task('less', function() {
    gulp.src(paths.styles)
        .pipe(less({
            paths: [path.join(__dirname, 'styles')]
        }))
        .pipe(gulp.dest('./public/css'));
});

gulp.task('lint', function() {
    gulp.src(['index.js','./app/**/*.js']).pipe(jshint())
    .pipe(jshint.reporter('default'));
});

//'app/**',
gulp.task('nodemon', function() {
    nodemon({
            script: 'index.js',
            ext: 'js',
            ignore: ['public/']
        })
        .on('change', ['lint'])
        .on('restart', function() {
            console.log('>> node restart');
        })
});

gulp.task('watch', function() {
    // livereload.listen({ port: 35729 });
    gulp.watch(paths.jade, ['jade']);
    gulp.watch(paths.styles, ['less']);
    // gulp.watch(paths.public).on('change', livereload.changed);
});

gulp.task('img', function() {
   return gulp.src(paths.img)
    .pipe(gulp.dest('public/'));
});

gulp.task('watchify', function() {
    var bundler = watchify(browserify('./app/application.js', watchify.args));

    bundler.transform(stringify(['.html']));
    // bundler.transform(es6ify);

    bundler.on('update', rebundle);

    function rebundle() {
        return bundler.bundle()
            // log errors if they happen
            .on('error', gutil.log.bind(gutil, 'Browserify Error'))
            .pipe(source('index.js'))
            .pipe(gulp.dest('./public/js'));
    }

    return rebundle();
});

gulp.task('browserify', function() {
 var b = browserify();
 b.add('./app/application.js');
 return b.bundle()
 .on('success', gutil.log.bind(gutil, 'Browserify Rebundled'))
 .on('error', gutil.log.bind(gutil, 'Browserify Error: in browserify gulp task'))
 .pipe(source('index.js'))
 .pipe(gulp.dest('./public/js'));
});
// gulp.task('usemin', function() {
//   gulp.src('public/*.html')
//     .pipe(usemin({
//       css: [minifyCss(), 'concat'],
//       html: [minifyHtml({empty: true})],
//       js: [uglify(), rev()]
//     }))
//     .pipe(gulp.dest('public'));
// });

gulp.task('test:lib', function() {
    return gulp.src(paths.libTest)
        .pipe(mocha({
            reporter: 'dot',
            timeout: 60000
        }));
});

gulp.task('test:ui',['browserify'], function() {
    // Be sure to return the stream
    return gulp.src(paths.unitTest)
        .pipe(karma({
            configFile: 'karma.conf.js',
            action: 'run'
        }));
                // .on('error', function(err) {
        //     // Make sure failed tests cause gulp to exit non-zero
        //     throw err;
        // });
});

gulp.task('test',['test:ui','test:lib']);
gulp.task('heroku:production', ['bower', 'jade', 'less','img','browserify']);
gulp.task('production', ['nodemon','bower','jade', 'less','watchify','img']);
gulp.task('default', ['nodemon', 'jade', 'less', 'watch', 'watchify','img']);
gulp.task('build', ['jade', 'less', 'watchify','img']);
<commit_msg>re-added pipe exit<commit_after>var browserify = require('browserify'),
    concat = require('gulp-concat'),
    es6ify = require('es6ify'),
    gulp = require('gulp'),
    bower = require('gulp-bower'),
    jshint = require('gulp-jshint'),
    gutil = require('gulp-util'),
    jade = require('gulp-jade'),
    jshint = require('gulp-jshint'),
    less = require('gulp-less'),
    minifyCss = require('gulp-minify-css'),
    minifyHtml = require('gulp-minify-html'),
    nodemon = require('gulp-nodemon'),
    path = require('path'),
    rev = require('gulp-rev'),
    source = require('vinyl-source-stream'),
    streamify = require('gulp-streamify'),
    stringify = require('stringify'),
    uglify = require('gulp-uglify'),
    karma = require('gulp-karma'),
    exit = require('gulp-exit'),
    watchify = require('watchify'),
    mocha = require('gulp-mocha');

var paths = {
    public: 'public/**',
    jade: 'app/**/*.jade',
    scripts: 'app/**/*.js',
    img:['app/**/*.jpg',
        'app/**/*.png',
        'app/**/*.jpeg',
        'app/**/*.ico'],
    libTest: ['lib/tests/service.spec.js'],
    unitTest: [
      'public/lib/angular/angular.js',
      'public/lib/angular-mocks/angular-mocks.js',
      'public/lib/moment/moment.js',
      'public/lib/firebase/firebase.js',
      'public/lib/angular-aria/angular-aria.js',
      'public/lib/angular-ui-router/release/angular-ui-router.min.js',
      'public/lib/hammerjs/hammer.min.js',
      'public/lib/angular-material/angular-material.js',
      'public/lib/angular-route/angular-route.js',
      'public/lib/angular-cookies/angular-cookies.js',
      'public/lib/angular-bootstrap/ui-bootstrap.js',
      'public/lib/angular-animate/angular-animate.js',
      'public/lib/angular-sanitize/angular-sanitize.js',
      'public/lib/angularfire/dist/angularfire.js',
      'public/lib/lodash/dist/lodash.min.js',
      'public/js/index.js',
      'app/test/specs.js'
    ],
    styles: 'app/styles/*.+(less|css)'
};

gulp.task('bower', function() {
  return bower()
    .pipe(gulp.dest('public/lib/'))
});

gulp.task('lint', function() {
  return gulp.src('./lib/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('YOUR_REPORTER_HERE'));
});

gulp.task('jade', function() {
    gulp.src('./app/**/*.jade')
        .pipe(jade())
        .pipe(gulp.dest('./public/'))
});

gulp.task('less', function() {
    gulp.src(paths.styles)
        .pipe(less({
            paths: [path.join(__dirname, 'styles')]
        }))
        .pipe(gulp.dest('./public/css'));
});

gulp.task('lint', function() {
    gulp.src(['index.js','./app/**/*.js']).pipe(jshint())
    .pipe(jshint.reporter('default'));
});

//'app/**',
gulp.task('nodemon', function() {
    nodemon({
            script: 'index.js',
            ext: 'js',
            ignore: ['public/']
        })
        .on('change', ['lint'])
        .on('restart', function() {
            console.log('>> node restart');
        })
});

gulp.task('watch', function() {
    // livereload.listen({ port: 35729 });
    gulp.watch(paths.jade, ['jade']);
    gulp.watch(paths.styles, ['less']);
    // gulp.watch(paths.public).on('change', livereload.changed);
});

gulp.task('img', function() {
   return gulp.src(paths.img)
    .pipe(gulp.dest('public/'));
});

gulp.task('watchify', function() {
    var bundler = watchify(browserify('./app/application.js', watchify.args));

    bundler.transform(stringify(['.html']));
    // bundler.transform(es6ify);

    bundler.on('update', rebundle);

    function rebundle() {
        return bundler.bundle()
            // log errors if they happen
            .on('error', gutil.log.bind(gutil, 'Browserify Error'))
            .pipe(source('index.js'))
            .pipe(gulp.dest('./public/js'));
    }

    return rebundle();
});

gulp.task('browserify', function() {
 var b = browserify();
 b.add('./app/application.js');
 return b.bundle()
 .on('success', gutil.log.bind(gutil, 'Browserify Rebundled'))
 .on('error', gutil.log.bind(gutil, 'Browserify Error: in browserify gulp task'))
 .pipe(source('index.js'))
 .pipe(gulp.dest('./public/js'));
});
// gulp.task('usemin', function() {
//   gulp.src('public/*.html')
//     .pipe(usemin({
//       css: [minifyCss(), 'concat'],
//       html: [minifyHtml({empty: true})],
//       js: [uglify(), rev()]
//     }))
//     .pipe(gulp.dest('public'));
// });

gulp.task('test:lib', function() {
    return gulp.src(paths.libTest)
        .pipe(mocha({
            reporter: 'dot',
            timeout: 60000
        }));
});

gulp.task('test:ui',['browserify'], function() {
    // Be sure to return the stream
    return gulp.src(paths.unitTest)
        .pipe(karma({
            configFile: 'karma.conf.js',
            action: 'run'
        }))
        .pipe(exit());
                // .on('error', function(err) {
        //     // Make sure failed tests cause gulp to exit non-zero
        //     throw err;
        // });
});

gulp.task('test',['test:ui','test:lib']);
gulp.task('heroku:production', ['bower', 'jade', 'less','img','browserify']);
gulp.task('production', ['nodemon','bower','jade', 'less','watchify','img']);
gulp.task('default', ['nodemon', 'jade', 'less', 'watch', 'watchify','img']);
gulp.task('build', ['jade', 'less', 'watchify','img']);
<|endoftext|>


<commit_before>'use strict';

if (!process.env.BASE_DIR) {
    process.env.BASE_DIR = __dirname;
}
global.requireDb = function () {
    return require('elyoos-server-lib').neo4j;
};
global.requireModel = function (name) {
    return require(`${__dirname}/models/${name}`);
};

require('elyoos-server-lib').jsonValidation;
require('elyoos-server-lib').version.setVersion(require('./package.json').version);
let Promise = require('bluebird');

Promise.Promise.config({warnings: false, longStackTraces: true, cancellation: true});

let emailService = require('./models/eMailService/eMail');
let kraken = require('kraken-js');
let dbConfig = require('elyoos-server-lib').databaseConfig;
let app = require('express')();
let options = require('elyoos-server-lib').spec(app);
let logger = require('elyoos-server-lib').logging.getLogger(__filename);
let port = process.env.PORT || 8082;

if (process.env.NODE_ENV === 'production') {
    app.enable('trust proxy');
    logger.info('Enabled trust proxy');
}

app.use(kraken(options));

app.listen(port, function (err) {
    if (err) {
        logger.fatal('Admin Server failed to start', {message: err});
    } else {
        logger.info('[' + app.settings.env + '] Listening on http://localhost:' + port);
    }
});

app.on('start', function () {
    dbConfig.connected.then(function () {
        emailService.start();
        logger.info('Admin Server started');
    });
});

app.on('exit', function () {
    requireDb().closeDriver();
});

module.exports = app;

<commit_msg>Add init of elyoos lib.<commit_after>'use strict';

if (!process.env.BASE_DIR) {
    process.env.BASE_DIR = __dirname;
}
require('elyoos-server-lib').init('elyoos');
global.requireDb = function () {
    return require('elyoos-server-lib').neo4j;
};
global.requireModel = function (name) {
    return require(`${__dirname}/models/${name}`);
};

require('elyoos-server-lib').jsonValidation;
require('elyoos-server-lib').version.setVersion(require('./package.json').version);
let Promise = require('bluebird');

Promise.Promise.config({warnings: false, longStackTraces: true, cancellation: true});

let emailService = require('./models/eMailService/eMail');
let kraken = require('kraken-js');
let dbConfig = require('elyoos-server-lib').databaseConfig;
let app = require('express')();
let options = require('elyoos-server-lib').spec(app);
let logger = require('elyoos-server-lib').logging.getLogger(__filename);
let port = process.env.PORT || 8082;

if (process.env.NODE_ENV === 'production') {
    app.enable('trust proxy');
    logger.info('Enabled trust proxy');
}

app.use(kraken(options));

app.listen(port, function (err) {
    if (err) {
        logger.fatal('Admin Server failed to start', {message: err});
    } else {
        logger.info('[' + app.settings.env + '] Listening on http://localhost:' + port);
    }
});

app.on('start', function () {
    dbConfig.connected.then(function () {
        emailService.start();
        logger.info('Admin Server started');
    });
});

app.on('exit', function () {
    requireDb().closeDriver();
});

module.exports = app;

<|endoftext|>


<commit_before>/*
 * Copyright 2013 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Eclipse Public License version 1.0, available at http://www.eclipse.org/legal/epl-v10.html
 */
/*
 example:
 var options = { host: 'http://127.0.0.1', port: 8080 };
 var liveOak = LiveOak( options );
*/
var LiveOak = function( options ) {
    options = options || {};

    // Allow instantiation without using new
    if(!(this instanceof LiveOak)) {
        return new LiveOak( options );
    }

    // Use address of liveoak.js if server address not specified
    if (!options.host) {
        var server = parseScriptUrl();
        options.host = server.host;
        options.port = server.port;
        options.secure = server.secure;
    }

    var http = new Http(options);
    var auth;
    var stomp_client = new Stomp.Client( options.host, options.port, options.secure );

    this.connect = function( callback ) {
      // TODO: Better way to do this...
      if (arguments.length == 1) {
         stomp_client.connect( arguments[0] );
      }
      if (arguments.length == 2) {
        stomp_client.connect( arguments[0], arguments[1] );
      }
      if (arguments.length == 3) {
        stomp_client.connect( arguments[0], arguments[1], arguments[2] );
      }
      if (arguments.length == 4) {
        stomp_client.connect( arguments[0], arguments[1], arguments[2], arguments[3] );
      }
    };

    this.onStompError = function( callback ) {
        stomp_client.onerror = callback;
    }

    this.create = http.create;
    this.read = http.read;
    this.readMembers = http.readMembers;
    this.save = http.save;
    this.update = http.update;
    this.remove = http.remove;

    this.subscribe = function( path, callback ) {
        stomp_client.subscribe( path, function(msg) {
            var data = JSON.parse( msg.body );
            callback( data );
        });
    };

    if (options.auth) {
        if (!options.auth.url) {
            var port = options.port ? options.port + 303 : 8383;
            options.auth.url = (options.secure ? 'https://' : 'http://') + options.host + ':' + port + '/auth';
        }

        auth = new Keycloak(options.auth);
        this.auth = auth;

        http.getToken = function() {
            return auth.token;
        }
    }

    function parseScriptUrl() {
        var scripts = document.getElementsByTagName('script');
        for (var i = 0; i < scripts.length; i++)  {
            if (scripts[i].src.match(/.*liveoak\.js/)) {
                var parts = scripts[i].src.split('/');
                var server = {};
                if (parts[2].indexOf(':') == -1) {
                    server.host = parts[2];
                } else {
                    server.host = parts[2].substring(0, parts[2].indexOf(':'));
                    server.port = parseInt(parts[2].substring(parts[2].indexOf(':') + 1));
                }
                if (parts[0] == 'https') {
                    server.secure = true;
                }
                return server;
            }
        }
    }
};
<commit_msg>LIVEOAK-137 distinguish between the CUD operations for client subscriptions  - Pass msg.headers.action into callback. Possible values are 'create', 'update', 'delete'.<commit_after>/*
 * Copyright 2013 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Eclipse Public License version 1.0, available at http://www.eclipse.org/legal/epl-v10.html
 */
/*
 example:
 var options = { host: 'http://127.0.0.1', port: 8080 };
 var liveOak = LiveOak( options );
*/
var LiveOak = function( options ) {
    options = options || {};

    // Allow instantiation without using new
    if(!(this instanceof LiveOak)) {
        return new LiveOak( options );
    }

    // Use address of liveoak.js if server address not specified
    if (!options.host) {
        var server = parseScriptUrl();
        options.host = server.host;
        options.port = server.port;
        options.secure = server.secure;
    }

    var http = new Http(options);
    var auth;
    var stomp_client = new Stomp.Client( options.host, options.port, options.secure );

    this.connect = function( callback ) {
      // TODO: Better way to do this...
      if (arguments.length == 1) {
         stomp_client.connect( arguments[0] );
      }
      if (arguments.length == 2) {
        stomp_client.connect( arguments[0], arguments[1] );
      }
      if (arguments.length == 3) {
        stomp_client.connect( arguments[0], arguments[1], arguments[2] );
      }
      if (arguments.length == 4) {
        stomp_client.connect( arguments[0], arguments[1], arguments[2], arguments[3] );
      }
    };

    this.onStompError = function( callback ) {
        stomp_client.onerror = callback;
    }

    this.create = http.create;
    this.read = http.read;
    this.readMembers = http.readMembers;
    this.save = http.save;
    this.update = http.update;
    this.remove = http.remove;

    this.subscribe = function( path, callback ) {
        stomp_client.subscribe( path, function(msg) {
            var data = JSON.parse( msg.body );
            callback( data, msg.headers.action );
        });
    };

    if (options.auth) {
        if (!options.auth.url) {
            var port = options.port ? options.port + 303 : 8383;
            options.auth.url = (options.secure ? 'https://' : 'http://') + options.host + ':' + port + '/auth';
        }

        auth = new Keycloak(options.auth);
        this.auth = auth;

        http.getToken = function() {
            return auth.token;
        }
    }

    function parseScriptUrl() {
        var scripts = document.getElementsByTagName('script');
        for (var i = 0; i < scripts.length; i++)  {
            if (scripts[i].src.match(/.*liveoak\.js/)) {
                var parts = scripts[i].src.split('/');
                var server = {};
                if (parts[2].indexOf(':') == -1) {
                    server.host = parts[2];
                } else {
                    server.host = parts[2].substring(0, parts[2].indexOf(':'));
                    server.port = parseInt(parts[2].substring(parts[2].indexOf(':') + 1));
                }
                if (parts[0] == 'https') {
                    server.secure = true;
                }
                return server;
            }
        }
    }
};
<|endoftext|>